* test(init): red — existing project with missing server DB must refuse init
be-5up5: server mode never has a local dolt/ directory, whether this is a
genuine fresh clone or an existing project whose database was lost from the
server — doltDirExists==false alone (GH#2433's signal) can't distinguish
them. Adds TestInitGuard_ExistingProjectMissingServerDB_Refuses, which spins
up a real dolt sql-server with no database and a metadata.json carrying a
non-empty project_id (proof of a prior real init). Currently fails: the
guard returns nil and lets init silently recreate the database as empty,
which is the 2026-08-11 fleet-wide data loss.
RED only — checkExistingBeadsDataAt is not yet fixed.
* fix(init): refuse to recreate a missing server-mode database (be-5up5)
bd init's server-mode "already initialized" check treated a missing or
unreachable database the same as a genuine fresh clone, silently
returning nil and letting init proceed to create an empty database —
even when metadata.json's project_id proved this was an existing
project whose database had gone missing (the 2026-08-11 fleet-wide
data loss).
Guard on cfg.ProjectID != "" to distinguish the two cases. An existing
project now gets a refusal (initGuardMissingServerDBMessage) that
names bd doctor / bd dolt status / bd backup restore as the recovery
path and explicitly does not recommend bd bootstrap, since bootstrap
has its own related mode-blind create bug (tracked separately). A new
--recreate-missing flag is required to opt into creating fresh in this
case — never implied by --force, config, or env. Genuine fresh clones
(empty project_id) are unaffected.
Also:
- doctor/gitignore.go: drop the "bd init (safe to re-run)" fix hint,
since re-running bd init is exactly the unsafe action this fix
prevents in the case that matters.
- storage/dolt/errors.go: the general "database not found" hint no
longer claims bd bootstrap is a safe first step for "an existing
project" — only for genuine fresh-clone / shared-server-recovery,
which is what the existing tests actually cover.
* test(init): pin exit_contract's bootstrap-not-recommended requirement (be-5up5)
TestInitGuard_ExistingProjectMissingServerDB_Refuses checked the refusal
and the absence of --force, but not the exit_contract's explicit "does
not recommend bd bootstrap for a server-mode workspace" requirement —
that was only verified by hand during self-review. Pin it directly, and
assert the message names an actual recovery path.
* test(init): cover --recreate-missing positive path (be-ab3b)
be-5up5's guard already correctly permits init to proceed when
--recreate-missing is set; only the negative path (flag absent -> refuse)
had test coverage. Adds TestInitGuard_ExistingProjectMissingServerDB_
RecreateMissingAllows, covering both guard sites the flag gates:
init.go:2566 (server reachable, database confirmed missing) and
init.go:2578 (server unreachable / errored during the check).
refs be-3mvz (review round 1 request-changes), closes be-ab3b
* chore: release gate PASS for bd init missing-server-DB guard fix (be-udx2)
* chore: record full pre-PR contributor check results for be-udx2 gate
* test(init): red — bd init --force recreates a missing server DB as empty
--force is a deprecated alias for --reinit-local (init.go ~395), and the
existing-data guard is gated on !reinitLocal (~763), so --force skips
checkExistingBeadsData — and with it the be-5up5 missing-database refusal
this PR added. The reinit path's own typed confirmation does not cover the
gap either: it keys on countExistingIssues, which returns 0 or an error in
exactly the case where the server-side database is missing, so no prompt
and no destroy token are ever required.
Net effect at this commit, measured against a real dolt sql-server
(2.2.3) holding no "myproject" database, with metadata.json carrying a
project_id:
$ bd init --force --prefix myproject --skip-hooks
...
Database: myproject
Issue prefix: myproject
Run bd quickstart to get started.
$ echo $?
0
$ ls <server data-dir>
config.yaml .dolt .doltcfg myproject <-- created, empty
An empty database at the name the real one used to occupy, exit 0, no
prompt. That is the 2026-08-11 fleet-wide data-loss reflex, reached
through the flag an operator in a panic is most likely to reach for.
This test drives the real binary because that is the only way to exercise
the --force -> reinitLocal -> "skip the guard" path end to end; a unit
test on the guard function cannot see that the caller never runs it.
Both subtests fail at this commit.
Reported in review of PR #5791 by bee-ghosttrack, item 1.
* fix(init): green — --reinit-local/--force cannot bypass the missing-DB guard
Add guardMissingServerDatabaseAt, a narrowed form of the be-5up5 refusal
that answers only one question — is this an already-initialized
server-mode project whose configured database is missing or
unconfirmable? — and run it on the reinitLocal path, which
checkExistingBeadsData never reaches.
The distinction the guard encodes: --reinit-local/--force authorize
destroying a database that EXISTS. They do not authorize inventing an
empty one where the configured database has gone missing. Only the
explicit, per-invocation --recreate-missing does that, which is what makes
that flag's "never implied by --force" help text an honest guarantee
rather than an aspiration. The review suggested softening that help text
instead; making the claim true seemed better than documenting that it
isn't.
Deliberately narrow. It returns nil for every state except the missing
database — no metadata, non-Dolt backend, non-server mode, empty
project_id, or a local dolt/ directory all fall through — so it never
resurrects the "already initialized" refusal that --reinit-local is
legitimately meant to bypass. The "stays silent on a fresh clone with no
project_id" subtest pins that boundary.
Same scenario as the previous commit, now:
$ bd init --force --prefix myproject --skip-hooks
Error:
(warn) Database "myproject" not found on server at 127.0.0.1:34813 ...
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.
$ echo $?
1
$ ls <server data-dir>
config.yaml .dolt .doltcfg <-- nothing created
Addresses review of PR #5791 by bee-ghosttrack, item 1.
* test(init): cover the unreachable-server refuse branch
Review of PR #5791, item 2. The PR claimed
TestInitGuard_ExistingProjectMissingServerDB_Refuses covered both guard
sites — server reachable with the database missing, and server unreachable
or errored while checking. It does not: that test starts a live dolt
sql-server, so it only ever exercises the first. The unreachable site had
coverage on the PERMIT side only (the BEADS_DOLT_SERVER_PORT=1 subtest of
_RecreateMissingAllows), which would not notice if its refusal were
dropped.
TestInitGuard_UnreachableServerRefuses closes that: port 1 is unreachable
by construction, so it needs no dolt binary and runs in the fast lane.
Also drops a comment reference to scripts/repro-bd-init-recreates-empty-db.sh,
which is not in the repo or in this diff (item 3, third bullet), and
describes the state the test sets up instead.
Addresses review of PR #5791 by bee-ghosttrack, item 2.
* docs(init-safety): document --recreate-missing and its known limits
Review of PR #5791, item 3 (doc drift), plus the non-blocking note.
The flag's own help pointed users at `bd help init-safety`, whose FLAG
SURFACE section did not list it — so the one place the help sends you was
the one place it was missing. Added there, stating plainly that it is
per-invocation only and never implied by --force/--reinit-local, config,
or env.
docs/recovery/init-safety.md gains an init-missing-server-db section (and
a TOC entry) covering the refusal users will actually hit: why the
fresh-clone and lost-database cases are indistinguishable from the local
filesystem in server mode, why the old "assume fresh clone" answer caused
the 2026-08-11 loss, and the three ways out in the order they should be
tried — diagnose the server first (a stopped server or wrong --data-dir
presents identically and needs no re-init), then restore from an export,
then --recreate-missing as the deliberate last resort.
Both limits the review flagged as non-blocking are recorded there and in
the guard comment rather than left as folklore:
- The guard keys on project_id, minted by GH#2372. A pre-GH#2372 workspace
carries none and is indistinguishable from a fresh clone, so it FAILS
OPEN. Accepted deliberately — failing closed would block legitimate
first inits on every such clone, and this guard's job is to stop a
silent recreate where prior initialization can be PROVEN, not to guess
where it cannot.
- Server mode only. Proxied-server mode returns early on a missing root
and never reaches the guard, and bd bootstrap has its own separate
mode-blind create path.
Addresses review of PR #5791 by bee-ghosttrack, item 3 and the
non-blocking notes.
* docs(changelog): record the --force missing-database bypass fix
Under Unreleased/Fixed. This is a behavior change to bd init --force on
every server-mode workspace whose database has gone missing, and it was
not recorded anywhere users read.
* fix(init): make the missing-server-database guard fire in shared-server mode
Review round 2, item 1 (blocking): the guard was a no-op in shared-server mode
— the topology of the 2026-08-11 data loss, and so the primary case.
guardMissingServerDatabaseAt statted doltserver.ResolveDoltDir(beadsDir) and
returned early when it was a directory, reading that as "there is local data to
protect". In shared mode ResolveDoltDir returns the machine-global
~/.beads/shared-server/dolt, and SharedDoltDir() MkdirAlls it
(internal/doltserver/doltserver.go:281). The stat therefore always succeeded and
checkDatabaseOnServer was never reached, while every per-project test kept
passing.
Fix per the reviewer's first option: test for THIS project's database directory
rather than the data directory that holds it. A Dolt data dir contains one
subdirectory per database, each with its own .dolt — verified on disk — so
<doltDir>/<dbName>/.dolt is the correct probe in BOTH modes, and it is strictly
more precise in per-project mode too: a data dir that exists but holds no
database for this project no longer counts as local data to protect.
Two new tests, both against a real dolt sql-server rather than an unreachable
port, covering the two cases the reviewer noted were uncovered:
TestInitGuard_SharedServerMode_MissingServerDB_Refuses
reachable server, database absent -> must refuse. This is the actual
loss shape. Reverting the one-line guard change turns it red with
"got nil error"; the pre-existing per-project tests stay green, so it
pins the shared-mode gap specifically.
TestInitGuard_SharedServerMode_PresentServerDB_Allows
reachable server, database present -> must NOT refuse, so --reinit-local
and ordinary reinit keep working. The reviewer verified this by hand and
flagged it as untested.
Also from the same review:
- docs/recovery/init-safety.md overstated the proxied limit. The proxied path
does not reach THIS guard (dispatch at init.go:619 precedes the
initAllowRecreateMissing assignment at :767), but it does reach the older
checkExistingBeadsData (init_proxied_server.go:89) — and because the flag is
never assigned there, --recreate-missing is inert under --proxied-server.
Documented as pre-existing rather than silently fixed.
- Shared-server mode now named explicitly in the same Limits section.
- checkExistingBeedsData typo corrected.
- The "### 3." heading wrapped onto a second line and rendered broken.
Verified: full TestInitGuard suite 15/15 PASS, 0 SKIP (12.1s), including all
pre-existing guard tests. go build ./... clean, gofmt clean, go vet clean.
Refs be-ok1tt, be-udx2.
* test(init): redirect the shared-mode fixtures with BEADS_SHARED_SERVER_DIR
Round-3 MINOR-2, unaddressed through round 4. The two shared-server tests
redirected HOME so SharedDoltDir() would resolve inside the test tree, but
SharedServerPath() reads BEADS_SHARED_SERVER_DIR first and only then falls
back to os.UserHomeDir(). An ambient BEADS_SHARED_SERVER_DIR — the override
that function's own comment advertises for testing — silently won, and the
pair then wrote into and asserted against the developer's real
~/.beads/shared-server/dolt, failing spuriously if a real "myproject" lived
there. HOME is also a no-op on Windows, where os.UserHomeDir() reads
%USERPROFILE%.
Set the variable the resolver actually consults first. No behavior change.
* test(init): make the present-database control pin the early return
Round-3 NIT-4, unaddressed through round 4, and demonstrated there: with the
local-database probe reverted, _SharedServerMode_PresentServerDB_Allows stayed
green, so it pinned nothing of the early return that commit rewrote. It
returned nil via the server check alone, because the fixture never gave this
project a database directory under the shared data dir.
Create that directory, the way a real shared-mode install has one, and then
assert the early return specifically: with the server made unreachable, the
local database directory alone must still satisfy the guard. Removing the
early return now turns this test red.
* test(init): red — the documented --recreate-missing recovery cannot reach its opt-in
Round-3 MAJOR-1 / round-4 finding 1. checkExistingBeadsDataAt derives "is this
project's database here?" from os.Stat(ResolveDoltDir(beadsDir)) — the DATA
directory, which exists on every initialized workspace (shared-server mode
MkdirAlls the machine-global one in SharedDoltDir; per-project mode MkdirAlls
it in ensureDoltInit). So the FR-010 missing-vs-present branch never runs and
both --recreate-missing opt-ins inside it are unreachable.
Four surfaces tell the operator to run `bd init --recreate-missing --prefix
<p>`: the flag help, `bd help init-safety`, docs/recovery/init-safety.md, and
the guard's own refusal text. That command exits 1 with a false "already
initialized" message pointing back at --reinit-local, which is the destructive
path. The documented recovery is a dead end and the only thing that works,
--reinit-local --recreate-missing, is named nowhere.
The existing _Refuses/_RecreateMissingAllows fixtures cannot see this: they
omit the data directory entirely, so their branch condition is true for the
wrong reason. These two add it, which is the state of every real workspace
whose server-side database was dropped.
Both fail at this commit.
* fix(init): green — probe this project's database directory, not the data dir holding it
Round-3 MAJOR-1 / round-4 finding 1. Test for <dolt-data-dir>/<database>/.dolt
instead of the data directory itself, so the FR-010 missing-vs-present branch
is reachable on an initialized workspace and `bd init --recreate-missing`
reaches its own opt-in. This is the same probe, for the same reason, that
guardMissingServerDatabaseAt already uses on the reinit path.
Making that branch reachable also exposes states the data-dir stat used to
shadow, and permitting them would be a new fail-open policy rather than a fix.
The clearest is a workspace that predates GH#2372: it carries no project_id,
so `existingProject` is false, and the branch would permit a silent empty
recreate on exactly the installed base this guard exists to protect. The
data-dir stat therefore stays — it stops being the gate and becomes the permit
condition, admitting only what the old probe already admitted, plus the
explicit per-invocation opt-in. Net behavior change is the opt-in becoming
reachable, and the false "already initialized" message being replaced by the
accurate missing-database refusal where the database is genuinely gone.
Choosing a better proof of prior local init is deliberately NOT done here.
project_id comes from git-tracked .beads/metadata.json, so a fresh clone
inherits one (round-4 finding 2); the replacement signal needs a different
answer in per-project and shared-server mode, and is tracked as its own
architecture decision on be-5pjhd. The known limit is now recorded in the
guard comment and in docs/recovery/init-safety.md rather than left implicit.
Tests: the two red tests from the previous commit now pass, and two more pin
the narrowing — a pre-project_id workspace with a local data dir stays blocked,
and --recreate-missing still opens it.
* docs: record the --recreate-missing fix and the fresh-clone project_id limit
Round-3 NIT-3 / round-4 finding 4: the round-3 probe change (data dir to
<dolt-data-dir>/<database>/.dolt) was never written down, and it is
user-visible wherever the data dir exists but the database is gone. Both that
and this round's --recreate-missing fix are now under [Unreleased] / ### Fixed.
The stray double blank line is gone with the section's move.
Also records, in docs/recovery/init-safety.md's "Limits worth knowing", that
project_id is inherited by a fresh clone because .beads/metadata.json is
git-tracked by default — the round-4 finding-2 gap this series deliberately
does not close. It fails in the safe direction and --recreate-missing is the
supported way through it; the replacement signal is tracked separately.
* docs(adr): ADR-0004 — proof-of-prior-init signal for the missing-database guards
Round-4 finding 2 asked what should replace project_id as the proof that a
workspace was initialized locally, and what the fail-open/fail-closed policy
should be per server mode. It needed a design decision rather than a
mechanical fix, so it was escalated; this records the answer.
The decision is to formalize what the code already does for local hosts and
keep project_id where nothing local can ever help. Presence of this project's
own <dolt-data-dir>/<database>/.dolt is unconditional proof, because the path
is gitignored and only a real local process creates it. Its ABSENCE, however,
cannot be promoted to proof in either direction: it looks identical whether
the workspace was never initialized here or was initialized here and lost its
storage — and the second is the shape of the 2026-08-11 incident. For a
genuinely remote host the probe is not merely silent today, it is structurally
silent forever, since the only code that creates that directory runs on local
server-management paths.
So project_id stays as the tier-2 fallback with its git-inheritance weakness
accepted, and --recreate-missing is the permanent resolution UX rather than a
stopgap. A local-only init marker and repurposing .local_version are recorded
as rejected, with reasons, so neither is re-proposed each review round.
Extends ADR 0002, which set the init safety invariants but left the evidence
question open.
* test(init): red — the reinit guard waves through a pre-project_id workspace
ADR-0004 follow-up 1. guardMissingServerDatabaseAt is the safety net for
--reinit-local and --force, which bypass checkExistingBeadsDataAt entirely. It
returns nil the moment cfg.ProjectID is empty, BEFORE it ever reaches the
per-database .dolt probe eighteen lines below.
checkExistingBeadsDataAt does the opposite: it probes first, and only falls
back to project_id — narrowed by the coarse-directory permit condition — when
that probe comes up empty. So a workspace initialized before GH#2372 minted
project_id, whose local Dolt storage has since been lost, is protected under
plain `bd init` and waved straight through under the two flags an operator
reaches for in a panic. The weaker path is the one behind --force.
Three tests through guardMissingServerDatabaseAt, mirroring the plain-init
trio: no project_id with a local data dir present must refuse; no project_id
with nothing local at all is a genuine fresh clone and must be allowed; and
--recreate-missing must still open the refused case.
The first fails at this commit. The other two pass, and pin the directions the
fix must not break.
* fix(init): green — probe the local database before consulting project_id
ADR-0004 follow-up 1. Move the per-database <dolt-data-dir>/<database>/.dolt
probe above the project_id check in guardMissingServerDatabaseAt, and run it
unconditionally, so this guard reasons in the same order as the plain-init
guard it backstops.
When the probe comes up empty and project_id is also absent, apply the same
coarse-directory permit condition checkExistingBeadsDataAt uses: allow only
when there is no local Dolt data directory either. A data directory with no
database in it still says this workspace has touched local Dolt storage, and
that is exactly the pre-GH#2372 lost-storage case the old early return waved
through under --reinit-local and --force.
One cell of the behavior matrix changes: no project_id, no local database, but
a local data directory present now refuses instead of returning nil.
Everything else is untouched, --recreate-missing still returns nil at the top
of the function, and a workspace with nothing local at all is still treated as
a fresh clone.
The comment records the shared-server asymmetry ADR-0004 accepts — there the
coarse directory is machine-global, so that cell is more conservative — as
settled rather than as an open defect, since it fails toward refuse and its
population only shrinks.
* docs: cite ADR-0004 from the plain-init guard, the recovery doc and CHANGELOG
The comment at checkExistingBeadsDataAt's project_id check said the limit was
"OPEN and tracked by be-5pjhd" and that the replacement signal was
"deliberately not made here". It is made now, so the comment says settled
instead of open, and points at the ADR rather than at a bead — with a note to
read it before reopening, since the two obvious alternatives are recorded
there as rejected rather than unconsidered.
docs/recovery/init-safety.md said the same thing in operator language and is
updated the same way, plus a new bullet stating that the guard now applies
equally to bd init, --reinit-local and --force. That equality is the
user-visible half of the fix and was not previously stated anywhere.
Its "Last reviewed" marker moves to today. The doc is freshness-tracked
against cmd/bd/init.go, which this series changes, and leaving the marker at
2026-09-08 would claim text written today had been reviewed eight days before
it existed.
* chore: remove leaked internal release-gate doc from PR branch
release-gates/be-udx2-init-missing-db-guard-gate.md
Tracked our internal gc-management/beads-rig release-gate checklist and
should never have been committed to this upstream branch -- it's process
residue from our deploy tooling, not part of the change itself.
Per maintainer bee-ghosttrack's request during review of PR #6571. The
root cause (our deploy tooling auto-committing this file) is already fixed
as of gm-qatxl1; this branch predates that fix, so this commit is cleanup
only -- no other content on this branch is touched.
Ref: be-lk7o3
* chore(bazel): enumerate init_guard_force_e2e_test.go in cmd/bd srcs
The PR adds cmd/bd/init_guard_force_e2e_test.go under a plain '//go:build cgo'
tag, which is the tag class cmd/bd/BUILD.bazel enumerates (the 23 unenumerated
test files in this package are all 'cgo && integration', 'scripttests' or
'chaos'). cmd/bd/BUILD.bazel is base-added, so the contributor's branch could
not have carried this row. Generated by 'make bazel-sync'; no hand edits.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* fix(init): honor --recreate-missing on the proxied route; scope the refusal's evidence claim
Maintainer review fixes for PR #5791 (iteration 1). Five review minors; the
three substantive ones:
1. --recreate-missing was inert under --proxied-server. runInit dispatches to
runInitProxiedServer and returns before the assignment site, while
runInitProxiedServer calls checkExistingBeadsData, which reads the global —
so converting a server-mode workspace with a missing database to proxied
mode was refused despite the explicit opt-in, and the refusal named the
exact flag the operator had just passed. It failed closed, so there was no
data hazard, only a recovery dead-end. The assignment now sits beside its
flag read, upstream of every dispatch in runInit.
The PR's recovery runbook documented this inertness as "pre-existing
behaviour, not introduced here". The early dispatch is pre-existing, but
--recreate-missing is introduced by this PR, so the flag could not have had
pre-existing inertness. That paragraph is rewritten to the new behaviour.
2. initGuardMissingServerDBMessage asserted "metadata.json has a project_id"
unconditionally, but the --reinit-local/--force guard also emits it for a
workspace predating GH#2372 where only local Dolt storage proves prior use —
the population the CHANGELOG bullet names. The evidence sentence is now
selected by the caller, so the message never cites an artifact its caller
does not have. Pinned from both sides: the project_id cell must cite that
evidence, the no-project_id cell must not.
3. The new doc comment claimed initGuardServerMessage is "used when there is no
evidence either way". It has no production caller, so the contrast was
asserted as two live code paths. Reworded to intent. The dead message's
surviving "existing project -> bd bootstrap" sentence is pre-existing, is
pinned by four tests, and is left for a follow-up.
Also re-cited two stale path:line references by symbol and branch (the recovery
runbook's three, and a test comment's two), and expanded the else-branch comment
in checkExistingBeadsDataAt to cover the reachable-but-missing fall-through that
lands there — the branch's guards are correct for both cases only because their
conditions do not mention reachability.
Declined, with reasons, as out of scope for opportunistic cleanup: restructuring
the fall-through itself (a control-flow change in the diff's most complex
function, which both review lanes agree is behaviourally correct today);
rewording the caller-less message's bootstrap sentence (four pinned tests,
pre-existing); and adding --recreate-missing to the generated CLI reference
(the required check-doc-flags job passes at this head and seven other registered
initCmd flags are equally absent, so that page is not a flag enumeration).
Validation: go build ./... and go vet ./cmd/bd/ clean; gofmt clean;
go test ./cmd/bd/ -run 'TestInitGuard|TestCheckExistingBeadsData' ok (26 tests,
real Dolt servers); scripts/check-doc-freshness.sh PASSED; git diff --check
clean. The evidence pin was proved non-vacuous by mutation: forcing the reinit
call site back to an unconditional project_id claim reddens exactly the
no-project_id test and nothing else.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* fix(doctor): drop the bd init hint from #5634's permissions warning
1d7629213b on this branch removed "bd init (safe to re-run)" from the
.beads/.gitignore fix hints, because re-running bd init is the unsafe
action be-5up5 guards against. #5634 (c33738d209) reached main while
this PR was open. It added a CheckGitignore warning for unexpected file
permissions that still carries the old hint, so after the merge it was
the only gitignore check that suggested bd init.
Give it the same "Run: bd doctor --fix" hint as the four other
gitignore warnings. That is a complete repair here: FixGitignore
restores mode 0600, and #5634's test already checks that the warning
clears after it runs.
TestCheckGitignore_WarnsOnLoosePermsWhenPatternComplete only checked
that Fix was non-empty. It now pins the exact hint. With the old
gitignore.go line put back, the test fails.
Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Gas City Adopt-PR
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* docs(init): name the real gitignore template in ADR-0004 and init.go
ADR-0004 and the matching comment in init.go both cite
`defaultGitignoreContent` in cmd/bd/doctor/gitignore.go as the place
that says .beads/metadata.json is git-tracked by default. No symbol by
that name exists, in this branch or in main's history. The constant
that says it is GitignoreTemplate. Its closing lines read "Config files
(metadata.json, config.yaml) are tracked by git by default since no
pattern above ignores them".
Rename the reference in both places. The claim itself is unchanged.
Neither file changes outside that one identifier.
Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Gas City Adopt-PR
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
226 lines
9 KiB
Go
226 lines
9 KiB
Go
package dolt
|
|
|
|
import (
|
|
"database/sql"
|
|
"errors"
|
|
"fmt"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
|
|
mysql "github.com/go-sql-driver/mysql"
|
|
|
|
"github.com/steveyegge/beads/internal/storage"
|
|
"github.com/steveyegge/beads/internal/storage/dberrors"
|
|
)
|
|
|
|
// Sentinel errors for the dolt storage layer.
|
|
// These complement the storage-level sentinels (storage.ErrNotFound, etc.)
|
|
// with dolt-specific error types.
|
|
var (
|
|
// ErrTransaction indicates a transaction begin/commit/rollback failure.
|
|
ErrTransaction = errors.New("transaction error")
|
|
|
|
// ErrQuery indicates a database query failure.
|
|
ErrQuery = errors.New("query error")
|
|
|
|
// ErrScan indicates a failure scanning database rows into Go values.
|
|
ErrScan = errors.New("scan error")
|
|
|
|
// ErrExec indicates a database exec (INSERT/UPDATE/DELETE) failure.
|
|
ErrExec = errors.New("exec error")
|
|
|
|
// ErrDanglingReference indicates that the pre-push integrity check detected
|
|
// missing chunks in the local Dolt noms store. The push was aborted to
|
|
// prevent propagating the corruption to the remote. Run bd dolt verify
|
|
// to diagnose and recover.
|
|
ErrDanglingReference = errors.New("dangling chunk reference")
|
|
|
|
// ErrFSCKTimeout indicates that the pre-push integrity check (dolt fsck) did
|
|
// not complete within the configured timeout. The push was aborted without
|
|
// verifying chunk integrity — the store is not necessarily corrupt. Large
|
|
// stores can be shrunk with `dolt gc` (or `CALL DOLT_GC()` on a running
|
|
// sql-server); the timeout can be raised via the BEADS_FSCK_TIMEOUT
|
|
// environment variable.
|
|
ErrFSCKTimeout = errors.New("pre-push integrity check timed out")
|
|
|
|
// ErrCommitIndeterminate is the storage-wide no-replay sentinel. Keep this
|
|
// alias for server-Dolt callers while embedded Dolt returns the same value.
|
|
ErrCommitIndeterminate = storage.ErrCommitIndeterminate
|
|
)
|
|
|
|
// isTableNotExistError returns true if the error indicates a MySQL/Dolt
|
|
// "table doesn't exist" error (error 1146). Used to distinguish legitimate
|
|
// fallthrough (pre-migration databases without wisps table) from real errors
|
|
// (timeouts, connection failures, corrupt data).
|
|
func isTableNotExistError(err error) bool {
|
|
return dberrors.IsTableNotExist(err)
|
|
}
|
|
|
|
// isBranchTrackingError returns true if the error indicates that DOLT_PULL
|
|
// failed because upstream branch tracking is not configured. This happens
|
|
// when a remote was added via DOLT_REMOTE('add') or bd dolt remote add
|
|
// rather than via dolt clone / bd bootstrap, leaving repo_state.json with
|
|
// an empty "branches" map (GH#3144).
|
|
func isBranchTrackingError(err error) bool {
|
|
return err != nil && strings.Contains(err.Error(), "did not specify a branch")
|
|
}
|
|
|
|
// isSerializationError returns true if the error is a Dolt/MySQL serialization
|
|
// failure that guarantees the transaction was rolled back. Safe to retry.
|
|
// - 1213 (ER_LOCK_DEADLOCK): concurrent transactions conflict at commit time
|
|
// - 1205 (ER_LOCK_WAIT_TIMEOUT): lock wait exceeded, transaction rolled back
|
|
func isSerializationError(err error) bool {
|
|
var mysqlErr *mysql.MySQLError
|
|
if !errors.As(err, &mysqlErr) {
|
|
return false
|
|
}
|
|
return mysqlErr.Number == 1213 || mysqlErr.Number == 1205
|
|
}
|
|
|
|
// isDoltAutocommitRollbackError reports Dolt's explicit, rollback-guaranteed
|
|
// commit conflict. A MySQL error is retried only when its decoded code and
|
|
// server-provided semantic message identify this condition; newer Dolt builds
|
|
// append recovery guidance after the same sentence.
|
|
func isDoltAutocommitRollbackError(err error) bool {
|
|
var mysqlErr *mysql.MySQLError
|
|
return errors.As(err, &mysqlErr) &&
|
|
mysqlErr.Number == 1105 &&
|
|
(mysqlErr.Message == "Merge conflict detected, @autocommit transaction rolled back" ||
|
|
strings.HasPrefix(mysqlErr.Message, "Merge conflict detected, @autocommit transaction rolled back."))
|
|
}
|
|
|
|
// isIndeterminateCommitResponse reports whether a Commit error lacks a decoded
|
|
// server response proving a definite rejection or rollback. Every untyped
|
|
// protocol or transport error is conservatively indeterminate.
|
|
func isIndeterminateCommitResponse(err error) bool {
|
|
if err == nil {
|
|
return false
|
|
}
|
|
if errors.Is(err, ErrCommitIndeterminate) {
|
|
return true
|
|
}
|
|
var mysqlErr *mysql.MySQLError
|
|
return !errors.As(err, &mysqlErr)
|
|
}
|
|
|
|
func wrapSQLCommitError(op string, err error) error {
|
|
if err == nil {
|
|
return nil
|
|
}
|
|
if isIndeterminateCommitResponse(err) {
|
|
return fmt.Errorf("%s: %w: %w", op, err, ErrCommitIndeterminate)
|
|
}
|
|
return fmt.Errorf("%s: %w", op, err)
|
|
}
|
|
|
|
// wrapDBError wraps a database error with operation context.
|
|
// If err is sql.ErrNoRows, it is converted to storage.ErrNotFound.
|
|
// If err is nil, nil is returned.
|
|
func wrapDBError(op string, err error) error {
|
|
if err == nil {
|
|
return nil
|
|
}
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
return fmt.Errorf("%s: %w", op, storage.ErrNotFound)
|
|
}
|
|
return fmt.Errorf("%s: %w", op, err)
|
|
}
|
|
|
|
// wrapTransactionError wraps a transaction error with operation context.
|
|
func wrapTransactionError(op string, err error) error {
|
|
if err == nil {
|
|
return nil
|
|
}
|
|
return fmt.Errorf("%s: %w: %w", op, ErrTransaction, err)
|
|
}
|
|
|
|
// wrapScanError wraps a row scan error with operation context.
|
|
func wrapScanError(op string, err error) error {
|
|
if err == nil {
|
|
return nil
|
|
}
|
|
return fmt.Errorf("%s: %w: %w", op, ErrScan, err)
|
|
}
|
|
|
|
// wrapQueryError wraps a query error with operation context.
|
|
func wrapQueryError(op string, err error) error {
|
|
if err == nil {
|
|
return nil
|
|
}
|
|
return fmt.Errorf("%s: %w: %w", op, ErrQuery, err)
|
|
}
|
|
|
|
// wrapExecError wraps an exec error with operation context.
|
|
func wrapExecError(op string, err error) error {
|
|
if err == nil {
|
|
return nil
|
|
}
|
|
return fmt.Errorf("%s: %w: %w", op, ErrExec, err)
|
|
}
|
|
|
|
// databaseNotFoundError builds the "database not found" error with a config-aware
|
|
// hint about sync.remote and backup recovery. Extracted from openServerConnection
|
|
// for testability.
|
|
func databaseNotFoundError(cfg *Config) error {
|
|
var b strings.Builder
|
|
fmt.Fprintf(&b, "database %q not found on Dolt server at %s:%d\n\n", cfg.Database, cfg.ServerHost, cfg.ServerPort)
|
|
|
|
// Check if backup files exist — strong signal this is a branch-switch or
|
|
// fresh-clone scenario rather than a server misconfiguration (GH#2327).
|
|
if HasBackupFiles(cfg.BeadsDir) {
|
|
b.WriteString("Backup files found in .beads/backup/ — this may be a branch-switch\n")
|
|
b.WriteString("or fresh-clone scenario where the Dolt database doesn't exist yet.\n\n")
|
|
b.WriteString("Use the safe entry point for existing-project recovery:\n")
|
|
b.WriteString(" bd bootstrap # Auto-detect remote/backup/JSONL recovery or initialization\n")
|
|
b.WriteString(" bd backup restore # If backup recovery still needs manual restore\n\n")
|
|
b.WriteString("If this is NOT a branch switch, see common causes below.\n\n")
|
|
}
|
|
|
|
b.WriteString("Common causes:\n")
|
|
b.WriteString(" - Switched git branches (the Dolt database is runtime state, not in git)\n")
|
|
b.WriteString(" - The server is serving a different data directory than expected\n")
|
|
b.WriteString(" - The server was restarted and is using a different port\n")
|
|
b.WriteString(" - Another project's Dolt server is running on this port\n\n")
|
|
b.WriteString("To diagnose:\n")
|
|
b.WriteString(" bd doctor # Check server and database health\n")
|
|
b.WriteString(" bd dolt status # Show which data directory the server is using")
|
|
|
|
if cfg.SyncRemote != "" {
|
|
fmt.Fprintf(&b, "\n\nTip: sync.remote is configured (%s).\nRun bd bootstrap to recover from the remote or confirm what bootstrap will do with --dry-run.", cfg.SyncRemote)
|
|
} else {
|
|
// be-5up5: no longer claims bootstrap is a safe first step "if this is an
|
|
// existing project" — bootstrap can silently create an empty database in
|
|
// server mode (2026-08-11 fleet-wide loss), so that framing pointed
|
|
// existing projects with a missing database at the same danger this guard
|
|
// exists to stop. Fresh-clone / shared-server-recovery guidance (the
|
|
// common, safe case) is unchanged.
|
|
b.WriteString("\n\nTip: If this is a fresh clone or shared-server recovery, run bd bootstrap first.\n")
|
|
b.WriteString("If bootstrap cannot find the expected remote automatically, set sync.remote\nin .beads/config.yaml and re-run bd bootstrap.\n")
|
|
b.WriteString("Use bd bootstrap --dry-run if you need to confirm the plan before it initializes anything.\n")
|
|
b.WriteString("If this is an existing project whose database went missing, run bd doctor before\n")
|
|
b.WriteString("bootstrap or init — neither is guaranteed to recover it safely.\n")
|
|
b.WriteString("Use bd init only when creating a brand-new project with no existing .beads data.")
|
|
}
|
|
|
|
return errors.New(b.String())
|
|
}
|
|
|
|
// HasBackupFiles checks whether .beads/backup/ contains any JSONL files,
|
|
// indicating a prior backup that could be restored (GH#2327).
|
|
func HasBackupFiles(beadsDir string) bool {
|
|
if beadsDir == "" {
|
|
return false
|
|
}
|
|
backupDir := filepath.Join(beadsDir, "backup")
|
|
entries, err := os.ReadDir(backupDir)
|
|
if err != nil {
|
|
return false
|
|
}
|
|
for _, e := range entries {
|
|
if !e.IsDir() && strings.HasSuffix(e.Name(), ".jsonl") {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|