diff --git a/cmd/bd/BUILD.bazel b/cmd/bd/BUILD.bazel index 1fc1bff56..b6cbba384 100644 --- a/cmd/bd/BUILD.bazel +++ b/cmd/bd/BUILD.bazel @@ -282,6 +282,7 @@ go_library( "restore.go", "routed.go", "routing_read.go", + "routing_role.go", "rules.go", "sandbox_unix.go", "sandbox_windows.go", diff --git a/cmd/bd/close_routing_test.go b/cmd/bd/close_routing_test.go index 4e7e45fab..8073073e9 100644 --- a/cmd/bd/close_routing_test.go +++ b/cmd/bd/close_routing_test.go @@ -113,6 +113,10 @@ func TestResolveCloseTargets(t *testing.T) { if err := os.Chdir(repoDir); err != nil { t.Fatalf("chdir repoDir: %v", err) } + // Role detection reads the process-wide RepoContext cache, which the + // previous case built for its own, now-deleted repo. Rebuild it from + // repoDir. + resetRepoContextCachesForTest(t) results, cleanup, err := resolveCloseTargets(ctx, primaryStore, tc.inputIDs) if err != nil { diff --git a/cmd/bd/context_binding_test.go b/cmd/bd/context_binding_test.go index adaec2f6a..07e2f3338 100644 --- a/cmd/bd/context_binding_test.go +++ b/cmd/bd/context_binding_test.go @@ -1,13 +1,20 @@ package main import ( + "context" + "io" "os" + "os/exec" "path/filepath" + "strings" "testing" + "github.com/steveyegge/beads/internal/beads" "github.com/steveyegge/beads/internal/config" "github.com/steveyegge/beads/internal/configfile" "github.com/steveyegge/beads/internal/doltserver" + "github.com/steveyegge/beads/internal/git" + "github.com/steveyegge/beads/internal/routing" ) func writeTestConfigYAML(t *testing.T, beadsDir, contents string) { @@ -20,6 +27,44 @@ func writeTestConfigYAML(t *testing.T, beadsDir, contents string) { } } +func initGitRepoForContextTest(t *testing.T, dir string) { + t.Helper() + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatalf("mkdir repo: %v", err) + } + cmd := exec.Command("git", "init", "--quiet") + cmd.Dir = dir + if output, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("git init: %v\n%s", err, output) + } + cmd = exec.Command("git", "config", "core.hooksPath", ".git/hooks") + cmd.Dir = dir + if output, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("git config hooks: %v\n%s", err, output) + } +} + +func resetRepoContextCachesForTest(t *testing.T) { + t.Helper() + beads.ResetCaches() + git.ResetCaches() + t.Cleanup(func() { + beads.ResetCaches() + git.ResetCaches() + }) +} + +// setBeadsDirStartupProvenanceForTest pins whether this test simulates a +// caller who exported BEADS_DIR before bd started. The production value is +// captured once at process start, so tests must set it explicitly rather than +// inherit whatever environment the test process happened to launch with. +func setBeadsDirStartupProvenanceForTest(t *testing.T, provided bool) { + t.Helper() + old := beadsDirProvidedAtStartup + beadsDirProvidedAtStartup = provided + t.Cleanup(func() { beadsDirProvidedAtStartup = old }) +} + type flagSnapshot struct { value string changed bool @@ -145,6 +190,667 @@ func TestPrepareSelectedCommandContext_RebindsTargetConfig(t *testing.T) { } } +func TestDetectUserRoleForActiveRepoUsesSelectedBeadsDir(t *testing.T) { + resetRepoContextCachesForTest(t) + + callerDir := t.TempDir() + initGitRepoForContextTest(t, callerDir) + + targetDir := t.TempDir() + initGitRepoForContextTest(t, targetDir) + targetBeadsDir := filepath.Join(targetDir, ".beads") + writeTestConfigYAML(t, targetBeadsDir, "") + + cmd := exec.Command("git", "config", "beads.role", "maintainer") + cmd.Dir = targetDir + if output, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("git config beads.role: %v\n%s", err, output) + } + + t.Chdir(callerDir) + t.Setenv("BEADS_DIR", targetBeadsDir) + setBeadsDirStartupProvenanceForTest(t, true) + + readStderr, writeStderr, err := os.Pipe() + if err != nil { + t.Fatalf("pipe stderr: %v", err) + } + oldStderr := os.Stderr + os.Stderr = writeStderr + t.Cleanup(func() { + os.Stderr = oldStderr + _ = readStderr.Close() + _ = writeStderr.Close() + }) + + role, err := detectUserRoleForActiveRepo() + _ = writeStderr.Close() + stderrOutput, readErr := io.ReadAll(readStderr) + if readErr != nil { + t.Fatalf("read stderr: %v", readErr) + } + if err != nil { + t.Fatalf("detectUserRoleForActiveRepo: %v", err) + } + if role != routing.Maintainer { + t.Fatalf("role = %q, want %q", role, routing.Maintainer) + } + if strings.Contains(string(stderrOutput), "beads.role not configured") { + t.Fatalf("unexpected role warning from caller cwd:\n%s", stderrOutput) + } +} + +func TestActiveRepoPathForRoutingFallsBackToBeadsDirParent(t *testing.T) { + resetRepoContextCachesForTest(t) + + // targetDir must sit outside any git repo, or beads.GetRepoContext() + // succeeds against it and the FindBeadsDir fallback under test is never + // reached. t.TempDir() resolves under os.TempDir(), which + // internal/beads/context.go's isPathInSafeBoundary explicitly admits. + targetDir := t.TempDir() + targetBeadsDir := filepath.Join(targetDir, ".beads") + writeTestConfigYAML(t, targetBeadsDir, "") + + // The caller's CWD must also be outside any git repo, so + // beads.GetRepoContext() can't resolve via CWD either. + t.Chdir(t.TempDir()) + t.Setenv("BEADS_DIR", targetBeadsDir) + setBeadsDirStartupProvenanceForTest(t, true) + + // Compare through EvalSymlinks: on macOS t.TempDir() hands back a + // /var/... symlink while resolution may canonicalize to /private/var/... + // — the same directory. The sibling redirect tests already compare this + // way; asserting the raw string makes the test order-fragile there. + got := activeRepoPathForRouting() + gotResolved, err := filepath.EvalSymlinks(got) + if err != nil { + t.Fatalf("resolve got %q: %v", got, err) + } + wantResolved, err := filepath.EvalSymlinks(targetDir) + if err != nil { + t.Fatalf("resolve target %q: %v", targetDir, err) + } + if gotResolved != wantResolved { + t.Fatalf("activeRepoPathForRouting() = %q (resolved %q), want %q", got, gotResolved, wantResolved) + } +} + +func TestActiveRepoPathForRoutingKeepsWorkspaceRepoAcrossRedirect(t *testing.T) { + resetRepoContextCachesForTest(t) + + // A .beads/redirect relocates STORAGE, not the project: beads.role must + // still come from the workspace repo the user is operating in, not from + // wherever the redirect target lives (here: outside any git repo). Only + // an explicit BEADS_DIR selection (bd -C) may move role detection. + workspace := t.TempDir() + initGitRepoForContextTest(t, workspace) + storageDir := t.TempDir() + storageBeadsDir := filepath.Join(storageDir, ".beads") + writeTestConfigYAML(t, storageBeadsDir, "") + + workspaceBeadsDir := filepath.Join(workspace, ".beads") + if err := os.MkdirAll(workspaceBeadsDir, 0o700); err != nil { + t.Fatalf("mkdir workspace beads dir: %v", err) + } + redirectFile := filepath.Join(workspaceBeadsDir, beads.RedirectFileName) + if err := os.WriteFile(redirectFile, []byte(storageBeadsDir+"\n"), 0o600); err != nil { + t.Fatalf("write redirect file: %v", err) + } + + t.Chdir(workspace) + t.Setenv("BEADS_DIR", "") + setBeadsDirStartupProvenanceForTest(t, false) + + got := activeRepoPathForRouting() + // Compare through EvalSymlinks: git resolves the physical path while + // t.TempDir may hand back a symlinked one. + gotResolved, err := filepath.EvalSymlinks(got) + if err != nil { + t.Fatalf("resolve got %q: %v", got, err) + } + wantResolved, err := filepath.EvalSymlinks(workspace) + if err != nil { + t.Fatalf("resolve workspace %q: %v", workspace, err) + } + if gotResolved != wantResolved { + t.Fatalf("activeRepoPathForRouting() = %q (resolved %q), want workspace %q — a redirect must not move role detection to the storage root", got, gotResolved, wantResolved) + } +} + +func TestActiveRepoPathForRoutingSurvivesStartupRebindAcrossRedirect(t *testing.T) { + resetRepoContextCachesForTest(t) + + // The regression this pins: rootCmd's PersistentPreRunE resolves the + // redirect target and calls prepareSelectedCommandContext, which sets + // BEADS_DIR for EVERY command — redirects included. Role detection must + // not read that internal rebind as explicit user selection. The + // helper-only redirect test above leaves BEADS_DIR empty and so never + // exercises this startup path. + workspace := t.TempDir() + initGitRepoForContextTest(t, workspace) + storageDir := t.TempDir() + storageBeadsDir := filepath.Join(storageDir, ".beads") + writeTestConfigYAML(t, storageBeadsDir, "") + + workspaceBeadsDir := filepath.Join(workspace, ".beads") + if err := os.MkdirAll(workspaceBeadsDir, 0o700); err != nil { + t.Fatalf("mkdir workspace beads dir: %v", err) + } + redirectFile := filepath.Join(workspaceBeadsDir, beads.RedirectFileName) + if err := os.WriteFile(redirectFile, []byte(storageBeadsDir+"\n"), 0o600); err != nil { + t.Fatalf("write redirect file: %v", err) + } + + t.Chdir(workspace) + t.Setenv("BEADS_DIR", "") + setBeadsDirStartupProvenanceForTest(t, false) + + config.ResetForTesting() + t.Cleanup(config.ResetForTesting) + oldServerMode := serverMode + flagState := snapshotRootFlagState() + t.Cleanup(func() { + serverMode = oldServerMode + restoreRootFlagState(t, flagState) + }) + + // The same rebind PersistentPreRunE performs once discovery has followed + // the redirect to the storage .beads. + prepareSelectedCommandContext(storageBeadsDir, false) + + if got := os.Getenv("BEADS_DIR"); got != storageBeadsDir { + t.Fatalf("BEADS_DIR = %q, want %q (startup rebind should have run)", got, storageBeadsDir) + } + + got := activeRepoPathForRouting() + gotResolved, err := filepath.EvalSymlinks(got) + if err != nil { + t.Fatalf("resolve got %q: %v", got, err) + } + wantResolved, err := filepath.EvalSymlinks(workspace) + if err != nil { + t.Fatalf("resolve workspace %q: %v", workspace, err) + } + if gotResolved != wantResolved { + t.Fatalf("activeRepoPathForRouting() = %q (resolved %q), want workspace %q — the startup BEADS_DIR rebind must not turn a redirect into explicit selection", got, gotResolved, wantResolved) + } +} + +func TestActiveRepoPathForRoutingHonorsEnvFileSelection(t *testing.T) { + resetRepoContextCachesForTest(t) + + // .beads/.env routing (loadSelectionEnvironment) is user-authored + // selection: BEADS_DIR set there must keep binding role detection to the + // selected project, exactly like exporting BEADS_DIR before running bd. + callerDir := t.TempDir() + initGitRepoForContextTest(t, callerDir) + callerBeadsDir := filepath.Join(callerDir, ".beads") + writeTestConfigYAML(t, callerBeadsDir, "") + + targetDir := t.TempDir() + initGitRepoForContextTest(t, targetDir) + targetBeadsDir := filepath.Join(targetDir, ".beads") + writeTestConfigYAML(t, targetBeadsDir, "") + + if err := os.WriteFile(filepath.Join(callerBeadsDir, ".env"), []byte("BEADS_DIR="+targetBeadsDir+"\n"), 0o600); err != nil { + t.Fatalf("write .env: %v", err) + } + + t.Chdir(callerDir) + t.Setenv("BEADS_DIR", "") + t.Setenv("BEADS_DB", "") + t.Setenv("BD_DB", "") + setBeadsDirStartupProvenanceForTest(t, false) + + loadSelectionEnvironment() + + if got := os.Getenv("BEADS_DIR"); got != targetBeadsDir { + t.Fatalf("BEADS_DIR = %q, want %q (selection env load should have run)", got, targetBeadsDir) + } + + got := activeRepoPathForRouting() + gotResolved, err := filepath.EvalSymlinks(got) + if err != nil { + t.Fatalf("resolve got %q: %v", got, err) + } + wantResolved, err := filepath.EvalSymlinks(targetDir) + if err != nil { + t.Fatalf("resolve target %q: %v", targetDir, err) + } + if gotResolved != wantResolved { + t.Fatalf("activeRepoPathForRouting() = %q (resolved %q), want selected target %q — .env-provided BEADS_DIR is explicit selection", got, gotResolved, wantResolved) + } +} + +func TestActiveRepoPathForRoutingFallsBackToCurrentDirectory(t *testing.T) { + resetRepoContextCachesForTest(t) + + t.Chdir(t.TempDir()) + t.Setenv("BEADS_DIR", "") + setBeadsDirStartupProvenanceForTest(t, false) + + if got := activeRepoPathForRouting(); got != "." { + t.Fatalf("activeRepoPathForRouting() = %q, want %q", got, ".") + } +} + +// newRedirectedWorkspaceForTest builds the explicit x redirect fixture: a git +// workspace whose .beads holds only a redirect, pointing at a SEPARATE git +// repo's .beads that holds the project files. Two distinct repos is what makes +// buildRepoContext treat the context as external, so rc.RepoRoot really is the +// storage root and a wrong answer is visible instead of coincidentally right. +func newRedirectedWorkspaceForTest(t *testing.T) (workspace, storageBeadsDir string) { + t.Helper() + + workspace = filepath.Join(t.TempDir(), "workspace") + initGitRepoForContextTest(t, workspace) + storageBeadsDir = newStorageBeadsDirForTest(t) + writeRedirectForTest(t, filepath.Join(workspace, ".beads"), storageBeadsDir) + return workspace, storageBeadsDir +} + +// newStorageBeadsDirForTest returns the .beads of a fresh git repo that holds +// the project files, for a redirect fixture to point at. +func newStorageBeadsDirForTest(t *testing.T) string { + t.Helper() + + storage := filepath.Join(t.TempDir(), "storage") + initGitRepoForContextTest(t, storage) + storageBeadsDir := filepath.Join(storage, ".beads") + writeTestConfigYAML(t, storageBeadsDir, "") + return storageBeadsDir +} + +// writeRedirectForTest makes beadsDir a .beads that holds only a redirect to +// target. +func writeRedirectForTest(t *testing.T, beadsDir, target string) { + t.Helper() + + if err := os.MkdirAll(beadsDir, 0o700); err != nil { + t.Fatalf("mkdir redirect beads dir: %v", err) + } + redirectFile := filepath.Join(beadsDir, beads.RedirectFileName) + if err := os.WriteFile(redirectFile, []byte(target+"\n"), 0o600); err != nil { + t.Fatalf("write redirect file: %v", err) + } +} + +// newNestedRedirectedWorkspaceForTest builds a redirected workspace one +// directory below its git repo root, and the root holds no .beads, so discovery +// reaches the redirect only by walking up from the CWD. +func newNestedRedirectedWorkspaceForTest(t *testing.T) (cwd, repoRoot, redirectBeadsDir, storageBeadsDir string) { + t.Helper() + + repoRoot = filepath.Join(t.TempDir(), "repo") + initGitRepoForContextTest(t, repoRoot) + cwd = filepath.Join(repoRoot, "sub") + storageBeadsDir = newStorageBeadsDirForTest(t) + redirectBeadsDir = filepath.Join(cwd, ".beads") + writeRedirectForTest(t, redirectBeadsDir, storageBeadsDir) + return cwd, repoRoot, redirectBeadsDir, storageBeadsDir +} + +// newWorktreeInheritingRedirectForTest builds a git worktree with no .beads of +// its own, whose main checkout's .beads redirects to a separate storage repo. +// The worktree sits outside the main checkout, so discovery reaches that +// redirect only through GetWorktreeFallbackBeadsDir, never by walking up. +func newWorktreeInheritingRedirectForTest(t *testing.T) (cwd, repoRoot, redirectBeadsDir, storageBeadsDir string) { + t.Helper() + + mainCheckout := filepath.Join(t.TempDir(), "main") + initGitRepoForContextTest(t, mainCheckout) + runGitForWorktreeTest(t, mainCheckout, "config", "user.email", "test@example.com") + runGitForWorktreeTest(t, mainCheckout, "config", "user.name", "test") + runGitForWorktreeTest(t, mainCheckout, "commit", "-q", "--allow-empty", "-m", "init") + worktree := filepath.Join(t.TempDir(), "worktree") + runGitForWorktreeTest(t, mainCheckout, "worktree", "add", "-q", "--detach", worktree) + + storageBeadsDir = newStorageBeadsDirForTest(t) + redirectBeadsDir = filepath.Join(mainCheckout, ".beads") + writeRedirectForTest(t, redirectBeadsDir, storageBeadsDir) + return worktree, worktree, redirectBeadsDir, storageBeadsDir +} + +// setChangeDirForTest simulates `bd -C dir` for role detection, which reads the +// changeDir package var directly rather than the (already rebound) BEADS_DIR. +func setChangeDirForTest(t *testing.T, dir string) { + t.Helper() + old := changeDir + changeDir = dir + t.Cleanup(func() { changeDir = old }) +} + +// assertActiveRepoPath compares through EvalSymlinks: git resolves the physical +// path while t.TempDir may hand back a symlinked one. +func assertActiveRepoPath(t *testing.T, got, want, why string) { + t.Helper() + gotResolved, err := filepath.EvalSymlinks(got) + if err != nil { + t.Fatalf("resolve got %q: %v", got, err) + } + wantResolved, err := filepath.EvalSymlinks(want) + if err != nil { + t.Fatalf("resolve want %q: %v", want, err) + } + if gotResolved != wantResolved { + t.Fatalf("activeRepoPathForRouting() = %q (resolved %q), want %q (resolved %q) — %s", + got, gotResolved, want, wantResolved, why) + } +} + +func TestActiveRepoPathForRoutingKeepsWorkspaceWhenExplicitBeadsDirNamesWorkspaceRedirect(t *testing.T) { + resetRepoContextCachesForTest(t) + + workspace, _ := newRedirectedWorkspaceForTest(t) + + t.Chdir(workspace) + t.Setenv("BEADS_DIR", filepath.Join(workspace, ".beads")) + setBeadsDirStartupProvenanceForTest(t, true) + + assertActiveRepoPath(t, activeRepoPathForRouting(), workspace, + "exporting the workspace's OWN .beads selects the workspace, not the storage root its redirect points at") +} + +func TestActiveRepoPathForRoutingKeepsWorkspaceWhenExplicitBeadsDirNamesRedirectTarget(t *testing.T) { + resetRepoContextCachesForTest(t) + + workspace, storageBeadsDir := newRedirectedWorkspaceForTest(t) + + t.Chdir(workspace) + // The bd-wayc3 shape: tooling pre-sets BEADS_DIR to the already-resolved + // redirect target. That names where the DATA lives, not a different + // project, so it must not move role detection off the workspace. Both + // spellings reach here identically because ExplicitBeadsDir follows the + // redirect. + t.Setenv("BEADS_DIR", storageBeadsDir) + setBeadsDirStartupProvenanceForTest(t, true) + + assertActiveRepoPath(t, activeRepoPathForRouting(), workspace, + "a BEADS_DIR naming the CWD workspace's own redirect target is a vacuous selection") +} + +func TestActiveRepoPathForRoutingBindsChangeDirWorkspaceAcrossRedirect(t *testing.T) { + resetRepoContextCachesForTest(t) + + workspace, storageBeadsDir := newRedirectedWorkspaceForTest(t) + callerDir := filepath.Join(t.TempDir(), "caller") + initGitRepoForContextTest(t, callerDir) + + // `bd -C ` from an unrelated CWD, which is the GH#4242 shape: + // applyChangeDirSelection has already rewritten BEADS_DIR to the resolved + // target, so only the -C argument still names the project the user chose. + // A CWD-anchored redirect probe cannot see this case at all. + t.Chdir(callerDir) + t.Setenv("BEADS_DIR", storageBeadsDir) + setBeadsDirStartupProvenanceForTest(t, false) + setChangeDirForTest(t, workspace) + + assertActiveRepoPath(t, activeRepoPathForRouting(), workspace, + "bd -C must bind beads.role to the selected workspace, not to its storage repo") +} + +func TestActiveRepoPathForRoutingHonorsChangeDirSelectionWithoutRedirect(t *testing.T) { + resetRepoContextCachesForTest(t) + + targetDir := filepath.Join(t.TempDir(), "target") + initGitRepoForContextTest(t, targetDir) + targetBeadsDir := filepath.Join(targetDir, ".beads") + writeTestConfigYAML(t, targetBeadsDir, "") + + callerDir := filepath.Join(t.TempDir(), "caller") + initGitRepoForContextTest(t, callerDir) + + // Control for the three tests above: with no redirect in play, an explicit + // -C selection must still move role detection to the selected repo. That is + // the GH#4242 fix itself, and the redirect handling must not undo it. + t.Chdir(callerDir) + t.Setenv("BEADS_DIR", targetBeadsDir) + setBeadsDirStartupProvenanceForTest(t, false) + setChangeDirForTest(t, targetDir) + + assertActiveRepoPath(t, activeRepoPathForRouting(), targetDir, + "an explicit selection of a non-redirected project must still win") +} + +// TestActiveRepoPathForRoutingKeepsWorkspaceWhenExplicitBeadsDirNamesNonRootRedirect +// carries the two exported-BEADS_DIR workspace tests past the repo root: a +// workspace nested below its repo root, and a git worktree with no .beads of its +// own that inherits the main checkout's. Naming the redirect discovery finds +// there is just as vacuous, so every state of the variable must answer what the +// command answers with BEADS_DIR unset. The rebind state is what a live command +// sees, and there BEADS_DIR no longer names the redirect at all. +func TestActiveRepoPathForRoutingKeepsWorkspaceWhenExplicitBeadsDirNamesNonRootRedirect(t *testing.T) { + for _, shape := range []struct { + name string + build func(t *testing.T) (cwd, repoRoot, redirectBeadsDir, storageBeadsDir string) + }{ + {name: "nested workspace", build: newNestedRedirectedWorkspaceForTest}, + {name: "worktree without its own .beads", build: newWorktreeInheritingRedirectForTest}, + } { + t.Run(shape.name, func(t *testing.T) { + cwd, repoRoot, redirectBeadsDir, storageBeadsDir := shape.build(t) + t.Chdir(cwd) + setChangeDirForTest(t, "") + for _, state := range []struct { + name, beadsDir string + exported bool + }{ + {name: "unset", beadsDir: "", exported: false}, + {name: "as exported", beadsDir: redirectBeadsDir, exported: true}, + {name: "after the pre-RunE rebind", beadsDir: storageBeadsDir, exported: true}, + } { + t.Run("BEADS_DIR "+state.name, func(t *testing.T) { + resetRepoContextCachesForTest(t) + t.Setenv("BEADS_DIR", state.beadsDir) + setBeadsDirStartupProvenanceForTest(t, state.exported) + assertActiveRepoPath(t, activeRepoPathForRouting(), repoRoot, + "naming the CWD workspace's own redirect must not move role detection to the storage root") + }) + } + }) + } +} + +func TestActiveRepoPathForRoutingHonorsExplicitBeadsDirFromRedirectedWorkspace(t *testing.T) { + resetRepoContextCachesForTest(t) + + workspace, _ := newRedirectedWorkspaceForTest(t) + targetDir := filepath.Join(t.TempDir(), "target") + initGitRepoForContextTest(t, targetDir) + targetBeadsDir := filepath.Join(targetDir, ".beads") + writeTestConfigYAML(t, targetBeadsDir, "") + + // The converse of the vacuous cases: from a redirected workspace, an + // exported BEADS_DIR naming a DIFFERENT project is a real selection, and + // the CWD workspace's own redirect must not claim it. Only the redirect + // target comparison tells the two apart. + t.Chdir(workspace) + t.Setenv("BEADS_DIR", targetBeadsDir) + setBeadsDirStartupProvenanceForTest(t, true) + setChangeDirForTest(t, "") + + assertActiveRepoPath(t, activeRepoPathForRouting(), targetDir, + "a BEADS_DIR naming another project is explicit selection, even from a redirected workspace") +} + +func TestActiveRepoPathForRoutingBindsForeignRedirectedBeadsDirToStorage(t *testing.T) { + workspace, storageBeadsDir := newRedirectedWorkspaceForTest(t) + callerDir := filepath.Join(t.TempDir(), "caller") + initGitRepoForContextTest(t, callerDir) + + // The exported BEADS_DIR names a redirected workspace that is NOT the CWD + // repo, and the CWD repo has no .beads, so GetRedirectInfo would fall back + // to BEADS_DIR itself. The selection must not vouch for itself as the CWD + // workspace's own redirect and bind the unrelated caller's role. Only the + // exported arm pins that. The rebound storage .beads holds no redirect to + // vouch with, so the rebind arm (all a live command ever sees) checks only + // that both states of the variable agree. + t.Chdir(callerDir) + setBeadsDirStartupProvenanceForTest(t, true) + setChangeDirForTest(t, "") + for _, state := range []struct{ name, beadsDir string }{ + {name: "as exported", beadsDir: filepath.Join(workspace, ".beads")}, + {name: "after the pre-RunE rebind", beadsDir: storageBeadsDir}, + } { + resetRepoContextCachesForTest(t) + t.Setenv("BEADS_DIR", state.beadsDir) + assertActiveRepoPath(t, activeRepoPathForRouting(), filepath.Dir(storageBeadsDir), + "BEADS_DIR "+state.name+": a foreign redirected selection binds its storage root, not the CWD repo") + } +} + +// resetRolePathWarningForTest re-arms the once-per-process non-repo warning so +// a test asserting on it does not depend on whether an earlier test in the +// binary already spent it. +func resetRolePathWarningForTest(t *testing.T) { + t.Helper() + old := rolePathNotARepoWarned + rolePathNotARepoWarned = false + t.Cleanup(func() { rolePathNotARepoWarned = old }) +} + +func TestDetectUserRoleForActiveRepoWarnsWhenRolePathIsNotARepo(t *testing.T) { + resetRepoContextCachesForTest(t) + resetRolePathWarningForTest(t) + + // A storage dir outside any git repo: role detection lands on its parent, + // where `git config --get beads.role` still succeeds by reading the user's + // GLOBAL config, so routing.DetectUserRole returns before its own + // "beads.role not configured" notice can fire. The path must not be silent. + storageDir := t.TempDir() + storageBeadsDir := filepath.Join(storageDir, ".beads") + writeTestConfigYAML(t, storageBeadsDir, "") + + t.Chdir(t.TempDir()) + t.Setenv("BEADS_DIR", storageBeadsDir) + setBeadsDirStartupProvenanceForTest(t, true) + + readStderr, writeStderr, err := os.Pipe() + if err != nil { + t.Fatalf("pipe stderr: %v", err) + } + oldStderr := os.Stderr + os.Stderr = writeStderr + t.Cleanup(func() { + os.Stderr = oldStderr + _ = readStderr.Close() + _ = writeStderr.Close() + }) + + // Detect twice: an ID lookup re-runs role detection once per missing ID, + // and the warning must not repeat with it. + for range 2 { + if _, err := detectUserRoleForActiveRepo(); err != nil { + t.Fatalf("detectUserRoleForActiveRepo: %v", err) + } + } + _ = writeStderr.Close() + stderrOutput, readErr := io.ReadAll(readStderr) + if readErr != nil { + t.Fatalf("read stderr: %v", readErr) + } + if n := strings.Count(string(stderrOutput), "is not a git repository"); n != 1 { + t.Fatalf("non-repo role path warned %d times in one process, want exactly once; stderr:\n%s", n, stderrOutput) + } +} + +// unsetRoutingConfigEnvForTest removes every env spelling of the routing keys. +// Blanking them is not enough: GetValueSource counts a set-but-empty variable +// as an env source, viper then answers with the key's default, and the +// defaults for routing.maintainer and routing.contributor are non-empty, so a +// blanked variable would configure a role repo the test never set. +func unsetRoutingConfigEnvForTest(t *testing.T) { + t.Helper() + for _, key := range routingConfigKeys { + suffix := strings.ToUpper(strings.NewReplacer(".", "_", "-", "_").Replace(key)) + for _, name := range []string{"BD_" + suffix, "BEADS_" + suffix} { + t.Setenv(name, "") // registers the restore + if err := os.Unsetenv(name); err != nil { + t.Fatalf("unset %s: %v", name, err) + } + } + } +} + +// TestDetermineAutoRoutedRepoPathDetectsRoleOnlyWhenRoutingReadsIt pins role +// detection to the fully resolved routing config. The fixture makes any +// detection visible: the project is not a git repository, so its role path +// warns, while a global beads.role gives `git config --get` something to fall +// back on. Routing that cannot read the role must leave stderr clean, and the +// legacy contributor.auto_route switch must still detect with routing.mode +// empty. +func TestDetermineAutoRoutedRepoPathDetectsRoleOnlyWhenRoutingReadsIt(t *testing.T) { + planningDir := t.TempDir() + tests := []struct { + name string + config map[string]string + wantRepo string + wantDetect bool + }{ + {name: "routing unset", wantRepo: "."}, + { + name: "explicit mode", + config: map[string]string{"routing.mode": "explicit", "routing.contributor": planningDir}, + wantRepo: ".", + }, + { + name: "auto mode without a role repo", + config: map[string]string{"routing.mode": "auto"}, + wantRepo: ".", + }, + { + name: "auto mode", + config: map[string]string{"routing.mode": "auto", "routing.contributor": planningDir}, + wantRepo: planningDir, + wantDetect: true, + }, + { + name: "legacy contributor.auto_route", + config: map[string]string{"contributor.auto_route": "true", "contributor.planning_repo": planningDir}, + wantRepo: planningDir, + wantDetect: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + home := t.TempDir() + for _, key := range []string{"HOME", "USERPROFILE", "XDG_CONFIG_HOME", "APPDATA"} { + t.Setenv(key, home) + } + if err := os.WriteFile(filepath.Join(home, ".gitconfig"), []byte("[beads]\n\trole = contributor\n"), 0o600); err != nil { + t.Fatalf("write global gitconfig: %v", err) + } + unsetRoutingConfigEnvForTest(t) + + project := t.TempDir() + writeTestConfigYAML(t, filepath.Join(project, ".beads"), "") + t.Chdir(project) + t.Setenv("BEADS_DIR", "") + setBeadsDirStartupProvenanceForTest(t, false) + setChangeDirForTest(t, "") + + initConfigForTest(t) + for key, value := range tt.config { + config.Set(key, value) + } + resetRepoContextCachesForTest(t) + resetRolePathWarningForTest(t) + + var got string + stderr := captureStderr(t, func() { + got, _ = determineAutoRoutedRepoPath(context.Background(), nil) + }) + if got != tt.wantRepo { + t.Errorf("determineAutoRoutedRepoPath() = %q, want %q", got, tt.wantRepo) + } + if detected := strings.Contains(stderr, "is not a git repository"); detected != tt.wantDetect { + t.Errorf("role detected = %v, want %v; stderr:\n%s", detected, tt.wantDetect, stderr) + } + }) + } +} + func TestPrepareSelectedCommandContext_DoesNotMergeCallerConfigForUnsetKeys(t *testing.T) { t.Setenv("BEADS_DOLT_SERVER_DATABASE", "") t.Setenv("BEADS_DOLT_SERVER_PORT", "") diff --git a/cmd/bd/create.go b/cmd/bd/create.go index e124bef67..e65c9ab82 100644 --- a/cmd/bd/create.go +++ b/cmd/bd/create.go @@ -299,12 +299,6 @@ var createCmd = &cobra.Command{ // Explicit --repo flag overrides auto-routing repoPath = repoOverride } else { - // Auto-routing based on user role - userRole, err := routing.DetectUserRole(".") - if err != nil { - debug.Logf("Warning: failed to detect user role: %v\n", err) - } - // Build routing config with backward compatibility for legacy contributor.* keys. // Prefer config.yaml values, but fall back to DB config values set by bd init --contributor. routingMode := getRoutingConfigValue(rootCtx, store, "routing.mode") @@ -328,6 +322,9 @@ var createCmd = &cobra.Command{ ExplicitOverride: repoOverride, } + // Auto-routing based on user role, detected only once the resolved + // config shows routing will read it. + userRole := detectUserRoleForRouting(routingConfig) repoPath = routing.DetermineTargetRepo(routingConfig, userRole, ".") } diff --git a/cmd/bd/envfile_test.go b/cmd/bd/envfile_test.go index 7d9e69e1e..677c68892 100644 --- a/cmd/bd/envfile_test.go +++ b/cmd/bd/envfile_test.go @@ -49,4 +49,49 @@ func TestLoadBeadsEnvFile(t *testing.T) { // Should not panic or error loadBeadsEnvFile("") }) + + // A .env-provided BEADS_DIR is user selection on this broad loader too, not + // only via loadBeadsSelectionEnvFile: that loader early-returns whenever + // BEADS_DB or BD_DB is already exported (loadSelectionEnvironment), and this + // one then imports the same .env line. One .env line must mean one thing. + t.Run("marks selection provenance when .env sets an unset BEADS_DIR", func(t *testing.T) { + dir := t.TempDir() + target := filepath.Join(t.TempDir(), ".beads") + if err := os.WriteFile(filepath.Join(dir, ".env"), []byte("BEADS_DIR="+target+"\n"), 0600); err != nil { + t.Fatal(err) + } + t.Setenv("BEADS_DIR", "") + os.Unsetenv("BEADS_DIR") + setBeadsDirStartupProvenanceForTest(t, false) + + loadBeadsEnvFile(dir) + + if got := os.Getenv("BEADS_DIR"); got != target { + t.Fatalf("BEADS_DIR = %q, want %q", got, target) + } + if !beadsDirProvidedAtStartup { + t.Fatal("a .env-provided BEADS_DIR must record selection provenance, or role detection treats the same .env line as mere discovery") + } + }) + + // The mirror image: prepareSelectedCommandContext rebinds BEADS_DIR for + // every command and then calls this loader, so an already-set BEADS_DIR must + // NOT be read as user selection — internal rebinds are discovery. + t.Run("leaves provenance alone when BEADS_DIR was already set", func(t *testing.T) { + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, ".env"), []byte("BEADS_DIR=/from/env/file\n"), 0600); err != nil { + t.Fatal(err) + } + t.Setenv("BEADS_DIR", "/already/selected") + setBeadsDirStartupProvenanceForTest(t, false) + + loadBeadsEnvFile(dir) + + if got := os.Getenv("BEADS_DIR"); got != "/already/selected" { + t.Fatalf("BEADS_DIR = %q, want the pre-set value to win", got) + } + if beadsDirProvidedAtStartup { + t.Fatal("an internal BEADS_DIR rebind must not be promoted to user selection") + } + }) } diff --git a/cmd/bd/main.go b/cmd/bd/main.go index f4cc8be21..625577fd2 100644 --- a/cmd/bd/main.go +++ b/cmd/bd/main.go @@ -472,7 +472,18 @@ func loadBeadsEnvFile(beadsDir string) { if _, err := os.Stat(envFile); err != nil { return } + // A .env-provided BEADS_DIR is user-authored selection wherever it is + // imported from, not only via loadBeadsSelectionEnvFile: that loader + // early-returns whenever BEADS_DB or BD_DB is already exported + // (loadSelectionEnvironment), and this broad loader then imports the very + // same .env line. Marking provenance here keeps one .env line meaning one + // thing, instead of target-role or CWD-role depending on the caller's + // unrelated BEADS_DB export. + beadsDirWasSet := os.Getenv("BEADS_DIR") != "" _ = gotenv.Load(envFile) + if !beadsDirWasSet && os.Getenv("BEADS_DIR") != "" { + beadsDirProvidedAtStartup = true + } } func logConfigDiscovery(beadsDir, reason string) { @@ -507,6 +518,12 @@ func loadBeadsSelectionEnvFile(beadsDir string) { } if value, ok := pairs[key]; ok && strings.TrimSpace(value) != "" { _ = os.Setenv(key, value) + if key == "BEADS_DIR" { + // A .beads/.env that routes commands via BEADS_DIR is + // user-authored selection, same as exporting the variable + // before running bd; role detection must honor it. + beadsDirProvidedAtStartup = true + } } } } @@ -972,6 +989,22 @@ func resolveChangeDirBeadsDir(path string) (string, error) { return beadsDir, nil } +// beadsDirProvidedAtStartup records whether BEADS_DIR carries user intent: it +// was present in the environment when the process started, or a .beads/.env +// selector file set it (loadBeadsSelectionEnvFile). Internal rebinds set +// BEADS_DIR for every command (prepareSelectedCommandContext, +// applyChangeDirSelection), so by the time role detection runs, the live env +// var can no longer say who set it. +var beadsDirProvidedAtStartup = os.Getenv("BEADS_DIR") != "" + +// explicitBeadsSelection reports whether the active beads project was selected +// by the user (bd -C, or BEADS_DIR exported before bd ran) rather than +// discovered from the CWD — including discovery through a .beads/redirect, +// which relocates storage but must not move role detection off the workspace. +func explicitBeadsSelection() bool { + return beadsDirProvidedAtStartup || strings.TrimSpace(changeDir) != "" +} + func applyChangeDirSelection() error { if strings.TrimSpace(changeDir) == "" { return nil diff --git a/cmd/bd/routing_read.go b/cmd/bd/routing_read.go index fedc43bb1..0d21e9f48 100644 --- a/cmd/bd/routing_read.go +++ b/cmd/bd/routing_read.go @@ -49,11 +49,6 @@ func getRoutingConfigValue(ctx context.Context, store storage.DoltStorage, key s } func determineAutoRoutedRepoPath(ctx context.Context, store storage.DoltStorage) (string, routing.RoutingRule) { - userRole, err := routing.DetectUserRole(".") - if err != nil { - debug.Logf("Warning: failed to detect user role: %v\n", err) - } - var dbValues map[string]string if store != nil { all, allErr := store.GetAllConfig(ctx) @@ -89,6 +84,7 @@ func determineAutoRoutedRepoPath(ctx context.Context, store storage.DoltStorage) ExplicitOverride: "", } + userRole := detectUserRoleForRouting(routingConfig) return routing.DetermineTargetRepoWithRule(routingConfig, userRole, ".") } diff --git a/cmd/bd/routing_read_test.go b/cmd/bd/routing_read_test.go index ef9d571b5..c6b6c4a35 100644 --- a/cmd/bd/routing_read_test.go +++ b/cmd/bd/routing_read_test.go @@ -9,6 +9,8 @@ import ( "path/filepath" "testing" + "github.com/steveyegge/beads/internal/beads" + "github.com/steveyegge/beads/internal/git" "github.com/steveyegge/beads/internal/routing" ) @@ -42,6 +44,10 @@ func TestDetermineAutoRoutedRepoPath_ContributorToPlanning(t *testing.T) { if err := os.Chdir(repoDir); err != nil { t.Fatalf("chdir repoDir: %v", err) } + // Role detection reads the process-wide RepoContext cache, which an + // earlier test in this binary may have built for its own, now-deleted + // repo. Rebuild it from repoDir. + resetRepoContextCachesForTest(t) got, rule := determineAutoRoutedRepoPath(ctx, sourceStore) if got != planningDir { @@ -52,6 +58,61 @@ func TestDetermineAutoRoutedRepoPath_ContributorToPlanning(t *testing.T) { } } +func TestDetermineAutoRoutedRepoPath_UsesSelectedBeadsDirRole(t *testing.T) { + initConfigForTest(t) + // Viper binds BEADS_ROUTING_MODE / BD_ROUTING_MODE onto the routing.mode + // key (internal/config), which outranks the routing.mode=auto this test + // writes into the store. Hosts that export either var (developer shells and + // agent runtimes do) would otherwise read routing.mode=off and get "." back. + t.Setenv("BEADS_ROUTING_MODE", "") + t.Setenv("BD_ROUTING_MODE", "") + beads.ResetCaches() + git.ResetCaches() + t.Cleanup(func() { + beads.ResetCaches() + git.ResetCaches() + }) + + tmpDir := t.TempDir() + callerDir := filepath.Join(tmpDir, "caller") + repoDir := filepath.Join(tmpDir, "repo") + planningDir := filepath.Join(tmpDir, "planning") + + runCmd(t, tmpDir, "git", "init", callerDir) + runCmd(t, tmpDir, "git", "init", repoDir) + runCmd(t, repoDir, "git", "config", "beads.role", "contributor") + + sourceStore := newTestStoreIsolatedDB(t, filepath.Join(repoDir, ".beads", "beads.db"), "src") + ctx := context.Background() + + if err := sourceStore.SetConfig(ctx, "routing.mode", "auto"); err != nil { + t.Fatalf("failed to set routing.mode: %v", err) + } + if err := sourceStore.SetConfig(ctx, "routing.contributor", planningDir); err != nil { + t.Fatalf("failed to set routing.contributor: %v", err) + } + + oldWD, err := os.Getwd() + if err != nil { + t.Fatalf("os.Getwd failed: %v", err) + } + t.Cleanup(func() { + _ = os.Chdir(oldWD) + }) + if err := os.Chdir(callerDir); err != nil { + t.Fatalf("chdir callerDir: %v", err) + } + t.Setenv("BEADS_DIR", filepath.Join(repoDir, ".beads")) + // This test simulates a caller who exported BEADS_DIR before bd started; + // selection provenance is captured at process start, so pin it explicitly. + setBeadsDirStartupProvenanceForTest(t, true) + + got, _ := determineAutoRoutedRepoPath(ctx, sourceStore) + if got != planningDir { + t.Fatalf("determineAutoRoutedRepoPath() = %q, want %q", got, planningDir) + } +} + func TestDetermineAutoRoutedRepoPath_MaintainerToPlanning(t *testing.T) { initConfigForTest(t) @@ -82,6 +143,10 @@ func TestDetermineAutoRoutedRepoPath_MaintainerToPlanning(t *testing.T) { if err := os.Chdir(repoDir); err != nil { t.Fatalf("chdir repoDir: %v", err) } + // Role detection reads the process-wide RepoContext cache, which an + // earlier test in this binary may have built for its own, now-deleted + // repo. Rebuild it from repoDir. + resetRepoContextCachesForTest(t) got, rule := determineAutoRoutedRepoPath(ctx, sourceStore) if got != planningDir { @@ -165,6 +230,10 @@ func TestOpenRoutedReadStore_ContributorRouting(t *testing.T) { if err := os.Chdir(repoDir); err != nil { t.Fatalf("chdir repoDir: %v", err) } + // Role detection reads the process-wide RepoContext cache, which an + // earlier test in this binary may have built for its own, now-deleted + // repo. Rebuild it from repoDir. + resetRepoContextCachesForTest(t) routedStore, routed, rule, err := openRoutedReadStore(ctx, sourceStore) if err != nil { diff --git a/cmd/bd/routing_role.go b/cmd/bd/routing_role.go new file mode 100644 index 000000000..cbd5a3912 --- /dev/null +++ b/cmd/bd/routing_role.go @@ -0,0 +1,190 @@ +package main + +import ( + "fmt" + "os" + "path/filepath" + "strings" + + "github.com/steveyegge/beads/internal/beads" + "github.com/steveyegge/beads/internal/debug" + "github.com/steveyegge/beads/internal/routing" +) + +// activeRepoPathForRouting returns the repository whose beads.role governs +// routing for this command. +// +// NOTE: internal/beads owns a second, independent role oracle, +// RepoContext.Role() (internal/beads/context.go), which short-circuits to +// Contributor whenever the beads dir is redirected or external. It is a known +// divergence from the doctrine below — `bd context` can print Contributor while +// `bd create` routes with the selected repo's beads.role — that pre-dates this +// helper; unifying the two oracles is out of scope here. +func activeRepoPathForRouting() string { + rc, err := beads.GetRepoContext() + if err != nil || rc == nil || rc.RepoRoot == "" { + if beadsDir := beads.FindBeadsDir(); beadsDir != "" { + return logRolePath("beads-dir-parent", filepath.Dir(beadsDir), false) + } + return logRolePath("cwd-no-repo-context", ".", false) + } + + // Two ways BeadsDir can resolve outside the CWD's repo, with opposite + // answers for role detection: + // - explicit selection (bd -C, or the user exported BEADS_DIR before + // bd ran): the user chose that beads project, so its repo root is + // the active repo. This is the GH#4242 fix. + // - a .beads/redirect followed from the CWD workspace: the redirect + // relocates STORAGE, not the project — beads.role belongs to the + // workspace repo the user is operating in, not to wherever its + // data happens to live (which may not even be a git repo). + // The live BEADS_DIR env var cannot make this distinction: normal + // command startup (prepareSelectedCommandContext) sets it to the + // resolved target for every command, redirects included, so only + // startup provenance separates user selection from discovery. + if explicitBeadsSelection() { + // A selection is not automatically a selection OF the storage root. + // Every resolver follows a .beads/redirect before this guard runs + // (ExplicitBeadsDir, FindBeadsDir, and -C's own resolution), so an + // explicit selection of a REDIRECTED workspace arrives here already + // rewritten to the storage root — the same misroute GH#4242 reported, + // one resolution step further in. Recover the workspace the user + // actually named before honoring the selection. + if workspace := selectedWorkspaceRepoRoot(rc); workspace != "" { + return logRolePath("explicit-selection-through-redirect", workspace, rc.IsRedirected) + } + return logRolePath("explicit-selection", rc.RepoRoot, rc.IsRedirected) + } + if !rc.IsRedirected { + return logRolePath("cwd-repo", rc.RepoRoot, false) + } + if rc.CWDRepoRoot != "" { + return logRolePath("redirect-workspace", rc.CWDRepoRoot, true) + } + return logRolePath("cwd-redirected-no-workspace-repo", ".", true) +} + +// selectedWorkspaceRepoRoot returns the repo root of the workspace the user +// explicitly selected, but only when that selection resolved THROUGH a +// .beads/redirect and so no longer names the project that was selected. It +// returns "" when the selection genuinely names its own project's storage, in +// which case rc.RepoRoot is already the right answer and must be kept — that is +// the GH#4242 fix this helper must not undo. +func selectedWorkspaceRepoRoot(rc *beads.RepoContext) string { + // `bd -C dir`: the selection is the -C argument, and it must be read + // PRE-redirect. applyChangeDirSelection has already rewritten BEADS_DIR to + // the resolved target, and GetRedirectInfo would answer about the process + // CWD — an unrelated directory under `bd -C` — so ask about dir itself. + // GetRedirectInfoFrom is documented for exactly this `bd -C dir` case + // (GH#5509) and deliberately does not consult BEADS_DIR. + if dir := strings.TrimSpace(changeDir); dir != "" { + if !beads.GetRedirectInfoFrom(dir).IsRedirected { + return "" + } + return beads.RepoRootFor(dir) + } + + // Exported BEADS_DIR: the selection is vacuous when it merely names the CWD + // workspace's own redirect, and it is vacuous under both spellings of it, + // because ExplicitBeadsDir follows the redirect: BEADS_DIR=/.beads + // and BEADS_DIR=/.beads both arrive here as the storage dir (the + // bd-wayc3 tooling shape). + // + // "Own" is the redirect discovery finds from the CWD with BEADS_DIR ignored, + // which is the redirect that keeps role detection on the CWD workspace + // when BEADS_DIR is unset. GetRedirectInfo cannot stand in for it: when the + // CWD repo root's .beads holds no redirect it falls back to BEADS_DIR itself. + // That masks a workspace nested below its repo root, or a git worktree that + // inherits its main checkout's redirect, since the pre-RunE rebind + // (prepareSelectedCommandContext) has already replaced BEADS_DIR with the + // storage dir, and it would let a selected FOREIGN workspace vouch for its + // own redirect. A foreign redirected selection therefore falls through to + // rc.RepoRoot, its storage root. Binding the foreign workspace itself would + // need the raw startup BEADS_DIR, which nothing keeps; that is a known + // limit, not an oversight. + own := beads.GetDiscoveredRedirectInfo() + if !own.IsRedirected || !sameDirPath(beads.ExplicitBeadsDir(), own.TargetDir) { + return "" + } + return rc.CWDRepoRoot +} + +// sameDirPath reports whether two directory paths name the same directory, +// tolerating the relative/absolute and symlink differences the various beads-dir +// resolvers introduce (t.TempDir hands back symlinked paths on macOS, and git +// reports physical ones). +func sameDirPath(a, b string) bool { + if a == "" || b == "" { + return false + } + return canonicalDirPath(a) == canonicalDirPath(b) +} + +func canonicalDirPath(dir string) string { + abs, err := filepath.Abs(dir) + if err != nil { + abs = dir + } + if resolved, err := filepath.EvalSymlinks(abs); err == nil { + abs = resolved + } + return filepath.Clean(abs) +} + +// logRolePath records which branch answered, then returns the path unchanged. +// A GH#4242-class misroute report hinges on knowing which of the six sources +// role detection used, and the downstream "failed to detect user role" warning +// fires on none of them. +func logRolePath(branch, path string, redirected bool) string { + debug.Logf("role detection path: %s -> %s (explicit=%v redirected=%v)\n", + branch, path, explicitBeadsSelection(), redirected) + return path +} + +// rolePathNotARepoWarned limits warnIfRolePathIsNotARepo to one warning per +// process: an ID lookup falls back to auto-routing once per missing ID +// (resolveViaAutoRouting), and every fallback re-runs role detection. +var rolePathNotARepoWarned bool + +// warnIfRolePathIsNotARepo warns when role detection is about to read beads.role +// from a path that is not inside a git repository. `git config --get` still +// succeeds there by falling back to the user's GLOBAL config, and +// routing.DetectUserRole returns on that first success, so its own "beads.role +// not configured" notice never fires: without this warning the command would be +// routed with the global role and no diagnostic on any stream. +func warnIfRolePathIsNotARepo(repoPath string) { + if rolePathNotARepoWarned || beads.RepoRootFor(repoPath) != "" { + return + } + rolePathNotARepoWarned = true + fmt.Fprintf(os.Stderr, "warning: role detection path %q is not a git repository;\n", repoPath) //nolint:gosec // G705: stderr, not a browser context + fmt.Fprintln(os.Stderr, " beads.role will be read from your global git config, which may not match this project.") + fmt.Fprintln(os.Stderr, " Fix: set beads.role in the project you intend to route to,") + fmt.Fprintln(os.Stderr, " or select that project explicitly with bd -C .") +} + +func detectUserRoleForActiveRepo() (routing.UserRole, error) { + repoPath := activeRepoPathForRouting() + warnIfRolePathIsNotARepo(repoPath) + return routing.DetectUserRole(repoPath) +} + +// detectUserRoleForRouting returns the user role for the routing decision cfg +// describes, but detects it only when that decision can depend on it +// (cfg.UsesUserRole), so cfg must already be fully resolved, legacy +// contributor.* fallbacks included. Detection runs git and can print the +// non-repo warning above or routing.DetectUserRole's "beads.role not +// configured" notice; neither belongs on a command whose routing never reads +// the role, which is every command while routing is off (the default). This is +// also what makes `routing.mode explicit` disable role detection entirely, as +// docs/multi-agent/routing.md promises. +func detectUserRoleForRouting(cfg *routing.RoutingConfig) routing.UserRole { + if !cfg.UsesUserRole() { + return "" + } + userRole, err := detectUserRoleForActiveRepo() + if err != nil { + debug.Logf("Warning: failed to detect user role: %v\n", err) + } + return userRole +} diff --git a/internal/beads/beads.go b/internal/beads/beads.go index ff04a75a9..2629ba508 100644 --- a/internal/beads/beads.go +++ b/internal/beads/beads.go @@ -365,6 +365,17 @@ func GetRedirectInfo() RedirectInfo { return redirectInfoFor(findLocalBdsDirInRepo(), findLocalBeadsDir) } +// GetDiscoveredRedirectInfo is GetRedirectInfo without the BEADS_DIR override: +// it reports the redirect that discovery finds from the cwd, the one the cwd's +// own workspace holds. GetRedirectInfo cannot answer that once BEADS_DIR is +// set, because when the repo root's .beads holds no redirect it checks +// BEADS_DIR itself. A workspace redirect nested below the repo root or +// inherited by a git worktree is then masked, and a BEADS_DIR naming another +// workspace's redirected .beads reports that redirect as if the cwd held it. +func GetDiscoveredRedirectInfo() RedirectInfo { + return redirectInfoFor(findLocalBdsDirInRepo(), findDiscoveredLocalBeadsDir) +} + // GetRedirectInfoFrom is GetRedirectInfo for the workspace at dir rather than // the process cwd: the .beads directory at dir's git repository root is // checked for a redirect first, then the nearest .beads walking up from dir. @@ -475,7 +486,12 @@ func findLocalBeadsDir() string { if beadsDir := os.Getenv("BEADS_DIR"); beadsDir != "" { return canonicalizeBeadsDirPath(beadsDir) } + return findDiscoveredLocalBeadsDir() +} +// findDiscoveredLocalBeadsDir is findLocalBeadsDir without the BEADS_DIR +// override: the local .beads directory discovery finds from the cwd. +func findDiscoveredLocalBeadsDir() string { // For worktrees, check worktree-local redirect first (per-worktree override). // Returns the raw worktree .beads dir (not the resolved target) since // findLocalBeadsDir doesn't follow redirects — callers use FollowRedirect. diff --git a/internal/beads/beads_coverage_test.go b/internal/beads/beads_coverage_test.go index 87b6d6f5e..5f30f2e5e 100644 --- a/internal/beads/beads_coverage_test.go +++ b/internal/beads/beads_coverage_test.go @@ -485,6 +485,64 @@ func TestGetRedirectInfoFrom(t *testing.T) { } } +// TestGetDiscoveredRedirectInfo pins the BEADS_DIR-free redirect probe on the +// two shapes where GetRedirectInfo's BEADS_DIR fallback answers for the wrong +// workspace. A redirect the cwd reaches only by walking up past a repo root +// without .beads is masked once BEADS_DIR names the store. Another workspace's +// redirected .beads named in BEADS_DIR is reported as if the cwd held it. +func TestGetDiscoveredRedirectInfo(t *testing.T) { + t.Cleanup(git.ResetCaches) + tmpDir := t.TempDir() + tmpDir, _ = filepath.EvalSymlinks(tmpDir) + + storeDir := filepath.Join(tmpDir, "store", ".beads") + repo := filepath.Join(tmpDir, "repo") + nested := filepath.Join(repo, "sub") + other := filepath.Join(tmpDir, "other") + for _, dir := range []string{storeDir, filepath.Join(nested, ".beads"), filepath.Join(other, ".beads")} { + if err := os.MkdirAll(dir, 0755); err != nil { + t.Fatal(err) + } + } + // Target must contain a recognizable database for FollowRedirect to + // honor the redirect (gastownhall/beads#4692 guard). + if err := os.WriteFile(filepath.Join(storeDir, "beads.db"), []byte{}, 0644); err != nil { + t.Fatal(err) + } + for _, dir := range []string{nested, other} { + if err := os.WriteFile(filepath.Join(dir, ".beads", "redirect"), []byte(storeDir+"\n"), 0644); err != nil { + t.Fatal(err) + } + } + cmd := exec.Command("git", "init", "-q") + cmd.Dir = repo + if err := cmd.Run(); err != nil { + t.Skipf("git not available: %v", err) + } + + // cwd = nested workspace, BEADS_DIR = the store it redirects to. + t.Chdir(nested) + git.ResetCaches() + t.Setenv("BEADS_DIR", storeDir) + if GetRedirectInfo().IsRedirected { + t.Fatal("control: a BEADS_DIR naming the store must mask the nested redirect from GetRedirectInfo") + } + if info := GetDiscoveredRedirectInfo(); !info.IsRedirected || info.TargetDir != storeDir { + t.Errorf("GetDiscoveredRedirectInfo() in the nested workspace = %+v, want redirect to %q", info, storeDir) + } + + // cwd = repo root without .beads, BEADS_DIR = another workspace's redirect. + t.Chdir(repo) + git.ResetCaches() + t.Setenv("BEADS_DIR", filepath.Join(other, ".beads")) + if !GetRedirectInfo().IsRedirected { + t.Fatal("control: GetRedirectInfo must fall back to a redirected BEADS_DIR") + } + if info := GetDiscoveredRedirectInfo(); info.IsRedirected { + t.Errorf("GetDiscoveredRedirectInfo() with another workspace's BEADS_DIR = %+v, want no redirect", info) + } +} + // TestRepoLocalBeadsDirCanonicalizesRepoRoot pins both halves of the shared // repo-local tier's contract (gastownhall/beads#5509): the repo root is // canonicalized before it is joined, so the From locator's raw diff --git a/internal/beads/context.go b/internal/beads/context.go index dc0b1514b..63c63394c 100644 --- a/internal/beads/context.go +++ b/internal/beads/context.go @@ -348,6 +348,22 @@ func repoRootForBeadsDir(beadsDir string) string { return filepath.Dir(beadsDir) } +// RepoRootFor returns the git repository root containing dir, or "" when dir is +// not inside a git repository (or when dir is empty). An empty result therefore +// answers two questions at once: callers that need a path-scoped repo root get +// it, and callers that only need to know whether a path is a repository at all +// can test for "". +func RepoRootFor(dir string) string { + if dir == "" { + return "" + } + repoRoot, err := getRepoRootFromPath(dir) + if err != nil { + return "" + } + return repoRoot +} + // getRepoRootFromPath returns the git repository root for a given path. func getRepoRootFromPath(path string) (string, error) { cmd := exec.Command("git", "-C", path, "rev-parse", "--show-toplevel") diff --git a/internal/routing/routing.go b/internal/routing/routing.go index e83019633..8f90d5101 100644 --- a/internal/routing/routing.go +++ b/internal/routing/routing.go @@ -216,7 +216,8 @@ func DetermineTargetRepoWithRule(config *RoutingConfig, userRole UserRole, repoP return config.ExplicitOverride, RuleExplicitOverride } - // Auto mode: route based on user role + // Auto mode: route based on user role. UsesUserRole mirrors this clause; + // change the two together. if config.Mode == "auto" { if userRole == Maintainer && config.MaintainerRepo != "" { return config.MaintainerRepo, RuleMaintainer @@ -235,6 +236,16 @@ func DetermineTargetRepoWithRule(config *RoutingConfig, userRole UserRole, repoP return ".", RuleNone } +// UsesUserRole reports whether DetermineTargetRepoWithRule's answer for c can +// depend on the user role: only auto mode consults it, only when no explicit +// override wins first, and only when a role-specific repo is configured. +// Callers use it to skip role detection, which runs git and can print +// diagnostics, when the detected role would be discarded. +func (c *RoutingConfig) UsesUserRole() bool { + return c.ExplicitOverride == "" && c.Mode == "auto" && + (c.MaintainerRepo != "" || c.ContributorRepo != "") +} + // ExpandPath expands ~ to home directory and resolves relative paths to absolute. // Returns the original path if expansion fails. func ExpandPath(path string) string { diff --git a/internal/routing/routing_test.go b/internal/routing/routing_test.go index 338b172fe..05cbadb45 100644 --- a/internal/routing/routing_test.go +++ b/internal/routing/routing_test.go @@ -89,6 +89,46 @@ func TestDetermineTargetRepo(t *testing.T) { } } +// TestUsesUserRoleMatchesDetermineTargetRepo holds UsesUserRole to the rules +// DetermineTargetRepoWithRule actually applies, in both directions: where it +// reports false, every role (an undetected one included) must route the same +// way, so callers may skip detection; where it reports true, some role must +// change the answer, so detection is never skipped while routing would use it. +func TestUsesUserRoleMatchesDetermineTargetRepo(t *testing.T) { + type answer struct { + repo string + rule RoutingRule + } + for _, mode := range []string{"", "auto", "explicit"} { + for mask := 0; mask < 1<<4; mask++ { + config := &RoutingConfig{Mode: mode} + if mask&1 != 0 { + config.ExplicitOverride = "override-repo" + } + if mask&2 != 0 { + config.MaintainerRepo = "maintainer-repo" + } + if mask&4 != 0 { + config.ContributorRepo = "contributor-repo" + } + if mask&8 != 0 { + config.DefaultRepo = "default-repo" + } + + answers := map[answer]bool{} + for _, role := range []UserRole{"", Maintainer, Contributor} { + repo, rule := DetermineTargetRepoWithRule(config, role, ".") + answers[answer{repo, rule}] = true + } + roleChangesAnswer := len(answers) > 1 + if got := config.UsesUserRole(); got != roleChangesAnswer { + t.Errorf("UsesUserRole() = %v for %+v, want %v (answers by role: %v)", + got, *config, roleChangesAnswer, answers) + } + } + } +} + func TestDetectUserRole_Fallback(t *testing.T) { // Test fallback behavior when git is not available - local projects default to maintainer role, err := DetectUserRole("/nonexistent/path/that/does/not/exist")