fix(context): resolve from .beads when outside a git repository (#4772) (#4792)

* 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>
This commit is contained in:
Harry Miller 2026-10-01 07:08:12 -07:00 • committed by GitHub
commit 1cc19040af
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
11 changed files with 844 additions and 4 deletions

View file

@ -174,6 +174,36 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
(default 24h) controls how often the pause is re-announced. Manual `bd
backup` / `bd backup sync` are not capped.
- **`bd context` resolves a workspace outside a git repository instead of
hard-failing** ([#4772](https://github.com/gastownhall/beads/issues/4772)).
The command's own help promises it "does not require the database to be open,
making it useful for diagnostics in degraded states", but it exited with
`cannot determine repository root` whenever the working directory was not
inside a git repo — even with a perfectly valid `.beads/` present — so
consumers using `bd context --json` as a health probe got a false
"unreachable" in healthy non-git scopes.
`GetRepoContext()` finds and boundary-validates `.beads/` *before* it asks
git for a root, so that one failure means only that git is missing. It now
returns a typed `*beads.NoRepoRootError`, and `GetRepoContextAllowingNoGit()`
selects it with `errors.As` and roots the context at the `.beads` parent.
Typed rather than by message text on purpose: the SEC-003 unsafe-location
rejection embeds the offending path verbatim, so a substring test would let a
workspace under a hostile path clear its own security refusal. Every other
failure, that one included, propagates untouched.
Scoped to the callers that only read config: `bd context` on both routes, and
the `domain/fs` context provider — which `bd serve` also resolves through, so
`bd serve` in a non-git directory with a valid `.beads/` now proceeds rather
than failing at context resolution. Anything that runs git commands still
uses `GetRepoContext()`. The synthesized context roots at the repository
containing the `.beads/` (falling back to its parent when git cannot be asked
there either) and decides `is_redirected` positionally — whether discovery
standing in the working directory would have found that `.beads/` — so
`--db`, `BEADS_DB`/`BD_DB` and `-C` are reported the same way `BEADS_DIR` is.
`bd context` also prints `cwd repo: git: unavailable` rather than silently
omitting the one degraded state it exists to report.
- **`bd comment`/`bd comments add` refuse an abbreviated id and a reserved
word instead of silently resolving one to the wrong issue**
([#5393](https://github.com/gastownhall/beads/pull/5393)). `bd comment list

View file

@ -602,6 +602,7 @@ go_test(
"context_identity_test.go",
"context_proxied_integration_test.go",
"context_test.go",
"context_text_test.go",
"contributor_embedded_test.go",
"contributor_routing_e2e_test.go",
"cook_qnt_test.go",

View file

@ -75,7 +75,7 @@ Examples:
prepareSelectedNoDBContext(selected)
}
rc, err := beads.GetRepoContext()
rc, err := beads.GetRepoContextAllowingNoGit()
if err != nil {
if jsonOutput {
if jerr := outputJSON(map[string]string{"error": fmt.Sprintf("cannot resolve repo context: %v", err)}); jerr != nil {
@ -164,6 +164,15 @@ func printContextText(info ContextInfo) {
fmt.Printf(" repo root: %s\n", info.RepoRoot)
if info.CWDRepoRoot != "" && info.CWDRepoRoot != info.RepoRoot {
fmt.Printf(" cwd repo: %s\n", info.CWDRepoRoot)
} else if info.CWDRepoRoot == "" {
// The one degraded state this command exists to report, and the one
// it used to swallow. An empty CWD repo root means git answered
// nothing for the working directory — usually "not inside a repo",
// but also a dangling gitfile, a dubious-ownership refusal, or no git
// on PATH. Printing nothing here left the text output with no hint
// that anything was unusual, while --json callers could still infer
// it from the omitted field.
fmt.Printf(" cwd repo: %s\n", "git: unavailable")
}
if info.IsRedirected {
fmt.Printf(" redirected: yes\n")

View file

@ -3,12 +3,16 @@
package main
import (
"encoding/json"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"sync"
"testing"
"github.com/steveyegge/beads/internal/configfile"
)
func TestEmbeddedContext(t *testing.T) {
@ -45,6 +49,134 @@ func TestEmbeddedContext(t *testing.T) {
t.Error("expected non-empty context --json output")
}
})
// bd context must resolve from a discoverable .beads directory even when
// the scope is not inside a git repository — git is a means of finding the
// repo root, not a hard requirement for this diagnostic (GH#4772).
t.Run("context_json_without_git_repo", func(t *testing.T) {
nonGitDir, _, _ := bdInit(t, bd, "--prefix", "ng")
if err := os.RemoveAll(filepath.Join(nonGitDir, ".git")); err != nil {
t.Fatalf("remove .git: %v", err)
}
cmd := exec.Command(bd, "context", "--json")
cmd.Dir = nonGitDir
cmd.Env = bdEnv(nonGitDir)
stdout, stderr, err := runCommandBuffers(t, cmd)
if err != nil {
t.Fatalf("bd context --json failed outside git repo: %v\nstdout:\n%s\nstderr:\n%s", err, stdout.String(), stderr.String())
}
out := stdout.String()
// Decode rather than probing for key names: ContextInfo's fields are
// not omitempty, so a wrong or empty beads_dir still emits the key.
var info ContextInfo
if jerr := json.Unmarshal([]byte(out), &info); jerr != nil {
t.Fatalf("decoding context JSON: %v\noutput:\n%s", jerr, out)
}
assertNonGitContext(t, info, nonGitDir)
})
// The other side of the same question, and the one that has to be driven
// through the real binary: only a subprocess has an environment the
// caller actually supplied. In-process tests stub the snapshot, so they
// cannot tell a caller-supplied BEADS_DIR from one bd exported for
// itself — which is exactly the distinction under test.
t.Run("context_json_without_git_repo_with_caller_beads_dir", func(t *testing.T) {
nonGitDir, _, _ := bdInit(t, bd, "--prefix", "nr")
if err := os.RemoveAll(filepath.Join(nonGitDir, ".git")); err != nil {
t.Fatalf("remove .git: %v", err)
}
beadsDir := filepath.Join(nonGitDir, ".beads")
// Run from somewhere else entirely, so the only way this workspace
// can be found is the BEADS_DIR the caller sets here.
elsewhere := t.TempDir()
cmd := exec.Command(bd, "context", "--json")
cmd.Dir = elsewhere
cmd.Env = append(bdEnv(nonGitDir), "BEADS_DIR="+beadsDir)
stdout, stderr, err := runCommandBuffers(t, cmd)
if err != nil {
t.Fatalf("bd context --json failed with a caller-supplied BEADS_DIR: %v\nstdout:\n%s\nstderr:\n%s", err, stdout.String(), stderr.String())
}
var info ContextInfo
if jerr := json.Unmarshal([]byte(stdout.String()), &info); jerr != nil {
t.Fatalf("decoding context JSON: %v\noutput:\n%s", jerr, stdout.String())
}
assertRedirectedNonGitContext(t, info, beadsDir)
})
}
// assertNonGitContext holds `bd context` to the exact answer it must give for
// a workspace at dir that is not inside a git repository: the workspace is
// identified from .beads, the repo root falls back to the .beads parent, and
// the backend still resolves from config.
//
// Paths are compared through EvalSymlinks because the test's temp dir is
// reported canonically (/private/var/... on macOS) by the binary under test.
func assertNonGitContext(t *testing.T, info ContextInfo, dir string) {
t.Helper()
resolve := func(p string) string {
if r, err := filepath.EvalSymlinks(p); err == nil {
return r
}
return p
}
wantBeadsDir := resolve(filepath.Join(dir, ".beads"))
if got := resolve(info.BeadsDir); got != wantBeadsDir {
t.Errorf("beads_dir = %q, want %q", info.BeadsDir, wantBeadsDir)
}
wantRepoRoot := resolve(dir)
if got := resolve(info.RepoRoot); got != wantRepoRoot {
t.Errorf("repo_root = %q, want %q (the .beads parent, since there is no git root)", info.RepoRoot, wantRepoRoot)
}
if info.Backend != configfile.BackendDolt {
t.Errorf("backend = %q, want %q — backend identity must still resolve from config", info.Backend, configfile.BackendDolt)
}
if info.BdVersion == "" {
t.Error("bd_version should be populated")
}
if info.IsWorktree {
t.Error("is_worktree should be false outside a git repository")
}
// The identity half, which is the reason a consumer runs this command.
// A workspace found by walking up from the working directory is NOT a
// redirect, and reporting one makes the probe lie about identity. bd
// exports a BEADS_DIR for itself just before resolving, so this assertion
// is what keeps the answer keyed to the caller's environment rather than
// the live one.
if info.IsRedirected {
t.Error("is_redirected should be false for a .beads found by the working-directory walk")
}
}
// assertRedirectedNonGitContext is the other half: a workspace the CALLER
// named with BEADS_DIR is a redirect, and carries the Contributor role that
// RepoContext.Role() documents for external-repo mode — even with no git
// repository to compare against.
func assertRedirectedNonGitContext(t *testing.T, info ContextInfo, beadsDir string) {
t.Helper()
resolve := func(p string) string {
if r, err := filepath.EvalSymlinks(p); err == nil {
return r
}
return p
}
if got, want := resolve(info.BeadsDir), resolve(beadsDir); got != want {
t.Errorf("beads_dir = %q, want %q", info.BeadsDir, want)
}
if !info.IsRedirected {
t.Error("is_redirected should be true for a workspace the caller named with BEADS_DIR")
}
if info.Role != "contributor" {
t.Errorf("role = %q, want \"contributor\" — BEADS_DIR implies external repo mode", info.Role)
}
}
func TestEmbeddedContextConcurrent(t *testing.T) {

View file

@ -4,6 +4,7 @@ package main
import (
"encoding/json"
"os"
"path/filepath"
"strings"
"sync"
@ -59,6 +60,31 @@ func TestProxiedServerContext(t *testing.T) {
}
})
// The proxied route must survive a workspace outside git for the same
// reason the direct route does — its context provider reads config files
// only (GH#4772). This gets its own project because it removes .git, which
// the shared one's parallel subtests still need.
t.Run("json_without_git_repo", func(t *testing.T) {
t.Parallel()
np := newSharedProxiedProject(t, bd, "ctxng")
if err := os.RemoveAll(filepath.Join(np.dir, ".git")); err != nil {
t.Fatalf("remove .git: %v", err)
}
stdout, stderr, err := bdProxiedRunBuffers(t, bd, np.dir, "context", "--json")
if err != nil {
t.Fatalf("bd context --json failed outside git repo: %v\nstdout:\n%s\nstderr:\n%s", err, stdout, stderr)
}
var info ContextInfo
if jerr := json.Unmarshal([]byte(stdout), &info); jerr != nil {
t.Fatalf("decoding context JSON: %v\noutput:\n%s", jerr, stdout)
}
assertNonGitContext(t, info, np.dir)
if info.DoltMode != configfile.DoltModeProxiedServer {
t.Errorf("dolt_mode = %q, want %q", info.DoltMode, configfile.DoltModeProxiedServer)
}
})
t.Run("concurrent", func(t *testing.T) {
t.Parallel()
const numWorkers = 8

View file

@ -0,0 +1,95 @@
package main
import (
"os"
"path/filepath"
"strings"
"testing"
)
// captureContextText returns what printContextText writes to stdout.
func captureContextText(t *testing.T, info ContextInfo) string {
t.Helper()
stdioMutex.Lock()
defer stdioMutex.Unlock()
path := filepath.Join(t.TempDir(), "stdout")
f, err := os.Create(path)
if err != nil {
t.Fatalf("create stdout capture: %v", err)
}
oldStdout := os.Stdout
func() {
defer func() { os.Stdout = oldStdout }()
os.Stdout = f
printContextText(info)
}()
if err := f.Close(); err != nil {
t.Fatalf("close stdout capture: %v", err)
}
out, err := os.ReadFile(path)
if err != nil {
t.Fatalf("read stdout capture: %v", err)
}
return string(out)
}
// The degraded state this command exists to report must survive into the TEXT
// output, not only into --json's omitted field.
//
// `cwd repo` printed only when it was non-empty AND different from the repo
// root, so an empty one — git answered nothing for the working directory —
// vanished from the human-readable output entirely. A JSON consumer could
// still infer it from the absent key; a person reading the output could not
// see that anything was unusual.
func TestPrintContextText_SaysWhenGitCouldNotAnswer(t *testing.T) {
out := captureContextText(t, ContextInfo{
BdVersion: "test",
BeadsDir: "/ws/.beads",
RepoRoot: "/ws",
// Empty: no git root for the working directory.
CWDRepoRoot: "",
})
if !strings.Contains(out, "cwd repo:") {
t.Fatalf("text output says nothing about the working directory's repo:\n%s", out)
}
if !strings.Contains(out, "git: unavailable") {
t.Errorf("empty cwd repo root is not reported as git being unavailable:\n%s", out)
}
}
// The two cases that must NOT gain the line: a CWD inside the same repository
// as the workspace (nothing worth saying), and one inside a different repo
// (the existing disclosure, which is a path and not a diagnosis).
func TestPrintContextText_CWDRepoRootCases(t *testing.T) {
t.Run("same repo prints no cwd repo line", func(t *testing.T) {
out := captureContextText(t, ContextInfo{
BdVersion: "test",
BeadsDir: "/ws/.beads",
RepoRoot: "/ws",
CWDRepoRoot: "/ws",
})
if strings.Contains(out, "cwd repo:") {
t.Errorf("cwd repo line printed when it matches the repo root:\n%s", out)
}
})
t.Run("different repo prints the path", func(t *testing.T) {
out := captureContextText(t, ContextInfo{
BdVersion: "test",
BeadsDir: "/ws/.beads",
RepoRoot: "/ws",
CWDRepoRoot: "/other",
})
if !strings.Contains(out, "cwd repo: /other") {
t.Errorf("cwd repo line missing the working directory's own repo root:\n%s", out)
}
if strings.Contains(out, "git: unavailable") {
t.Errorf("a resolvable cwd repo root must not be reported as unavailable:\n%s", out)
}
})
}

View file

@ -125,6 +125,45 @@ $ bd dolt push
| `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

View file

@ -34,6 +34,7 @@ go_test(
"cwd_priority_test.go",
"explicit_beads_dir_test.go",
"fingerprint_test.go",
"no_repo_root_test.go",
"routing_integration_test.go",
"sqlite_database_path_test.go",
"suite_temp_test.go",

View file

@ -31,6 +31,7 @@ import (
"github.com/steveyegge/beads/internal/git"
"github.com/steveyegge/beads/internal/gitenv"
"github.com/steveyegge/beads/internal/utils"
)
// UserRole represents the user's relationship to a repository.
@ -100,6 +101,143 @@ func GetRepoContext() (*RepoContext, error) {
return repoCtx, repoCtxErr
}
// NoRepoRootError reports that a .beads directory was found and cleared the
// SEC-003 safe-boundary check, but git could not tell us a repository root for
// it.
//
// "Git could not tell us", not "there is no repo": git.GetMainRepoRoot bottoms
// out in a single `git rev-parse`, and every failure of that command arrives
// here. The common case is the plain one — the workspace is not inside a git
// repo — but a dangling gitfile, a dubious-ownership refusal, or git missing
// from PATH all land here too. Recovering is equally safe in all of them (the
// workspace is located and boundary-checked either way), but a caller
// reporting on the workspace should not claim to know which it was. `bd
// context` says so by leaving cwd_repo_root empty, and printContextText prints
// "git: unavailable" for it.
//
// It is deliberately distinct from the other two failures buildRepoContext can
// return ("no .beads directory found" and the unsafe-location rejection):
// those mean bd does not know which workspace it is looking at, while this one
// means it does. Only this failure is safe for a git-independent caller to
// recover from, and only a typed error can say so — the unsafe-location
// message embeds the offending path verbatim, so any substring test over the
// message text is a path-controlled discriminator.
type NoRepoRootError struct {
// BeadsDir is the resolved, boundary-checked .beads directory.
BeadsDir string
// Err is the underlying git failure.
Err error
}
func (e *NoRepoRootError) Error() string {
return fmt.Sprintf("cannot determine repository root: %v", e.Err)
}
func (e *NoRepoRootError) Unwrap() error { return e.Err }
// GetRepoContextAllowingNoGit returns the repository context for callers that
// only need to locate the workspace, not operate on git — `bd context` and the
// context provider behind the proxied route, both of which read config files
// and are documented to answer in degraded states.
//
// It behaves exactly like GetRepoContext except for NoRepoRootError, where it
// synthesizes a context rooted at the .beads parent. Every other failure,
// including the unsafe-location rejection, propagates untouched. Callers that
// actually run git commands must keep using GetRepoContext, so that a missing
// repository stays an error at the point where it matters (GH#4772).
func GetRepoContextAllowingNoGit() (*RepoContext, error) {
return recoverNoGit(GetRepoContext())
}
// recoverNoGit is the selection itself, split out from
// GetRepoContextAllowingNoGit so a test can drive the discriminator rather than
// re-deriving errors.As over hand-built values — which is a property of the
// standard library, not of this package's choice of discriminator.
//
// It returns (rc, err) untouched for every error that is not a
// *NoRepoRootError, and a synthesized context for the one that is.
func recoverNoGit(rc *RepoContext, err error) (*RepoContext, error) {
var noRoot *NoRepoRootError
if !errors.As(err, &noRoot) {
return rc, err
}
return &RepoContext{
BeadsDir: noRoot.BeadsDir,
// Root from the .beads side, not at filepath.Dir(BeadsDir). The failure
// that reaches here is the CWD's missing repository, not the .beads's —
// so when the .beads DOES live inside a repo, naming its parent would
// report a subdirectory and the same workspace would answer differently
// depending only on where the caller stood. repoRootForBeadsDir asks git
// from the .beads directory, which needs no CWD repo, and already falls
// back to filepath.Dir(beadsDir) when git cannot answer — so the
// no-git-anywhere result is unchanged.
RepoRoot: repoRootForBeadsDir(noRoot.BeadsDir),
// Known-empty, not merely usually: GetMainRepoRoot, GetRepoRoot and
// IsWorktree all read one sync.Once-cached gitContext, so reaching
// recoverNoGit means that cached lookup has already failed and all three
// degrade together. The call stays because it documents where the value
// comes from, but it cannot return anything but "" here.
CWDRepoRoot: git.GetRepoRoot(),
// Externality is decided POSITIONALLY: the resolved .beads is a redirect
// iff discovery standing in the current working directory would not have
// found it.
//
// Why position rather than an inventory of environment variables: bd has
// four caller-directed workspace channels — BEADS_DIR, --db,
// BEADS_DB/BD_DB and -C — and every one but BEADS_DIR reaches
// FindBeadsDir only after cmd/bd has rewritten BEADS_DIR for itself
// (selectedNoDBBeadsDir; applyChangeDirSelection for -C, which resolves a
// .beads and exports it WITHOUT changing the process directory). Reading
// the environment therefore cannot distinguish a workspace the caller
// named from one bd just found and re-exported, an inventory goes stale
// as channels are added, and a further BEADS_DIR writer already exists in
// the save/restore pair in cmd/bd/doctor.go. Asking where the caller is
// STANDING needs no inventory and covers all four channels uniformly.
//
// isExternalBeadsDir answers this by comparing git COMMON DIRS on the
// normal path; the CWD side of that comparison needs a repository, which
// is precisely what is missing here, so position is the substitute.
IsRedirected: beadsDirIsExternalToCWD(noRoot.BeadsDir),
// IsWorktree stays false for the same reason CWDRepoRoot is empty: the
// one cached git context this all reads has already failed, so
// git.IsWorktree() cannot be true here.
}, nil
}
// beadsDirIsExternalToCWD reports whether beadsDir is external to the working
// directory — whether workspace discovery, standing in the CWD, would have
// found something other than beadsDir, or nothing at all.
//
// It reuses FindBeadsDirFrom, which is both the primitive -C itself resolves
// through (resolveChangeDirBeadsDir) and purely positional: it consults none of
// the caller-directed variables, and its git probe scrubs routing env, so bd's
// own re-exported BEADS_DIR cannot make a walk-found workspace look named.
//
// Settled boundary (the unspecified case the review flagged): a store reachable
// only by being named is a redirect, INCLUDING one in a sibling directory of the
// CWD. With no repository for the CWD there is no enclosing scope that could
// make a sibling local, so the ancestor walk is the only defensible notion of
// "the workspace I am standing in". This matches what Role() means by "external
// repo mode": you are not standing in this store's project.
func beadsDirIsExternalToCWD(beadsDir string) bool {
if beadsDir == "" {
return false
}
cwd, err := os.Getwd()
if err != nil {
// No position to compare against. Report no redirect rather than
// inventing one from a failure that says nothing about provenance.
return false
}
discovered := FindBeadsDirFrom(cwd)
if discovered == "" {
// Nothing is discoverable from here, yet a workspace was resolved, so
// some caller-directed channel must have named it.
return true
}
return !utils.PathsEqual(discovered, beadsDir)
}
// buildRepoContext constructs the RepoContext by resolving all paths.
// This is called once per process via sync.Once.
func buildRepoContext() (*RepoContext, error) {
@ -134,7 +272,12 @@ func buildRepoContext() (*RepoContext, error) {
var err error
repoRoot, err = git.GetMainRepoRoot()
if err != nil {
return nil, fmt.Errorf("cannot determine repository root: %w", err)
// Typed so callers that can work without git select this exact
// failure with errors.As instead of matching the message text.
// beadsDir is carried along because it has already cleared steps
// 1 and 2 above (found, and inside the safe boundary), which is
// precisely what makes the no-git fallback safe to take.
return nil, &NoRepoRootError{BeadsDir: beadsDir, Err: err}
}
}

View file

@ -0,0 +1,355 @@
package beads
import (
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"github.com/steveyegge/beads/internal/git"
)
// TestGetRepoContextAllowingNoGit_RecoversOutsideGitRepo verifies the
// git-independent entry point resolves a workspace that is not inside a git
// repository, rooting the context at the .beads parent (GH#4772).
func TestGetRepoContextAllowingNoGit_RecoversOutsideGitRepo(t *testing.T) {
tmpDir := t.TempDir()
beadsDir := filepath.Join(tmpDir, ".beads")
if err := os.MkdirAll(beadsDir, 0o750); err != nil {
t.Fatalf("failed to create .beads dir: %v", err)
}
if err := os.WriteFile(filepath.Join(beadsDir, "beads.db"), []byte{}, 0o600); err != nil {
t.Fatalf("failed to create beads.db: %v", err)
}
// An inherited BEADS_DIR wins at FindBeadsDir step 1 (beads.go:929) and would
// bind an unrelated workspace instead of the one this test just built, so the
// walk-discovery assertions below would grade the ambient environment rather
// than the code. The package TestMain scrubs HOME and GIT_CONFIG_* but not
// BEADS_DIR; three sibling tests already use this per-test convention.
t.Setenv("BEADS_DIR", "")
origWD, err := os.Getwd()
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
_ = os.Chdir(origWD)
ResetCaches()
git.ResetCaches()
})
ResetCaches()
git.ResetCaches()
if err := os.Chdir(tmpDir); err != nil {
t.Fatal(err)
}
// Baseline: the git-requiring entry point still refuses, and does so with
// the typed error rather than a bare fmt.Errorf.
if _, err := GetRepoContext(); err == nil {
t.Fatal("GetRepoContext should still fail outside a git repository")
} else {
var noRoot *NoRepoRootError
if !errors.As(err, &noRoot) {
t.Fatalf("GetRepoContext error = %v, want a *NoRepoRootError", err)
}
}
rc, err := GetRepoContextAllowingNoGit()
if err != nil {
t.Fatalf("GetRepoContextAllowingNoGit failed outside a git repository: %v", err)
}
wantBeadsDir := resolveSymlinks(beadsDir)
if rc.BeadsDir != wantBeadsDir {
t.Errorf("BeadsDir = %q, want %q", rc.BeadsDir, wantBeadsDir)
}
if want := filepath.Dir(wantBeadsDir); rc.RepoRoot != want {
t.Errorf("RepoRoot = %q, want %q (the .beads parent)", rc.RepoRoot, want)
}
if rc.CWDRepoRoot != "" {
t.Errorf("CWDRepoRoot = %q, want empty outside a git repository", rc.CWDRepoRoot)
}
// The .beads here is discoverable by walking up from the working directory, so
// the caller is standing in this workspace and the synthesized context must
// not claim a redirect. Because externality is decided positionally rather
// than from an environment snapshot, the BEADS_DIR scrub above is all this
// assertion needs — there is no package-init value left to stub.
// TestRecoverNoGit_RedirectProvenance covers the other side.
if rc.IsRedirected {
t.Error("IsRedirected = true for a .beads found by the working-directory walk")
}
if rc.IsWorktree {
t.Error("IsWorktree = true with no git repository to be a worktree of")
}
}
// TestNoRepoRootError_DoesNotMatchUnsafeLocation is the regression for the
// discriminator itself.
//
// The no-git fallback must fire on exactly one failure: "a valid,
// boundary-checked .beads was found, but there is no git root". The other
// failure buildRepoContext can return — the SEC-003 unsafe-location rejection
// — embeds the offending path verbatim in its message, so a substring test
// over the message text is controlled by the path being rejected: a workspace
// whose path contains the probe phrase would take the fallback and have its
// unsafe-location error silently cleared.
//
// errors.As over a typed error cannot be spoofed that way, which is why the
// selection is typed.
func TestNoRepoRootError_DoesNotMatchUnsafeLocation(t *testing.T) {
const probe = "cannot determine repository root"
hostilePath := filepath.Join("/etc", probe, ".beads")
unsafeErr := fmt.Errorf("BEADS_DIR points to unsafe location: %s", hostilePath)
// The old discriminator: a path-controlled false positive.
if !strings.Contains(unsafeErr.Error(), probe) {
t.Fatalf("test setup no longer reproduces the substring collision: %v", unsafeErr)
}
// The assertion that matters: drive the SELECTION, not errors.As. Asking
// errors.As about two hand-built values tests the standard library and
// passes no matter which discriminator this package actually uses — with
// the typed check swapped back for strings.Contains, a test shaped that
// way stays green while the bug it is named after is fully reintroduced.
// recoverNoGit is that selection, so this drives it directly.
if rc, err := recoverNoGit(nil, unsafeErr); err == nil {
t.Errorf("unsafe-location error was recovered into a context (%+v); it must propagate", rc)
} else if err != unsafeErr {
t.Errorf("unsafe-location error came back changed: %v", err)
}
// The other two failures buildRepoContext can return must also pass
// through untouched, for the same reason.
noBeadsErr := fmt.Errorf("no .beads directory found")
if _, err := recoverNoGit(nil, noBeadsErr); err != noBeadsErr {
t.Errorf("no-.beads error came back changed: %v", err)
}
if rc, err := recoverNoGit(&RepoContext{BeadsDir: "/tmp/ok/.beads"}, nil); err != nil || rc == nil || rc.BeadsDir != "/tmp/ok/.beads" {
t.Errorf("a successful context must pass through untouched: rc=%+v err=%v", rc, err)
}
// And the one failure that IS recoverable must be recovered, with the
// boundary-checked directory the error carried.
realErr := &NoRepoRootError{BeadsDir: "/tmp/ws/.beads", Err: errors.New("not a git repository")}
rc, err := recoverNoGit(nil, realErr)
if err != nil {
t.Fatalf("recoverNoGit(NoRepoRootError) = %v, want a synthesized context", err)
}
if rc.BeadsDir != "/tmp/ws/.beads" {
t.Errorf("BeadsDir = %q, want the boundary-checked dir carried by the error", rc.BeadsDir)
}
if rc.RepoRoot != filepath.Dir("/tmp/ws/.beads") {
t.Errorf("RepoRoot = %q, want the .beads parent", rc.RepoRoot)
}
if !strings.Contains(realErr.Error(), probe) {
t.Errorf("error message changed: %q — the wording is user-facing", realErr.Error())
}
if !errors.Is(realErr, realErr.Err) {
t.Error("NoRepoRootError must unwrap to the underlying git failure")
}
}
// TestRecoverNoGit_RootsAtTheRepoContainingBeadsDir is the regression for
// rooting the synthesized context.
//
// The failure that reaches recoverNoGit is the CWD's missing repository, not the
// .beads's. Rooting at filepath.Dir(BeadsDir) conflated the two, so a .beads
// that did live inside a repo reported a SUBDIRECTORY of that repo as repo_root
// and the same workspace answered differently depending only on where the caller
// stood. repoRootForBeadsDir asks git from the .beads side, which needs no CWD
// repo.
func TestRecoverNoGit_RootsAtTheRepoContainingBeadsDir(t *testing.T) {
repoRoot := resolveSymlinks(t.TempDir())
cmd := exec.Command("git", "init", "-q")
cmd.Dir = repoRoot
if out, err := cmd.CombinedOutput(); err != nil {
t.Skipf("git init unavailable: %v: %s", err, out)
}
// The .beads lives in a SUBDIRECTORY of the repo, which is the case that
// distinguishes the two rootings.
beadsDir := filepath.Join(repoRoot, "sub", ".beads")
if err := os.MkdirAll(beadsDir, 0o750); err != nil {
t.Fatal(err)
}
rc, err := recoverNoGit(nil, &NoRepoRootError{BeadsDir: beadsDir, Err: errors.New("not a git repository")})
if err != nil {
t.Fatalf("recoverNoGit: %v", err)
}
if got := resolveSymlinks(rc.RepoRoot); got != repoRoot {
t.Errorf("RepoRoot = %q, want %q (the repository containing .beads, not its parent directory %q)",
got, repoRoot, filepath.Dir(beadsDir))
}
}
// TestRecoverNoGit_RootsAtBeadsParentWithNoGitAnywhere pins the other half of
// the same change: when git cannot answer from the .beads side either,
// repoRootForBeadsDir falls back to the .beads parent, so the documented
// no-git-anywhere behaviour is preserved exactly.
func TestRecoverNoGit_RootsAtBeadsParentWithNoGitAnywhere(t *testing.T) {
workspace := resolveSymlinks(t.TempDir())
beadsDir := filepath.Join(workspace, ".beads")
if err := os.MkdirAll(beadsDir, 0o750); err != nil {
t.Fatal(err)
}
rc, err := recoverNoGit(nil, &NoRepoRootError{BeadsDir: beadsDir, Err: errors.New("not a git repository")})
if err != nil {
t.Fatalf("recoverNoGit: %v", err)
}
if got := resolveSymlinks(rc.RepoRoot); got != workspace {
t.Errorf("RepoRoot = %q, want the .beads parent %q", got, workspace)
}
}
// TestRecoverNoGit_RedirectProvenance pins what the synthesized context says
// about identity, which is the question `bd context` exists to answer.
//
// isExternalBeadsDir compares git COMMON DIRS, and the CWD side cannot be
// computed without a repository — which is precisely the state this fallback
// serves. Position is the substitute: the workspace is a redirect iff discovery
// standing in the CWD would not have found it. That covers all four
// caller-directed channels (BEADS_DIR, --db, BEADS_DB/BD_DB, -C) uniformly,
// because it asks where the caller IS rather than which variable was set — and
// bd rewrites BEADS_DIR for itself before resolving, so the environment cannot
// answer this question at all.
func TestRecoverNoGit_RedirectProvenance(t *testing.T) {
newWorkspace := func(t *testing.T, parent string) string {
t.Helper()
beadsDir := filepath.Join(parent, ".beads")
if err := os.MkdirAll(beadsDir, 0o750); err != nil {
t.Fatal(err)
}
// hasBeadsProjectFiles gates discovery, so the workspace needs to look
// like a real one to be found by the walk.
if err := os.WriteFile(filepath.Join(beadsDir, "metadata.json"), []byte("{}\n"), 0o600); err != nil {
t.Fatal(err)
}
return resolveSymlinks(beadsDir)
}
// chdirTo moves the process into dir for the duration of the subtest. Only
// the caller's POSITION decides provenance now, so this is the control.
chdirTo := func(t *testing.T, dir string) {
t.Helper()
origWD, err := os.Getwd()
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
_ = os.Chdir(origWD)
ResetCaches()
git.ResetCaches()
})
ResetCaches()
git.ResetCaches()
if err := os.Chdir(dir); err != nil {
t.Fatal(err)
}
}
t.Run("discoverable from the CWD is not redirected", func(t *testing.T) {
t.Setenv("BEADS_DIR", "")
workspace := resolveSymlinks(t.TempDir())
beadsDir := newWorkspace(t, workspace)
chdirTo(t, workspace)
rc, err := recoverNoGit(nil, &NoRepoRootError{BeadsDir: beadsDir, Err: errors.New("not a git repository")})
if err != nil {
t.Fatalf("recoverNoGit: %v", err)
}
if rc.IsRedirected {
t.Error("IsRedirected = true for a .beads discoverable by walking up from the working directory")
}
})
t.Run("bd's own re-exported BEADS_DIR does not fake a redirect", func(t *testing.T) {
workspace := resolveSymlinks(t.TempDir())
beadsDir := newWorkspace(t, workspace)
chdirTo(t, workspace)
// bd exports a BEADS_DIR for itself before resolving (context_cmd.go
// calls prepareSelectedNoDBContext immediately beforehand), so a
// walk-found workspace always has one in the environment by the time
// this runs. Position must be indifferent to it; an environment
// inventory would report a redirect here.
t.Setenv("BEADS_DIR", beadsDir)
rc, err := recoverNoGit(nil, &NoRepoRootError{BeadsDir: beadsDir, Err: errors.New("not a git repository")})
if err != nil {
t.Fatalf("recoverNoGit: %v", err)
}
if rc.IsRedirected {
t.Error("IsRedirected = true for a walk-discoverable workspace that bd merely re-exported")
}
})
t.Run("named from a directory that cannot reach it is redirected", func(t *testing.T) {
t.Setenv("BEADS_DIR", "")
beadsDir := newWorkspace(t, resolveSymlinks(t.TempDir()))
// Stand somewhere with no .beads on its ancestor chain. This is the
// shape every caller-directed channel produces: --db, BEADS_DB/BD_DB
// and -C all resolve a store the CWD could never have discovered.
chdirTo(t, resolveSymlinks(t.TempDir()))
rc, err := recoverNoGit(nil, &NoRepoRootError{BeadsDir: beadsDir, Err: errors.New("not a git repository")})
if err != nil {
t.Fatalf("recoverNoGit: %v", err)
}
if !rc.IsRedirected {
t.Error("IsRedirected = false for a workspace the working directory cannot discover")
}
if role, ok := rc.Role(); !ok || role != Contributor {
t.Errorf("Role() = (%q, %v), want (%q, true) — a redirect implies contributor", role, ok, Contributor)
}
})
t.Run("a sibling of the CWD is redirected", func(t *testing.T) {
t.Setenv("BEADS_DIR", "")
// The boundary the review left unspecified, settled deliberately: a
// store reachable only by being named is a redirect even when it sits
// beside the caller. With no repository for the CWD there is no
// enclosing scope that could make a sibling local.
parent := resolveSymlinks(t.TempDir())
here := filepath.Join(parent, "here")
sibling := filepath.Join(parent, "sibling")
if err := os.MkdirAll(here, 0o750); err != nil {
t.Fatal(err)
}
if err := os.MkdirAll(sibling, 0o750); err != nil {
t.Fatal(err)
}
beadsDir := newWorkspace(t, sibling)
chdirTo(t, here)
rc, err := recoverNoGit(nil, &NoRepoRootError{BeadsDir: beadsDir, Err: errors.New("not a git repository")})
if err != nil {
t.Fatalf("recoverNoGit: %v", err)
}
if !rc.IsRedirected {
t.Error("IsRedirected = false for a .beads in a sibling directory of the working directory")
}
})
t.Run("a different discoverable workspace is still a redirect", func(t *testing.T) {
t.Setenv("BEADS_DIR", "")
// The CWD can discover a workspace, but not THIS one.
local := resolveSymlinks(t.TempDir())
newWorkspace(t, local)
named := newWorkspace(t, resolveSymlinks(t.TempDir()))
chdirTo(t, local)
rc, err := recoverNoGit(nil, &NoRepoRootError{BeadsDir: named, Err: errors.New("not a git repository")})
if err != nil {
t.Fatalf("recoverNoGit: %v", err)
}
if !rc.IsRedirected {
t.Error("IsRedirected = false, but the resolved workspace is not the one the CWD discovers")
}
})
}

View file

@ -26,8 +26,12 @@ func (r *contextRepositoryImpl) beadsDir(ctx context.Context) string {
return r.fsRepo.ResolveBeadsDirPath(ctx).BeadsDir
}
// RepoContext resolves the workspace paths behind `bd context`'s proxied
// route. It tolerates the absence of a git repository for the same reason the
// direct route does: this provider only reads config files, and a workspace
// outside git is a supported degraded state, not a failure (GH#4772).
func (r *contextRepositoryImpl) RepoContext(ctx context.Context) (domain.RepoPaths, error) {
rc, err := beads.GetRepoContext()
rc, err := beads.GetRepoContextAllowingNoGit()
if err != nil {
return domain.RepoPaths{}, err
}
@ -41,10 +45,15 @@ func (r *contextRepositoryImpl) RepoContext(ctx context.Context) (domain.RepoPat
}
func (r *contextRepositoryImpl) Role(ctx context.Context) (string, bool, error) {
rc, err := beads.GetRepoContext()
rc, err := beads.GetRepoContextAllowingNoGit()
if err != nil {
return "", false, err
}
// Outside a git repo rc.Role() still answers: an explicit BEADS_DIR
// resolves to Contributor directly, and otherwise `git config --get
// beads.role` reads the global and system files, which are readable with
// no repository. It reports "not configured" only when none of those
// carry a role — it does not fail the command either way.
role, ok := rc.Role()
return string(role), ok, nil
}