diff --git a/cmd/bd/fs_adapters.go b/cmd/bd/fs_adapters.go index 1f64c054a..b4a923dce 100644 --- a/cmd/bd/fs_adapters.go +++ b/cmd/bd/fs_adapters.go @@ -34,3 +34,15 @@ func newFileSystemAdapters() domain.BeadsDirFSAdapters { SetYAMLConfig: config.SetYamlConfig, } } + +// newInitFileSystemAdapters keeps the selected Git project separate from storage paths. +func newInitFileSystemAdapters(workDir string) domain.BeadsDirFSAdapters { + adapters := newFileSystemAdapters() + adapters.SetupForkExclude = func(verbose bool) error { + return setupForkExcludeAt(workDir, verbose) + } + adapters.SetupStealthMode = func(verbose bool) error { + return setupStealthModeAt(workDir, verbose) + } + return adapters +} diff --git a/cmd/bd/init.go b/cmd/bd/init.go index 8c08c9edd..3b6b78865 100644 --- a/cmd/bd/init.go +++ b/cmd/bd/init.go @@ -1016,7 +1016,7 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1): // reinit has passed its held-gate confirmation. Remote safety above // still evaluates the flag before this point. if stealth { - if err := setupStealthMode(!quiet); err != nil { + if err := setupStealthModeAt(cwd, !quiet); err != nil { return fmt.Errorf("setting up stealth mode: %v", err) } @@ -1996,15 +1996,15 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1): setupExclude, _ := cmd.Flags().GetBool("setup-exclude") if setupExclude { // Manual flag - always configure - if err := setupForkExclude(!quiet); err != nil { + if err := setupForkExcludeAt(cwd, !quiet); err != nil { fmt.Fprintf(os.Stderr, "Warning: failed to configure git exclude: %v\n", err) } - } else if !stealth && isGitRepo() { + } else if !stealth && isInitRoleGitRepo(ctx) { // Auto-detect fork and prompt (skip if stealth - it handles exclude already) if isFork, upstreamURL := detectForkSetup(); isFork { if nonInteractive { // In non-interactive mode, auto-configure fork exclude - if err := setupForkExclude(!quiet); err != nil { + if err := setupForkExcludeAt(cwd, !quiet); err != nil { fmt.Fprintf(os.Stderr, "Warning: failed to configure git exclude: %v\n", err) } } else { @@ -2016,7 +2016,7 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1): } } if shouldExclude { - if err := setupForkExclude(!quiet); err != nil { + if err := setupForkExcludeAt(cwd, !quiet); err != nil { fmt.Fprintf(os.Stderr, "Warning: failed to configure git exclude: %v\n", err) } } diff --git a/cmd/bd/init_embedded_test.go b/cmd/bd/init_embedded_test.go index 4f1a855d2..b2aa498a4 100644 --- a/cmd/bd/init_embedded_test.go +++ b/cmd/bd/init_embedded_test.go @@ -1447,86 +1447,6 @@ func TestInitGateBusyClassifiedAsLockContention(t *testing.T) { } } -func TestEmbeddedInitGitBootstrapRouting(t *testing.T) { - if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" { - t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded dolt init tests") - } - bd := buildEmbeddedBD(t) - for _, name := range []string{"fresh", "decoy", "invalid", "existing_invalid", "explicit_storage", "quiet"} { - t.Run(name, func(t *testing.T) { - existing, decoy, home := newInitRoleFixture(t) - target := t.TempDir() - if name == "existing_invalid" { - target = existing - } - global := filepath.Join(home, ".gitconfig") - initRoleFixtureGit(t, existing, "config", "--file", global, "user.name", "Bootstrap Fixture") - initRoleFixtureGit(t, existing, "config", "--file", global, "user.email", "bootstrap@example.invalid") - missingGit := filepath.Join(home, "missing git dir") - if name == "invalid" || name == "existing_invalid" { - t.Setenv("GIT_DIR", missingGit) - } else if name == "decoy" || name == "explicit_storage" { - t.Setenv("GIT_DIR", filepath.Join(decoy, ".git")) - t.Setenv("GIT_WORK_TREE", decoy) - } - preserveInitRoleInputs(t, global, filepath.Join(decoy, ".git", "config"), filepath.Join(decoy, ".git", "HEAD")) - beadsDir := filepath.Join(target, ".beads") - args := []string{"init", "--prefix", "bootstrapfixture", "--non-interactive", "--skip-hooks", "--skip-agents", "--role", "maintainer"} - if name == "quiet" { - args = append(args, "--quiet") - } - cmd := exec.Command(bd, args...) - cmd.Dir = target - env := bdEnv(home) - for _, key := range []string{"BEADS_DIR", "BEADS_DB", "BD_DB", "BD_DOLT_HOST", "BD_DOLT_PORT"} { - env = envWithout(env, key) - } - if name == "explicit_storage" { - beadsDir = filepath.Join(home, "separate storage", ".beads") - if err := os.MkdirAll(filepath.Dir(beadsDir), 0750); err != nil { - t.Fatal(err) - } - env = append(env, "BEADS_DIR="+beadsDir) - } - cmd.Env = append(env, "DOLT_ROOT_PATH="+home, "BD_DOLT_MODE=embedded", "BD_EVENTS_JOURNAL=false") - out, err := cmd.CombinedOutput() - if err != nil { - t.Fatalf("embedded bootstrap failed: %v\n%s", err, out) - } - cfg, err := configfile.Load(beadsDir) - if err != nil || cfg == nil || cfg.DoltMode != configfile.DoltModeEmbedded { - t.Fatalf("embedded metadata missing: %+v (%v)", cfg, err) - } - if info, err := os.Stat(filepath.Join(beadsDir, "embeddeddolt", "bootstrapfixture", ".dolt")); err != nil || !info.IsDir() { - t.Fatalf("embedded database missing: %v", err) - } - gitDir := filepath.Join(target, ".git") - if name == "explicit_storage" { - if _, err := os.Stat(gitDir); !os.IsNotExist(err) { - t.Fatalf("explicit storage must skip repository creation: %v", err) - } - } else { - actualGit := initRoleFixtureGit(t, target, "rev-parse", "--absolute-git-dir") - wantInfo, err := os.Stat(gitDir) - if err != nil { - t.Fatal(err) - } - actualInfo, err := os.Stat(actualGit) - if err != nil || !os.SameFile(wantInfo, actualInfo) { - t.Fatalf("selected Git directory = %q (%v)", actualGit, err) - } - } - wantBanner := name != "quiet" && name != "existing_invalid" && name != "explicit_storage" - if got := strings.Count(string(out), "Initialized git repository"); (wantBanner && got != 1) || (!wantBanner && got != 0) { - t.Errorf("initialization banner count = %d, want visible=%v: %s", got, wantBanner, out) - } - if _, err := os.Stat(missingGit); !os.IsNotExist(err) { - t.Errorf("init created the inherited invalid Git directory: %v", err) - } - }) - } -} - func TestEmbeddedInitRoleRouting(t *testing.T) { if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" { t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded dolt init tests") @@ -1606,6 +1526,90 @@ func TestEmbeddedInitRoleRouting(t *testing.T) { } } +func TestEmbeddedInitSelectedExcludeRouting(t *testing.T) { + if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" { + t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded dolt init tests") + } + bd := buildEmbeddedBD(t) + for _, name := range []string{"stealth_decoy", "stealth_invalid", "fork_decoy", "fork_invalid", "quiet_stealth", "quiet_fork", "fork_auto_invalid"} { + t.Run(name, func(t *testing.T) { + target, decoy, home := newInitRoleFixture(t) + global := filepath.Join(home, ".gitconfig") + initRoleFixtureGit(t, target, "config", "--file", global, "user.name", "Exclude Fixture") + initRoleFixtureGit(t, target, "config", "--file", global, "user.email", "exclude@example.invalid") + exclude := filepath.Join(target, ".git", "info", "exclude") + const existing = "# owned project exclude\nkeep-me/\n" + if err := os.WriteFile(exclude, []byte(existing), 0600); err != nil { + t.Fatal(err) + } + preserveInitRoleInputs(t, filepath.Join(decoy, ".git", "config"), filepath.Join(decoy, ".git", "info", "exclude"), global) + missing := filepath.Join(home, "missing-inherited.git") + routing := filepath.Join(decoy, ".git") + if strings.HasSuffix(name, "invalid") { + routing = missing + } + t.Setenv("GIT_DIR", routing) + t.Setenv("GIT_WORK_TREE", decoy) + storage := filepath.Join(home, "separate storage", ".beads") + if err := os.MkdirAll(filepath.Dir(storage), 0750); err != nil { + t.Fatal(err) + } + args := []string{"init", "--prefix", "excludefixture", "--non-interactive", "--skip-hooks", "--skip-agents", "--role", "maintainer"} + stealth, quiet := strings.Contains(name, "stealth"), strings.HasPrefix(name, "quiet") + want := "**/RECOVERY*.md" + banner := "Added to .git/info/exclude:" + if stealth { + args = append(args, "--stealth") + want, banner = ".claude/settings.local.json", "Stealth mode configured successfully!" + } else if strings.Contains(name, "auto") { + // Auto-detect arm: without --setup-exclude the exclude write is + // reached only through the fork auto-detect gate, so this row + // covers that gate's own repository probe rather than the + // already-hardened writer. An upstream remote makes the scrubbed + // detectForkSetup report a fork; --role=maintainer keeps + // autoConfigureForkContributor an early return, so the gate is + // the only path that can add the pattern. + initRoleFixtureGit(t, target, "remote", "add", "upstream", filepath.Join(home, "upstream.git")) + if isGitRepo() { + t.Fatal("invalid routing must refuse the inherited repository probe") + } + } else { + args = append(args, "--setup-exclude") + } + if quiet { + args = append(args, "--quiet") + } + env := bdEnv(home) + for _, key := range []string{"BEADS_DIR", "BEADS_DB", "BD_DB", "BD_DOLT_HOST", "BD_DOLT_PORT"} { + env = envWithout(env, key) + } + cmd := exec.Command(bd, args...) + cmd.Dir, cmd.Env = target, append(env, "BEADS_DIR="+storage, "DOLT_ROOT_PATH="+home, "BD_DOLT_MODE=embedded", "BD_EVENTS_JOURNAL=false") + out, err := cmd.CombinedOutput() + if err != nil { + t.Fatalf("embedded exclude init failed: %v\n%s", err, out) + } + data, err := os.ReadFile(exclude) + if err != nil || !strings.HasPrefix(string(data), existing) || !containsExactPattern(string(data), want) || !containsExactPattern(string(data), ".beads/") { + t.Fatalf("selected exclude = %q (%v); want original lines and %q", data, err, want) + } + if strings.Contains(string(out), banner) == quiet { + t.Errorf("exclude banner does not match quiet=%v: %s", quiet, out) + } + cfg, err := configfile.Load(storage) + if err != nil || cfg == nil || cfg.DoltMode != configfile.DoltModeEmbedded { + t.Fatalf("selected storage metadata = %+v, %v", cfg, err) + } + if info, err := os.Stat(filepath.Join(storage, "embeddeddolt", "excludefixture", ".dolt")); err != nil || !info.IsDir() { + t.Fatalf("embedded database missing from selected storage: %v", err) + } + if _, err := os.Stat(missing); !os.IsNotExist(err) { + t.Errorf("inherited Git directory was created: %v", err) + } + }) + } +} + func TestEmbeddedInitArtifactRouting(t *testing.T) { if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" { t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded dolt init tests") @@ -1648,3 +1652,83 @@ func TestEmbeddedInitArtifactRouting(t *testing.T) { t.Errorf("embedded init did not commit target metadata: %v: %s", err, got) } } + +func TestEmbeddedInitGitBootstrapRouting(t *testing.T) { + if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" { + t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded dolt init tests") + } + bd := buildEmbeddedBD(t) + for _, name := range []string{"fresh", "decoy", "invalid", "existing_invalid", "explicit_storage", "quiet"} { + t.Run(name, func(t *testing.T) { + existing, decoy, home := newInitRoleFixture(t) + target := t.TempDir() + if name == "existing_invalid" { + target = existing + } + global := filepath.Join(home, ".gitconfig") + initRoleFixtureGit(t, existing, "config", "--file", global, "user.name", "Bootstrap Fixture") + initRoleFixtureGit(t, existing, "config", "--file", global, "user.email", "bootstrap@example.invalid") + missingGit := filepath.Join(home, "missing git dir") + if name == "invalid" || name == "existing_invalid" { + t.Setenv("GIT_DIR", missingGit) + } else if name == "decoy" || name == "explicit_storage" { + t.Setenv("GIT_DIR", filepath.Join(decoy, ".git")) + t.Setenv("GIT_WORK_TREE", decoy) + } + preserveInitRoleInputs(t, global, filepath.Join(decoy, ".git", "config"), filepath.Join(decoy, ".git", "HEAD")) + beadsDir := filepath.Join(target, ".beads") + args := []string{"init", "--prefix", "bootstrapfixture", "--non-interactive", "--skip-hooks", "--skip-agents", "--role", "maintainer"} + if name == "quiet" { + args = append(args, "--quiet") + } + cmd := exec.Command(bd, args...) + cmd.Dir = target + env := bdEnv(home) + for _, key := range []string{"BEADS_DIR", "BEADS_DB", "BD_DB", "BD_DOLT_HOST", "BD_DOLT_PORT"} { + env = envWithout(env, key) + } + if name == "explicit_storage" { + beadsDir = filepath.Join(home, "separate storage", ".beads") + if err := os.MkdirAll(filepath.Dir(beadsDir), 0750); err != nil { + t.Fatal(err) + } + env = append(env, "BEADS_DIR="+beadsDir) + } + cmd.Env = append(env, "DOLT_ROOT_PATH="+home, "BD_DOLT_MODE=embedded", "BD_EVENTS_JOURNAL=false") + out, err := cmd.CombinedOutput() + if err != nil { + t.Fatalf("embedded bootstrap failed: %v\n%s", err, out) + } + cfg, err := configfile.Load(beadsDir) + if err != nil || cfg == nil || cfg.DoltMode != configfile.DoltModeEmbedded { + t.Fatalf("embedded metadata missing: %+v (%v)", cfg, err) + } + if info, err := os.Stat(filepath.Join(beadsDir, "embeddeddolt", "bootstrapfixture", ".dolt")); err != nil || !info.IsDir() { + t.Fatalf("embedded database missing: %v", err) + } + gitDir := filepath.Join(target, ".git") + if name == "explicit_storage" { + if _, err := os.Stat(gitDir); !os.IsNotExist(err) { + t.Fatalf("explicit storage must skip repository creation: %v", err) + } + } else { + actualGit := initRoleFixtureGit(t, target, "rev-parse", "--absolute-git-dir") + wantInfo, err := os.Stat(gitDir) + if err != nil { + t.Fatal(err) + } + actualInfo, err := os.Stat(actualGit) + if err != nil || !os.SameFile(wantInfo, actualInfo) { + t.Fatalf("selected Git directory = %q (%v)", actualGit, err) + } + } + wantBanner := name != "quiet" && name != "existing_invalid" && name != "explicit_storage" + if got := strings.Count(string(out), "Initialized git repository"); (wantBanner && got != 1) || (!wantBanner && got != 0) { + t.Errorf("initialization banner count = %d, want visible=%v: %s", got, wantBanner, out) + } + if _, err := os.Stat(missingGit); !os.IsNotExist(err) { + t.Errorf("init created the inherited invalid Git directory: %v", err) + } + }) + } +} diff --git a/cmd/bd/init_proxied_server.go b/cmd/bd/init_proxied_server.go index 73a5dba7c..d0cf6674e 100644 --- a/cmd/bd/init_proxied_server.go +++ b/cmd/bd/init_proxied_server.go @@ -5,6 +5,7 @@ import ( "encoding/json" "fmt" "os" + "os/exec" "path/filepath" "strings" "time" @@ -14,7 +15,9 @@ import ( "github.com/steveyegge/beads/internal/beads" "github.com/steveyegge/beads/internal/config" "github.com/steveyegge/beads/internal/configfile" + "github.com/steveyegge/beads/internal/gitenv" "github.com/steveyegge/beads/internal/storage/domain" + domaingit "github.com/steveyegge/beads/internal/storage/domain/git" "github.com/steveyegge/beads/internal/storage/fs" "github.com/steveyegge/beads/internal/storage/git" "github.com/steveyegge/beads/internal/storage/uow" @@ -95,7 +98,7 @@ func runInitProxiedServer(cmd *cobra.Command, ctx context.Context, in initProxie return fmt.Errorf("failed to get current directory: %v", err) } - fsProvider := fs.NewFileSystemProvider(cwd, newBeadsDirTemplates(), newFileSystemAdapters()) + fsProvider := fs.NewFileSystemProvider(cwd, newBeadsDirTemplates(), newInitFileSystemAdapters(cwd)) fsUseCase := fsProvider.BeadsDirFSUseCase() gitUC := git.NewGitProvider(cwd).GitUseCase() @@ -283,6 +286,7 @@ func runInitProxiedServer(cmd *cobra.Command, ctx context.Context, in initProxie } return runInitProxiedServerTail(cmd, ctx, in, runInitTailContext{ + workDir: cwd, beadsDir: beadsDir, prefix: adoptedPrefix, dbName: dbName, @@ -507,6 +511,7 @@ func buildProxiedServerClientInfo(rootPath, configPath, logPath string, port int } type runInitTailContext struct { + workDir string beadsDir string prefix string dbName string @@ -516,17 +521,34 @@ type runInitTailContext struct { gitUC domain.GitUseCase } -func runInitProxiedServerTail(cmd *cobra.Command, ctx context.Context, in initProxiedServerInput, t runInitTailContext) error { - isRepo := t.gitUC.IsGitRepo(ctx) +func (t runInitTailContext) isRoleGitRepo(ctx context.Context, fallback bool) bool { + // Isolated tail contexts without a selected path retain their supplied use case. + if t.workDir == "" { + return fallback + } + // Dropping discovery ceilings can select a containing parent repository, + // matching the role adapter's existing scrubbed reads and writes. + probe := exec.CommandContext(ctx, "git", "rev-parse", "--git-dir") + probe.Dir, probe.Env = t.workDir, gitenv.ScrubRouting(os.Environ()) + return probe.Run() == nil +} - if isRepo { +func runInitProxiedServerTail(cmd *cobra.Command, ctx context.Context, in initProxiedServerInput, t runInitTailContext) error { + gitUC := t.gitUC + if t.workDir != "" { + // Only the selected tail uses this scope; earlier bootstrap keeps its provider. + gitUC = domain.NewGitUseCase(t.workDir, domaingit.NewInitGitRepository(t.workDir)) + } + isRepo := gitUC.IsGitRepo(ctx) + + if t.isRoleGitRepo(ctx, isRepo) { role := in.roleFlag if role == "" { role = "maintainer" } - _, hasRole, _ := t.gitUC.BeadsRole(ctx) + _, hasRole, _ := gitUC.BeadsRole(ctx) if !hasRole || in.roleFlag != "" { - if err := t.gitUC.SetBeadsRole(ctx, role); err != nil && !in.quiet { + if err := gitUC.SetBeadsRole(ctx, role); err != nil && !in.quiet { fmt.Fprintf(os.Stderr, "Warning: failed to set beads.role: %v\n", err) } } @@ -538,7 +560,7 @@ func runInitProxiedServerTail(cmd *cobra.Command, ctx context.Context, in initPr fmt.Fprintf(os.Stderr, "Warning: failed to configure git exclude: %v\n", err) } } else if !in.stealth && isRepo { - if isFork, upstreamURL, _ := t.gitUC.DetectFork(ctx); isFork { + if isFork, upstreamURL, _ := gitUC.DetectFork(ctx); isFork { if in.nonInteractive { if err := t.fsUseCase.SetupForkExclude(ctx, !in.quiet); err != nil { fmt.Fprintf(os.Stderr, "Warning: failed to configure git exclude: %v\n", err) @@ -562,8 +584,8 @@ func runInitProxiedServerTail(cmd *cobra.Command, ctx context.Context, in initPr if hooksInstalled() && !in.quiet { fmt.Printf(" Updating hooks to version %s...\n", Version) } - isJJ := t.gitUC.IsJujutsuRepo(ctx) - isColocated := t.gitUC.IsColocatedJJGit(ctx) + isJJ := gitUC.IsJujutsuRepo(ctx) + isColocated := gitUC.IsColocatedJJGit(ctx) switch { case isJJ && !isColocated: if !in.quiet { @@ -606,7 +628,7 @@ func runInitProxiedServerTail(cmd *cobra.Command, ctx context.Context, in initPr if resolvedAgentsFile == "" { resolvedAgentsFile = config.SafeAgentsFile() } - isBare := t.gitUC.IsBareGitRepo(ctx) + isBare := gitUC.IsBareGitRepo(ctx) if isBare { if !in.quiet { fmt.Printf(" Skipping %s generation in bare repository\n", resolvedAgentsFile) @@ -627,7 +649,7 @@ func runInitProxiedServerTail(cmd *cobra.Command, ctx context.Context, in initPr } if !in.stealth && isRepo && t.useLocalBeads { - commitResult, err := t.gitUC.CommitInitArtifacts(ctx, domain.CommitInitArtifactsParams{ + commitResult, err := gitUC.CommitInitArtifacts(ctx, domain.CommitInitArtifactsParams{ BeadsDir: ".beads/", OptionalPaths: []string{ config.SafeAgentsFile(), @@ -648,7 +670,7 @@ func runInitProxiedServerTail(cmd *cobra.Command, ctx context.Context, in initPr } if isRepo && !in.quiet { - if t.gitUC.HasAnyRemotes(ctx) && !t.gitUC.HasUpstream(ctx) { + if gitUC.HasAnyRemotes(ctx) && !gitUC.HasUpstream(ctx) { fmt.Fprintf(os.Stderr, "\n%s Git upstream not configured\n", ui.RenderWarn("⚠")) fmt.Fprintf(os.Stderr, " For sync workflows, set your upstream with:\n") fmt.Fprintf(os.Stderr, " %s\n\n", ui.RenderAccent("git remote add upstream ")) diff --git a/cmd/bd/init_proxied_server_test.go b/cmd/bd/init_proxied_server_test.go index 909aadf8d..1c4c6060f 100644 --- a/cmd/bd/init_proxied_server_test.go +++ b/cmd/bd/init_proxied_server_test.go @@ -1,12 +1,24 @@ package main import ( + "context" "encoding/json" + "os" + "os/exec" + "path/filepath" + "runtime" + "slices" + "strings" "testing" "time" + "github.com/spf13/cobra" "github.com/steveyegge/beads/internal/configfile" + "github.com/steveyegge/beads/internal/gitenv" "github.com/steveyegge/beads/internal/storage/dbproxy/proxy" + "github.com/steveyegge/beads/internal/storage/domain" + storagefs "github.com/steveyegge/beads/internal/storage/fs" + storagegit "github.com/steveyegge/beads/internal/storage/git" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -226,3 +238,337 @@ func TestIsTeamServerManaged_RequiresProxiedServerMode(t *testing.T) { cfg.DoltMode = configfile.DoltModeProxiedServer assert.True(t, cfg.IsTeamServerManaged()) } + +func TestProxiedInitTailRoleIgnoresInheritedGitRouting(t *testing.T) { + for _, entry := range os.Environ() { + key := gitenv.EntryKey(entry) + if gitenv.IsRoutingKeyForOS(key, runtime.GOOS) { + t.Setenv(key, "") + require.NoError(t, os.Unsetenv(key)) + } + } + home := t.TempDir() + for _, key := range []string{"HOME", "USERPROFILE", "XDG_CONFIG_HOME"} { + t.Setenv(key, home) + } + globalPath := filepath.Join(home, ".gitconfig") + require.NoError(t, os.WriteFile(globalPath, nil, 0600)) + runGit := func(t *testing.T, dir string, args ...string) string { + t.Helper() + cmd := exec.Command("git", args...) + cmd.Dir, cmd.Env = dir, gitenv.ScrubRouting(os.Environ()) + out, err := cmd.CombinedOutput() + require.NoError(t, err, "fixture git %v: %s", args, out) + return strings.TrimSpace(string(out)) + } + for _, tc := range []struct { + name, initial, flag, want string + }{ + {"explicit", "maintainer", "contributor", "contributor"}, + {"default", "", "", "maintainer"}, + {"retained", "contributor", "", "contributor"}, + } { + for _, poison := range []string{"repository", "inline_config"} { + t.Run(tc.name+"/"+poison, func(t *testing.T) { + target, decoy := t.TempDir(), t.TempDir() + for _, dir := range []string{target, decoy} { + runGit(t, dir, "init", "--quiet") + runGit(t, dir, "config", "--local", "core.hooksPath", ".git/hooks") + } + if tc.initial != "" { + runGit(t, target, "config", "--local", "beads.role", tc.initial) + } + runGit(t, decoy, "config", "--local", "beads.role", "decoy-role") + if poison == "repository" { + t.Setenv("GIT_DIR", filepath.Join(decoy, ".git")) + t.Setenv("GIT_WORK_TREE", decoy) + } else { + t.Setenv("GIT_CONFIG_COUNT", "1") + t.Setenv("GIT_CONFIG_KEY_0", "beads.role") + t.Setenv("GIT_CONFIG_VALUE_0", "injected-role") + } + env := os.Environ() + before, err := os.ReadFile(filepath.Join(decoy, ".git", "config")) + require.NoError(t, err) + gitUC := storagegit.NewGitProvider(target).GitUseCase() + require.True(t, gitUC.IsGitRepo(t.Context()), "valid inherited repository must reach role branch") + cmd := &cobra.Command{} + cmd.Flags().Bool("setup-exclude", false, "") + // Existing flags exclude all filesystem integrations; nil fsUseCase must stay unused. + in := initProxiedServerInput{roleFlag: tc.flag, quiet: true, stealth: true, skipHooks: true, skipAgents: true} + require.NoError(t, runInitProxiedServerTail(cmd, t.Context(), in, runInitTailContext{gitUC: gitUC})) + require.Equal(t, tc.want, runGit(t, target, "config", "--local", "--get", "beads.role")) + after, err := os.ReadFile(filepath.Join(decoy, ".git", "config")) + require.NoError(t, err) + require.Equal(t, string(before), string(after), "proxied tail changed decoy") + globalAfter, err := os.ReadFile(globalPath) + require.NoError(t, err) + require.Empty(t, globalAfter) + require.True(t, slices.Equal(env, os.Environ()), "proxied tail changed inherited environment") + }) + } + } +} + +type proxiedRoleProbeUseCase struct { + domain.GitUseCase + roleReads int +} + +func (u *proxiedRoleProbeUseCase) BeadsRole(ctx context.Context) (string, bool, error) { + u.roleReads++ + return u.GitUseCase.BeadsRole(ctx) +} + +func TestProxiedInitTailRoleProbeUsesSelectedDirectory(t *testing.T) { + for _, entry := range os.Environ() { + key := gitenv.EntryKey(entry) + if gitenv.IsRoutingKeyForOS(key, runtime.GOOS) { + t.Setenv(key, "") + require.NoError(t, os.Unsetenv(key)) + } + } + t.Setenv("GIT_CONFIG_NOSYSTEM", "1") + runGit := func(t *testing.T, dir string, args ...string) string { + t.Helper() + cmd := exec.Command("git", args...) + cmd.Dir, cmd.Env = dir, gitenv.ScrubRouting(os.Environ()) + out, err := cmd.CombinedOutput() + require.NoError(t, err, "fixture git %v: %s", args, out) + return strings.TrimSpace(string(out)) + } + for _, tc := range []struct { + name, kind, initial, flag, want string + }{ + {"explicit", "ordinary", "maintainer", "contributor", "contributor"}, + {"default", "ordinary", "", "", "maintainer"}, + {"retained", "ordinary", "contributor", "", "contributor"}, + {"bare_explicit", "bare", "maintainer", "contributor", "contributor"}, + {"bare_default", "bare", "", "", "maintainer"}, + {"bare_retained", "bare", "contributor", "", "contributor"}, + {"nonrepo_with_decoy_and_global_role", "nonrepo", "", "", ""}, + } { + t.Run(tc.name, func(t *testing.T) { + home, target, decoy := t.TempDir(), t.TempDir(), t.TempDir() + for _, key := range []string{"HOME", "USERPROFILE", "XDG_CONFIG_HOME"} { + t.Setenv(key, home) + } + globalData := "" + if tc.kind == "nonrepo" { + globalData = "[beads]\n\trole = global-role\n" + } + globalPath := filepath.Join(home, ".gitconfig") + require.NoError(t, os.WriteFile(globalPath, []byte(globalData), 0600)) + runGit(t, decoy, "init", "--quiet") + runGit(t, decoy, "config", "--local", "core.hooksPath", ".git/hooks") + runGit(t, decoy, "config", "--local", "beads.role", "decoy-role") + if tc.kind == "bare" { + runGit(t, target, "init", "--bare", "--quiet") + runGit(t, target, "config", "--local", "core.hooksPath", filepath.Join(target, "hooks")) + } else if tc.kind == "ordinary" { + runGit(t, target, "init", "--quiet") + runGit(t, target, "config", "--local", "core.hooksPath", ".git/hooks") + } + if tc.initial != "" { + runGit(t, target, "config", "--local", "beads.role", tc.initial) + } + probe := exec.Command("git", "rev-parse", "--git-dir") + probe.Dir, probe.Env = target, gitenv.ScrubRouting(os.Environ()) + require.Equal(t, tc.kind != "nonrepo", probe.Run() == nil, "owned target repository precondition") + if tc.kind == "nonrepo" { + t.Setenv("GIT_DIR", filepath.Join(decoy, ".git")) + } else { + invalid := filepath.Join(t.TempDir(), "invalid-git-dir") + require.NoError(t, os.WriteFile(invalid, []byte("not a Git directory\n"), 0600)) + t.Setenv("GIT_DIR", invalid) + } + t.Setenv("GIT_WORK_TREE", decoy) + t.Chdir(decoy) + base := storagegit.NewGitProvider(target).GitUseCase() + require.Equal(t, tc.kind == "nonrepo", base.IsGitRepo(t.Context()), "inherited probe precondition") + if tc.kind == "nonrepo" { + role, found, err := base.BeadsRole(t.Context()) + require.NoError(t, err) + require.True(t, found) + require.Equal(t, "global-role", role, "global config alone must not manufacture a repository") + } + gitUC := &proxiedRoleProbeUseCase{GitUseCase: base} + before, err := os.ReadFile(filepath.Join(decoy, ".git", "config")) + require.NoError(t, err) + env := os.Environ() + cmd := &cobra.Command{} + cmd.Flags().Bool("setup-exclude", false, "") + in := initProxiedServerInput{roleFlag: tc.flag, quiet: true, stealth: true, skipHooks: true, skipAgents: true} + require.NoError(t, runInitProxiedServerTail(cmd, t.Context(), in, runInitTailContext{workDir: target, gitUC: gitUC})) + require.Zero(t, gitUC.roleReads, "selected tail must bypass the inherited role provider") + if tc.kind == "nonrepo" { + entries, err := os.ReadDir(target) + require.NoError(t, err) + require.Empty(t, entries) + } else { + require.Equal(t, tc.want, runGit(t, target, "config", "--local", "--get", "beads.role")) + } + after, err := os.ReadFile(filepath.Join(decoy, ".git", "config")) + require.NoError(t, err) + require.Equal(t, string(before), string(after), "tail changed decoy config") + globalAfter, err := os.ReadFile(globalPath) + require.NoError(t, err) + require.Equal(t, globalData, string(globalAfter)) + require.True(t, slices.Equal(env, os.Environ()), "tail changed inherited environment") + }) + } +} + +type initTailForkObservation struct { + domain.BeadsDirFSUseCase + calls int +} + +func (f *initTailForkObservation) SetupForkExclude(context.Context, bool) error { + f.calls++ + return nil // Observe fork selection; the exclude writer has separate coverage. +} + +func TestProxiedInitTailGitUsesSelectedDirectory(t *testing.T) { + for _, entry := range os.Environ() { + key := gitenv.EntryKey(entry) + if gitenv.IsRoutingKeyForOS(key, runtime.GOOS) { + t.Setenv(key, "") + require.NoError(t, os.Unsetenv(key)) + } + } + home := t.TempDir() + for _, key := range []string{"HOME", "USERPROFILE", "XDG_CONFIG_HOME"} { + t.Setenv(key, home) + } + runGit := func(dir string, args ...string) string { + t.Helper() + cmd := exec.Command("git", args...) + cmd.Dir, cmd.Env = dir, gitenv.ScrubRouting(os.Environ()) + out, err := cmd.CombinedOutput() + require.NoError(t, err, "fixture git %v: %s", args, out) + return strings.TrimSpace(string(out)) + } + read := func(path string) []byte { + t.Helper() + data, err := os.ReadFile(path) + require.NoError(t, err) + return data + } + for _, name := range []string{"decoy", "invalid", "nonrepo"} { + t.Run(name, func(t *testing.T) { + target, decoy := t.TempDir(), t.TempDir() + for _, dir := range []string{target, decoy} { + if dir != target || name != "nonrepo" { + runGit(dir, "init", "--quiet") + for key, value := range map[string]string{"user.name": "Fixture", "user.email": "fixture@example.test", "commit.gpgSign": "false", "core.hooksPath": ".git/hooks"} { + runGit(dir, "config", "--local", key, value) + } + require.NoError(t, os.WriteFile(filepath.Join(dir, "seed"), []byte("seed\n"), 0600)) + runGit(dir, "add", "seed") + runGit(dir, "-c", "core.hooksPath=", "commit", "-m", "seed") + } + require.NoError(t, os.Mkdir(filepath.Join(dir, ".beads"), 0755)) + require.NoError(t, os.WriteFile(filepath.Join(dir, ".beads", "artifact"), []byte(dir), 0600)) + require.NoError(t, os.WriteFile(filepath.Join(dir, "CLAUDE.md"), []byte("optional\n"), 0600)) + } + runGit(decoy, "remote", "add", "upstream", "https://example.test/decoy.git") + runGit(decoy, "config", "beads.role", "decoy-role") + foreignIndex := filepath.Join(t.TempDir(), "foreign-index") + require.NoError(t, os.WriteFile(foreignIndex, read(filepath.Join(decoy, ".git", "index")), 0600)) + preserved := map[string][]byte{} + for _, path := range []string{foreignIndex, filepath.Join(decoy, ".git", "index"), filepath.Join(decoy, ".git", "config")} { + preserved[path] = read(path) + } + decoyHead := runGit(decoy, "rev-parse", "HEAD") + gitDir := filepath.Join(decoy, ".git") + if name == "invalid" { + gitDir = filepath.Join(t.TempDir(), "missing-git-dir") + } + t.Setenv("GIT_DIR", gitDir) + t.Setenv("GIT_WORK_TREE", decoy) + t.Setenv("GIT_INDEX_FILE", foreignIndex) + t.Chdir(decoy) + env := os.Environ() + cmd := &cobra.Command{} + cmd.Flags().Bool("setup-exclude", false, "") + fs := &initTailForkObservation{} + in := initProxiedServerInput{skipHooks: true, skipAgents: true, nonInteractive: true} + stderr := captureStderr(t, func() { + require.NoError(t, runInitProxiedServerTail(cmd, t.Context(), in, runInitTailContext{workDir: target, beadsDir: filepath.Join(target, ".beads"), useLocalBeads: true, fsUseCase: fs, gitUC: storagegit.NewGitProvider(target).GitUseCase()})) + }) + require.Zero(t, fs.calls, "decoy fork selected") + require.NotContains(t, stderr, "Git upstream not configured", "decoy remotes selected") + if name == "nonrepo" { + _, err := os.Stat(filepath.Join(target, ".git")) + require.True(t, os.IsNotExist(err), "tail manufactured a repository") + } else { + require.Equal(t, "2", runGit(target, "rev-list", "--count", "HEAD"), "target artifacts were not committed") + require.Equal(t, target, runGit(target, "show", "HEAD:.beads/artifact")) + require.Equal(t, "optional", runGit(target, "show", "HEAD:CLAUDE.md")) + require.Empty(t, runGit(target, "diff", "--cached", "--name-only")) + } + require.Equal(t, decoyHead, runGit(decoy, "rev-parse", "HEAD"), "decoy HEAD changed") + for path, before := range preserved { + require.Equal(t, before, read(path), "tail changed %s", path) + } + require.True(t, slices.Equal(env, os.Environ()), "tail changed inherited environment") + }) + } +} + +func TestProxiedInitExcludeUsesSelectedDirectory(t *testing.T) { + for _, name := range []string{"stealth", "setup_exclude", "target_fork", "decoy_fork"} { + t.Run(name, func(t *testing.T) { + worktree, decoy, commonExclude, privateExclude := newInitExcludeRepos(t) + if name == "target_fork" { + initExcludeGit(t, worktree, "remote", "add", "upstream", "https://example.test/target.git") + } else if name == "decoy_fork" { + initExcludeGit(t, decoy, "remote", "add", "upstream", "https://example.test/decoy.git") + } + storage := t.TempDir() + t.Setenv("BEADS_DIR", storage) + t.Setenv("GIT_DIR", filepath.Join(decoy, ".git")) + t.Setenv("GIT_WORK_TREE", decoy) + decoyConfig, err := os.ReadFile(filepath.Join(decoy, ".git", "config")) + require.NoError(t, err) + env := os.Environ() + // Construct the same selected provider/adapter used before the real init tail. + fsUseCase := storagefs.NewFileSystemProvider(worktree, newBeadsDirTemplates(), newInitFileSystemAdapters(worktree)).BeadsDirFSUseCase() + cmd := &cobra.Command{} + cmd.Flags().Bool("setup-exclude", name == "setup_exclude", "") + in := initProxiedServerInput{stealth: name == "stealth", quiet: true, nonInteractive: true, skipHooks: true, skipAgents: true} + tail := runInitTailContext{workDir: worktree, beadsDir: storage, fsUseCase: fsUseCase, gitUC: storagegit.NewGitProvider(worktree).GitUseCase()} + for range 2 { + stderr := captureStderr(t, func() { + if in.stealth { + require.NoError(t, fsUseCase.SetupStealthMode(t.Context(), false)) + } + require.NoError(t, runInitProxiedServerTail(cmd, t.Context(), in, tail)) + }) + require.Empty(t, stderr) + } + want := "# preserved\r\n" + if in.stealth { + want += "\r\n# Beads stealth mode (added by bd init --stealth)\r\n.beads/\r\n.claude/settings.local.json\r\n" + } else if name != "decoy_fork" { + want += "\r\n# Beads fork protection (bd init)\r\n.beads/\r\n**/RECOVERY*.md\r\n**/SESSION*.md\r\n" + } + data, err := os.ReadFile(commonExclude) + require.NoError(t, err) + require.Equal(t, want, string(data), "selected common exclude bytes") + data, err = os.ReadFile(filepath.Join(decoy, ".git", "info", "exclude")) + require.NoError(t, err) + require.Equal(t, "# preserved\r\n", string(data)) + data, err = os.ReadFile(filepath.Join(decoy, ".git", "config")) + require.NoError(t, err) + require.Equal(t, decoyConfig, data) + _, err = os.Stat(privateExclude) + require.ErrorIs(t, err, os.ErrNotExist) + entries, err := os.ReadDir(storage) + require.NoError(t, err) + require.Empty(t, entries, "storage location became the Git project") + require.True(t, slices.Equal(env, os.Environ())) + }) + } +} diff --git a/cmd/bd/init_stealth.go b/cmd/bd/init_stealth.go index 3270131df..1d1c5a90d 100644 --- a/cmd/bd/init_stealth.go +++ b/cmd/bd/init_stealth.go @@ -24,8 +24,12 @@ import ( // - .git/info/exclude is designed for user-specific, repo-local ignores // - Patterns are relative to repo root, so ".beads/" works correctly func setupStealthMode(verbose bool) error { + return setupStealthModeAt("", verbose) +} + +func setupStealthModeAt(repoPath string, verbose bool) error { // Setup per-repository git exclude file (skip if not in a git repo) - if err := setupGitExclude(verbose); err != nil { + if err := setupGitExcludeAt(repoPath, verbose); err != nil { if strings.Contains(err.Error(), "not a git repository") { if verbose { fmt.Printf("Not in a git repository — skipping git exclude setup\n") @@ -49,7 +53,11 @@ func setupStealthMode(verbose bool) error { // This is the correct approach for per-repository user-specific ignores (GitHub #704). // Unlike global gitignore, patterns here are relative to the repo root. func setupGitExclude(verbose bool) error { - added, excludePath, err := addExcludePatterns("", + return setupGitExcludeAt("", verbose) +} + +func setupGitExcludeAt(repoPath string, verbose bool) error { + added, excludePath, err := addExcludePatterns(repoPath, "# Beads stealth mode (added by bd init --stealth)", []string{".beads/", ".claude/settings.local.json"}) if err != nil { @@ -343,7 +351,11 @@ func checkProjectExcludeStealth(repoPath string) doctor.DoctorCheck { // This is separate from stealth mode - fork protection is specifically about // preventing beads/Claude files from appearing in upstream PRs. func setupForkExclude(verbose bool) error { - added, _, err := addExcludePatterns("", + return setupForkExcludeAt("", verbose) +} + +func setupForkExcludeAt(repoPath string, verbose bool) error { + added, _, err := addExcludePatterns(repoPath, "# Beads fork protection (bd init)", []string{".beads/", "**/RECOVERY*.md", "**/SESSION*.md"}) if err != nil { diff --git a/cmd/bd/init_stealth_test.go b/cmd/bd/init_stealth_test.go index a06420871..0c686db71 100644 --- a/cmd/bd/init_stealth_test.go +++ b/cmd/bd/init_stealth_test.go @@ -10,6 +10,8 @@ import ( "testing" "github.com/steveyegge/beads/cmd/bd/doctor" + "github.com/steveyegge/beads/internal/gitenv" + "github.com/stretchr/testify/require" ) // TestSetupGitExclude_Worktree verifies that setupGitExclude writes to the main @@ -620,6 +622,77 @@ func TestAddExcludePatternsCreatesMissingFile(t *testing.T) { } } +func initExcludeGit(t *testing.T, dir string, args ...string) string { + t.Helper() + cmd := exec.Command("git", args...) + cmd.Dir, cmd.Env = dir, gitenv.ScrubRouting(os.Environ()) + out, err := cmd.CombinedOutput() + require.NoError(t, err, "fixture git %v: %s", args, out) + return strings.TrimSpace(string(out)) +} + +func newInitExcludeRepos(t *testing.T) (worktree, decoy, commonExclude, privateExclude string) { + t.Helper() + for _, entry := range os.Environ() { + key := gitenv.EntryKey(entry) + if gitenv.IsRoutingKeyForOS(key, runtime.GOOS) { + // Setenv registers restoration; Unsetenv then makes the key absent during the test. + t.Setenv(key, "") + require.NoError(t, os.Unsetenv(key)) + } + } + home := t.TempDir() + for _, key := range []string{"HOME", "USERPROFILE", "XDG_CONFIG_HOME"} { + t.Setenv(key, home) + } + mainDir, decoy := t.TempDir(), t.TempDir() + for _, dir := range []string{mainDir, decoy} { + initExcludeGit(t, dir, "init", "--quiet") + for key, value := range map[string]string{"user.name": "Fixture", "user.email": "fixture@example.test", "commit.gpgSign": "false", "core.hooksPath": filepath.Join(home, "hooks")} { + initExcludeGit(t, dir, "config", "--local", key, value) + } + require.NoError(t, os.WriteFile(filepath.Join(dir, ".git", "info", "exclude"), []byte("# preserved\r\n"), 0600)) + } + initExcludeGit(t, mainDir, "commit", "--allow-empty", "-m", "fixture") + worktree = filepath.Join(t.TempDir(), "selected worktree") + initExcludeGit(t, mainDir, "worktree", "add", "--quiet", "-b", "selected", worktree) + commonExclude = filepath.Join(mainDir, ".git", "info", "exclude") + privateExclude = filepath.Join(initExcludeGit(t, worktree, "rev-parse", "--absolute-git-dir"), "info", "exclude") + t.Chdir(decoy) + return worktree, decoy, commonExclude, privateExclude +} + +func TestGitExcludeExplicitPathSelectsCommonDir(t *testing.T) { + for _, key := range []string{"GIT_DIR", "GIT_COMMON_DIR"} { + t.Run(key, func(t *testing.T) { + worktree, decoy, commonExclude, privateExclude := newInitExcludeRepos(t) + t.Setenv(key, filepath.Join(decoy, ".git")) + t.Setenv("GIT_WORK_TREE", decoy) + // The empty-path API resolves against the current directory, which is the + // decoy here; the probe scrubs inherited routing, so that selection comes + // from the working directory rather than from the key set above. + inherited, err := resolveGitExcludePath("") + require.NoError(t, err) + got, err := os.Stat(inherited) + require.NoError(t, err) + want, err := os.Stat(filepath.Join(decoy, ".git", "info", "exclude")) + require.NoError(t, err) + require.True(t, os.SameFile(got, want)) + added, _, err := addExcludePatterns(worktree, "# selected", []string{".beads/"}) + require.NoError(t, err) + require.Equal(t, []string{".beads/"}, added) + data, err := os.ReadFile(commonExclude) + require.NoError(t, err) + require.Equal(t, "# preserved\r\n\r\n# selected\r\n.beads/\r\n", string(data)) + data, err = os.ReadFile(filepath.Join(decoy, ".git", "info", "exclude")) + require.NoError(t, err) + require.Equal(t, "# preserved\r\n", string(data)) + _, err = os.Stat(privateExclude) + require.ErrorIs(t, err, os.ErrNotExist) + }) + } +} + func TestCheckProjectExcludeStealthReadBoundaries(t *testing.T) { for _, name := range []string{"directory", "directory_clean", "missing", "dangling_symlink", "patterns", "leak"} { t.Run(name, func(t *testing.T) { diff --git a/cmd/bd/worktree_cmd.go b/cmd/bd/worktree_cmd.go index ed29649af..968e7c705 100644 --- a/cmd/bd/worktree_cmd.go +++ b/cmd/bd/worktree_cmd.go @@ -709,8 +709,10 @@ func worktreeGitEnvKey(entry string) string { // clearWorktreeGitRoutingEnv establishes the command working directory as the // repository-selection boundary without changing process identity or signal -// semantics. Startup config discovery applies the same boundary to its one -// pre-hook Git probe. +// semantics. Startup config discovery applies the same scrub to its pre-hook +// config-path probe only; the .beads database discovery probes in +// internal/beads still honor inherited routing, so the two planes can resolve +// different repositories. func clearWorktreeGitRoutingEnv(cmd *cobra.Command) error { if !hasWorktreeCommandAncestor(cmd) { return nil diff --git a/docs/reference/worktrees.md b/docs/reference/worktrees.md index 827cc88b5..18dbd61aa 100644 --- a/docs/reference/worktrees.md +++ b/docs/reference/worktrees.md @@ -15,10 +15,15 @@ override discovery with `BEADS_DIR`. Startup *config* discovery — the `rev-parse` probe in `internal/config`'s `gitDirsForRepo`, which locates a linked worktree's shared `.beads` config — scrubs inherited Git routing variables such as `GIT_DIR` and `GIT_WORK_TREE` -from its subprocess environment. Other startup Git probes still honor inherited -routing, including `internal/git`'s process-cached repository context. Clearing -those variables from the `bd` process environment applies only to `bd worktree` -commands. +from its subprocess environment whenever it runs. The scrub is unconditional for +that probe, but the probe is a fallback, not a per-command step: it runs only +when nothing earlier in startup has already resolved a config path +(`internal/config/config.go`), so an ancestor `.beads/config.yaml` or an +explicit `BEADS_DIR` short-circuits it. Other startup Git probes still honor +inherited routing, including `internal/git`'s process-cached repository context +and the `.beads` database discovery probes in `internal/beads`, so those +variables can still select which workspace `bd` opens. Clearing those variables +from the `bd` process environment applies only to `bd worktree` commands. ``` project/ diff --git a/internal/storage/domain/git/git.go b/internal/storage/domain/git/git.go index 1fdb6eb14..4a9071546 100644 --- a/internal/storage/domain/git/git.go +++ b/internal/storage/domain/git/git.go @@ -11,6 +11,7 @@ import ( "strings" internalgit "github.com/steveyegge/beads/internal/git" + "github.com/steveyegge/beads/internal/gitenv" "github.com/steveyegge/beads/internal/storage/domain" ) @@ -18,15 +19,22 @@ func NewGitRepository(workDir string) domain.GitRepository { return &gitRepositoryImpl{workDir: workDir} } +// NewInitGitRepository binds init artifact operations to the selected workDir. +// The generic constructor retains inherited routing for its existing callers. +func NewInitGitRepository(workDir string) domain.GitRepository { + return &gitRepositoryImpl{workDir: workDir, env: gitenv.ScrubRouting(os.Environ())} +} + type gitRepositoryImpl struct { workDir string + env []string } var _ domain.GitRepository = (*gitRepositoryImpl)(nil) func (r *gitRepositoryImpl) gitCmd(ctx context.Context, args ...string) *exec.Cmd { cmd := exec.CommandContext(ctx, "git", args...) - cmd.Dir = r.workDir + cmd.Dir, cmd.Env = r.workDir, r.env return cmd } @@ -98,7 +106,11 @@ func (r *gitRepositoryImpl) GetConfig(ctx context.Context, key string) (string, if key == "" { return "", false, fmt.Errorf("git: GetConfig: key must not be empty") } - out, err := r.gitCmd(ctx, "config", "--get", key).Output() + cmd := r.gitCmd(ctx, "config", "--get", key) + if key == "beads.role" && r.env == nil { + cmd.Env = gitenv.ScrubRouting(os.Environ()) + } + out, err := cmd.Output() if err != nil { var exitErr *exec.ExitError if errors.As(err, &exitErr) { @@ -121,7 +133,11 @@ func (r *gitRepositoryImpl) SetConfig(ctx context.Context, key, value string) er if key == "" { return fmt.Errorf("git: SetConfig: key must not be empty") } - out, err := r.gitCmd(ctx, "config", key, value).CombinedOutput() + cmd := r.gitCmd(ctx, "config", key, value) + if key == "beads.role" && r.env == nil { + cmd.Env = gitenv.ScrubRouting(os.Environ()) + } + out, err := cmd.CombinedOutput() if err != nil { return fmt.Errorf("git: SetConfig %s: %w: %s", key, err, bytes.TrimSpace(out)) } diff --git a/internal/storage/domain/git/git_test.go b/internal/storage/domain/git/git_test.go index 5cf4e3f4a..8e555986a 100644 --- a/internal/storage/domain/git/git_test.go +++ b/internal/storage/domain/git/git_test.go @@ -5,9 +5,14 @@ import ( "os" "os/exec" "path/filepath" + "runtime" + "slices" "strings" + "testing" + "github.com/steveyegge/beads/internal/gitenv" "github.com/steveyegge/beads/internal/storage/domain" + "github.com/stretchr/testify/require" ) func (s *testSuite) TestIsGitRepo_FalseOutsideRepo() { @@ -72,7 +77,9 @@ func (s *testSuite) TestConfig_ReadFailuresAreNotMissing() { }{ {"malformed_config", "beads.role", 128}, {"invalid_key", "invalid", 1}, - {"invalid_routing_boolean", "beads.role", 128}, + // beads.role reads now scrub GIT_CONFIG* routing, so a routing poison can + // only reach a key that is not role-scoped. + {"invalid_routing_boolean", "test.marker", 128}, } { s.Run(tc.name, func() { switch tc.name { @@ -97,11 +104,21 @@ func (s *testSuite) TestConfig_ReadFailuresAreNotMissing() { diagnostic := strings.TrimSpace(string(exitErr.Stderr)) s.Require().NotEmpty(diagnostic) s.Contains(err.Error(), diagnostic) - if tc.name != "invalid_key" { + if tc.name == "malformed_config" { _, _, roleErr := domain.NewGitUseCase(s.tmpDir, s.repo).BeadsRole(s.Ctx()) s.Require().Error(roleErr) s.ErrorAs(roleErr, &exitErr) } + if tc.name == "invalid_routing_boolean" { + // The same poison that fails the read above cannot reach beads.role, + // which resolves as absent rather than as a preserved read failure. + role, roleFound, roleErr := s.repo.GetConfig(s.Ctx(), "beads.role") + s.Require().NoError(roleErr) + s.False(roleFound) + s.Empty(role) + _, _, useCaseErr := domain.NewGitUseCase(s.tmpDir, s.repo).BeadsRole(s.Ctx()) + s.Require().NoError(useCaseErr) + } }) } } @@ -288,3 +305,180 @@ func (s *testSuite) TestExec_HappensInWorkDir() { s.Require().NoError(err) s.True(info.IsDir()) } + +func TestRoleConfigIgnoresInheritedGitRouting(t *testing.T) { + for _, entry := range os.Environ() { + key := gitenv.EntryKey(entry) + if gitenv.IsRoutingKeyForOS(key, runtime.GOOS) { + t.Setenv(key, "") + require.NoError(t, os.Unsetenv(key)) + } + } + home := t.TempDir() + for _, key := range []string{"HOME", "USERPROFILE", "XDG_CONFIG_HOME"} { + t.Setenv(key, home) + } + runGit := func(t *testing.T, dir string, args ...string) string { + t.Helper() + cmd := exec.Command("git", args...) + cmd.Dir, cmd.Env = dir, gitenv.ScrubRouting(os.Environ()) + out, err := cmd.CombinedOutput() + require.NoError(t, err, "fixture git %v: %s", args, out) + return strings.TrimSpace(string(out)) + } + for _, tc := range []struct { + name, local, global, want string + }{ + {"repository", "maintainer", "", "maintainer"}, + {"inline_config", "maintainer", "", "maintainer"}, + {"default_global", "", "contributor", "contributor"}, + {"absent", "", "", ""}, + {"literal", "custom role = exact", "", "custom role = exact"}, + {"empty", " \t ", "", ""}, + } { + t.Run(tc.name, func(t *testing.T) { + target, decoy := t.TempDir(), t.TempDir() + for _, dir := range []string{target, decoy} { + runGit(t, dir, "init", "--quiet") + runGit(t, dir, "config", "--local", "core.hooksPath", ".git/hooks") + } + runGit(t, target, "config", "--local", "test.marker", "target") + runGit(t, decoy, "config", "--local", "test.marker", "decoy") + runGit(t, decoy, "config", "--local", "beads.role", "decoy-role") + if tc.local != "" { + runGit(t, target, "config", "--local", "beads.role", tc.local) + } + global := "" + if tc.global != "" { + global = "[beads]\n\trole = " + tc.global + "\n" + } + globalPath := filepath.Join(home, ".gitconfig") + require.NoError(t, os.WriteFile(globalPath, []byte(global), 0600)) + wantGeneric, changedDir := "decoy", decoy + if tc.name == "inline_config" { + t.Setenv("GIT_CONFIG_COUNT", "2") + t.Setenv("GIT_CONFIG_KEY_0", "beads.role") + t.Setenv("GIT_CONFIG_VALUE_0", "injected-role") + t.Setenv("GIT_CONFIG_KEY_1", "test.marker") + t.Setenv("GIT_CONFIG_VALUE_1", "injected-marker") + wantGeneric, changedDir = "injected-marker", target + } else { + t.Setenv("GIT_DIR", filepath.Join(decoy, ".git")) + t.Setenv("GIT_WORK_TREE", decoy) + } + env := os.Environ() + before, err := os.ReadFile(filepath.Join(decoy, ".git", "config")) + require.NoError(t, err) + repo := NewGitRepository(target) + useCase := domain.NewGitUseCase(target, repo) + got, found, err := useCase.BeadsRole(t.Context()) + require.NoError(t, err) + require.Equal(t, tc.want, got) + require.Equal(t, tc.want != "", found) + require.NoError(t, useCase.SetBeadsRole(t.Context(), "new role = exact")) + require.Equal(t, "new role = exact", runGit(t, target, "config", "--local", "--get", "beads.role")) + after, err := os.ReadFile(filepath.Join(decoy, ".git", "config")) + require.NoError(t, err) + require.Equal(t, string(before), string(after), "role write changed decoy") + // Ordinary config commands keep their existing inherited context. + got, found, err = repo.GetConfig(t.Context(), "test.marker") + require.NoError(t, err) + require.True(t, found) + require.Equal(t, wantGeneric, got) + require.NoError(t, repo.SetConfig(t.Context(), "test.marker", "changed")) + require.Equal(t, "changed", runGit(t, changedDir, "config", "--local", "--get", "test.marker")) + globalAfter, err := os.ReadFile(globalPath) + require.NoError(t, err) + require.Equal(t, global, string(globalAfter)) + require.True(t, slices.Equal(env, os.Environ()), "adapter changed inherited environment") + }) + } +} + +func TestInitGitRepositoryUsesSelectedDirectory(t *testing.T) { + for _, entry := range os.Environ() { + key := gitenv.EntryKey(entry) + if gitenv.IsRoutingKeyForOS(key, runtime.GOOS) { + t.Setenv(key, "") + require.NoError(t, os.Unsetenv(key)) + } + } + home := t.TempDir() + for _, key := range []string{"HOME", "USERPROFILE", "XDG_CONFIG_HOME"} { + t.Setenv(key, home) + } + runGit := func(dir string, args ...string) string { + t.Helper() + cmd := exec.Command("git", args...) + cmd.Dir, cmd.Env = dir, gitenv.ScrubRouting(os.Environ()) + out, err := cmd.CombinedOutput() + require.NoError(t, err, "fixture git %v: %s", args, out) + return strings.TrimSpace(string(out)) + } + for _, kind := range []string{"ordinary", "nested", "linked", "bare", "nonrepo", "captured_home"} { + t.Run(kind, func(t *testing.T) { + target, decoy := t.TempDir(), t.TempDir() + runGit(decoy, "init", "--quiet") + runGit(decoy, "config", "test.marker", "decoy") + if kind == "bare" { + runGit(target, "init", "--bare", "--quiet") + } else if kind != "nonrepo" { + runGit(target, "init", "--quiet") + } + if kind != "nonrepo" { + runGit(target, "config", "test.marker", "target") + } + if kind == "nested" { + target = filepath.Join(target, "nested") + require.NoError(t, os.Mkdir(target, 0755)) + } else if kind == "linked" { + runGit(target, "-c", "user.name=Fixture", "-c", "user.email=fixture@example.test", "-c", "commit.gpgSign=false", "-c", "core.hooksPath=", "commit", "--allow-empty", "-m", "seed") + linked := filepath.Join(t.TempDir(), "linked") + runGit(target, "-c", "core.hooksPath=", "worktree", "add", "--detach", linked) + target = linked + } + t.Setenv("GIT_DIR", filepath.Join(decoy, ".git")) + t.Setenv("GIT_WORK_TREE", decoy) + t.Chdir(decoy) + inherited := NewGitRepository(target) + marker, found, err := inherited.GetConfig(t.Context(), "test.marker") + require.NoError(t, err) + require.True(t, found) + require.Equal(t, "decoy", marker, "generic constructor must retain inherited routing") + env := os.Environ() + selected := NewInitGitRepository(target) + isRepo, err := selected.IsGitRepo(t.Context()) + require.NoError(t, err) + require.Equal(t, kind != "nonrepo", isRepo) + bare, err := selected.IsBareGitRepo(t.Context()) + require.NoError(t, err) + require.Equal(t, kind == "bare", bare) + marker, found, err = selected.GetConfig(t.Context(), "test.marker") + require.NoError(t, err) + require.Equal(t, kind != "nonrepo", found) + if found { + require.Equal(t, "target", marker) + } + require.True(t, slices.Equal(env, os.Environ())) + if kind == "captured_home" { + changedHome := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(changedHome, ".gitconfig"), []byte("[invalid\n"), 0600)) + for _, key := range []string{"HOME", "USERPROFILE", "XDG_CONFIG_HOME"} { + t.Setenv(key, changedHome) + } + role, found, err := inherited.GetConfig(t.Context(), "beads.role") + // The generic reader runs under the caller's current environment, so the + // broken HOME config surfaces as a preserved read failure, not absence. + require.Error(t, err, "generic role reads still use the current caller environment") + require.False(t, found) + require.Empty(t, role) + require.Error(t, inherited.SetConfig(t.Context(), "beads.role", "decoy")) + require.NoError(t, selected.SetConfig(t.Context(), "beads.role", "contributor")) + role, found, err = selected.GetConfig(t.Context(), "beads.role") + require.NoError(t, err) + require.True(t, found) + require.Equal(t, "contributor", role, "role reads and writes share the constructor's captured HOME") + } + }) + } +}