* fix(routing): bind role detection to the -C target repo (re-port of #4242) Role detection previously called routing.DetectUserRole(".") directly, which resolves against the caller's CWD rather than the repo selected via `bd -C <target>` (BEADS_DIR-driven). This meant auto-routing and role-based behavior could silently apply the wrong repo's role when invoked with -C. Introduce activeRepoPathForRouting(), which prefers beads.GetRepoContext().RepoRoot (the BEADS_DIR-bound target) and falls back to the parent of beads.FindBeadsDir(), then to ".". Route role detection in cmd/bd/create.go and cmd/bd/routing_read.go through the new detectUserRoleForActiveRepo() helper instead of calling routing.DetectUserRole(".") directly. Faithful re-port of gastownhall/beads#4242 (osamu2001) onto current main: determineAutoRoutedRepoPath's signature changed to (string, routing.RoutingRule) since the PR was opened (89a4d6ed8/ #4866), so the one-line call-site change re-applies inside the new function body, and the new routing_read_test.go coverage destructures both return values. All other ported content (routing_role.go, context_binding_test.go, the create.go call site) is unchanged from the original PR. Co-authored-by: Osamu Okano <okano.osamu@gmail.com> Agent-Signature: claude-fable-5-high on behalf of maphew * test(routing): fix the sole CI failure in the re-ported #4242 test TestActiveRepoPathForRoutingFallsBackToBeadsDirParent created its fake project under this repo's tree, so beads.GetRepoContext() resolved a real repo root from the caller's CWD and the FindBeadsDir fallback the test claimed to cover was never exercised — an unreachable assertion that CI reproduced as the PR's only failing test. Rewrite it to target a directory that is genuinely outside any git repo: targetDir now comes from t.TempDir() (its .beads/config.yaml still written via writeTestConfigYAML), and the caller CWD is also moved to a fresh t.TempDir() via t.Chdir() so GetRepoContext() can't resolve through the CWD either. Both resolve under os.TempDir(), which internal/beads/context.go's isPathInSafeBoundary explicitly admits, so this stays safe under the existing boundary check. This makes safeTempDirForContextTest (the manual git-repo-relative temp dir helper the original test used to dodge the same problem) dead code; delete it. Co-authored-by: Osamu Okano <okano.osamu@gmail.com> Agent-Signature: claude-fable-5-high on behalf of maphew * fix(routing): a .beads/redirect must not move role detection to the storage root Cross-vendor review of e8600e732 caught a regression the re-port would have introduced for redirect users: with a .beads/redirect pointing at storage outside any git repo, RepoContext.RepoRoot is the redirect target's parent, so beads.role would be read from the storage location instead of the workspace repo — silently bypassing contributor routing. The two external-BeadsDir shapes now get their opposite answers explicitly: an explicit BEADS_DIR selection (what bd -C plumbs) binds role detection to the selected project (the GH#4242 fix), while a followed redirect keeps it on the CWD workspace repo (pre-existing semantics — a redirect relocates storage, not the project). Mutation-tested: with the guard removed, the new test fails by resolving to the storage root. Co-authored-by: Osamu Okano <okano.osamu@gmail.com> Agent-Signature: claude-fable-5-high on behalf of maphew * fix(routing): read BEADS_DIR selection provenance at startup, not the live env var The self-review on this PR found a startup-path gap: rootCmd's PersistentPreRunE calls prepareSelectedCommandContext for every command, which sets BEADS_DIR to the resolved target — redirects included. By the time role detection ran, activeRepoPathForRouting's os.Getenv("BEADS_DIR") check was therefore always true, classifying a plain .beads/redirect as explicit selection and binding beads.role to the storage root instead of the workspace repo. Capture whether BEADS_DIR was present in the environment at process start, and treat selection as explicit only for that case or a -C flag. The new TestActiveRepoPathForRoutingSurvivesStartupRebindAcrossRedirect goes through the real startup rebind with a real redirect and fails on the previous logic; the two tests that simulate a caller-exported BEADS_DIR now pin their provenance explicitly. Agent-Signature: claude-fable-5-high on behalf of maphew * fix(routing): .env-provided BEADS_DIR is user selection, mark its provenance Cross-vendor review of the previous commit caught a regression it would have introduced: loadBeadsSelectionEnvFile intentionally lets a project's .beads/.env route commands via BEADS_DIR, and that selection happens after the process-start snapshot. Flip the provenance flag when the selector loader sets BEADS_DIR, so .env routing keeps binding role detection to the selected project. TestActiveRepoPathForRoutingHonorsEnvFileSelection pins it end to end through loadSelectionEnvironment. Agent-Signature: claude-fable-5-high on behalf of maphew * test(routing): make the BeadsDir-parent fallback test order-robust on macOS The macOS CI leg failed on /private/var vs /var: the test asserted a raw string path while resolution can hand back the canonicalized spelling of the same directory depending on which branch wins under test ordering. Compare through EvalSymlinks like the sibling redirect tests, and pin selection provenance in the two tests that had not declared theirs. Agent-Signature: claude-fable-5-high on behalf of maphew * ci: retrigger - dolt-install/download infra outage (curl 56/503) killed 4 jobs Agent-Signature: claude-fable-5-high on behalf of maphew * build(bazel): enumerate cmd/bd/routing_role.go in bd_lib srcs The PR adds cmd/bd/routing_role.go, whose detectUserRoleForActiveRepo is called from create.go and routing_read.go. cmd/bd/BUILD.bazel lists go_library srcs explicitly, so the unenumerated new file broke the Bazel library compile: cmd/bd/create.go:303:21: undefined: detectUserRoleForActiveRepo cmd/bd/routing_read.go:52:19: undefined: detectUserRoleForActiveRepo Generated by `bazel run //:gazelle` (one srcs row, idempotent; no deps row owed because the library already carries internal/beads and internal/routing). Base parity at89348699b0was 336/336 non-test .go files enumerated in cmd/bd, so the gap was PR-introduced, not pre-existing. * fix(routing): bind role to the selected workspace across a .beads/redirect Maintainer review fixup for the adopted PR (review iterations 1 to 3). Iteration 1 addressed the one gating major plus both minors and both nits from its review synthesis. Iteration 2 addressed the major, the minor and the nit that the next synthesis raised against that fixup, and iteration 3 addresses the minor and the nit raised against iteration 2; see "Review iteration 2" and "Review iteration 3" below. The major: routing_role.go ordered its guard `explicitBeadsSelection() || !rc.IsRedirected`, but every beads-dir resolver follows a .beads/redirect before that guard can run (ExplicitBeadsDir via FollowRedirect, FindBeadsDir, and -C's own resolution). So an explicit selection of a REDIRECTED workspace arrived already rewritten to the storage root, short-circuited the redirect doctrine the PR had just written, and bound beads.role to wherever the DATA lives — the same misroute GH#4242 reported, one resolution step further in. Worse, it was silent: `git config --get beads.role` succeeds outside a repo by reading GLOBAL config, and routing.DetectUserRole returns on that first success, so its own "beads.role not configured" notice never fired and a contributor workspace could be routed with the user's global role with no diagnostic on any stream. The remedy has to be anchored per shape, because the two selection shapes carry the pre-redirect directory in different places: - `bd -C <dir>`: applyChangeDirSelection has already rewritten BEADS_DIR to the resolved target, so only the -C argument still names the chosen project. CWD-anchored GetRedirectInfo() cannot see this case at all — under -C the CWD is some unrelated directory — so this arm asks GetRedirectInfoFrom(dir), which is documented for exactly this case (GH#5509) and deliberately does not consult BEADS_DIR. - exported BEADS_DIR: here the CWD *is* the selected workspace, so the CWD-anchored probe is the correct one. The selection is vacuous when it merely names that workspace's own redirect, under both spellings of it: BEADS_DIR=<workspace>/.beads and BEADS_DIR=<storage>/.beads both arrive as the storage dir (the bd-wayc3 tooling shape), so both fall through to rc.CWDRepoRoot. An explicit selection of a genuinely different, non-redirected project still wins — that is the GH#4242 fix itself, and a control test pins it. Also in this commit: - A role path that is not a git repository now warns instead of quietly inheriting global beads.role (new beads.RepoRootFor answers both "what is the repo root for this dir" and "is this a repo at all"). - A .env-provided BEADS_DIR records selection provenance on the broad loader too, not only via loadBeadsSelectionEnvFile. That loader early-returns whenever BEADS_DB or BD_DB is already exported, and loadBeadsEnvFile then imports the same .env line, so one .env line meant target-role or CWD-role depending on the caller's unrelated BEADS_DB export. Internal rebinds are unaffected: the marking is conditional on BEADS_DIR having been unset, which is what separates user selection from prepareSelectedCommandContext's per-command rebind. - The four-way role-path choice is logged via debug.Logf, since the downstream "failed to detect user role" warning fires on none of those branches. - The PR's new routing test neutralizes BEADS_ROUTING_MODE / BD_ROUTING_MODE, which viper binds onto the routing.mode key and which reds the test on any host that exports them. - routing_role.go now cross-references RepoContext.Role(), the second, known-divergent role oracle in internal/beads. No behavior change there. Tests: the explicit x redirect cell was the one combination the PR's new tests left empty. Both probe shapes land as tests, plus the `bd -C <redirected-ws>` shape, a non-redirected -C control, the non-repo warning, and both provenance polarities. Each new pin was verified to FAIL against the pre-fix code. Review iteration 2: - Major: the non-repo warning above ran inside detectUserRoleForActiveRepo, which create.go and determineAutoRoutedRepoPath called before resolving the routing config. Routing is off by default and only auto mode reads the role, so in any non-git beads project every bd create/list/ready printed a 4-line warning about a role nothing used. The leak also broke six TestParity* characterization tests at the iteration-1 head: CreateHumanOutput, CreateOnOccupiedIDRefuses, CreateParentNotFoundExits1, CreateMissingDepTargetIsFatal, CreateJSONErrorShape and ReopenErrorExits1Silently. Detection now runs only when the fully resolved config can use its answer: new RoutingConfig.UsesUserRole (auto mode, no explicit override, a role-specific repo configured) gates the new detectUserRoleForRouting, which both call sites invoke after building the config, so the legacy contributor.auto_route=true fallback to auto counts where a raw routing.mode check would miss it. Side effect: routing's own GH#2950 "beads.role not configured" notice is also skipped when routing cannot use the role, as docs/multi-agent/routing.md already promises when it calls `routing.mode explicit` "disabling role detection entirely". - Minor: for an exported BEADS_DIR, selectedWorkspaceRepoRoot called the selection vacuous when the CWD-anchored GetRedirectInfo reported a redirect to it. With no redirect in the CWD repo, GetRedirectInfo falls back to the raw BEADS_DIR, so a FOREIGN redirected workspace vouched for its own redirect and the CWD repo's role was bound. The check now also requires the redirect to sit in the CWD repo's own .beads (RedirectInfo.LocalDir). A foreign redirected selection falls through to its storage root, which is the answer a live command already reaches after the pre-RunE rebind, so unit and command behavior agree. Binding the foreign workspace itself would need the raw startup BEADS_DIR, which nothing keeps; the routing_role.go comment records that limit. - Nit: the non-repo warning prints at most once per process. An ID lookup falls back to auto-routing once per missing ID, and each fallback re-ran detection. - Test isolation: the PR makes role detection read the process-wide beads.GetRepoContext() cache, a sync.Once. Three existing tests chdir between temp repos without resetting it and so read beads.role from an earlier test's deleted repo: TestResolveCloseTargets/ contributor_mixed_local_and_routed, TestDetermineAutoRoutedRepoPath_ContributorToPlanning and TestOpenRoutedReadStore_ContributorRouting fail in a broad cmd/bd run at86b8abff3fand 8dbfc6c721 and pass at base89348699b0. The failure is order-dependent, and the tests skip without a Dolt test server. Each now rebuilds the cache after its chdir, as does the MaintainerToPlanning sibling, which has the same exposure. Iteration-2 tests: a property test pins UsesUserRole to DetermineTargetRepoWithRule (true exactly when the answer varies by role, across unset/auto/explicit modes and every override and repo combination). A table test covers routing unset, explicit mode, auto without a role repo, auto, and legacy auto_route. Two more cover the foreign redirected BEADS_DIR cell and repeated detection (the once-guard). Each pin was mutation-checked: dropping the gate, gating on the raw mode, or dropping the LocalDir guard, the once-guard, the role-repo clause or the override clause turns a test red. Validated (iteration 1): gofmt, go build ./..., go vet ./cmd/bd/ ./internal/beads/, focused go test over cmd/bd role/routing/envfile/context tests and ./internal/beads/ ./internal/routing/, gazelle (0 srcs rows owed), and bazel build //cmd/bd:bd_lib //internal/beads:beads. Validated (iteration 2): gofmt, git diff --check, go build ./..., go vet ./cmd/bd/ ./internal/routing/ ./internal/beads/ with and without cgo, golangci-lint v2.10.1 --new-from-rev=HEAD on cmd/bd and internal/routing (0 issues), go test ./internal/routing/ ./internal/beads/, and a broad cmd/bd routing/role/redirect/context/Parity run. The only reds on this host, TestInitRedirect/RedirectCreatesDBInTarget, TestBareParentWorktreeCoreCommandsWithoutRedirect and TestServeIssueRolesComeFromBeneathTheHookDecorator, fail the same way at base89348699b0. No files were added and the only new import is stdlib, so no BUILD.bazel change is owed. Review iteration 3: - Minor: the iteration-2 guard counted a redirect as the CWD workspace's own only when it sat in the CWD git root's .beads (Dir(LocalDir) == rc.CWDRepoRoot), which equates the workspace with the git root. From a workspace nested below its repo root (<repo>/sub/.beads/redirect), or from a git worktree that inherits its main checkout's redirect, exporting that workspace's own .beads therefore moved role detection from the CWD repo to the storage root: the env-dependent inconsistency the iteration-1 vacuous rule exists to remove. Dropping the guard would not have fixed it. When the repo root's .beads holds no redirect, GetRedirectInfo checks BEADS_DIR itself, and prepareSelectedCommandContext has rebound BEADS_DIR to the storage .beads before RunE. After that rebind GetRedirectInfo finds no redirect in either shape, so the iteration-1 rule bound the storage root there too. New beads.GetDiscoveredRedirectInfo is GetRedirectInfo without the BEADS_DIR override: the redirect discovery finds from the CWD (the repo root's .beads, then the worktree-local redirect, the main checkout's .beads for a worktree, and the walk-up from the CWD), via findDiscoveredLocalBeadsDir, the BEADS_DIR-free half of findLocalBeadsDir. The exported-BEADS_DIR arm now calls a selection vacuous exactly when that discovered redirect exists and targets the selected storage. A foreign redirected selection still falls through to its storage root, because discovery from the CWD finds no redirect or one with a different target. - Nit: the foreign-selection test's comment now says only the exported arm pins the guard. The rebound storage .beads holds no redirect, so the rebind arm only checks that both states of the variable agree. Iteration-3 tests: nested-workspace and worktree-without-own-.beads cells, each with BEADS_DIR unset, as exported, and as rebound before RunE. Against the unchanged 07c7373dfb code the four set-BEADS_DIR cells fail and both unset controls pass. A new test pins the target comparison: from a redirected workspace, an exported BEADS_DIR naming a different, non-redirected project still binds that project. TestGetDiscoveredRedirectInfo pins the new API against GetRedirectInfo in both directions (a nested redirect that BEADS_DIR masks, and a BEADS_DIR redirect the CWD does not hold). Five mutants each turn a test red: probing with GetRedirectInfo again (the iteration-1 rule, which fails both rebind cells and the foreign test), dropping the target comparison, dropping the worktree-fallback tier, letting discovery honor BEADS_DIR, and restoring the git-root guard. Validated (iteration 3): gofmt, git diff --check, go build ./..., go vet ./cmd/bd/ ./internal/beads/ ./internal/routing/, golangci-lint v2.10.1 --new-from-rev=HEAD on cmd/bd and internal/beads (0 issues), go test ./internal/beads/ ./internal/routing/, and a focused cmd/bd run over the role, routing, redirect, envfile and context-binding tests against the Dolt test server (47 passed, 0 failed, 0 skipped). No files were added, so no BUILD.bazel change is owed. Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Gas City Adopt-PR Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Osamu Okano <okano.osamu@gmail.com> Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local> Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
97 lines
3.1 KiB
Go
97 lines
3.1 KiB
Go
package main
|
|
|
|
import (
|
|
"os"
|
|
"path/filepath"
|
|
"testing"
|
|
)
|
|
|
|
func TestLoadBeadsEnvFile(t *testing.T) {
|
|
t.Run("loads env vars from .env file", func(t *testing.T) {
|
|
dir := t.TempDir()
|
|
envFile := filepath.Join(dir, ".env")
|
|
if err := os.WriteFile(envFile, []byte("BEADS_TEST_LOAD_VAR=hello_from_env\n"), 0600); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
t.Setenv("BEADS_TEST_LOAD_VAR", "") // clear
|
|
os.Unsetenv("BEADS_TEST_LOAD_VAR")
|
|
|
|
loadBeadsEnvFile(dir)
|
|
|
|
if got := os.Getenv("BEADS_TEST_LOAD_VAR"); got != "hello_from_env" {
|
|
t.Errorf("expected BEADS_TEST_LOAD_VAR=hello_from_env, got %q", got)
|
|
}
|
|
os.Unsetenv("BEADS_TEST_LOAD_VAR")
|
|
})
|
|
|
|
t.Run("shell env takes precedence over .env", func(t *testing.T) {
|
|
dir := t.TempDir()
|
|
envFile := filepath.Join(dir, ".env")
|
|
if err := os.WriteFile(envFile, []byte("BEADS_TEST_PRECEDENCE=from_file\n"), 0600); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
t.Setenv("BEADS_TEST_PRECEDENCE", "from_shell")
|
|
|
|
loadBeadsEnvFile(dir)
|
|
|
|
if got := os.Getenv("BEADS_TEST_PRECEDENCE"); got != "from_shell" {
|
|
t.Errorf("expected shell env to win, got %q", got)
|
|
}
|
|
})
|
|
|
|
t.Run("no-op when .env does not exist", func(t *testing.T) {
|
|
dir := t.TempDir()
|
|
// Should not panic or error
|
|
loadBeadsEnvFile(dir)
|
|
})
|
|
|
|
t.Run("no-op when beadsDir is empty", func(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")
|
|
}
|
|
})
|
|
}
|