beads/docs/recovery/init-safety.md
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

27 KiB

title description
Recovery Playbooks Step-by-step recovery for bd init and bd dolt push/pull refusals, including the primary-key fork playbook

Last reviewed: 2026-10-01

Freshness source: cmd/bd/init.go, cmd/bd/init_safety.go, cmd/bd/init_safety_test.go, cmd/bd/init_safety_help.go, and cmd/bd/dolt.go.

This document lives next to the ADRs and matches the structure of bd's error messages: each named refusal in bd init and bd dolt push/pull has a labeled anchor here with step-by-step recovery instructions. The bd dolt push/pull fork refusal deep-links its anchor directly; since #5310 the bd init refusals point at bd help init-safety, which links this document as a whole — match those by exit code and symptom text.

See also: bd help init-safety, and ADR 0002 — bd init safety invariants.

Table of contents


init-force-refused

Exit code: 10 (ExitRemoteDivergenceRefused)

Symptom

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. ...

Why this happens

bd init --force (or --reinit-local) tells bd to bypass the local data-safety guard, and only that guard: neither flag bypasses this refusal or the missing server-side database refusal. bd init --from-jsonl selects a local JSONL export as the source. But the remote already has project history. Proceeding would create an orphan local Dolt branch with no common ancestor on origin. The next bd dolt push would either fail (no common ancestor) or — worse, if force-pushed — destroy the team's data.

Recovery paths

Pick the one that matches your intent.

1. You want to adopt the remote's history (most common)

bd bootstrap

This clones the remote's Dolt database into a fresh local .beads/. Your local state is ignored; the team's history becomes yours.

If you set aside the old .beads/dolt instead of deleting it, or bd list fails right after this with table not found: leases, see re-clone-gotchas below before you do anything else.

2. You want to diagnose what went wrong before deciding

bd doctor
bd dolt status

bd doctor walks the local + remote state and names concrete problems. bd dolt status shows the Dolt-level view. Neither modifies anything.

3. You intentionally want to overwrite the remote's history (destructive)

This is a cross-boundary operation that affects every collaborator. You need to pair the local-source init (--reinit-local or --from-jsonl) with --discard-remote. In interactive mode bd will prompt for confirmation; in non-interactive mode you must supply a --destroy-token. See bd help init-safety for the token format.

After bd init --reinit-local --discard-remote, your next bd dolt push must be a history-replacing push. Coordinate with your team before doing this.


init-token-missing

Exit code: 12 (ExitDestroyTokenMissing)

Symptom

bd init refuses: --discard-remote requires an explicit destroy-token in non-interactive mode.

Or, re-initializing over existing local issues with no TTY:

Refusing to destroy N issues in non-interactive mode.
  See 'bd help init-safety' for the required --destroy-token format.

Why this happens

You're running non-interactively (CI, agent, piped input) and asked for a destructive re-init. Destructive operations cannot be authorized silently, so bd requires --destroy-token in place of the interactive confirmation it cannot prompt for.

Both destructive paths need the token, not just the cross-boundary one:

  • --discard-remote, which would discard the remote's Dolt history.
  • plain --reinit-local over existing local issues, which would destroy them (see init-local-exists).

Recovery paths

1. Run interactively

Re-run in a TTY. bd init --reinit-local --discard-remote will prompt you to type the destroy-token at confirmation time.

2. Supply the token explicitly (CI/automation)

The token format is DESTROY-<issue-prefix>. For a project whose issue prefix is bd:

# Destroys local issues only:
bd init --reinit-local --destroy-token=DESTROY-bd

# Also discards the remote's Dolt history:
bd init --reinit-local --discard-remote --destroy-token=DESTROY-bd

Automation should template the token from project state, not from error output. See ADR 0002 — Invariant 4 for why the token is never echoed in bd's error messages.


init-local-exists

Exit code: 11 (ExitLocalExistsRefused) interactively; 12 (ExitDestroyTokenMissing) non-interactively

Symptom

Interactive (TTY): you declined the typed destroy N issues confirmation. This is the only path that exits 11.

Type 'destroy N issues' to confirm:
Aborted. Database was NOT modified.

Non-interactive (CI, agent, piped input) — note this exits 12, not 11:

