* 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>
142 lines
5.6 KiB
Go
142 lines
5.6 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
|
|
"github.com/spf13/cobra"
|
|
|
|
"github.com/steveyegge/beads/internal/metrics"
|
|
)
|
|
|
|
// initSafetyHelpCmd documents the init flag surface and the destroy-token
|
|
// format. Its contents are the authoritative runtime reference for the
|
|
// error-message-no-echo invariant: refusal texts point here rather than
|
|
// constructing copy-pasteable destructive invocations. See
|
|
// engdocs/adr/0002-init-safety-invariants.md.
|
|
var initSafetyHelpCmd = &cobra.Command{
|
|
Use: "init-safety",
|
|
Short: "Explain bd init flag semantics and the destroy-token format",
|
|
Long: `bd init flag safety contract.
|
|
|
|
Every bd init invocation resolves project_id from exactly one explicitly
|
|
named source (local reinit, remote adoption, or a fresh mint). When the
|
|
source is ambiguous, bd init refuses.
|
|
|
|
FLAG SURFACE
|
|
|
|
bd init Mint a new identity. Bootstraps from
|
|
origin if it has refs/dolt/data.
|
|
|
|
bd init --reinit-local Re-initialize local .beads/ over existing
|
|
local data. Does NOT authorize discarding
|
|
remote history. If origin has Dolt data
|
|
this will refuse — pair with
|
|
--discard-remote to override. Nor does it
|
|
authorize recreating a missing server-mode
|
|
database; that takes --recreate-missing.
|
|
|
|
bd init --reinit-local \ Discard the remote's Dolt history and
|
|
--discard-remote replace it with the local reinit. First
|
|
bd dolt push after this will be a
|
|
history-replacing force-push.
|
|
|
|
bd init --force Deprecated alias for --reinit-local, with
|
|
the same limits. Kept working for ≥2
|
|
releases.
|
|
|
|
bd init --recreate-missing Authorize creating a fresh, empty database
|
|
when this project's configured server-mode
|
|
database is missing or unreachable. Opt-in
|
|
per invocation only: never implied by
|
|
--force/--reinit-local, config, or env.
|
|
Without it, bd init REFUSES rather than
|
|
silently recreating a lost database as
|
|
empty (be-5up5). First rule out a stopped
|
|
server or a wrong port or data dir, and
|
|
restore if you can; the playbook is
|
|
init-missing-server-db in
|
|
docs/recovery/init-safety.md. Only when
|
|
nothing is recoverable:
|
|
|
|
bd init --recreate-missing --prefix <prefix>
|
|
|
|
bd init --from-jsonl Import from configured import.path. If
|
|
origin has Dolt data, this refuses unless
|
|
--discard-remote authorizes replacing that
|
|
remote history.
|
|
|
|
ADOPTING A REMOTE
|
|
|
|
If you want to use the remote's existing history, use:
|
|
|
|
bd bootstrap
|
|
|
|
bd init will automatically suggest this when a remote is detected.
|
|
|
|
DESTROY-TOKEN (non-interactive only)
|
|
|
|
When running with no TTY (CI, agents, piped input), a destructive
|
|
re-init requires an explicit --destroy-token value. That covers both
|
|
--discard-remote and --reinit-local over existing issues. The token
|
|
format is:
|
|
|
|
DESTROY-<issue-prefix>
|
|
|
|
For example, if your issue prefix is "bd", the token is "DESTROY-bd":
|
|
|
|
bd init --reinit-local --discard-remote --destroy-token=DESTROY-bd
|
|
|
|
In interactive (TTY) mode you confirm via a typed prompt instead. The
|
|
token is not echoed by bd's runtime error messages — this is a
|
|
deliberate guard against pattern-matched one-liners (see
|
|
engdocs/adr/0002-init-safety-invariants.md).
|
|
|
|
EXIT CODES
|
|
|
|
10 refused: remote has Dolt history and you selected local history
|
|
without --discard-remote
|
|
11 refused: existing local data and you declined the destroy confirm
|
|
(interactive mode only)
|
|
12 refused: destructive re-init (--discard-remote, or --reinit-local
|
|
over existing issues) without a valid --destroy-token
|
|
(non-interactive mode); also returned when the interactive
|
|
--discard-remote typed-token confirmation is declined
|
|
15 refused: run directly in your home directory, which is not itself
|
|
a git repository, with no BEADS_DIR named by the caller
|
|
|
|
RECOVERY
|
|
|
|
If you hit a refusal, see docs/recovery/init-safety.md for step-by-step recovery
|
|
playbooks for each exit code.
|
|
|
|
RE-CLONE GOTCHAS
|
|
|
|
Setting a damaged or superseded database directory aside by hand, or
|
|
relying on a fresh clone right away? Two gotchas from live recovery:
|
|
|
|
Crash-loop: a set-aside store left INSIDE data_dir makes the sql-server
|
|
treat it as a database and crash-loop with "root hash doesn't exist:
|
|
<hash>". Move it OUTSIDE data_dir instead.
|
|
|
|
Missing tables: a fresh clone lacks clone-local tables (leases, wisps,
|
|
events, ...) until you run "bd migrate schema" (no --force). You'll see
|
|
"table not found: leases" until then; "Schema already at v<N>" after
|
|
running it is expected, not an error.
|
|
|
|
See docs/recovery/init-safety.md#re-clone-gotchas for full detail.
|
|
`,
|
|
Run: func(cmd *cobra.Command, _ []string) {
|
|
evt := metrics.NewCommandEvent("init-safety")
|
|
defer func() {
|
|
if c := metrics.Global(); c != nil {
|
|
c.CloseEventAndAdd(evt)
|
|
}
|
|
}()
|
|
|
|
fmt.Print(cmd.Long)
|
|
},
|
|
}
|
|
|
|
func init() {
|
|
rootCmd.AddCommand(initSafetyHelpCmd)
|
|
}
|