fix(routing): bind role detection to the bd -C target repo (re-port of #4242) (#5243)

* 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 at 89348699b0 was 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 at
    86b8abff3f and 8dbfc6c721 and pass at base 89348699b0. 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 base
89348699b0. 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>
This commit is contained in:
matt wilkie 2026-10-04 05:47:27 -07:00 • committed by GitHub
commit e249a5a539
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
14 changed files with 1194 additions and 12 deletions

View file

@ -282,6 +282,7 @@ go_library(
"restore.go",
"routed.go",
"routing_read.go",
"routing_role.go",
"rules.go",
"sandbox_unix.go",
"sandbox_windows.go",

View file

@ -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 {

View file

@ -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 <workspace>` 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 <redirected-workspace> 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", "")

View file

@ -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, ".")
}

View file

@ -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")
}
})
}

View file

@ -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

View file

@ -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, ".")
}

View file

@ -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 {

190
cmd/bd/routing_role.go Normal file
View file

@ -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=<workspace>/.beads
// and BEADS_DIR=<storage>/.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 <dir>.")
}
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
}

View file

@ -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.

View file

@ -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

View file

@ -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")

View file

@ -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 {

View file

@ -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")