Refusing to destroy N issues in non-interactive mode.
  See 'bd help init-safety' for the required --destroy-token format.

Why this happens

Local .beads/ has existing issues. bd init --reinit-local (or its deprecated alias --force) would permanently destroy them, so bd demands an explicit confirmation first: the typed prompt in a TTY, and a --destroy-token when there is no TTY. This applies to --reinit-local on its own — --discard-remote is not required to trigger it.

A plain bd init over an initialized workspace does not reach either code: the local-safety guard refuses it with an ordinary error before this point.

Recovery paths

1. Export first, then proceed

bd export > issue-export.jsonl

# Interactive: confirm at the typed prompt.
bd init --reinit-local

# Non-interactive: the token stands in for the prompt. Without it this
# re-runs straight back into the exit-12 refusal above.
bd init --reinit-local --destroy-token=DESTROY-<issue-prefix>

issue-export.jsonl lets you re-import individual issues if needed. It is not a full database backup; use bd backup when the Dolt database is healthy enough to create a restorable backup before reinitializing.

2. Investigate why you hit this

If you did NOT expect bd init to be the right command here, run bd doctor first — you may be looking at a server config issue that a re-init won't fix.


init-home-refused

Exit code: 15 (ExitHomeDirRefused)

Symptom

bd init refuses: /Users/you is your home directory, and it is not itself a git repository.
  Why: init sets up the directory it runs in as a project: it runs
       'git init' there unless it finds a repository, and installs agent
       files ...

Why this happens

bd init sets up the directory it runs in as a project: it creates a git repository there unless it finds one, then writes agent scaffolding next to it: CLAUDE.md, AGENTS.md, .gitignore, .claude/, .codex/, .cursor/, .agents/. Run in your home directory, that turns everything you own into one git working tree, and most of those agent files are your agents' user-wide settings there: ~/.claude/settings.json is the file Claude Code reads in every project, so bd's hooks would run everywhere. A project is virtually never the home directory itself, so bd init refuses rather than ask.

The refusal is deliberately narrow. It fires only when all of these hold:

  • the working directory is exactly your home directory (a subdirectory of home is an ordinary project and is never refused);
  • your home directory is not itself a git repository — if you deliberately track your dotfiles in a repository at your home directory, nothing changes. A home that only sits inside some enclosing repository, or a GIT_DIR inherited from the environment, does not count, because init would still write its files into your home;
  • you did not name a beads directory yourself by exporting BEADS_DIR. A BEADS_DIR that bd reads from a .beads/.env it discovered does not count: from your home directory that file is the legacy ~/.beads/.env.

--force and --reinit-local do not override it. They bypass the local data-safety guard, which is a different question from "is this the right directory".

Recovery paths

Pick the one that matches your intent.

You meant to initialize a project. This is almost always the case — the working directory was simply not what you thought:

cd ~/some-project
bd init

You want a beads workspace in a directory you name, without setting up your home directory as a project. Name the beads directory explicitly. Its parent directory has to exist first:

mkdir -p ~/workspaces/notes
BEADS_DIR=~/workspaces/notes/.beads bd init

Note this is a different init, not the refused one with the guard lifted. An explicit BEADS_DIR skips the git init, and from your home directory bd init also skips the agent files and the .gitignore it would otherwise write there (it prints a note saying so). It also treats your home directory as outside every repository. If your home sits inside one, such as a dotfiles or monorepo checkout above it, init installs no hooks in it, records no beads.role there, takes no Dolt remote from its origin, and makes no bootstrap commit to it. Flags that ask for a change there still make it: --stealth and --setup-exclude add their patterns to that repository's .git/info/exclude, the interactive --contributor wizard records beads.role in it, and the interactive --team wizard can create a sync branch in it. Your home directory is not set up as a project; the workspace lives in ~/workspaces/notes. That is the point, but it also means you get no agent integration. To install one for every project on purpose, use the global form of bd setup, for example bd setup claude --global.

You really do want your home directory tracked by git and scaffolded. Make it a git repository first, deliberately, and the guard stands aside:

cd ~
git init
bd init

How to detect this in a script

The refusal exits 15 and prints to stderr, so branch on the code rather than the text:

