beads/cmd/bd/init_home_guard_test.go
gascity-eddie[bot] d2748411c4
fix(init): refuse to initialize directly in the home directory (#4635) (follow-up to #4795) (#7609)
* fix(init): refuse to initialize directly in the home directory

`bd init` in a directory that isn't a git repo (and has no explicit
BEADS_DIR) unconditionally `git init`s the directory, writes agent
scaffolding (CLAUDE.md, AGENTS.md, .gitignore, .agents/, .codex/,
.claude/settings.json), and commits — with no confirmation. Run in the
home directory this silently turns $HOME into a git repository and can
clobber an existing ~/CLAUDE.md. It's worse under --non-interactive
(auto-engaged whenever stdin isn't a TTY, i.e. whenever an agent runs
`bd init`): all of it happens with zero prompt (GH#4635).

Refuse the init when the current directory is the user's home directory
and it isn't already a git repo (and no explicit BEADS_DIR was given),
with a clear error pointing at the alternatives (cd into a project, or
set BEADS_DIR). The common fresh-project flow (mkdir proj && cd proj &&
bd init) and already-git-tracked homes are unaffected.

The guard runs as the first statement in init's RunE, ahead of every
path that has an effect. Position is the whole fix: --reinit-local /
--force reach countExistingIssues, which opens a real store (creating
the data directory, able to run migrations), and --proxied-server
dispatches to runInitProxiedServer -> EnsureGitRepo, i.e. a `git init`
in the current directory. Both run long before the point where a guard
placed with the rest of the path validation would fire.

Home is resolved from the OS account database (user.Current) in
preference to $HOME, so the guard keys off the real account home even
when $HOME is repointed — which this repo's own tests do constantly.
Both sources are best-effort: a CGO-free build's user.Current() falls
back to os.UserHomeDir() (i.e. $HOME on Unix) when the account is absent
from the passwd database, so this is a preference, not a guarantee of
$HOME-independence. Mirrors the home resolution in internal/beads'
isPathInSafeBoundary.

Tests: TestIsUserHomeDir and TestGuardInitInHomeDir cover the decision
(resolver stubbed, so the real home is never touched);
TestInitCommand_RefusesInHomeDirBeforeAnySideEffect runs the actual
command for plain / --reinit-local / --force / --proxied-server and
asserts not just the refusal but that nothing — .git, .beads, CLAUDE.md,
AGENTS.md, .gitignore, .agents, .codex, .claude — exists afterwards.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(init): key the home guard on caller intent, and give it a named exit code

Three blocking items, two reviewers converging on the first.

1. The guard read os.Getenv("BEADS_DIR") as "the user explicitly opted in".
   It is not. Cobra's root PersistentPreRunE runs before RunE and, for a
   no-DB command like init, resolves a beads dir and exports it
   (selectedNoDBBeadsDir -> prepareSelectedNoDBContext ->
   prepareSelectedCommandContext). That resolution bottoms out in
   beads.FindBeadsDir(), which accepts any ancestor .beads/ for which
   hasBeadsProjectFiles is true - and a config.yaml alone is enough. That is
   the shape of this project's own legacy user-level ~/.beads/config.yaml,
   so anyone carrying it got BEADS_DIR set for them and the guard failed
   open. `bd -C <dir> init` opened the same hole, and that one does not even
   move the working directory the scaffolding lands in.

   The damage is not self-cancelling. The `git init` half is separately
   gated on the same env so it stayed skipped, but the agent scaffolding is
   not gated at all: addAgentsInstructions, InstallClaudeProject,
   InstallCodexProject and InstallCursorProject all write relative to CWD.
   So the bypass still clobbered ~/CLAUDE.md, ~/AGENTS.md and
   ~/.claude/settings.json - the files the guard exists to protect.

   beadsDirFromCaller captures BEADS_DIR as the process INHERITED it, at
   package initialization, which the language guarantees runs before main
   and therefore before any bd code exports one of its own. The guard
   consults that snapshot, so the question it asks is "did the caller name a
   beads dir", not "does the process env happen to have one".

2. The refusal skipped all three of init's refusal conventions.
   ExitHomeDirRefused = 13 joins 10/11/12, the message is printed and the
   error carries only the code (the ExitLocalExistsRefused pattern), and
   docs/recovery/init-safety.md gains an init-home-refused anchor - TOC
   entry, symptom, why, three recovery paths, and the script-branching
   snippet - which the message points at. `bd help init-safety` lists it.

   NOT added: a cmd/bd/protocol case. That corpus states that §E3 freezes
   10/11/12/130 and that a new stable code requires a spec revision, so
   asserting 13 there would be claiming wire status the spec has not
   granted. The constant plus the docs anchor give the refusal the same
   in-repo scriptability without that claim; say the word if the spec should
   be revised and I will add the corpus case too.

3. CHANGELOG [Unreleased] entry, citing #4635 and stating the scope limits.

Also from review: the message's BEADS_DIR escape hatch said "set BEADS_DIR
if you really mean to initialize here", which is not what happens - an
explicit BEADS_DIR makes hasExplicitBeadsDir true, skipping the git init and
the CWD-local .beads. It now says so.

Test coverage answers the point both reviewers made about the RunE-only
tests. TestInitThroughRootCmd_RefusesInHomeDirWithDiscoveredBeadsDir runs
through rootCmd.Execute, in a home carrying only .beads/config.yaml, and
asserts the precondition (pre-run really does discover it) before asserting
the refusal and that no scaffolding landed. --backend names a backend that
cannot exist as a circuit breaker, so a future fail-open stops there instead
of building a store in someone's home directory. Against the old code it
reproduces maphew's observation verbatim:

    init ran past the home guard and got as far as backend selection:
    unknown backend "review4795-home-guard-sentinel"

plus a unit case pinning that a bd-exported BEADS_DIR is not caller opt-in.

Reported-by: maphew, 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(init): harden the home-dir guard (opt-out, git probe, exit 15)

Maintainer fixup on top of #4795 by harry-miller-trimble, for the three
majors and three of the minors from the adopt-pr review, the major, the
minor and the nit from its second round, and two of the minors from its
third. The contributor's commits are unchanged.

The BEADS_DIR opt-out still set up $HOME (major). The refusal said
`BEADS_DIR=<path>/.beads bd init` writes nothing in the home directory,
but an explicit BEADS_DIR only skips the git init. The agent files
(CLAUDE.md, AGENTS.md, .claude/, .codex/, .cursor/, .agents/) are
written relative to the working directory whatever BEADS_DIR says, and a
BEADS_DIR under $HOME counts as local, so ~/.gitignore was appended to
as well. guardInitInHomeDir now returns keepHomeClean for that case.
RunE forces skipAgents, which the proxied route also reads from its
input, and both routes gate the project .gitignore on keepHomeClean.
Init prints a note saying so, with a `bd setup <recipe> --global`
pointer for anyone who wanted an integration everywhere.

The refusal text, the CHANGELOG entry and the recovery playbook now say
what the opt-out does: it sets up only the named workspace, after a
`mkdir -p`, because init refuses a BEADS_DIR whose parent does not
exist. They no longer say nothing else is written, because Dolt and
metrics keep their own state under $HOME. The refusal's Why also stops
saying init overwrites existing files: it installs into them, and in
$HOME those are user-wide agent settings.

TestInitInUntrackedHomeWithCallerBeadsDir_SetsUpOnlyTheWorkspace runs
the direct route end to end against a Dolt server, once with the
workspace outside the home and once under it. Every seeded file must
come out unchanged, with nothing added. The proxied route's agent-file
and .gitignore gates are not covered by a test: there is no in-process
proxied init fixture to drive them.

The tracked-home probe trusted git's routing environment (major).
isGitRepo() is a plain `git rev-parse --git-dir`, so an inherited
GIT_DIR, or a home that only sits inside an enclosing work tree, stood
the guard down. Init's own git-init decision scrubs that environment,
then runs git init in the home and installs agent files into it. The
guard now asks isGitWorkTreeRoot(cwd), which runs
`rev-parse --show-toplevel` through initArtifactGitCommand and matches
the result against the home itself. Two new subtests pin both false
positives. Each asserts that isGitRepo() still reports true, so the
subtests keep reproducing the old probe.

Exit 13 was already taken (major). It is ExitGuardMismatch, "racer won,
skip gracefully", and 14 is ExitMigrationFrozen, so a wrapper branching
on exit codes would read this refusal as a benign skip. The refusal now
exits 15. The change is in init_safety.go, `bd help init-safety`,
ADR 0002, the playbook and the CHANGELOG. ADR 0002 also notes that 15
sits outside the protocol v0 §E3 freeze pinned in
cmd/bd/protocol/exit_codes_init_test.go.

The opt-out still set up a repository around the home (second round,
major). The tracked-home probe sends a home that only sits inside an
enclosing work tree, such as a dotfiles or monorepo checkout above it,
to the BEADS_DIR opt-out. Git finds that repository from the home, so
init set it up as the project: core.hooksPath, beads.role, fork routing
and the fork exclude, its origin as the workspace's Dolt remote, and a
bootstrap commit. That commit staged the home's legacy ~/.beads and then
whatever agent files the home holds, ~/.codex/auth.json among them, and
committed them with --no-verify. The proxied route did the same from its
tail.

keepHomeClean now also means "outside every repository". It is only
true when the home is not a work-tree root, so no repository git finds
from there is the home's own. On the direct route, RunE forces skipHooks
beside skipAgents; projectRoleRepo holds the six isInitRoleGitRepo
gates (the role prompt and pins, the GH#2950 safety net, fork routing,
the fork exclude) to keepHomeClean; and both origin-as-remote gates, the
bootstrap commit and the upstream advice are gated on it. On the proxied
route, the tail's isRepo probe, which gates the role, the fork exclude,
the commit and the upstream advice, and resolveProxiedInitRemoteURL are
gated on it; skipHooks reaches the tail through its input. What a flag
asks for still happens: --stealth and --setup-exclude write their
exclude, and an explicit --remote or a configured sync remote is still
used. The note, the refusal text, the CHANGELOG entry and the playbook
say what the opt-out leaves alone. Gating the commit also drops the
"skipped bootstrap commit" note the opt-out printed from an untracked
home.

Tests for it:
- The end-to-end test gains home_inside_a_repository. The home sits in
  a repository with one commit and an origin, and holds a legacy
  ~/.beads; init runs without --quiet. The repository must keep its one
  commit, nothing staged and its .git/config byte for byte (so no
  core.hooksPath or beads.role). The workspace must not take its origin
  as its Dolt remote, and init must print the note and no upstream
  advice. The repository has no upstream remote, because fork routing
  would create ~/.beads-planning under the suite's real HOME.
- TestProxiedInitTailKeepHomeCleanLeavesEnclosingRepoAlone runs the
  proxied tail from a home inside a repository with an origin and an
  upstream, so the fork exclude would fire. It requires no fork
  exclude, no commit, nothing staged and the same .git/config.
- TestProxiedInitRemoteURLUsesSelectedProject gains a keep_home_clean
  row (the origin is not used) and a configured_keep_home_clean row (a
  configured remote still is).
- The guard's enclosing-repository subtest also checks that a caller
  BEADS_DIR there returns keepHomeClean.

Second-round minor and nit:
- beadsDirFromCaller's comment and the playbook say why a BEADS_DIR read
  from a .beads/.env does not count as the caller's, although
  beadsDirProvidedAtStartup counts it for role detection. From the home
  that file is the legacy ~/.beads/.env, so counting it would let the
  same discovered ~/.beads opt out of the guard.
- The guard tests use t.Chdir, and the hand-rolled chdir helper is gone.

Validation: the init, home-guard and proxied-init tests pass against
the Dolt test container, as do the embedded init lane and the
proxied-server init integration tests. Mutation checks:
- Dropping the forced skipAgents fails both workspace subtests.
- Dropping the .gitignore gate fails the under-home subtest.
- Restoring the plain isGitRepo() probe fails both new false-positive
  subtests.
- Disabling the guard fails every refusal test at the sentinel backend.
- Second round: dropping the forced skipHooks, the projectRoleRepo
  gate, the commit gate, the late origin gate, the upstream advice gate
  or the note each fails home_inside_a_repository on its own check.
  Dropping the proxied tail's gate fails the tail test, and dropping the
  proxied remote gate fails the keep_home_clean row. The third round
  pins the early origin gate (below).

Third-round minors:
- The early origin gate picks the remote the early remote-safety check
  probes, and a failed probe counts as Dolt history. The end-to-end
  test gains unreachable_origin_reinit_local and
  unreachable_origin_force: the home sits in a repository whose origin
  path holds nothing, and init runs with --reinit-local or with --force.
  Both must succeed and leave the repository as it was. Dropping the
  early gate makes init probe that origin and refuse both rows with
  exit 10.
- The playbook, the CHANGELOG entry and guardInitInHomeDir's comment
  name the flags that still change the repository around the home:
  --stealth and --setup-exclude write its .git/info/exclude, and the
  interactive --contributor and --team wizards work in it (beads.role,
  and possibly a sync branch). The opt-out's note is unchanged: none of
  those writes is on its list.

Left for a follow-up:
- The proxied route's .gitignore gate is still unpinned. It needs an
  in-process proxied init fixture, or the
  `useLocalBeads && beadsDirIsLocal && !keepHomeClean` predicate pulled
  out into a table-tested helper.
- Both routes still record the enclosing repository's origin-derived
  repo_id, and its clone_id, on an opt-out workspace. That predates this
  PR for every explicit-BEADS_DIR init and writes nothing to the
  repository; skipping it is a behavior change of its own.

Third-round validation: the home-guard, init-tail and proxied-remote
tests pass in a hermetic env -i run against the Dolt 2.2.0 CI pin (41
tests and subtests, none skipped). Dropping !keepHomeClean from the
early origin gate fails both new rows with exit 10 and leaves the other
three rows passing. go vet, gofmt, the docsync test and the doc
freshness check pass.

Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Harry Miller <harry_miller@trimble.com>

---------

Co-authored-by: Harry Miller <harry_miller@trimble.com>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-authored-by: Eddie the Engineer <adopt-pr@gascity.com>
Co-authored-by: Eddie the Engineer <julianknutsen@users.noreply.github.com>
2026-10-16 13:52:00 +00:00

413 lines
16 KiB
Go

package main
import (
"os"
"path/filepath"
"strings"
"testing"
)
// TestIsUserHomeDir covers the guard decision used to refuse `bd init` directly
// in the user's home directory (GH#4635). The resolver is stubbed so the test
// does not depend on (or touch) the real home directory.
func TestIsUserHomeDir(t *testing.T) {
home := t.TempDir()
stubHomeDir(t, home)
if !isUserHomeDir(home) {
t.Errorf("isUserHomeDir(home) = false, want true for %q", home)
}
if sub := filepath.Join(home, "project"); isUserHomeDir(sub) {
t.Errorf("isUserHomeDir(%q) = true, want false (subdir of home)", sub)
}
if parent := filepath.Dir(home); isUserHomeDir(parent) {
t.Errorf("isUserHomeDir(%q) = true, want false (parent of home)", parent)
}
}
// TestIsUserHomeDir_UnresolvableHome verifies the guard never fires when the
// home directory cannot be resolved (fail-open: better to allow init than to
// wrongly refuse every directory).
func TestIsUserHomeDir_UnresolvableHome(t *testing.T) {
stubHomeDir(t, "")
if isUserHomeDir("/some/dir") {
t.Error("isUserHomeDir should be false when home is unresolvable")
}
}
// TestGuardInitInHomeDir covers the guard's three answers: refuse (an
// untracked home, no BEADS_DIR from the caller), proceed but keep the home
// clean (the same home, with one), and stand aside (a home that is itself a
// git repository, or any directory that simply is not home).
func TestGuardInitInHomeDir(t *testing.T) {
t.Run("refuses_in_untracked_home", func(t *testing.T) {
home := t.TempDir()
stubHomeDir(t, home)
t.Chdir(home)
stubCallerBeadsDir(t, "")
_, err := guardInitInHomeDir()
if err == nil {
t.Fatal("guardInitInHomeDir() = nil, want a refusal in an untracked home")
}
assertHomeDirRefusal(t, err)
})
// The opt-out the refusal offers is a different init, not this one with
// the guard lifted: it may proceed, but it must not set the home up as a
// project (TestInitInUntrackedHomeWithCallerBeadsDir_SetsUpOnlyTheWorkspace
// runs it).
t.Run("caller_beads_dir_proceeds_but_keeps_home_clean", func(t *testing.T) {
home := t.TempDir()
stubHomeDir(t, home)
t.Chdir(home)
stubCallerBeadsDir(t, filepath.Join(home, "elsewhere", ".beads"))
keepHomeClean, err := guardInitInHomeDir()
if err != nil {
t.Fatalf("guardInitInHomeDir() = %v, want nil when the caller named a BEADS_DIR", err)
}
if !keepHomeClean {
t.Error("keepHomeClean = false, want true: init would install agent files into the untracked home")
}
})
// The bypass this guard shipped with: BEADS_DIR in the live environment is
// not evidence the caller asked for anything. bd exports one itself for
// every no-DB command, and beads.FindBeadsDir() accepts an ancestor
// .beads/ holding nothing but a config.yaml — which is where this
// project's own legacy user-level config lives, at ~/.beads/config.yaml.
// So the users most likely to have scaffolding in $HOME worth protecting
// were exactly the ones the guard failed open for.
t.Run("refuses_when_bd_exported_beads_dir_for_itself", func(t *testing.T) {
home := t.TempDir()
stubHomeDir(t, home)
t.Chdir(home)
stubCallerBeadsDir(t, "")
// What the root pre-run does, and what `bd -C <dir>` does: set the
// live env without the caller having named anything.
t.Setenv("BEADS_DIR", filepath.Join(home, ".beads"))
_, err := guardInitInHomeDir()
if err == nil {
t.Fatal("guardInitInHomeDir() = nil; a bd-exported BEADS_DIR is not caller opt-in")
}
assertHomeDirRefusal(t, err)
})
// "Is this home tracked?" has to be asked the way init's own `git init`
// decision asks it, with git's routing environment scrubbed. A plain probe
// believes an inherited GIT_DIR, while init does not: it would find the
// home untracked, `git init` it and install agent files there.
t.Run("refuses_when_git_dir_is_inherited", func(t *testing.T) {
other := t.TempDir()
gitInitAt(t, other)
home := t.TempDir()
stubHomeDir(t, home)
t.Chdir(home)
stubCallerBeadsDir(t, "")
t.Setenv("GIT_DIR", filepath.Join(other, ".git"))
if !isGitRepo() {
t.Fatal("precondition: isGitRepo() = false under an inherited GIT_DIR, so this no longer reproduces the plain probe's false positive")
}
_, err := guardInitInHomeDir()
if err == nil {
t.Fatal("guardInitInHomeDir() = nil; an inherited GIT_DIR does not make the home a repository")
}
assertHomeDirRefusal(t, err)
})
// Only a repository rooted at the home itself means someone set the home
// up on purpose. A home that merely sits inside an enclosing work tree
// still gets init's agent files, so it is refused like any untracked one,
// and a caller BEADS_DIR there is the same opt-out: keepHomeClean, which
// also keeps init out of the enclosing repository
// (TestInitInUntrackedHomeWithCallerBeadsDir_SetsUpOnlyTheWorkspace).
t.Run("refuses_when_home_only_sits_inside_an_enclosing_repo", func(t *testing.T) {
root := t.TempDir()
gitInitAt(t, root)
home := filepath.Join(root, "home")
if err := os.Mkdir(home, 0o750); err != nil {
t.Fatal(err)
}
stubHomeDir(t, home)
t.Chdir(home)
stubCallerBeadsDir(t, "")
if !isGitRepo() {
t.Fatal("precondition: isGitRepo() = false inside the enclosing repository, so this no longer reproduces the plain probe's false positive")
}
_, err := guardInitInHomeDir()
if err == nil {
t.Fatal("guardInitInHomeDir() = nil; an enclosing repository does not make the home itself tracked")
}
assertHomeDirRefusal(t, err)
stubCallerBeadsDir(t, filepath.Join(t.TempDir(), ".beads"))
if keepHomeClean, err := guardInitInHomeDir(); err != nil || !keepHomeClean {
t.Errorf("with a caller BEADS_DIR: guardInitInHomeDir() = (%v, %v), want (true, nil)", keepHomeClean, err)
}
})
// A home that is itself a repository was set up as a project on purpose,
// so init runs there exactly as anywhere else, BEADS_DIR or not.
t.Run("stands_aside_when_home_is_itself_a_git_repo", func(t *testing.T) {
home := t.TempDir()
stubHomeDir(t, home)
t.Chdir(home)
gitInitAt(t, home)
for _, callerBeadsDir := range []string{"", filepath.Join(home, "notes", ".beads")} {
stubCallerBeadsDir(t, callerBeadsDir)
if keepHomeClean, err := guardInitInHomeDir(); err != nil || keepHomeClean {
t.Errorf("caller BEADS_DIR %q: guardInitInHomeDir() = (%v, %v), want (false, nil) in a tracked home", callerBeadsDir, keepHomeClean, err)
}
}
})
t.Run("stands_aside_in_an_ordinary_project_dir", func(t *testing.T) {
home := t.TempDir()
stubHomeDir(t, home)
project := filepath.Join(home, "project")
if err := os.MkdirAll(project, 0o750); err != nil {
t.Fatal(err)
}
t.Chdir(project)
for _, callerBeadsDir := range []string{"", filepath.Join(home, "notes", ".beads")} {
stubCallerBeadsDir(t, callerBeadsDir)
if keepHomeClean, err := guardInitInHomeDir(); err != nil || keepHomeClean {
t.Errorf("caller BEADS_DIR %q: guardInitInHomeDir() = (%v, %v), want (false, nil) for a project dir under home", callerBeadsDir, keepHomeClean, err)
}
}
})
}
// TestInitCommand_RefusesInHomeDirBeforeAnySideEffect runs the actual init
// command, which is where the guard's *position* is under test rather than its
// decision. Both flag shapes below reach a side effect before the guard's
// original location did:
//
// - --reinit-local / --force run countExistingIssues, which opens a real
// store (creating the data directory, and able to run migrations);
// - --proxied-server dispatches to runInitProxiedServer, which calls
// EnsureGitRepo — a `git init` in the current directory.
//
// So the assertion is not merely "it errors": the home must still be empty.
//
// Every case also names a backend that cannot exist, as a circuit breaker: if
// the guard ever fails open, init stops at the unknown-backend check, ahead of
// every effect, and the failure below names the guard instead of a store being
// built in the temp home.
func TestInitCommand_RefusesInHomeDirBeforeAnySideEffect(t *testing.T) {
cases := []struct {
name string
flags map[string]string
}{
{name: "plain", flags: nil},
{name: "reinit_local", flags: map[string]string{"reinit-local": "true"}},
{name: "force", flags: map[string]string{"force": "true"}},
{name: "proxied_server", flags: map[string]string{"proxied-server": "true"}},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
home := t.TempDir()
stubHomeDir(t, home)
t.Chdir(home)
stubCallerBeadsDir(t, "")
t.Setenv("BEADS_DIR", "")
t.Setenv("BD_NON_INTERACTIVE", "1")
setInitFlag(t, "backend", homeGuardSentinelBackend)
for name, value := range tc.flags {
setInitFlag(t, name, value)
}
err := initCmd.RunE(initCmd, nil)
if err == nil {
t.Fatal("bd init in an untracked home returned nil, want a refusal")
}
if strings.Contains(err.Error(), homeGuardSentinelBackend) {
t.Fatalf("init ran past the home guard and got as far as backend selection: %v", err)
}
assertHomeDirRefusal(t, err)
// A refusal that still left something behind is not a refusal.
entries, readErr := os.ReadDir(home)
if readErr != nil {
t.Fatal(readErr)
}
for _, entry := range entries {
t.Errorf("init created %s in the home directory despite refusing", entry.Name())
}
})
}
}
// homeGuardSentinelBackend is a --backend no bd can have: the home-guard
// tests' circuit breaker. Init rejects it before any effect, so a guard that
// fails open ends at that error, which names it, instead of at a real store.
const homeGuardSentinelBackend = "review4795-home-guard-sentinel"
// assertHomeDirRefusal checks that err is the home-directory refusal, by its
// exit code rather than its message: the code is the scriptable contract
// (docs/recovery/init-safety.md#init-home-refused), the wording is not.
func assertHomeDirRefusal(t *testing.T, err error) {
t.Helper()
code, ok := exitCodeFromError(err)
if !ok {
t.Fatalf("refusal did not carry an exit code: %v", err)
}
if code != ExitHomeDirRefused {
t.Fatalf("exit code = %d, want %d (ExitHomeDirRefused)", code, ExitHomeDirRefused)
}
}
// stubCallerBeadsDir sets what the guard sees as the caller-supplied BEADS_DIR.
// The real value is captured at package init from the inherited environment, so
// a test cannot move it with t.Setenv — which is the whole point of the
// snapshot, and why it has to be stubbed here instead.
func stubCallerBeadsDir(t *testing.T, dir string) {
t.Helper()
orig := beadsDirFromCaller
beadsDirFromCaller = dir
t.Cleanup(func() { beadsDirFromCaller = orig })
}
// stubHomeDir points the guard's home resolver at dir for the duration of the
// test. Stubbing rather than setting $HOME is deliberate: the resolver prefers
// the OS account database, so $HOME alone would not move it.
func stubHomeDir(t *testing.T, dir string) {
t.Helper()
orig := resolveUserHomeDir
resolveUserHomeDir = func() string { return dir }
t.Cleanup(func() { resolveUserHomeDir = orig })
}
// gitInitAt makes dir a git repository, with git's routing environment
// scrubbed so an inherited GIT_DIR cannot send the init somewhere else.
func gitInitAt(t *testing.T, dir string) {
t.Helper()
cmd := initArtifactGitCommand(dir, "init")
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("git init failed: %v\n%s", err, out)
}
}
// setInitFlag sets a flag on the shared initCmd and restores it afterwards —
// cobra commands are package-level singletons, so a leaked flag would bleed
// into every later test in this package.
func setInitFlag(t *testing.T, name, value string) {
t.Helper()
flag := initCmd.Flags().Lookup(name)
if flag == nil {
t.Fatalf("init has no --%s flag", name)
}
orig := flag.Value.String()
origChanged := flag.Changed
if err := initCmd.Flags().Set(name, value); err != nil {
t.Fatalf("setting --%s=%s: %v", name, value, err)
}
t.Cleanup(func() {
_ = initCmd.Flags().Set(name, orig)
flag.Changed = origChanged
})
}
// TestInitThroughRootCmd_RefusesInHomeDirWithDiscoveredBeadsDir is the
// regression for the bypass, and it has to run through rootCmd rather than
// calling initCmd.RunE directly — the whole failure lives in a hook RunE-only
// tests skip.
//
// Cobra's root PersistentPreRunE runs first, and for a no-DB command like init
// it resolves a beads dir and exports it (main.go, selectedNoDBBeadsDir ->
// prepareSelectedNoDBContext). That resolution accepts an ancestor .beads/
// holding nothing but a config.yaml, which is precisely the shape of this
// project's legacy user-level ~/.beads/config.yaml. A guard reading the LIVE
// BEADS_DIR therefore saw a value it had set for itself and stood down.
//
// The half that made this worth blocking on: the `git init` is separately
// gated on the same env, so it stayed skipped — but the agent scaffolding is
// not. CLAUDE.md, AGENTS.md, .claude/, .codex/, .cursor/ and .agents/ are
// written relative to the working directory whatever BEADS_DIR says, so the
// bypass still installed into $HOME the user-wide agent settings the guard
// exists to keep out of it.
//
// --backend names a backend that cannot exist (homeGuardSentinelBackend), as
// a circuit breaker: if the guard ever fails open again, init stops at the
// unknown-backend error instead of building a real store in someone's home
// directory, and the assertion below reports that error rather than hanging
// on Dolt.
func TestInitThroughRootCmd_RefusesInHomeDirWithDiscoveredBeadsDir(t *testing.T) {
home := t.TempDir()
stubHomeDir(t, home)
t.Chdir(home)
stubCallerBeadsDir(t, "")
// The caller named nothing. Anything in BEADS_DIR from here on was put
// there by bd itself.
t.Setenv("BEADS_DIR", "")
t.Setenv("HOME", home)
t.Setenv("BD_NON_INTERACTIVE", "1")
// The legacy user-level config, which is all beads.FindBeadsDir needs.
beadsDir := filepath.Join(home, ".beads")
if err := os.MkdirAll(beadsDir, 0o750); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(beadsDir, "config.yaml"), []byte("actor: someone\n"), 0o600); err != nil {
t.Fatal(err)
}
// Confirm the precondition rather than assuming it: if discovery stops
// resolving this, the test would pass for the wrong reason. Compared
// through EvalSymlinks because macOS reports the same temp dir as both
// /var/... and /private/var/....
if got, want := evalSymlinks(t, selectedNoDBBeadsDir(initCmd)), evalSymlinks(t, beadsDir); got != want {
t.Fatalf("precondition: selectedNoDBBeadsDir = %q, want %q — pre-run no longer discovers a config.yaml-only .beads, so this test no longer reproduces the bypass", got, want)
}
origStore, origDBPath := store, dbPath
t.Cleanup(func() {
rootCmd.SetArgs(nil)
store, dbPath = origStore, origDBPath
_ = initCmd.Flags().Set("backend", "")
_ = initCmd.Flags().Set("prefix", "")
})
store, dbPath = nil, ""
rootCmd.SetArgs([]string{"init", "--backend", homeGuardSentinelBackend, "--prefix", "hg"})
err := rootCmd.Execute()
if err == nil {
t.Fatal("bd init in an untracked home returned nil, want a refusal")
}
if strings.Contains(err.Error(), homeGuardSentinelBackend) {
t.Fatalf("init ran past the home guard and got as far as backend selection: %v", err)
}
assertHomeDirRefusal(t, err)
// The files the bypass could still install, none of which is gated on
// BEADS_DIR: scaffolding is written relative to the working directory.
for _, name := range []string{".git", "CLAUDE.md", "AGENTS.md", ".gitignore", ".agents", ".codex", ".claude", ".cursor"} {
if _, statErr := os.Stat(filepath.Join(home, name)); statErr == nil {
t.Errorf("init created %s in the home directory despite refusing", name)
}
}
}
// evalSymlinks resolves path for comparison, tolerating a path that does not
// exist (nothing to resolve is not a test failure here).
func evalSymlinks(t *testing.T, path string) string {
t.Helper()
if path == "" {
return ""
}
resolved, err := filepath.EvalSymlinks(path)
if err != nil {
return path
}
return resolved
}