beads/cmd/bd/context_embedded_test.go
Harry Miller 1cc19040af
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>
2026-10-01 07:08:12 -07:00

220 lines
7.4 KiB
Go

//go:build cgo
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) {
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded dolt integration tests")
}
t.Parallel()
bd := buildEmbeddedBD(t)
dir, _, _ := bdInit(t, bd, "--prefix", "tx")
t.Run("context_default", func(t *testing.T) {
cmd := exec.Command(bd, "context")
cmd.Dir = dir
cmd.Env = bdEnv(dir)
stdout, stderr, err := runCommandBuffers(t, cmd)
if err != nil {
t.Fatalf("bd context failed: %v\nstdout:\n%s\nstderr:\n%s", err, stdout.String(), stderr.String())
}
if !strings.Contains(stdout.String(), "embedded") && !strings.Contains(stdout.String(), ".beads") {
t.Errorf("expected embedded mode or .beads in context output: %s", stdout.String())
}
})
t.Run("context_json", func(t *testing.T) {
cmd := exec.Command(bd, "context", "--json")
cmd.Dir = dir
cmd.Env = bdEnv(dir)
stdout, stderr, err := runCommandBuffers(t, cmd)
if err != nil {
t.Fatalf("bd context --json failed: %v\nstdout:\n%s\nstderr:\n%s", err, stdout.String(), stderr.String())
}
if len(strings.TrimSpace(stdout.String())) == 0 {
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) {
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded dolt integration tests")
}
t.Parallel()
bd := buildEmbeddedBD(t)
dir, _, _ := bdInit(t, bd, "--prefix", "xx")
const numWorkers = 8
type workerResult struct {
worker int
err error
}
results := make([]workerResult, numWorkers)
var wg sync.WaitGroup
wg.Add(numWorkers)
for w := 0; w < numWorkers; w++ {
go func(worker int) {
defer wg.Done()
r := workerResult{worker: worker}
cmd := exec.Command(bd, "context")
cmd.Dir = dir
cmd.Env = bdEnv(dir)
out, err := cmd.CombinedOutput()
if err != nil {
r.err = fmt.Errorf("context (worker %d): %v\n%s", worker, err, out)
}
results[worker] = r
}(w)
}
wg.Wait()
for _, r := range results {
if r.err != nil && !strings.Contains(r.err.Error(), "one writer at a time") {
t.Errorf("worker %d failed: %v", r.worker, r.err)
}
}
}