bd init || case $? in
  15) echo "wrong directory — cd into the project first" ;;
esac

init-missing-server-db

Symptom

⚠ Database "myproject" not found on server at 127.0.0.1:3306 (or the server could not be reached to confirm).
This workspace was already initialized (metadata.json has a project_id from a prior
bd init), so this looks like a recovery situation, not a fresh clone
...
bd init will NOT create an empty database here — that would strand any existing
issue data behind a new, empty database of the same name.

What happened

This workspace is in server mode and shows evidence of a prior bd init: .beads/metadata.json carries a project_id, or (under --reinit-local or --force) a workspace that predates project_id still has a local Dolt data directory, in which case the message cites that instead of metadata.json. Yet its configured database is not on the server, or the server could not be reached to confirm.

That is treated as a recovery situation, not a fresh clone, and the two are otherwise indistinguishable from the local filesystem alone: this project's own database directory is absent either way, because it was never created here or because it was lost with the local storage. bd init used to resolve the ambiguity by assuming "fresh clone" and creating the database. When the assumption was wrong, the result was a new, empty database sitting at the name the real one used to occupy — the 2026-08-11 fleet-wide data loss.

bd init now refuses instead, and the refusal is not bypassed by --force or --reinit-local. Those flags authorize destroying a database that exists; they do not authorize inventing an empty one where the configured database has gone missing.

1. Find out where the database went (do this first)

bd doctor          # check project health
bd dolt status     # inspect Dolt server state

A stopped server, a server started on the wrong port, or a wrong --data-dir all present exactly like this — and none of them need a re-init. Fixing the server brings the data back untouched.

2. Restore from an export

bd backup restore                  # if a local backup snapshot exists

Also check .beads/backup/ for a JSONL export you can import manually.

3. Create a fresh empty database at this name

Destructive to any unrecovered data.

Only when you are certain no recoverable data exists:

bd init --recreate-missing --prefix myproject

--recreate-missing is per-invocation only. It is deliberately never implied by --force, --reinit-local, a config key, or an environment variable, because it authorizes the one thing this guard exists to prevent.

The refusal names --recreate-missing but does not print this command: it also fires when the server merely could not be reached, so it sends you through steps 1 and 2 here instead of handing you a line to paste. See ADR 0002 — Invariant 4.

Limits worth knowing

Whether a workspace meets this refusal depends on two pieces of local evidence: whether this project's own database directory (<dolt-data-dir>/<database>/.dolt) exists, and whether metadata.json carries a project_id (introduced by GH#2372). With the configured database missing from the server, or the server unreachable:

Local Dolt storage project_id bd init bd init --reinit-local / --force
This project's database directory present Either Refused as already initialized, not by this guard Not this guard; the ordinary re-init path
Data dir present, database directory absent Present This refusal This refusal
Data dir present, database directory absent Absent Refused as already initialized, not by this guard This refusal
No Dolt data dir Present This refusal This refusal
No Dolt data dir Absent Proceeds, as for a fresh clone Proceeds, as for a fresh clone

Adding --recreate-missing lifts every refusal in the last four rows, including the third row's "already initialized". It changes nothing in the first row, where this project's database is still on local disk. In shared-server mode the data dir is machine-global (see below), so the last two rows rarely apply there.

  • project_id is also inherited by a fresh clone, because .beads/metadata.json is git-tracked by default. Cloning a beads-managed repo whose server-side database does not exist yet therefore meets this refusal rather than a plain first init. It fails in the safe direction — nothing is created silently, and no existing data can be stranded — and --recreate-missing above is the supported way through it. This is settled, not pending: engdocs/adr/0004-missing-database-guard-signal.md records why no purely-local signal can replace project_id here (absence of local state cannot tell "never initialized here" from "initialized here, storage since lost"), and why --recreate-missing is the permanent resolution path rather than a stopgap.
  • Server mode only, and shared-server mode counts as server mode — the guard tests for this project's database directory under the resolved Dolt data dir, not for the data dir itself, which in shared mode is the machine-global ~/.beads/shared-server/dolt that is created on demand.
  • Proxied-server mode does not reach the --reinit-local/--force guard — the --proxied-server dispatch in runInit (cmd/bd/init.go) returns before it. It does reach the plain-init guard, because runInitProxiedServer calls checkExistingBeadsData, so --recreate-missing works under --proxied-server too: the flag is assigned beside its flag read, upstream of every dispatch in runInit. Keep it there. It was previously assigned next to the guard it gates, which is downstream of the proxied dispatch, and the flag was therefore inert on that one route while the refusal still told the operator to pass it.
  • bd bootstrap has its own separate mode-blind create path.

