* fix(context): resolve from .beads when outside a git repository
`bd context` is documented to read directly from config files and work "in
degraded states", but it hard-failed with "cannot determine repository root:
not a git repository" whenever the working directory wasn't inside a git
repo — even with a valid, discoverable .beads/ present. Consumers that use
`bd context --json` as a health/identity probe got a false "unreachable" in
healthy non-git scopes (GH#4772).
When GetRepoContext returns the repo-root error, a boundary-checked .beads
directory has already been found and the only missing piece is the git repo
root. Fall back to the .beads parent as the repo root and continue, so
backend identity still resolves from config. Only this specific error
triggers the fallback; "no .beads directory found" and unsafe-location
errors still surface as before.
Adds an embedded regression subtest that removes .git from a workspace and
asserts `bd context --json` still resolves (backend/beads_dir populated, no
error). Verified end-to-end: reproduced the exact "cannot determine
repository root" error pre-fix; post-fix reports backend=dolt.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* fix(context): select the no-git fallback by type, and cover both routes
Review follow-up on the GH#4772 fix.
The fallback was selected with strings.Contains(err.Error(), "cannot
determine repository root"). buildRepoContext's other failure — the
SEC-003 unsafe-location rejection — embeds the offending path verbatim
in its message, so the discriminator was controlled by the path being
rejected: a workspace whose path contained the probe phrase would take
the fallback and have its unsafe-location error cleared.
Replace it with a typed error. buildRepoContext now returns
*beads.NoRepoRootError, carrying the .beads directory that has already
cleared the found + safe-boundary checks — which is exactly what makes
recovering from this one failure safe, and removes the need to
re-derive it with a second FindBeadsDir call. The message text is
unchanged.
The recovery itself moves into beads.GetRepoContextAllowingNoGit, so
both `bd context` routes share it: the direct one in context_cmd.go and
the proxied one, whose provider (domain/fs contextRepositoryImpl
RepoContext + Role) propagated GetRepoContext's error unchanged and so
still failed outside git. Callers that actually run git commands keep
using GetRepoContext, so a missing repository stays an error where it
matters.
Tests:
- Discriminator regression: an unsafe-location error built with a
hostile path still matches the old substring test but does NOT
satisfy errors.As for *NoRepoRootError.
- GetRepoContextAllowingNoGit resolves a non-git workspace (BeadsDir,
RepoRoot = .beads parent, empty CWDRepoRoot) while GetRepoContext
still refuses.
- The embedded regression now decodes ContextInfo and asserts exact
beads_dir, repo_root, backend, bd_version and is_worktree instead of
probing for a key name (fields are not omitempty, so an empty or
wrong value passed before).
- Same assertions added for the proxied route.
- ngDir -> nonGitDir.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* fix(context): report the redirect on the no-git path, and test the discriminator
Two blocking items.
B1. The synthesized context left IsRedirected at its zero value, so a
workspace reached via BEADS_DIR from a non-git working directory denied
being redirected, and Role() withheld the Contributor that
"BEADS_DIR implies contributor (external repo mode)" promises. That
contradicts the field's own contract two screens up in the same file,
and a probe sold as a health/identity check giving the wrong identity is
a worse failure than the error it replaced.
The normal path's answer is genuinely unavailable here:
isExternalBeadsDir compares git COMMON DIRS, and the CWD side of that
comparison cannot be computed without a repository — which is exactly
the state this branch serves. An explicitly-set BEADS_DIR is the only
evidence left, and it is the same signal FindBeadsDir's step 1 used to
choose the directory, so the fallback now mirrors that condition. A
.beads found by the working-directory walk still reports false.
IsWorktree stays false, with a comment saying why rather than by
omission.
B2. TestNoRepoRootError_DoesNotMatchUnsafeLocation never called the
selection. Asking errors.As about two hand-built values tests the
standard library, and passes whatever discriminator this package
actually uses — which the reviewer demonstrated by swapping the typed
check for the substring test the test is named after and watching it
stay green.
The selection is now recoverNoGit(rc, err), split out of
GetRepoContextAllowingNoGit, and the test drives it: the unsafe-location
error must come back out unchanged, and so must the no-.beads error and
a successful context. Under the reviewer's probe B it now fails, naming
the context the substring version wrongly recovered.
Nits, taken:
N1. NoRepoRootError's doc claimed the workspace "is not inside a git repo".
It means git could not tell us a root: GetMainRepoRoot bottoms out in
one `git rev-parse`, so a dangling gitfile, a dubious-ownership refusal
or git missing from PATH all arrive the same way. Recovery is equally
safe in all of them, but the command whose pitch is diagnostics in
degraded states should not swallow the fact — printContextText now
prints `cwd repo: git: unavailable` instead of nothing, which is the
text-output counterpart of the omitted JSON field.
N2. The comment on fs/context.go claimed there is no `git config beads.role`
to read outside a repo. `git config --get` reads global and system
config with no repository; I hit it by accident running the probe above,
where Role() returned "maintainer" from my own ~/.gitconfig. Comment
corrected — the behavior was fine.
N3. CHANGELOG [Unreleased] entry citing #4772, and a "Resolving Without Git"
section in engdocs/REPO_CONTEXT.md — the reference for this module,
which documented the boundary validation and the IsRedirected semantics
B1 bends but neither the new entry point nor the no-git case. It carries
the typed-selection rationale and a table of what the synthesized
context can and cannot know.
N4 (allocation) noted and left: correctness first, and two allocations on a
config-reading path is not worth a cache whose invalidation would be a new
thing to get wrong.
Reported-by: bee-ghosttrack
Agent-Signature: claude-code-opus-5-unknown-reasoning on behalf of Harry Miller
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* fix(context): ask the caller's BEADS_DIR, not the one bd exported for itself
Round-2 blocker, and an embarrassing one: this is the same provenance bug I
fixed in #4795 an hour earlier, reintroduced one layer up.
beadsDirNamedByEnv read os.Getenv("BEADS_DIR") live. By the time
recoverNoGit runs, bd has already exported one: cmd/bd/context_cmd.go:75
calls prepareSelectedNoDBContext(selected) immediately before
GetRepoContextAllowingNoGit, and that ends in os.Setenv("BEADS_DIR", ...)
with whatever discovery just found. The proxied route arrives the same way
through the root pre-run. So on the no-git path EVERY walk-found workspace
reported itself as a redirect and claimed Contributor — the opposite of the
Round-1 bug, and worse, because it is the common case rather than the
unusual one. Reproduced against the built binary:
$ cd $T/proj/sub && env -u BEADS_DIR bd context --json
"is_redirected": true, "role": "contributor" ← no BEADS_DIR anywhere
internal/beads now takes the same package-init snapshot package main does,
for the same reason: provenance has to be captured before the process starts
overwriting the evidence. beadsDirNamedByCaller compares against that.
Two things worth recording while I was in there. First, a redirect FILE
cannot be missed by this branch: buildRepoContext checks GetRedirectInfo()
at step 3, and a redirect sends it down the isExternal branch that never
asks git for a root — so by construction the only redirect this code can be
looking at is a caller-named BEADS_DIR. That is now a comment rather than an
assumption. Second, the unit tests passed through the bug because they drive
recoverNoGit directly with an env they set themselves, which is exactly the
distinction that cannot be tested in process.
So the regression is end-to-end, on both routes, as asked:
- assertNonGitContext (shared by the embedded and proxied route tests) now
asserts is_redirected == false for the walk-found case. Reverting the fix:
"is_redirected should be false for a .beads found by the
working-directory walk".
- a new embedded subtest runs the binary from an unrelated directory with
BEADS_DIR supplied in the subprocess environment — the only place a
caller-supplied value is distinguishable from a bd-exported one — and
asserts is_redirected == true AND role == contributor.
N1: the `cwd repo: git: unavailable` line was unpinned (their probe P3
deleted the branch and every -run Context test stayed green).
TestPrintContextText_* now pins all three cases: empty CWD repo root reports
git unavailable, a matching one prints nothing, a differing one prints the
path and must NOT say unavailable. Deleting the branch now fails. Kept as an
in-process capture rather than another subprocess, since cmd/bd has no
runtime budget to spare (GH#6253).
N2: filed as GH#6560 — and my attribution on the PR thread was wrong. It is
not a legacy ~/.beads/config.yaml (I have none); it is BEADS_ACTOR in the
environment, which resolveConfiguredActor deliberately checks ahead of
config.yaml as the fix for GH#4645. `env -u BEADS_ACTOR` makes both tests
pass.
Reported-by: bee-ghosttrack
Agent-Signature: claude-code-opus-5-unknown-reasoning on behalf of Harry Miller
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* chore(bazel): enumerate the PR's two new test files in go_test srcs
Pre-review CI repair for PR #4792. The helper reads CI Readiness: pass, but
those nine green runs were created 2026-09-23 against the contributor head
961aa6239 -- before this branch was rebased onto 8269a88cb, an advance that
brings in the entire Bazel scaffold (.bazelrc, .bazelignore,
.github/actions/setup-bazel). So the green cohort predates the Bazel lanes
entirely and cannot certify them; the adopted head has never been seen by CI.
Both affected packages declare go_test srcs as an EXPLICIT list, not a glob, so
the PR's two added test files were invisible to bazel:
cmd/bd/BUILD.bazel + "context_text_test.go"
internal/beads/BUILD.bazel + "no_repo_root_test.go"
Base parity puts the obligation on this PR rather than on base: neither file
exists at the rebase base, so neither row could have been owed there.
The failure mode is a FAKE GREEN, not a red, which is why no check caught it.
Measured on //internal/beads:beads_test: with the row, bazel runs
TestGetRepoContextAllowingNoGit_RecoversOutsideGitRepo (rc=0). With the row
removed, the target still exits 0 -- and that test never runs. A silently
unexecuted regression test is exactly what this enumeration prevents.
Generated by the repository's own `make bazel-sync` (gazelle); the rows are
placed alphabetically, the diff is +1/-0 per file, and a second sync is a no-op.
* fix(context): root the no-git context at the .beads repo and decide redirects positionally
Maintainer review fixups for the two gating findings on the no-git recovery
path, plus the nearby non-gating cleanups.
Finding 1 (major) -- recoverNoGit rooted repo_root at filepath.Dir(BeadsDir),
but the failure that reaches it is the CWD's missing repository, not the
.beads's. A .beads that did live inside a repo therefore reported a
SUBDIRECTORY of that repo, so one workspace answered differently depending
only on where the caller stood. Root via repoRootForBeadsDir, which asks git
from the .beads side (needing no CWD repo) and already falls back to
filepath.Dir(beadsDir), so the documented no-git-anywhere answer is unchanged.
The conflated premise is corrected in the field comment and in
engdocs/REPO_CONTEXT.md.
Finding 2 (major) -- the provenance snapshot was captured at package init and
covered only BEADS_DIR, but bd has four caller-directed workspace channels:
--db, BEADS_DB/BD_DB and -C all resolve through selectedNoDBBeadsDir and end
in an os.Setenv("BEADS_DIR", ...) that runs after init, so the snapshot could
not see them and they reported is_redirected:false / role:maintainer outside
git. Decide externality POSITIONALLY instead: the resolved .beads is a
redirect iff discovery standing in the CWD would not have found it. This is
the reviewer's preferred arm -- it needs no environment inventory, so it
covers all four channels uniformly and stays correct as channels are added (a
further BEADS_DIR writer already exists in cmd/bd/doctor.go). It reuses
FindBeadsDirFrom, the same primitive -C itself resolves through, which reads
none of the routing variables and scrubs routing env from its git probe. The
package-init snapshot and its helper are removed. The boundary the review left
unspecified is settled deliberately: a store reachable only by being named is
a redirect, including one in a sibling directory of the CWD, because with no
repository for the CWD there is no enclosing scope that could make a sibling
local.
Finding 3 (minor) -- TestGetRepoContextAllowingNoGit_RecoversOutsideGitRepo
now scrubs BEADS_DIR, which takes priority at FindBeadsDir step 1. Measured:
three assertions fail under an ambient BEADS_DIR without the scrub and the
package is ok with it. The remedy's second part (stubbing the init snapshot)
is obsolete rather than skipped -- positional provenance reads no snapshot, so
there is nothing left to stub.
Findings 4 and 5 (nits) -- the beadsDirFromCaller / GH#4635 cross-reference
resolved to nothing at head or at base; it is gone along with the snapshot it
described. The CWDRepoRoot comment now states the value is known-empty because
the one cached git context its three readers share has already failed, which
is also a firmer justification for IsWorktree: false than "there is none".
Verification: both majors are pinned by new tests proven to red when the fix
is reverted, and measured end to end with a built binary from a non-git cwd --
BEADS_DIR, BEADS_DB, BD_DB, --db and -C all now report is_redirected:true /
role:contributor, while a walk-discoverable workspace correctly reports
false / maintainer. Contributor commits are preserved.
---------
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
9.7 KiB
Repository Context
This document explains how beads resolves repository context when commands run from
different directories than where .beads/ lives.
Problem
Git commands must run in the correct repository, but users may invoke bd from:
- A different repository (using
BEADS_DIRenvironment variable) - A git worktree (separate working directory, shared
.beads/) - A subdirectory within the repository
Without centralized handling, each command must implement its own path resolution, leading to bugs when assumptions don't match reality.
Solution: RepoContext API
The RepoContext API provides a single source of truth for repository resolution:
import "github.com/steveyegge/beads/internal/beads"
rc, err := beads.GetRepoContext()
if err != nil {
return err
}
// Run git in beads repository (not CWD)
cmd := rc.GitCmd(ctx, "status")
output, err := cmd.Output()
When to Use Each Method
| Method | Use Case | Example |
|---|---|---|
GitCmd() |
Git commands for beads operations | git add .beads/, git push |
GitCmdCWD() |
Git commands for user's working repo | git status (show user's changes) |
RelPath() |
Convert absolute path to repo-relative | Display paths in output |
GitCmd() vs GitCmdCWD()
The distinction matters when BEADS_DIR points to a different repository:
rc, _ := beads.GetRepoContext()
// GitCmd: runs in the beads repository
// Use for: committing .beads/, pushing/pulling beads data
cmd := rc.GitCmd(ctx, "add", ".beads/issues.jsonl")
// GitCmdCWD: runs in user's current repository
// Use for: checking user's uncommitted changes, status display
cmd := rc.GitCmdCWD(ctx, "status", "--porcelain")
Scenarios
Normal Repository
CWD is inside the repository containing .beads/:
/project/
├── .beads/
├── src/
└── README.md
$ cd /project/src
$ bd dolt push
# GitCmd() runs in /project (correct)
BEADS_DIR Redirect
User is in one repository but managing beads in another:
$ cd /repo-a # Has uncommitted changes
$ export BEADS_DIR=/repo-b/.beads
$ bd dolt push
# GitCmd() runs in /repo-b (correct, not /repo-a)
This pattern is common for:
- Fork contribution tracking (your tracker in separate repo)
- Shared team databases
- Monorepo setups
Git Worktree
User is in a worktree but .beads/ lives in main repository:
/project/ # Main repo
├── .beads/
├── .worktrees/
│ └── feature-branch/ # Worktree (CWD)
└── src/
$ cd /project/.worktrees/feature-branch
$ bd dolt push
# GitCmd() runs in /project (main repo, where .beads lives)
Combined: Worktree + Redirect
Both worktree and BEADS_DIR can be active simultaneously:
$ cd /repo-a/.worktrees/branch-x
$ export BEADS_DIR=/repo-b/.beads
$ bd dolt push
# GitCmd() runs in /repo-b (BEADS_DIR takes precedence)
RepoContext Fields
| Field | Description |
|---|---|
BeadsDir |
Actual .beads/ directory (after following redirects) |
RepoRoot |
Repository root containing BeadsDir |
CWDRepoRoot |
Repository root containing user's CWD (may differ) |
IsRedirected |
True if BEADS_DIR points to different repo than CWD |
IsWorktree |
True if CWD is in a git worktree |
Resolving Without Git
GetRepoContext() requires a git repository: it finds .beads/, validates the
path boundary, and only then asks git for a repository root. A workspace that
is located and boundary-checked but has no resolvable git root is therefore a
known workspace, not an unknown one — which is why it is the one failure that
is safe to recover from.
GetRepoContextAllowingNoGit() is that recovery, for callers that only read
config files and are documented to answer in degraded states: bd context and
the domain/fs context provider behind the proxied route (which bd serve
also resolves through). Anything that actually runs git commands must keep
using GetRepoContext(), so a missing repository stays an error where it
matters.
The selection is typed, deliberately. buildRepoContext() can fail three ways
— no .beads/, the SEC-003 unsafe-location rejection, and no git root — and
the unsafe-location message embeds the offending path verbatim. A substring
test over the message would therefore be a path-controlled discriminator: a
workspace under a path containing the probe phrase would take the fallback and
have its security rejection silently cleared. Only the third failure returns
*NoRepoRootError, and errors.As selects it.
The synthesized context differs from a normal one in what it can know:
| Field | Value without git | Why |
|---|---|---|
RepoRoot |
the repository containing .beads, else the .beads parent |
the missing git root is the CWD's, not the .beads's, so git is still asked from the .beads side (repoRootForBeadsDir); only when that cannot answer either does it fall back to the parent |
CWDRepoRoot |
"" |
known-empty, not merely unanswered: GetMainRepoRoot, GetRepoRoot and IsWorktree share one cached git context, and reaching this path means that lookup already failed |
IsRedirected |
true iff discovery standing in the CWD would not have found the resolved .beads |
isExternalBeadsDir compares git common dirs and the CWD side needs a repository, so externality is decided positionally instead. This covers all four caller-directed channels (BEADS_DIR, --db, BEADS_DB/BD_DB, -C) uniformly, where an environment inventory could not: bd rewrites BEADS_DIR for itself before resolving, so the variable cannot distinguish a workspace the caller named from one bd just discovered. A store reachable only by being named is a redirect — including one in a sibling directory of the CWD — which is what Role() means by "external repo mode" |
IsWorktree |
false | nothing to be a worktree of |
*NoRepoRootError means "git could not tell us a root", which is broader than
"there is no repo": a dangling gitfile, a dubious-ownership refusal, or git
missing from PATH all arrive the same way. Recovery is equally safe in all of
them, but a caller reporting on the workspace should not claim to know which it
was — bd context prints cwd repo: git: unavailable rather than inventing a
reason.
Security
Git Hooks Disabled
GitCmd() disables git hooks and templates to prevent code execution in
potentially malicious repositories:
cmd.Env = append(os.Environ(),
"GIT_HOOKS_PATH=", // Disable hooks
"GIT_TEMPLATE_DIR=", // Disable templates
)
This protects against scenarios where BEADS_DIR points to an untrusted
repository that contains malicious .git/hooks/ scripts.
Path Boundary Validation
GetRepoContext() validates that BEADS_DIR does not point to sensitive
system directories:
/etc,/usr,/var,/root(Unix system directories)/System,/Library(macOS system directories)- Other users' home directories
Temporary directories (e.g., /var/folders on macOS) are explicitly allowed
for test environments.
Server Mode Handling
CLI vs Server Context
For CLI commands, GetRepoContext() caches the result via sync.Once because:
- CWD doesn't change during command execution
- BEADS_DIR doesn't change during command execution
- Repeated filesystem access would be wasteful
For the Dolt server (long-running process), this caching is inappropriate:
- User may create new worktrees
- BEADS_DIR may change via direnv
- Multiple workspaces may be active simultaneously
Workspace-Specific API
The server uses GetRepoContextForWorkspace() for fresh resolution:
// For server mode: fresh resolution per-operation (no caching)
rc, err := beads.GetRepoContextForWorkspace(workspacePath)
// Validation hook for detecting stale contexts
if err := rc.Validate(); err != nil {
// Context is stale, need fresh resolution
}
This function:
- Does NOT cache results
- Does NOT respect BEADS_DIR (workspace path is explicit)
- Resolves worktree relationships correctly
- Validates that paths still exist
Migration Guide
Before (scattered resolution)
func doGitOperation(ctx context.Context) error {
// Each function resolved paths differently
beadsDir := beads.FindBeadsDir()
redirectInfo := beads.GetRedirectInfo()
var repoRoot string
if redirectInfo.IsRedirected {
repoRoot = filepath.Dir(beadsDir)
} else {
repoRoot = getRepoRootForWorktree(ctx)
}
cmd := exec.CommandContext(ctx, "git", "-C", repoRoot, "status")
// ...
}
After (centralized)
func doGitOperation(ctx context.Context) error {
rc, err := beads.GetRepoContext()
if err != nil {
return err
}
cmd := rc.GitCmd(ctx, "status")
// ...
}
Key Changes for Contributors
- Replace direct exec.Command: Use
rc.GitCmd()orrc.GitCmdCWD() - Remove manual path resolution: RepoContext handles all scenarios
- Clear caches in tests: Call
beads.ResetCaches()in test cleanup
Testing
Tests use beads.ResetCaches() to clear cached context between test cases:
func TestSomething(t *testing.T) {
t.Cleanup(func() {
beads.ResetCaches()
git.ResetCaches()
})
// Test code...
}
Related Documentation
- WORKTREES.md - Git worktree integration
- ROUTING.md - Multi-repository routing
- CONFIG.md - BEADS_DIR and environment variables
Implementation Notes
- Result is cached via
sync.Oncefor CLI efficiency - CWD and BEADS_DIR don't change during command execution
- Uses
cmd.Dirpattern (not-Cflag) for Go-idiomatic execution - Security mitigations implemented for git hooks and path traversal