* 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>
224 lines
7.5 KiB
Go
224 lines
7.5 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
|
|
"github.com/spf13/cobra"
|
|
"github.com/steveyegge/beads/internal/beads"
|
|
"github.com/steveyegge/beads/internal/configfile"
|
|
"github.com/steveyegge/beads/internal/doltserver"
|
|
"github.com/steveyegge/beads/internal/metrics"
|
|
"github.com/steveyegge/beads/internal/storage/domain"
|
|
)
|
|
|
|
// ContextInfo contains the effective backend identity and repository context.
|
|
type ContextInfo struct {
|
|
BeadsDir string `json:"beads_dir"`
|
|
RepoRoot string `json:"repo_root"`
|
|
CWDRepoRoot string `json:"cwd_repo_root,omitempty"`
|
|
IsRedirected bool `json:"is_redirected"`
|
|
IsWorktree bool `json:"is_worktree"`
|
|
Backend string `json:"backend"`
|
|
DoltMode string `json:"dolt_mode"`
|
|
ServerHost string `json:"server_host,omitempty"`
|
|
ServerPort int `json:"server_port,omitempty"`
|
|
ProxiedDir string `json:"proxied_dir,omitempty"`
|
|
Database string `json:"database"`
|
|
DataDir string `json:"data_dir,omitempty"`
|
|
ProjectID string `json:"project_id,omitempty"`
|
|
SyncRemote string `json:"sync_remote,omitempty"`
|
|
SyncGitRemote string `json:"sync_git_remote,omitempty"` // Deprecated: use sync_remote
|
|
Role string `json:"role,omitempty"`
|
|
BdVersion string `json:"bd_version"`
|
|
}
|
|
|
|
var contextCmd = &cobra.Command{
|
|
Use: "context",
|
|
GroupID: "setup",
|
|
Short: "Show effective backend identity and repository context",
|
|
Long: `Show the effective backend identity information including repository paths,
|
|
backend configuration, and sync settings.
|
|
|
|
This command reads directly from config files and does not require the
|
|
database to be open, making it useful for diagnostics in degraded states.
|
|
|
|
Examples:
|
|
bd context # Show context information
|
|
bd context --json # Output in JSON format
|
|
`,
|
|
SilenceUsage: true,
|
|
SilenceErrors: true,
|
|
RunE: func(cmd *cobra.Command, args []string) error {
|
|
evt := metrics.NewCommandEvent("context")
|
|
defer func() {
|
|
if c := metrics.Global(); c != nil {
|
|
c.CloseEventAndAdd(evt)
|
|
}
|
|
}()
|
|
|
|
if usesProxiedServer() {
|
|
return runContextProxiedServer(cmd, rootCtx)
|
|
}
|
|
|
|
// The direct route reads config files itself rather than through the
|
|
// contextinfo provider — it must answer in degraded states where no
|
|
// database can be opened — but it assembles the SAME snapshot the
|
|
// proxied route gets from the provider, and hands it to the same
|
|
// view. That is what keeps `bd context` one answer across two routes,
|
|
// and what puts both of them on the projection GET /v0/beads/context
|
|
// serves. TestContextRoutesNameOneWorkspaceTheSameWay holds them to it;
|
|
// until it existed both routes carried their own `Backend: dolt` and
|
|
// agreed by telling the same lie.
|
|
snapshot := domain.ContextInfo{BdVersion: Version}
|
|
|
|
if selected := selectedNoDBBeadsDir(cmd); selected != "" {
|
|
prepareSelectedNoDBContext(selected)
|
|
}
|
|
|
|
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 {
|
|
return jerr
|
|
}
|
|
return SilentExit()
|
|
}
|
|
return HandleError("cannot resolve repo context: %v", err)
|
|
}
|
|
|
|
snapshot.BeadsDir = rc.BeadsDir
|
|
snapshot.RepoRoot = rc.RepoRoot
|
|
snapshot.CWDRepoRoot = rc.CWDRepoRoot
|
|
snapshot.IsRedirected = rc.IsRedirected
|
|
snapshot.IsWorktree = rc.IsWorktree
|
|
|
|
if role, ok := rc.Role(); ok {
|
|
snapshot.Role = string(role)
|
|
}
|
|
|
|
cfg, err := configfile.LoadForDiscovery(rc.BeadsDir)
|
|
if err != nil {
|
|
cfg = configfile.DefaultConfig()
|
|
}
|
|
if cfg == nil {
|
|
cfg = configfile.DefaultConfig()
|
|
}
|
|
|
|
if err := applyContextBackend(&snapshot, rc.BeadsDir, cfg); err != nil {
|
|
return HandleError("%v", err)
|
|
}
|
|
|
|
snapshot.SyncRemote = resolveSyncRemoteFromDir(rc.BeadsDir)
|
|
|
|
info := contextInfoView(snapshot)
|
|
if jsonOutput {
|
|
return outputJSON(info)
|
|
}
|
|
printContextText(info)
|
|
return nil
|
|
},
|
|
}
|
|
|
|
// applyContextBackend records the backend half of the direct route's snapshot,
|
|
// off the config files it just read.
|
|
//
|
|
// It is a named function rather than a run of assignments inside the command so
|
|
// that the claim above it — that both `bd context` routes assemble the SAME
|
|
// snapshot — is something a test can drive rather than something a reader has
|
|
// to check by eye. TestContextRoutesNameOneWorkspaceTheSameWay does exactly
|
|
// that, comparing this against the contextinfo provider the proxied route and
|
|
// GET /v0/beads/context both go through.
|
|
//
|
|
// The identity itself goes through domain.SetBackendIdentity, which is the one
|
|
// policy both routes share: it is what stops a non-Dolt workspace from being
|
|
// described as embedded Dolt on database "beads", which is what both routes did
|
|
// while each held its own copy of `Backend: configfile.BackendDolt`.
|
|
func applyContextBackend(snapshot *domain.ContextInfo, beadsDir string, cfg *configfile.Config) error {
|
|
snapshot.SetBackendIdentity(cfg.GetBackend(), cfg.GetDoltMode(), cfg.GetDoltDatabase())
|
|
snapshot.ProjectID = cfg.ProjectID
|
|
|
|
if cfg.IsDoltServerMode() {
|
|
snapshot.ServerHost = cfg.GetDoltServerHost()
|
|
snapshot.ServerPort = doltserver.DefaultConfig(beadsDir).Port
|
|
}
|
|
if cfg.IsDoltProxiedServerMode() {
|
|
p, err := resolveProxiedServerRootPath(beadsDir)
|
|
if err != nil {
|
|
return fmt.Errorf("resolve proxied server root: %w", err)
|
|
}
|
|
snapshot.ProxiedDir = p
|
|
}
|
|
if dataDir := cfg.GetDoltDataDir(); dataDir != "" {
|
|
snapshot.DataDir = dataDir
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func printContextText(info ContextInfo) {
|
|
fmt.Printf("bd version: %s\n", info.BdVersion)
|
|
fmt.Println()
|
|
|
|
// Repository
|
|
fmt.Println("Repository:")
|
|
fmt.Printf(" beads dir: %s\n", info.BeadsDir)
|
|
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")
|
|
}
|
|
if info.IsWorktree {
|
|
fmt.Printf(" worktree: yes\n")
|
|
}
|
|
if info.Role != "" {
|
|
fmt.Printf(" role: %s\n", info.Role)
|
|
}
|
|
fmt.Println()
|
|
|
|
// Backend
|
|
fmt.Println("Backend:")
|
|
fmt.Printf(" type: %s\n", info.Backend)
|
|
// Dolt-only identity. A registered backend reports neither, and a bare
|
|
// "mode:" with nothing after it reads as a failure to determine rather than
|
|
// as not-applicable — so omit them, like every other optional field here.
|
|
if info.DoltMode != "" {
|
|
fmt.Printf(" mode: %s\n", info.DoltMode)
|
|
}
|
|
if info.Database != "" {
|
|
fmt.Printf(" database: %s\n", info.Database)
|
|
}
|
|
if info.ServerHost != "" {
|
|
fmt.Printf(" server: %s:%d\n", info.ServerHost, info.ServerPort)
|
|
}
|
|
if info.ProxiedDir != "" {
|
|
fmt.Printf(" proxied dir: %s\n", info.ProxiedDir)
|
|
}
|
|
if info.DataDir != "" {
|
|
fmt.Printf(" data dir: %s\n", info.DataDir)
|
|
}
|
|
if info.ProjectID != "" {
|
|
fmt.Printf(" project id: %s\n", info.ProjectID)
|
|
}
|
|
|
|
// Sync
|
|
if info.SyncRemote != "" {
|
|
fmt.Println()
|
|
fmt.Println("Sync:")
|
|
fmt.Printf(" remote: %s\n", info.SyncRemote)
|
|
}
|
|
}
|
|
|
|
func init() {
|
|
rootCmd.AddCommand(contextCmd)
|
|
readOnlyCommands["context"] = true
|
|
}
|