pk-fork-refused

Symptom

$ bd dolt pull
Error: ... cannot merge because table dependencies has different primary keys in its common ancestor

(or the variant without in its common ancestor). bd follows the error with a short version of the recovery recipe below.

Why this happens

The two histories being merged disagree about a table's primary key set — not about row contents. Dolt can cell-merge rows, but it refuses outright to merge a table whose primary key was reshaped differently on each side (or whose common ancestor had a different primary key than both sides). The refusal happens before any row conflicts materialize, so bd dolt pull's conflict auto-resolver never gets a chance to run. Retrying never helps: the histories are permanently un-mergeable.

The usual cause is upgrading bd independently on two clones while un-synced changes existed on both sides, across a release whose schema migrations reshape a primary key. Concretely: the #4259 incident — clones straddling the 0041/0043/0050 reshapes of dependencies (v1.0.4 → v1.0.6) hit exactly this on the first post-upgrade pull if both sides had unpushed dependency edits.

The remote-migrate prevention gate (v1.0.6+) exists to stop this from being created: it refuses to auto-migrate a remote-backed database and tells you to designate a single migrator. This playbook is for when the fork already exists.

Recovery: bootstrap from one canonical clone

The forked histories cannot be merged, so one side must be chosen as canonical and every other clone re-cloned from it. Issue data survives via JSONL export/import; only the un-mergeable Dolt history is discarded on the non-canonical clones.

1. Pick the canonical clone

Usually the most complete / most recently active clone. To compare, run on each clone (read-only):

bd stats
bd dolt status

2. On the canonical clone: upgrade, migrate, force-push

bd version                 # confirm the new bd binary
bd doctor                  # sanity-check before publishing
bd dolt push --force       # make the remote authoritative

