beads/cmd/bd/init_safety.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

290 lines
13 KiB
Go

package main
// Init-safety decision logic.
//
// See engdocs/adr/0002-init-safety-invariants.md for the ADR this encodes.
// The invariant: every `bd init` resolves `project_id` from exactly one
// explicitly-named source; ambiguous sources refuse. `--force` (or its
// replacement `--reinit-local`) bypasses the local data-safety guard only;
// it never authorizes silent divergence of remote history. When origin
// advertises `refs/dolt/data`, `bd init` refuses unless the caller
// authorizes the cross-boundary operation via `--discard-remote` + a
// destroy-token.
//
// Error-message contract: no runtime error may emit a complete destructive
// invocation. Flag identifiers and safe-tool names are permitted; token
// values and other friction-bearing arguments live in `bd help init-safety`
// and `docs/recovery/init-safety.md` only.
import "fmt"
// Exit codes for init-safety refusals. Stable values so CI scripts can
// branch on them without grep'ing stderr.
const (
// ExitRemoteDivergenceRefused signals a local-source init was called
// against a remote that already has `refs/dolt/data`, without
// `--discard-remote`. Ambiguous identity source.
ExitRemoteDivergenceRefused = 10
// ExitLocalExistsRefused signals the interactive typed-confirmation
// for a destructive re-init over existing local data was declined at
// the prompt. That TTY-only path is its sole source: the same guard's
// non-interactive branch returns ExitDestroyTokenMissing instead, and
// a plain `bd init` over an initialized workspace is refused by the
// local-safety guard with an ordinary error, not this code.
ExitLocalExistsRefused = 11
// ExitDestroyTokenMissing signals a destructive re-init was refused for
// want of a valid `--destroy-token`. Four sources:
// 1. non-interactive `--discard-remote` with no token;
// 2. non-interactive `--reinit-local` over existing local issues;
// 3. `--discard-remote` with a supplied token that does not match, in
// EITHER mode — a token that WAS supplied is always validated (#6480);
// 4. the interactive `--discard-remote` typed-token confirmation
// declined at the prompt.
// So a 12 does not on its own prove the caller was non-interactive.
// Supplying the matching token is the correct remedy for sources 1-3
// (format via `bd help init-safety`); source 4 was a deliberate decline.
ExitDestroyTokenMissing = 12
// ExitHomeDirRefused signals `bd init` was run directly in the user's
// home directory, which is not itself a git repository, without the
// caller naming a BEADS_DIR. Refused because init would `git init` $HOME
// and install agent files into it, where most of them are user-wide
// agent settings (GH#4635).
//
// 15 because 13 and 14 are taken: ExitGuardMismatch (update.go, "racer
// won, skip gracefully") and ExitMigrationFrozen (errors.go). A wrapper
// that branches on bd's exit codes without regard to the subcommand must
// never read this refusal as a benign skip.
//
// Not part of protocol v0 §E3 (pinned in
// cmd/bd/protocol/exit_codes_init_test.go), which freezes 10/11/12/130
// and says a new stable code needs a spec revision. This constant gives
// the refusal the same in-repo scriptability the other three have — a
// stable number instead of grepping stderr — without claiming wire
// status the spec has not granted.
ExitHomeDirRefused = 15
)
// RemoteSafetyAction names what the init command should do once it has
// observed the remote state and read the user's flag intent.
type RemoteSafetyAction int
const (
// ActionNoRemoteData — remote has no Dolt data; proceed with a normal
// init. Caller does not need to bootstrap.
ActionNoRemoteData RemoteSafetyAction = iota
// ActionBootstrap — remote has Dolt data; caller should clone from it
// instead of minting a fresh identity. This is the "adopt" path.
ActionBootstrap
// ActionRefuseDivergence — remote has Dolt data AND caller passed
// `--force` or `--reinit-local` without `--discard-remote`. The new
// identity would orphan-push over the remote on first write. Refuse
// with `ExitRemoteDivergenceRefused`.
ActionRefuseDivergence
// ActionRequireDestroyToken — caller passed `--discard-remote` but
// destroy-token validation failed: either a non-interactive caller
// supplied no token, or a token WAS supplied — in either mode — and did
// not match. Refuse with `ExitDestroyTokenMissing`. An interactive
// caller that supplied NO token does not land here: it gets
// ActionProceedWithDivergence and must prompt for confirmation instead.
ActionRequireDestroyToken
// ActionProceedWithDivergence — caller passed `--discard-remote` and
// destroy-token is valid (or will be supplied via TTY prompt by the
// caller). Skip bootstrap; wire the remote so the caller can
// force-push local history on next operation.
ActionProceedWithDivergence
)
// RemoteSafetyInput is the minimal input to CheckRemoteSafety. Pure
// function; no filesystem, no network, no git. Caller populates flag
// state and remote-detection state, gets back a decision.
type RemoteSafetyInput struct {
// Flag state. Force is kept as a separate field so callers can route
// deprecation warnings at the call site; CheckRemoteSafety treats it
// as equivalent to ReinitLocal.
Force bool
ReinitLocal bool
// FromJSONL selects local JSONL as the init source instead of remote
// Dolt history. When remote history exists, this is a local-source
// override and must not silently diverge without DiscardRemote.
FromJSONL bool
DiscardRemote bool
// Destroy-token supplied on the command line, plus the token the
// caller expects (computed from issue prefix). Both are empty when
// the caller hasn't computed them yet — ReinitLocal without
// DiscardRemote doesn't need a token check.
DestroyToken string
ExpectedToken string
// Observed state.
RemoteHasDoltData bool
// IsInteractive is true when the caller is attached to a TTY.
// Interactive callers can prompt for destroy-token confirmation, so the
// decision returned for an interactive caller that supplied NO token
// assumes it will prompt (ActionProceedWithDivergence is returned
// without a token match — the caller must do the prompt itself). A
// token that WAS supplied is always validated regardless of this field:
// the caller's prompt only fires when no token was given (#6480).
IsInteractive bool
}
// RemoteSafetyDecision is the action + human-readable reason. UserMessage
// is populated for Refuse* actions so the caller can print exactly what
// the ADR-compliant refusal text says.
type RemoteSafetyDecision struct {
Action RemoteSafetyAction
Reason string
ExitCode int
UserMessage string
}
// CheckRemoteSafety is the chokepoint the ADR names. Every future flag on
// `bd init` that can interact with remote history must go through this
// function — never add a new `&& !someFlag` at the call site. See the
// guard matrix test in init_safety_test.go.
func CheckRemoteSafety(in RemoteSafetyInput) RemoteSafetyDecision {
// No remote data → no cross-boundary concern. Proceed.
if !in.RemoteHasDoltData {
return RemoteSafetyDecision{Action: ActionNoRemoteData, Reason: "no-remote-data"}
}
// Any explicit override intent (force / reinit-local / from-jsonl /
// discard-remote)
// means the user is not accepting the default bootstrap. DiscardRemote
// is treated as override-intent too — naming discard explicitly
// implies the user knows the remote has data and wants to replace it.
userOverride := in.Force || in.ReinitLocal || in.FromJSONL || in.DiscardRemote
// Remote has data, user did not override anything. Bootstrap is the
// safe adoption path — this is the existing correct behavior.
if !userOverride {
return RemoteSafetyDecision{Action: ActionBootstrap, Reason: "bootstrap-from-remote"}
}
// User wanted to override but did NOT authorize the cross-boundary
// operation. This is the bd-q83 bug class: a local-source init flag
// (`--force`, `--reinit-local`, or `--from-jsonl`) without
// `--discard-remote`. Refuse with structured message.
if !in.DiscardRemote {
return RemoteSafetyDecision{
Action: ActionRefuseDivergence,
Reason: "force-without-discard-remote",
ExitCode: ExitRemoteDivergenceRefused,
UserMessage: refusalMessageDivergence(),
}
}
// User authorized. Non-interactive callers must supply a matching
// destroy-token. Interactive callers that supplied no token defer to the
// typed-confirmation prompt, but a token that WAS supplied is always
// validated: the caller's prompt only fires when no token was given, so
// an unvalidated wrong token would skip every confirmation (#6480).
if !in.IsInteractive || in.DestroyToken != "" {
if in.ExpectedToken == "" || in.DestroyToken != in.ExpectedToken {
// Carry token PRESENCE into the refusal. The two cases have
// different remedies and only one of them can be reached
// interactively, so a single conflated message necessarily
// misdirects one of them: telling a user who supplied a wrong
// token to "re-run interactively and confirm at the prompt"
// loops them through the identical refusal forever, because the
// prompt is gated on no token being supplied.
reason, message := "destroy-token-missing", refusalMessageTokenMissing()
if in.DestroyToken != "" {
reason, message = "destroy-token-mismatch", refusalMessageTokenMismatch()
}
return RemoteSafetyDecision{
Action: ActionRequireDestroyToken,
Reason: reason,
ExitCode: ExitDestroyTokenMissing,
UserMessage: message,
}
}
}
return RemoteSafetyDecision{Action: ActionProceedWithDivergence, Reason: "authorized-divergence"}
}
// refusalMessageDivergence returns the What/Why/Next refusal text for local
// source selection without `--discard-remote`. Deliberately does not echo a
// complete destructive invocation — the ADR invariant bars runtime error
// output from constructing a copy-pasteable override.
func refusalMessageDivergence() string {
return `bd init refuses: remote 'origin' already has Dolt history (refs/dolt/data).
Why: this init mode would create or reuse local history instead of
adopting the remote. --force / --reinit-local bypasses only the
LOCAL data-safety guard; --from-jsonl selects JSONL as the local
source. Neither authorizes silent divergence of remote history.
Next:
Adopt the remote (recommended):
bd bootstrap
Diagnose first:
bd doctor
Overwrite the remote intentionally (destructive):
See 'bd help init-safety' for the --discard-remote workflow.`
}
// refusalMessageTokenMissing returns the What/Why/Next refusal text for
// `--discard-remote` with NO destroy-token supplied. That combination is
// reachable only from a non-interactive caller — an interactive one with no
// token defers to the typed-confirmation prompt — so both the
// "non-interactive mode" framing and the "re-run interactively" remedy are
// accurate here. A supplied-but-wrong token gets
// refusalMessageTokenMismatch() instead, where that remedy would be a dead
// end. The text is reproduced in docs/recovery/init-safety.md under
// `init-token-missing`; keep them in sync. Deliberately does not echo the
// token value.
func refusalMessageTokenMissing() string {
return `bd init refuses: --discard-remote requires an explicit destroy-token in non-interactive mode.
Why: Destructive cross-boundary operations cannot be authorized
silently. The token exists so automation has to make a
deliberate, project-specific choice.
Next:
See 'bd help init-safety' for the destroy-token format.
Or re-run interactively (attached to a TTY) and confirm at the prompt.`
}
// refusalMessageTokenMismatch returns the What/Why/Next refusal text for
// `--discard-remote` with a destroy-token that was supplied but does not
// match. Unlike the missing-token case this is reachable in BOTH modes, so
// its Next must hold on a TTY too: re-running interactively with the same
// token repeats this refusal, because the typed-confirmation prompt fires
// only when no token was given. Dropping the flag is the remedy that
// actually reaches the prompt. Deliberately does not echo the token value.
func refusalMessageTokenMismatch() string {
return `bd init refuses: the supplied --destroy-token does not match this project's token.
Why: Destructive cross-boundary operations cannot be authorized
silently, and a token that does not match is not authorization.
The expected token is derived from the issue prefix; this refusal
deliberately does not echo it.
Next:
See 'bd help init-safety' for the destroy-token format, then re-run
with the matching value.
Or drop --destroy-token entirely and re-run interactively (attached
to a TTY): with no token supplied, bd asks for typed confirmation at
the prompt instead.`
}
// FormatDestroyToken returns the destroy-token the caller should supply
// for a given issue prefix. Callers that need to surface this to users
// should do so via `bd help init-safety` or `docs/recovery/init-safety.md` — NOT via
// runtime error text (see the ADR invariant).
func FormatDestroyToken(prefix string) string {
return fmt.Sprintf("DESTROY-%s", prefix)
}