@@ -400,6 +400,71 @@ func TestBdCmd_EnvImmutability(t *testing.T) {
400400 }
401401}
402402
403+ func TestBdCmd_WithBeadsDir_SetsEnv (t * testing.T ) {
404+ // WithBeadsDir should set BEADS_DIR in the environment
405+ bdc := BdCmd ("show" , "id" ).
406+ WithBeadsDir ("/town/rig/mayor/rig/.beads" )
407+ cmd := bdc .Build ()
408+ envMap := parseEnv (cmd .Env )
409+
410+ if envMap ["BEADS_DIR" ] != "/town/rig/mayor/rig/.beads" {
411+ t .Errorf ("BEADS_DIR = %q, want %q" , envMap ["BEADS_DIR" ], "/town/rig/mayor/rig/.beads" )
412+ }
413+ }
414+
415+ func TestBdCmd_WithBeadsDir_OverridesInherited (t * testing.T ) {
416+ // WithBeadsDir should override an inherited BEADS_DIR from the parent
417+ // process. This is the core fix for gt-ctir: without overriding,
418+ // bd could write to the wrong database (HQ instead of rig).
419+ baseEnv := []string {"PATH=/usr/bin" , "BEADS_DIR=/town/.beads" , "HOME=/home/user" }
420+
421+ bdc := & bdCmd {
422+ args : []string {"mol" , "wisp" , "create" , "proto-id" },
423+ env : baseEnv ,
424+ stderr : os .Stderr ,
425+ }
426+ bdc .WithBeadsDir ("/town/rig/mayor/rig/.beads" )
427+ cmd := bdc .Build ()
428+ envMap := parseEnv (cmd .Env )
429+
430+ if envMap ["BEADS_DIR" ] != "/town/rig/mayor/rig/.beads" {
431+ t .Errorf ("BEADS_DIR = %q, want %q (should override inherited)" , envMap ["BEADS_DIR" ], "/town/rig/mayor/rig/.beads" )
432+ }
433+
434+ // Verify exactly one BEADS_DIR entry (deduplication)
435+ count := 0
436+ for _ , e := range cmd .Env {
437+ if strings .HasPrefix (e , "BEADS_DIR=" ) {
438+ count ++
439+ }
440+ }
441+ if count != 1 {
442+ t .Errorf ("found %d BEADS_DIR entries, want 1 (dedup must remove old)" , count )
443+ }
444+ }
445+
446+ func TestBdCmd_EmptyBeadsDir_Skipped (t * testing.T ) {
447+ // Empty WithBeadsDir should not add BEADS_DIR to env
448+ bdc := BdCmd ("show" , "id" ).
449+ WithBeadsDir ("" )
450+ bdc .env = filterEnv (bdc .env , "BEADS_DIR" )
451+ cmd := bdc .Build ()
452+
453+ for _ , e := range cmd .Env {
454+ if strings .HasPrefix (e , "BEADS_DIR=" ) {
455+ t .Errorf ("BEADS_DIR should not be added when empty, found: %s" , e )
456+ }
457+ }
458+ }
459+
460+ func TestBdCmd_WithBeadsDir_Chaining (t * testing.T ) {
461+ // WithBeadsDir should return receiver for chaining
462+ bdc := BdCmd ("test" )
463+ if bdc .WithBeadsDir ("/test" ) != bdc {
464+ t .Error ("WithBeadsDir() should return receiver for chaining" )
465+ }
466+ }
467+
403468// filterEnv returns env with all entries matching the given key prefix removed.
404469func filterEnv (env []string , key string ) []string {
405470 prefix := key + "="
0 commit comments