(bd's migration gate may block here; that is exactly the designated-migrator case the gate is asking about — follow the guidance it prints on the canonical clone.)

3. On EVERY other clone: save local-only work, re-clone, re-apply

bd export --all -o /tmp/beads-local.jsonl    # safety net for un-synced work
rm -rf .beads/dolt                           # discard the un-mergeable history
bd bootstrap                                 # re-clone from the remote
bd import /tmp/beads-local.jsonl             # re-apply local-only work

bd import has upsert semantics: issues that only existed on this clone are re-created, newer local edits are applied, and rows older than what the remote already has are skipped. Spot-check with bd stats afterwards.

Doing this by hand (moving .beads/dolt aside instead of rm -rf, or skipping straight to bd list) can hit either of two live gotchas — see re-clone-gotchas below.

Prevention (upgrades across PK-reshaping migrations)

  • Sync before upgrading: bd dolt push + bd dolt pull on every clone while all clones still run the old version, then stop editing. Once the new binary is installed, bd dolt push/bd dolt pull are gated too, so this must happen first. The one exception is the data-behind stop — a clone level on schema but missing commits the remote has — where bd dolt pull is the remedy and is allowed through (a proxied-server workspace refuses it, so there the pull runs on the server host); the gate says so when it fires, and Clone behind the remote has the recipe. Plan for the rule, not the exception.
  • One designated migrator: upgrade one machine, let it migrate, then bd dolt push.
  • Every other clone takes the migrated database, does not migrate: after the migrator pushes, each other clone runs bd dolt pull while still on the old binary, then upgrades. Once the new binary is installed that pull is refused while the clone has pending migrations, and bd bootstrap never replaces an existing database — on its own it reports Nothing to do. — so a clone that upgraded first must move its local database aside before bd bootstrap can re-clone. The recipe is in Remote-backed databases and multiple clones.

re-clone-gotchas

Two gotchas hit during a live manual re-clone recovery (issue ga-vrq5pu), each of which cost real time because the symptom looks nothing like the cause. Both apply any time you set aside or replace a Dolt database directory by hand — during the pk-fork-refused playbook above, the init-force-refused bd bootstrap path, or any other manual re-clone.

Gotcha 1 — a damaged/set-aside store must go OUTSIDE data_dir

Symptom

root hash doesn't exist: <hash>

...printed repeatedly as the Dolt sql-server crash-loops under its supervisor/watchdog. Nothing in that message mentions a stray directory, so it does not look like "you left a directory lying around."

Why this happens

The sql-server treats every subdirectory of its data_dir (default .beads/dolt/, overridable via BEADS_DOLT_DATA_DIR or the dolt_data_dir field in metadata.json) as its own database and tries to load it. If you move a damaged or superseded database directory aside but leave it inside data_dir (for example, renaming .beads/dolt/mydb to .beads/dolt/mydb.bak instead of moving it out of .beads/dolt/ entirely), the server tries to load the damaged copy too and dies on it — even though the healthy database sitting right next to it is fine.

Check which mode you are in before you go looking for data_dir: in shared server mode (BEADS_DOLT_SHARED_SERVER=1, or the dolt.shared-server config key) it is ~/.beads/shared-server/dolt/ — or $BEADS_SHARED_SERVER_DIR/dolt/ — and that takes precedence over both of the per-project knobs above. That is also where this gotcha bites hardest: one shared data_dir holds every project's database on the machine, so a single stray subdirectory crash-loops the server for all of them.

The fix

When you set a database directory aside by hand, move it outside data_dir — e.g. up to /tmp/ or a sibling of .beads/, never to a sibling path still under .beads/dolt/.

Do not wait for an automated repair to do it for you: no bd doctor --fix repair performs this move here. The two that come closest are:

  • The corrupt-manifest repair renames the damaged database's own .dolt/ directory in place — <data_dir>/<db>/.dolt → <data_dir>/<db>/.dolt.<ts>.corrupt.backup — and reinitializes beside it, so in the standard <data_dir>/<db>/ layout the backup is nested inside the database directory rather than becoming a new direct child of data_dir. It also fires only once its scan can prove the store holds no recoverable chunk data, so it will not touch the superseded-but-populated copy this gotcha is about (internal/doltserver/manifest_recovery.go).
  • The rename that does move a whole data_dir to a timestamped sibling (data_dir → data_dir.<ts>.corrupt.backup) belongs to a different repair, the database-integrity recovery (cmd/bd/doctor/fix/database_integrity.go) — and that one refuses outright for a repo configured in Dolt server mode, so if the crash-looping server is your configured backend it is unavailable too.

Make the move by hand, and make sure it lands outside data_dir.

Gotcha 2 — a fresh clone needs bd migrate schema

Symptom

table not found: leases

(or a similar "table not found" error for wisps, events, local_metadata, or another clone-local table). A supervisor or agent harness that expects to load session beads right after a fresh clone fails here.

Why this happens

A handful of tables — leases, wisps, wisp_*, events, bd_events_*, local_metadata, ignored_schema_migrations, repo_mtimes — are dolt-ignored, clone-local tables: they exist on a running database but are deliberately excluded from what bd dolt push/pull/clone transfers, so a fresh clone starts without them.

A writable open normally re-materializes them on its own, whether it is embedded or reaches the database through a server or proxied sql-server: it runs the schema migration pass, which replays the clone-local ("ignored") series whenever that series' cursor table is behind — and the cursor table, ignored_schema_migrations, is itself clone-local, so a fresh clone always qualifies (internal/storage/schema/schema.go, internal/storage/uow/dolt_sql_provider.go). Reaching the error above therefore means the open that hit it was not one of those self-healing opens. The kinds that skip the pass, or only verify, include a deliberately non-mutating read-only or preview open, a team-server open (it checks the schema rather than migrating it), the preview-attach path, and any open whose open-time migration gate refused. Run the migration explicitly to close the gap.

The fix

bd migrate schema

No --force needed. This replays the clone-local tables and prints:

✓ Schema already at v<N>

That output is expected and reassuring, not an error — it means the versioned schema was already current; the clone-local tables have now been (re)created regardless. Run this once after any fresh clone or bd bootstrap, before relying on bd list or any other command that reads session state.