* fix(setup): keep bd setup claude --global's section in ~/.claude/CLAUDE.md
bd setup claude --global put its hook in ~/.claude/settings.json but wrote
the managed beads section into the current directory's CLAUDE.md, and
--remove --global stripped it from there. Run from $HOME it created
~/CLAUDE.md with project scaffolding, which stops Claude Code reading
AGENTS.md in projects below it; run inside a project it removed the
section that project's own install had written, leaving its hooks.
A global install and removal now manage the section in Claude Code's
user-level ~/.claude/CLAUDE.md (created holding only the section, no
project scaffolding), with hints naming bd setup claude --global. With
global or plugin hooks, --check reports that file when the project's
instructions have no beads section; a project install is still judged
on the project's file alone. Project installs are unchanged.
Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(setup): render the user-level CLAUDE.md section independently of the project
~/.claude/CLAUDE.md is shared by every project, but bd setup claude --global
rendered and --check judged its section with the current directory's beads
config (sync.remote, sync.git-remote, no-push). From a project with a remote
and one without, --check called the other's install stale and its hint
flipped the file back. The user-level file now always renders with the
default options, so install and --check agree across projects.
Also pin --check's fallback to the project's file and project hint when
neither file has a section, tell existing --global users to re-run it, and
name ~/.claude/CLAUDE.md in the ide-setup recipe table.
Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(setup): judge the user-level Claude files from $HOME and ~/.claude
Run from the home directory, the project's .claude/settings.json is the
global one, so bd setup claude --check reported a global install as project
hooks and judged ~/CLAUDE.md; its "Run: bd setup claude" hint then created
the ~/CLAUDE.md a global install exists to avoid. Run from ~/.claude, the
project's CLAUDE.md is the user-level file, and --check judged it with that
directory's render options and the project hint.
--check now reports hooks as global from $HOME and judges the user-level
file there and from ~/.claude with the fixed options and the --global hint.
With user-level hooks and no section in either file it names --global
unless the project has its own CLAUDE.md. A --remove run from $HOME, which
removes the global hooks, also removes the user-level section.
The init agent-artifact test ran bd setup claude with HOME at the project,
so its checks would now see a home directory; it gets a separate HOME and
its goldens are unchanged.
Rebase note (maintainer): rebased onto main after #7678 merged; main's
agent-artifact harness already runs bd with a separate HOME, so this
commit's harness edits to cmd/bd/agent_artifacts_embedded_test.go were
dropped.
Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* test(setup): pin --check's user-level choice beside project instructions
With global hooks, --check judges ~/.claude/CLAUDE.md when the project's
own CLAUDE.md has no beads section but the user-level file has one, and
when run from the home directory whose ~/CLAUDE.md has no section. Nothing
exercised either half of that condition: replacing it with false left the
suite and goldens green. Add a subtest for each; each now fails when its
half of the condition is dropped.
Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(setup): name --global when --check finds no hooks from $HOME
From the home directory --check with no hooks said 'Run: bd setup claude'.
Following it runs a project install there, which creates ~/CLAUDE.md with
project scaffolding, the file that stops Claude Code reading AGENTS.md in
the projects below it. The missing-section hint at home already names
--global; make the missing-hooks hint match, with a subtest.
Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* docs(setup): qualify the --global CHANGELOG entry; watch ~/.claude/CLAUDE.md
The CHANGELOG said --check from the home directory judges the user-level
files, but a beads section still in ~/CLAUDE.md is judged instead, and
the --global hint for a missing section applies only when the project has
no CLAUDE.md of its own. Say both, mention the new missing-hooks hint at
home, and re-wrap the paragraph.
The embedded agent-artifact harness comment said a global install writes
$HOME/CLAUDE.md; it now writes $HOME/.claude/CLAUDE.md. Track that path
too and reword the comment. The bd init goldens do not change.
Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(setup): word the user-level CLAUDE.md section for repositories that use beads
bd setup claude --global writes its section to ~/.claude/CLAUDE.md, which
Claude Code loads in every project, but rendered it with the project
wording: "This project uses bd (beads)" and "Use bd for ALL task tracking —
do NOT use TodoWrite". In a repository without beads that told the agent to
give up its own task tools and pointed it at bd, whose answer there is
"run 'bd init'", while the global hook, bd prime, stays silent outside a
workspace.
RenderOpts.UserLevel rewords the opening line and the task-tracking rules of
both profiles so they apply only in beads repositories. The global env fixes
it through agents.UserLevelRenderOpts, so install, in-place update and
--check agree on the hash from every directory, and a project-worded section
left in ~/.claude/CLAUDE.md reads as stale and is reworded by --global. The
new minimal-user and full-user variants are pinned by golden and hash; the
project rendering is unchanged.
Also pin sameDir's symlink following: --check from a symlink to $HOME or to
~/.claude still judges the user-level files.
Refreshed onto main past #7692, whose --remove takes the blank lines
around the section with it and whose setup appends a section after one
blank line: claude-setup-global-beside-project-install.golden no longer
records the old hole (an extra blank line before the appended section,
two left behind by --remove --global).
Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Co-authored-by: Eddie the Engineer <338826946+gascity-eddie[bot]@users.noreply.github.com>
`bd setup claude --remove` (and the factory, mux, opencode and gemini
recipes that share removeBeadsSection) cut exactly the managed section
and kept the blank lines that set it off, leaving a 3-line hole in the
CLAUDE.md bd init writes. installAgents then appended a re-added section
after two blank lines, so every remove/re-add cycle grew the file.
removeBeadsSection now drops the line breaks next to the section (never
text): the surrounding text is rejoined with one blank line, or none if
the section had none; a section at the top leaves no leading blank
lines and one at the bottom leaves a single final line break. CRLF is
preserved, and a marker sharing its line with text is still cut
exactly. installAgents appends like bd init's updateAgentFile: ensure a
final newline, then one blank line. remove(add(x)) == x for a file
ending in a newline, and after the first remove, setup and --remove
toggle between the same two files; a re-added section goes at the end.
Goldens regenerated with BD_UPDATE_GOLDEN=1.
Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* test(conformance): author R7.1 as-of-read conformance contract
Adds a new Phase 0 conformance contract for R7.1 (as-of reads,
gastownhall/beads#6136, design doc #5898 rev 9) -- no fixture existed for
this anywhere in backend/conformance/, so this is authored from scratch,
not un-skipped.
AsOfReadFixture supplies three hooks: Resolve (the read under test),
MintAt (seeds a version at a controlled accept-time), and
MakeUnanswerable (arranges a Gone/Unknown refusal independently of
RetentionFixture/EpochFixture's own removal machinery, since R7.1's
refusal is a sibling contract to R17/R20, not a dependent of them).
Five Run* functions cover the bead's five required-coverage points
verbatim:
- selector accepts either an instant or a version address, and both name
the same answer when they resolve to the same version;
- resolution returns the latest version at-or-before T, with a version
accepted after T strictly excluded even when close by;
- a served result reports the exact address it served;
- an unanswerable read refuses as a typed Gone*/Unknown outcome with a
reason, and never substitutes a neighboring version, the nearest
surviving version, or current state -- asserted directly by requiring
Address == "" on every refusal;
- local completeness only (TC3): a lineage minted into one of two stores
resolves there and refuses Unknown (FR-06) on the store that never
received it, asserting nothing about agreement between the two.
The file's doc comment states the Memory-plane-consumer-policy non-goal
explicitly (closed-before-T boundary, sibling exclusion, supersession
exclusion are consumer policy per #5877, not part of this primitive) so
the gap reads as deliberate scope, not an oversight.
Wired onto all three storage legs (dolt, embeddeddolt, uow) with
unconditional "not implemented" stubs rather than partial-real hooks, so
every case fails via MintAt on its first fixture call -- deterministic
RED with no risk of an accidental pass, per the precedent set by
be-x5jqd.1. Sentinel error messages reference be-x5jqd.5, the
implementation child this suite is written ahead of.
TestEveryLegWiresEveryRoleContract requires zero waivers: all 5 new
entrypoints are fully wired (not nil) on all three legs.
Branch cut from the rebased be-2h167 head (5fdfb92fe5).
Verified via go build ./..., go vet ./..., gofmt -l, and go test -tags
cgo across all three legs: all 5 new subtests (8 counting the 4-way
Gone/Unknown table) FAIL for the documented reason,
TestEveryLegWiresEveryRoleContract passes cleanly on all three legs, and
TestVersionedHistoryPhase0RunsInFullSkipMode is unaffected.
Bead: be-x5jqd.2
* fix(history): refuse metadata integers binary64 cannot hold exactly (refs be-wdlod, #6358 follow-up)
canonicalDurableState canonicalizes numbers per RFC 8785 (JCS), which
renders every number as an IEEE-754 binary64 double regardless of
magnitude. An integer-valued metadata literal past 2^53-1 therefore
rounds to a DIFFERENT VALUE on the way into durable_state -- not a
formatting change, a value change -- which can collapse two distinct
issue states onto one durable_state and therefore one content token.
refuseUnrepresentableIntegers is the fix: an admission gate, one layer
above the JCS step, that parses each JSON number literal exactly with
math/big (never float64 -- float64 rounding is the exact thing being
guarded against) and refuses whenever the literal's VALUE, not its
spelling, is an integer whose magnitude exceeds 2^53-1. Value-not-form
matters because the first cut of this gate skipped any literal
containing '.', 'e', or 'E' outright, reasoning that non-integer forms
round-trip losslessly -- true for genuinely fractional literals, but
not for an integer VALUE spelled in decimal or exponential form: QA
found that 9007199254740993.0 and 9.007199254740993e15 walked straight
past that first gate and canonicalized to the same colliding target as
the bare literal. The predicate now inspects the value via
big.Rat.SetString/.IsInt, so all three spellings are refused alike.
1e300 is refused too, no notation carve-out: it denotes the integer
10^300, and binary64 spacing near that magnitude is roughly 2^248 --
vastly wider than the collision window at the 2^53 boundary this gate
exists to close. Admitting that spelling while refusing 9007199254740993
would be the same defect with a bigger window (mayor's ruling, citing
this collision-window argument as decisive). Non-integer values stay
admissible past the bound (1.5e300 is fine): ES6 shortest-round-trip
formatting is a bijection on doubles, so two non-integer literals
collide only if they already denoted the same double before this gate
ever ran, and a fractional literal never carried a promise of exact
decimal storage the way an integer -- an id, a count, a timestamp --
carries a promise of exactness that silent rounding would corrupt.
jcsCanonicalize is canonicalDurableState's RFC 8785 step pulled out on
its own, below the gate rather than behind it, because refusing 1e300
puts the admission policy at odds with one of this store's own spec-
conformance fixtures: testdata/jcs/input/values.json, one of the 10
official RFC 8785 vectors shipped verbatim from the spec's reference
suite (not authored here), itself contains 1E30. RFC 8785 conformance
is a claim about the canonicalizer, not about this store's admission
policy, so TestCanonicalDurableStateIsJCS now runs all 10 shipped
vectors -- values.json included, still asserting 1E30 folds to 1e+30
per spec -- through the ungated jcsCanonicalize, while its two local ad
hoc cases keep exercising the full gated canonicalDurableState, since
neither conflicts and both are more faithful to production traffic that
way. The gate's own refusal of that magnitude is pinned separately, on
its own terms, in version_history_integer_admission_test.go.
Severity is MINOR, not MAJOR: Dolt's JSON column type already
renormalizes metadata to float64 on every read regardless of this gate
(measured on dolt 2.2.3: 9007199254740993 reads back as
9007199254740992, 1e300 as 1e+300), which converges two distinct
in-memory states to one stored state before any version row is minted.
The collision this gate closes is therefore unreachable through normal
bd update traffic on this backend; it stays real for off-path writes --
bd sql, a hand-written JSONL import, or a TEXT-column backend -- which
is why this landed as a follow-up rather than gating Phase 2 itself.
Verified clean: a full module compile; static analysis over the
storage tree; the complete issueops package suite (260 subtests); the
schema package suite; and the broader storage tree, apart from one
dolt-package test that fails identically against the pre-this-diff
baseline (a Dolt server port collision with a concurrent session's
process on this host) -- confirmed pre-existing and environmental, not
caused by this change.
* feat(issueops): implement R7.1 as-of read's store-layer primitive (be-x5jqd.5)
Turns backend/conformance/versioned_read_contract.go (authored RED in
6aefdce60, gastownhall/beads#5898 rev 9, #6136) towards GREEN. This
commit lands the shared production seam; wiring the three per-leg
fixtures (dolt, embeddeddolt, uow) onto it is a follow-up commit.
asof_read.go (new): AsOfReadInTx resolves an AsOfSelector (an instant
or a previously-served version address) to one issue_versions row --
the latest version accepted at or before T, everything later strictly
excluded -- and reports either its state and address, or a typed
refusal (gone-retention/gone-erasure/gone-reorganization/unknown) with
a reason. storeID is accepted only for signature parity with the
fixture hook shape (Design D: the conformance suite's own ad hoc
dispatch string selects among per-leg isolated test stores; issue_versions
carries no store_id column, matching CurrentEpochInTx's precedent).
AsOfRestriction is string-backed, unlike R20's int-backed
EpochRestriction, because it round-trips directly through the new
removed_restriction column with a plain cast.
Migration 0069 adds issue_versions.removed_restriction VARCHAR(30),
nullable (NULL = live, never a stored value). Sits alongside removed_at/
removed_reason (migration 0067, virgin until this slice); AsOfReadInTx
only READS all three -- a future R17 is the real writer via hold/remove/
erase primitives, no collision. Guarded PREPARE + CLI direct-DDL
override + schema_test.go hygiene entries, all modeled on 0068's
pattern; TestLatestVersionIncludesMigration0068 is superseded per the
one-pin-at-a-time convention.
version_history.go: splits RecordVersionInTx into a versionedHistoryEnabled-
gated wrapper and a new exported RecordVersionAtInTx, both delegating to
a shared recordVersionAtInTx(..., at time.Time) body. RecordVersionAtInTx
is test-support only -- ungated, caller-chosen timestamp -- so an as-of-
read fixture's MintAt hook can mint version rows dated in the past
without flipping a store's history-enabled flag. No behavior change for
existing RecordVersionInTx callers.
The new/moved code shifted which function each completeness guard sees
as the enclosing write site, so all three needed updating, not bypassing:
- row_lock_guard_test.go's funcNameExemptions key moves from
RecordVersionInTx to recordVersionAtInTx (the write's new actual
enclosing function), reasoning extended to cover both callers.
- journal_completeness_test.go's beadDMLExemptions and
version_completeness_test.go's versionExemptions each gain a
RecordVersionAtInTx entry mirroring RecordVersionInTx's own (test-
support twin, no production caller, no mutation of its own to
journal/mint beyond the seam itself).
Also fixed a latent test-helper gotcha found while writing the 0069
Dolt-CLI test: queryDoltCSV trims the whole `dolt sql -r csv` output
before parsing, so a row whose ONLY selected column is NULL renders as
a bare blank line that strings.TrimSpace silently swallows when it's
the trailing line, collapsing "one row, NULL value" into "zero rows".
Fixed by selecting a non-NULL anchor column (issue_id) alongside the
column under test.
Verification performed: full module compile and static analysis, gofmt
clean; the complete internal/storage/schema suite with the real-Dolt-CLI
lane enabled; and the complete internal/storage/issueops suite,
including every completeness/row-lock structural guard -- all clean.
* feat(issueops): wire dolt, embeddeddolt, and uow onto R7.1 as-of read (be-x5jqd.5)
Turns backend/conformance/versioned_read_contract.go fully GREEN
(authored RED in 6aefdce60, gastownhall/beads#5898 rev 9, #6136): this
follows up on 4da98a9a8's shared production seam by wiring all three
storage legs' AsOfReadFixture (Resolve/MintAt/MakeUnanswerable) onto
issueops.AsOfReadInTx, per that commit's own stated plan.
Each leg's asOfReadHarness is Design D's dispatch table: the
conformance suite invents storeID strings to select among N isolated
stores, and isolating them is entirely the harness's job --
AsOfReadInTx itself stays storeID-oblivious. The three legs differ
only in how they get that isolation cheaply:
- dolt: one shared testcontainer, N randomly-named databases
- embeddeddolt: N fully independent on-disk databases
- uow: one shared dolt sql-server subprocess (NewDoltServerUOWProvider's
adoption semantics collapse repeat calls against the same root dir
onto the same process), N randomly-named databases
All three harnesses are Fatalf/Skip-free below their own
TestAsOfReadContract body: AsOfReadFixture's hooks carry no *testing.T
of their own and run from inside t.Run subtest closures (sometimes
nested two deep), where FailNow/SkipNow would panic with "subtest may
have called FailNow on a parent test". Failures instead flow back as a
plain error into conformance.RunAsOfReadXXX, which Fatalfs correctly
on the subtest's own goroutine.
Two small companion fixes surfaced while wiring the legs on:
- issueops.asOfVersionAddress -> AsOfVersionAddress (exported): each
leg's MintAt needs to build the exact token its own
RecordVersionAtInTx write will resolve against, from a different
package than issueops.
- recordVersionAtInTx now truncates `at` to whole seconds before
writing it to issue_versions.change_at (DATETIME, migration 0067).
Measured on dolt 2.2.3: the column ROUNDS a sub-second value rather
than truncating it, so a change_at of 13:32:04.77 lands at 13:32:05
-- strictly later than the instant it was meant to record. That
breaks resolveAsOfRevisionInTx's "at or before T" comparison
(asof_read.go) for any T between the true instant and the rounded-
up one. This is a production correctness fix, not test-only:
RecordVersionInTx hits the identical hazard on every real
time.Now().UTC() call whose nanosecond component rounds up.
Verification performed:
- uow: TestAsOfReadContract green standalone (5 subtests, 4 nested
restriction variants) and the full uow package green in isolation
(673s, includes pre-existing TestReleaserContract and everything
else). A `go test ./internal/storage/...` full-tree sweep flagged
uow FAIL via a 600s hang inside TestReleaserContract's migration
lock -- traced to cross-package parallel resource contention from
running the whole storage tree's dolt-sql-server-spinning suites
concurrently, not a regression: the same test is clean when the
package runs alone.
- embeddeddolt: TestAsOfReadContract green (22.89s, all subtests and
all 4 restriction variants).
- dolt: skipped on this host -- no Docker for the leg's testcontainer,
the same pre-existing skipIfNoDolt gate the whole dolt package
already runs under, unrelated to this change.
- TestEveryLegWiresEveryRoleContract and
TestEveryContractImporterInTheStorageTreeIsRegistered both pass for
all three legs.
- gofmt clean; whole-module build and vet clean.
Bead: be-x5jqd.5
* feat(versions): bd versions + a config switch for versioned history (refs be-hs42e.6.2)
Versioned history has been buildable but not usable: migrations 0067+ create
issue_versions, and the Phase 2 writer fills it, but SetVersionedHistoryEnabled
was a Go method nothing in cmd/bd ever called. There was no supported way for a
person to turn the feature on, and no way at all to read it back without raw
Dolt SQL. This adds the switch and a reader.
- versioned-history.enabled (env BD_VERSIONED_HISTORY_ENABLED), default off,
applied at the top of wireStorageDecorators. It MUST run on the raw store:
the capability is a type assertion and no decorator forwards it, so applying
it after a wrap would silently leave history off while the config said it was
on. TestVersionedHistoryConfigAppliesToTheRawStore pins the ordering, and
fails rather than skips if a decorator ever starts forwarding.
- storage.VersionLister + issueops.ListVersionsInTx over issue_versions, on the
dolt and embeddeddolt legs. A narrow capability rather than a Storage method,
following ExternalRefHistoryQuerier: a backend that cannot know must be able
to say so instead of answering "none".
- bd versions <id>, with three distinguishable outcomes rather than two. Off,
unsupported, and empty are different answers with different fixes; an empty
list is a claim about the bead, and returning it for the other two would be a
wrong answer rather than an empty one. The four removal restrictions render
as four sentences, and unknown (no lineage knowledge here) is not gone.
- REV is printed as a local ordinal with a footer saying so. It is deliberately
NOT presented as a citable address: AsOfVersionAddress mints over the ordinal,
two clones can both hold revision 8 of the same bead, and the durable
version_id primary key has not landed. An address printed now would break
every citation once it does.
- bd version <id> now points at bd versions <id> instead of printing bd's own
build and looking like the bead has no history. Bare bd version is unchanged.
No migration: 0067/0068/0069 already carry every column this reads.
Verified on a scratch store: create + 2 updates + close with the flag on lists
4 attributed versions; with the flag off, 0 rows in issue_versions and the
command refuses naming the key.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* fix(versions): emit local_revision, not revision, in --json (bee's #5898 consumer read)
types.Issue already ships `json:"revision"` (types.go:1206) and it is the
row-lock CAS token — an unrelated value, and a string where this one is an
int64. Emitting "revision" from the versions payload would put two meanings
and two types on one key in the place machines read: the `bd version`
collision again, with worse consequences, since a script that learned one
shape gets the other and cannot tell.
local_revision also carries the non-citability with the value rather than
only in a footer no script parses, and needs no rename when version_id lands
beside it.
Raised by @bee-ghosttrack's consumer read on #5898, who reported a couple of
hundred script files parsing `bd … --json` — this is the part of the surface
they would actually touch. Pinned by
TestVersionsJSONDoesNotCollideWithIssueRevision.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* fix(versions): make the advertised switch actually switch it on (#6661 review)
@bee-ghosttrack's blocking finding: the help text and the off-refusal both
told the user to run `bd config set versioned-history.enabled true`, and that
command did not turn the feature on. The key is not yaml-only, so `bd config
set` routed it to the workspace DATABASE; both readers called config.GetBool,
which is viper (yaml + env) only. The user ran exactly what they were told,
was told it was set, and recording stayed off — configured on, actually off,
one layer up from the decorator-ordering hazard this command already guards.
Takes bee's option (b): read the switch from the store's own config, where
`bd config set` already writes it. That also makes recording a property of
the STORE rather than of whoever is calling, which is what closes finding 2 —
two clients of one sql-server can no longer disagree about whether a write is
recorded.
The two planes are OR'd rather than ranked. The hazard is a write that fails
to record, never one that records when it needn't, so either saying yes is
enough and neither can silently switch the other off. BD_VERSIONED_HISTORY_ENABLED
still works for a one-off run. A store with no settings plane (proxied, no-db)
falls back to viper instead of failing the command.
Also from that review:
- finding 3: the read no longer refuses just because recording is off. A store
that recorded for a month and was switched off HAS versions; refusing made a
claim about the store from a fact about this invocation's config, which
VersionLister's own doc says are independent. Rows are listed either way,
with a note when recording is currently off; refuse-with-remedy only when
off AND empty.
- finding 4: an unresolved id with no versions is "no such bead", not "none
yet". Falling through on an unresolved id stays right — a deleted bead can
still have versions — but only until the answer is empty.
- finding 5: the ordering test's escape hatch is t.Fatal, not t.Skip; a skip
returned before the assertion that actually guards the ordering. The
storage_chain.go doc cited a test name that never existed. version_lister.go
promised a list of compile-time assertions that was not there; the
assertions now exist in each leg's own package, where they can compile.
- `versioned-history.` is a recognized config prefix, so the set no longer
prints "not a recognized config key" immediately before confirming the set.
Test: TestVersionedHistorySwitchRoundTrip_Embedded drives the real
`bd config set` through to a real `bd versions` against a real store, with
BD_VERSIONED_HISTORY_ENABLED cleared so a pass proves the store setting
carried it alone. This is the round trip bee asked for, and it is the only
shape that could have caught the original defect — a fake-backed unit test
cannot see a disagreement between two real planes.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* docs(versions): name what the OR'd switch planes cost (#6661 review)
@bee-ghosttrack, round 2: with the two planes OR'd rather than ranked, the
consequence worth naming is that once the store setting says on,
BD_VERSIONED_HISTORY_ENABLED=0 cannot countermand it for a single run. The
help now says so, and says where to turn it off instead.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* fix(versions): gate the wiring store read on the capability, not a recover (#6661 review)
@bee-ghosttrack's round-3 blocking finding. wireStorageDecorators reads the
versioned-history switch off the raw store on every bd invocation, and did so
before anything established that the store could use the answer. cmd/bd's own
fakeProbingDoltStore embeds a nil storage.DoltStorage, so the promoted
WorkspaceConfig SIGSEGV'd at wiring time -- and a panic takes the whole test
binary down, which is why one unguarded read showed up as two red CI steps
(Test (macos-latest), PR Core (wrapper timing)) rather than one failed test.
Takes the fix bee prescribed: assert storage.VersionedHistoryConfigurer first
and read the store plane only when the store could act on the answer.
The previous round fixed this with a recover plus a WorkspaceConfig on the
fake, and left a comment arguing that no capability assertion could work. That
argument was wrong, and wrong in a specific way worth recording: it reasoned
about asserting WorkspaceConfig, which IS declared on storage.DoltStorage and
so matches every store including the nil-embedding fake. bee proposed
asserting VersionedHistoryConfigurer, which is a different interface --
SetVersionedHistoryEnabled is NOT part of DoltStorage, so the fake does not
promote it and does not satisfy it. The comment rebutted a fix that had not
been proposed. It now states what is actually true.
So the fake goes back to byte-identical with the pushed head: the wiring fix
fixes that test without touching it, as bee said it would, and the fake keeps
the "only the methods below may be called" constraint its own doc asserts.
The recover stays, as a backstop rather than the guard. It covers what the
assertion does not: versionedHistoryEnabled is also called from `bd versions`,
where the read is the point and no capability gate precedes it, and a store
that DOES implement the capability can still have a half-built settings plane.
The viper plane is still read first and unconditionally, so a set-but-unsupported
store still reaches applyVersionedHistoryConfig and still gets its warning. Only
the store-plane read is gated. The one case that loses a warning is a store whose
own settings plane says true but which lacks the capability -- and `bd config
set` could not have written that plane on such a store to begin with.
Tests, split so each layer fails for its own reason:
- TestWireStorageDecoratorsSkipsTheStoreReadForANonConfigurer asserts calls == 0,
not merely that it survived. "It survived" is what the recover delivers too,
which is how this regressed the first time.
- TestWireStorageDecoratorsSurvivesAStoreThatCannotAnswer keeps the recover's
case, now on a store that IS a configurer so the guard lets it through.
- TestVersionedHistoryEnabledForWiringReadsTheStoreWhenItCanRecord pins that the
guard did not stop reading the plane finding 1 existed to start reading.
Mutation-verified both ways: removing the guard fails the first test on
calls=1/want=0 while everything still "passes" by surviving; removing the
recover leaves the first test green and fails only the second.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* test(versions): name the embedded round-trip so CI selects it (#6661 review)
@bee-ghosttrack's round-3 finding 2. The round-trip test that proves the two
config planes agree ran only on the author's machine.
.github/scripts/embedded-test-shard.sh discovers what to run with
`grep -rh '^func TestEmbedded' cmd/bd/*_embedded_test.go` and validates
manifest entries against ^TestEmbedded[A-Za-z0-9_]+$.
TestVersionedHistorySwitchRoundTrip_Embedded matched neither, so the only
lane that sets BEADS_TEST_EMBEDDED_DOLT=1 for cmd/bd never selected it; the
generic Test jobs run without that env, where the test's own guard skipped it.
Skipped and passed look alike from outside, which is what made it invisible.
Renaming is the whole fix -- a test absent from the shard manifest still gets
a shard from the fallback distribution. Verified by running the script's own
selector over the tree and confirming the new name is discovered.
The rationale is now a comment on the test, because the old name reads more
naturally and nothing else in the file explains why the prefix is load-bearing.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* test(versions): drop the dead fixture, name the empty arm (#6661 review)
@bee-ghosttrack's round-3 finding 3. TestVersionsRefusesWhenFlagOff built a
backend holding one recorded version, handed it to nothing, and ended in
`_ = backend`.
The fixture was load-bearing for the assertion the test was named after --
that the read was refused BEFORE the backend was consulted. Finding 3 removed
that behaviour on purpose, so the assertion went with it; the fixture stayed
behind, unused, under a name still promising the old contract.
Renamed to TestVersionsOffAndEmptyRefusesWithRemedy for what it actually pins,
moved beside TestVersionsOffButRecordedStillLists so the two read as the pair
they are -- recording off decides the FOOTER, never whether to read; off with
rows lists them, off and empty is the one case that refuses -- and the dead
fixture is gone.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* fix(proxy): give bd versions a capability row, a typed refusal (#6661)
main's proxied-server capability registry (#6582) requires every command
path to carry a row, and TestProxyCapabilityRegistryCoversCommandTree
fails for `bd versions`, which this PR adds.
It is refused, reason unimplemented, rather than permitted. It is a pure
read (issueops.ListVersionsInTx in one read transaction), so nothing
about it is unsafe on a shared backend and "design" would be wrong. But
it reaches the backend only through the optional storage.VersionLister,
which the dolt and embedded stores implement and the uow provider does
not. Permitting it would open the proxied provider in the root pre-run
(starting the proxy and dolt) and then fail untyped at
errVersionsUnsupported. The row refuses with proxy.versions.unsupported
before any side effect, and its tracking names the missing piece: a
VersionLister over the proxied uow provider (tracker #6132).
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* test(uow): register verified shutdown cleanup in TestAsOfReadContract (#6661)
main's TestEveryServerFixtureRegistersVerifiedCleanup (#6441) requires
every server fixture to use verifiedShutdownCleanup(t, storeRootDir)
instead of calling proxy.Shutdown directly, so a shutdown that refuses
cannot leave a live dolt sql-server behind a green run. TestAsOfReadContract
still had its own proxy.Shutdown cleanup that only logged the error.
The cleanup is registered at the same point, so the LIFO ordering the
harness relies on (every provider closed before the shared server stops)
is unchanged.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* style(schema): gofmt cli_migrations.go after the 0070 renumber
The rebase onto upstream's 0069_widen_issue_versions_datetime_precision
(#6675) joined its const and the renumbered 0070 comment without the
separating blank line, which make fmt-check rejects.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(history): stop flooring change_at now that 0069 widened it (refs be-hs42e.10)
recordVersionAtInTx carried `at = at.Truncate(time.Second)`. That was correct
while 0067's plain DATETIME was in force: Dolt's datetime(0) does not truncate
sub-second input, it ROUNDS half-up, so a change_at could be stored strictly
LATER than the instant it recorded and break AsOfReadInTx's "latest version
accepted at or before T". Flooring first left nothing to round.
Migration 0069 widened change_at and removed_at to DATETIME(6), which removes
the rounding entirely and makes the floor actively harmful — it threw away the
microseconds the widening exists to keep. Two versions minted in the same
second collapsed onto one stored value and stopped being distinguishable by
change_at, which defeats --at, the only PORTABLE selector the read surface
offers while revision stays a per-store ordinal and no durable version address
has shipped.
This was measured, not inferred. On a store carrying both the widening and the
floor, four versions minted inside one second all read back 15:40:38.000000:
the column could hold microseconds and the writer refused to supply them. Two
correct fixes cancelling each other, and only the second one was visible.
removed_at needs no matching change: MarkLatestVersionRemovedInTx already
passes time.Now().UTC() straight through and was never floored. Audited rather
than assumed.
Pinned by TestRecordVersionKeepsSubSecondChangeAt (embeddeddolt), which mints
two versions 500ms apart inside one second and asserts both that the
fractional part survives and that the two differ. Verified it FAILS with the
floor restored — reporting exactly the 11:04:07.000000 collapse — and passes
without it, so it is a real guard rather than a test that passes either way.
The column's own half of the contract stays pinned by
TestMigration0069ChangeAtSurvivesSubSecondPrecisionThroughDoltCLI.
Also drops this branch's own tx-minting guard commit, which upstream landed
independently as #6833.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* test(feat): red — Activate versioned history in every store and provider factory, each store reading its own #6661 switch (stacked on #6661) (refs be-qxq70)
Tests first, all failing on the right reasons at fb6e219d6a (#6661's head):
- D1: on real embedded stores a routed update, a routed close and
`bd create --repo` into a rig whose OWN row is on each gain 0
issue_versions rows, want 1; the control (a write inside the rig) gains 1.
- D3: BD_VERSIONED_HISTORY_ENABLED=1 records into no routed store, and =0 is
shown not to switch off a store whose row is on.
- D4: TestEveryStoreConstructionActivatesVersionedHistory flags all 9 store and
provider factories, and its mutation probe reports "probed 0 of 9".
- wiring: wireStorageDecorators still reads the store's row (1 read) and
switches it on; activation belongs to the factories.
- internal/versionedhistory (does not exist yet) and the doctor repair opener:
the resolver, the provider read (K1), the error-vs-absent diagnostics and the
shared-activation requirement.
* feat: green — Activate versioned history in every store and provider factory, each store reading its own #6661 switch (stacked on #6661) (refs be-qxq70)
Stacked on #6661 (fb6e219d6a). #6661's plane and approved commits are
unchanged: the switch stays a row of the store's own config table, OR'd with
viper, and `bd config set versioned-history.enabled true` still writes that
row and not config.yaml.
The defect: applyVersionedHistoryConfig ran only from wireStorageDecorators, so
the one store a command opens for its own workspace was activated and every
store built by newDoltStoreFromConfig (prefix-routed update/close, `bd create
--repo`, the direct-mode open) was not. With the switch on they recorded no
issue_versions row while the command reported success.
- Activation moves to where a store or unit-of-work provider is constructed
(the store_factory.go/_nocgo.go twins, uow_factory.go's two provider
constructors, the personal-migration planning store, and bd doctor's repair
opener), on the raw store, before anything can wrap it. wireStorageDecorators
no longer activates, so each store's row is read once per open.
- One resolver, in internal/versionedhistory, reachable from doctor/fix which
cannot import package main. #6661's semantics are preserved: one key
spelling, viper first, then the capability check, then the row read, with
the recover backstop. The behavior-preserving refactor of #6661's
versioned_history_switch.go / storage_chain.go is the only edit to files
#6661 introduced; the resolver tests moved with the code, assertions
unchanged.
- K1: a provider has no DoltStorage, so its row is read through a unit of work
(NewUOW + ConfigUseCase().GetConfig) at construction: a pooled connection,
one SELECT, rolled back. The constructors have already run initSchema, so
this starts no server and creates nothing. It does not fall back to viper
alone.
- A row read that errors resolves to off but is reported under BD_DEBUG; an
absent row stays silent.
- Docs (configuration.md), a CHANGELOG entry, and a hint at `bd config set ...
true` time that the setting replicates and is single-writer only.
The bazel-sync run also wanted unrelated BUILD entries for files that already
exist at #6661's head (versions.go, versioned_read_contract.go, ...); they are
not part of this change and are left out.
* test(feat): green — a served mutation records from the provider's own row, on a real server (refs be-qxq70)
K1 is the one place the resolver cannot ask a DoltStorage: `bd serve` against a
server-mode workspace writes through a unit-of-work provider, so its flag is
read through NewUOW + ConfigUseCase().GetConfig at construction. The fakes in
internal/versionedhistory prove the read; this proves it WORKS against a real
Dolt server at that moment (pool open, database selected, schema migrated).
Two server-mode workspaces on the shared test container: the one whose own row
says on records a served HTTP mutation (+1 issue_versions row), the one with no
row records none.
Measured both ways: passes with the provider activation in place, and fails
("added 0 issue_versions row(s), want 1") with it deleted from both provider
constructors in uow_factory.go.
Proxied lane only (BEADS_TEST_PROXIED_SERVER=1 BEADS_TEST_ENV_RUN_DOLT=1
TESTCONTAINERS_RYUK_DISABLED=true), like TestServeActivatesTheEventsJournal, so
it skips in a plain make test.
* test(feat): red — #6661 review round, small items: findings 2, 4, 5, 6 and 8
Tests for the small findings in the second review round on #6661.
- 2: `bd versions` must decide "recording" from the store's own setting.
BD_VERSIONED_HISTORY_ENABLED=1 with the store's row unset and nothing
recorded must refuse, not answer "none yet"; the help text must not offer
the variable as a per-run switch for a read.
- 4: `bd versions --json` is one object, {"versions": [...], "recording":
bool}, with [] rather than null when nothing is recorded.
- 5: AsOfReadInTx reports any stored removed_restriction outside its four
values, "live" included, as unknown.
- 6: the 0070 header spells the restriction vocabulary with the underscore
spellings the code stores and compares.
- 8: `bd version <arg>` exits 1 and points at `bd versions <arg>`. This one
pins behaviour the branch already has, so it passes at red; it was shown
to fail with the guard removed.
Item 7 is a comment-only fix and has no test.
* feat: green — #6661 review round, small items: findings 2, 4, 5, 6 and 7
- 2: `bd versions` reports the store's own setting. It read the environment
and config.yaml as well, so BD_VERSIONED_HISTORY_ENABLED=1 made a store that
never recorded answer "No versions recorded yet" instead of refusing with
the remedy. It only reads, so those planes cannot make the store record.
The "for one run" hint is dropped from the help and the refusal, since it
could only ever produce the wrong answer.
- 4: `bd versions --json` is always {"versions": [...], "recording": bool},
with [] rather than null when nothing is recorded. Previously a bare array,
or null, and no recording flag.
- 5: AsOfReadInTx reports a stored removed_restriction outside its four
values, "live" included, as unknown instead of passing it through.
- 6: the 0070 header and its test use the underscore spellings the code
stores and compares. 0070 is unreleased, and this changes its content hash.
- 7: comment only. DATETIME(6) still rounds to the microsecond; the comment
said 0069 removed the rounding entirely.
* test(fix): red — #6661 number admission: fractions past the bound, exponent cost, pre-enable scan
Tests for the review round on the number-admission gate, written before the change:
- a fraction whose nearest double is at or past 2^53 is refused (9007199254740993.5,
9007199254740994.5, 9007199254740991.5), and the gate is closed under its own
canonicalization, checked as a property over a corpus
- classification depends on magnitude, not on the size of an exponent: 1e100000000 and
-1e400 are refusals, 1e-100000000 and 1e-400 are admitted, and allocation does not grow
with the exponent
- the sentinel's text names the I-JSON exact-integer range
- CheckMetadataVersionable agrees with the mint, and FindUnversionableMetadata finds what
the mint would refuse and skips what it never versions
- bd config set versioned-history.enabled true refuses, writing nothing, over rows the mint
would refuse, and false never scans
Guards that pass before and after by design: the verdict on every literal as the store
returns it, the mint's refusal writing nothing, and, on the server and embedded legs, the
store-level property that no two literals reading back as different numbers share a canonical
form. Those store tests also log what each Dolt holds for a number outside the range when
history is off, and pin that a later write to such a row is refused once history is on.
* fix: green — #6661 number admission: the nearest-double rule, ParseFloat classification, a pre-enable scan at the switch
The admission gate now refuses a JSON number literal if and only if the binary64 nearest to it
has magnitude above 2^53-1, or it overflows, whatever the literal's spelling:
- a fraction that rounds to or past 2^53 (9007199254740993.5, 9007199254740994.5,
9007199254740991.5) is refused, so the gate is closed under its own canonicalization
- literals are classified with strconv.ParseFloat, linear in their length, so 1e1000000 no
longer builds a million-digit integer inside the writer's transaction; an overflow is the
sentinel and a magnitude too small for binary64 is admitted; math/big is gone
- the sentinel reads "number is outside the I-JSON exact-integer range (magnitude above
2^53-1)"; ErrIntegerNotRepresentable keeps its name, with a comment saying why
- ordinary fractions such as 0.1 stay admitted; no verdict on a value the store hands back
changes
The header now says what the mint's refusal is: an integrity backstop inside the writer's
transaction, not an admission policy for metadata.
bd config set versioned-history.enabled true now checks the store first. It reads every issue
the mint would version, runs the mint's own function over each one's metadata
(issueops.CheckMetadataVersionable, through issueops.FindUnversionableMetadata), and refuses,
writing nothing, while any is refused, printing the count, the ids and the fix. There is no
override; setting it false never scans. The environment and config.yaml planes do not pass
through the command and rely on the refusal at write time.
Also: docs and a CHANGELOG entry, and comments in the existing admission tests that described
the old rule.
* test(fix): keep the exponent-cost allocation test stable under the race detector
TestNumberAdmissionAllocationsDoNotGrowWithTheExponent compared two
independently averaged allocation counts with a strict >. Under -race
sync.Pool drops one Put in four at random, and the refusal's fmt.Errorf
takes its printer from a pool, so a call now and then allocates one more
than it would. The test failed on most runs of `go test -race -short`, the
flag set of the required lane, and never without -race.
That noise only ever adds allocations, so compare the fewest allocations
over many single-call samples instead. The comparison stays strict, and it
still fails on the exact big.Rat gate this test exists to keep out (49
allocations for 1e1000000 against 36 for 1e400). The doc comment no longer
claims the count is deterministic under -race.
* test(fix): red — set-many skips the pre-enable scan; pin what the scan reads
bd config set-many versioned-history.enabled=true switches versioned history
on with no pre-enable scan: only bd config set makes it. With a row holding a
number outside the I-JSON exact-integer range the setting is turned on and the
next write to that row fails. The new embedded test drives the real verb over
such a row and expects the whole batch to be refused, writing nothing.
The scan's own embedded test only used open issues, so deleting AllFlag or
IncludeAllTypes, or replacing the unlimited Limit, left it green. It now adds a
closed, a pinned and a gate offender, and a second test imports more rows than
one default page and expects every one of them counted.
* fix: green — bd config set-many runs the pre-enable scan for versioned-history.enabled
bd config set refuses to turn versioned history on while an issue holds
metadata a version could not record. bd config set-many writes the same
setting through a validation loop of its own and made no such check, so it
switched history on over a row whose next write then failed. It now runs the
same check for that one key inside its validation loop, before any pair of
the batch is written, so a refusal stores nothing. The check reads through
the accessor it already used on both routes: the store the command has
opened on the direct route, the provider on the proxied one.
* chore: strip internal tracker ids from the comments and tests across #6661's range
Comment and test-text changes only; no behaviour changes. Across every commit from the
merge-base with upstream main to here, the comments and tests named internal tracker ids
(one bead id in eleven comments and in one test failure message, an example id in the
`bd version` guard's comment, and an internal decision's attribution in the huge-exponent
admission test). They now cite gastownhall/beads#5898 and #6136 only, which is what a reader
of the public branch can follow.
The 0070 migration's header comment is one of the edits. That migration is new on this branch
(it does not exist on upstream main), so the change is not an edit to a shipped migration, but
it does change the file's content hash; the schema tests that compute hashes are self-consistent.
Text that already exists on upstream main is left as it is, even where it mentions an id: this
commit does not rewrite lines the range did not add.
* chore(bazel): bazel-sync (gazelle) for the #6661 range
* fix(bazel): give fix_test the store.go its activation guard parses
TestVersionedHistoryDoctorRepairOpenerUsesTheSharedActivation parses
store.go from its working directory. `go test` runs in the package
directory, so the file is there. A Bazel test only sees its declared
runfiles, so the test failed with
parse store.go: open store.go: no such file or directory
in //cmd/bd/doctor/fix:fix_test (--config=ci) and in shard 1 of
//cmd/bd/doctor/fix:fix_dolt_test (--config=doltserver), which runs the
same binary through data = [":fix_test"].
Declare store.go as data on fix_test.
* test(fix): red — the pre-enable scan must check the whole issue, as the mint does
bd config set versioned-history.enabled true runs a check over every issue
before it turns history on. The check looked at each issue's metadata alone,
while the mint canonicalizes the whole issue. A gate's timeout is a
time.Duration that a version holds as nanoseconds, so a gate whose timeout is
past 2^53-1 ns (about 104.25 days) holds a number outside the I-JSON
exact-integer range: the mint refuses every write to it, the scan never
looked, and the switch could be turned on over it.
- The agreement test's domain widens from metadata documents to whole issues:
the metadata corpus, plus timeouts at 2500h (admitted), 2600h, 8760h and
-2600h (refused), exactly 2^53-1 ns (admitted) and 2^53 ns (refused).
- The scan test covers a gate over 105 days and expects the verdict to name
the field, "timeout".
- The mint-level refusal test covers the same gate and expects the refusal to
name the field as well as the literal, for a number in metadata too.
- An end-to-end test on the direct route and one on the proxied route create
gates with bd gate create --timeout, expect the enable to refuse and name
them, and expect the issues the scan names to be exactly the issues whose
next write the mint refuses.
- Three guards keep the scan's lite read from hiding a number: every column it
leaves out is a string or a list of strings, nothing the mint adds and the
scan does not load can hold a number, and no exported check over part of an
issue exists beside the one the mint runs. Each guard is also run against
shapes it must refuse, so it cannot pass by finding nothing.
The new symbols (CheckIssueVersionable, FindUnversionable and the Field of
UnversionableIssue) do not exist yet, so the issueops tests do not build.
* fix: green — the pre-enable scan runs the mint's own check over the whole issue
The check behind bd config set versioned-history.enabled true looked at each
issue's metadata alone. The mint canonicalizes the whole issue, and a gate's
timeout, a time.Duration held as nanoseconds, is a number outside the I-JSON
exact-integer range once it is past 2^53-1 ns (about 104.25 days). The mint
refuses every write to such a gate, the scan cleared the switch over it, and
the first write after that failed.
CheckIssueVersionable is now exactly canonicalDurableState's refusal over the
whole issue, and FindUnversionable runs it over every issue the mint would
version. It replaces FindUnversionableMetadata, and CheckMetadataVersionable
is gone, so no check over part of an issue is exported beside the one the mint
runs. A refusal names the top-level field it found the value in ("metadata",
"timeout") as well as the literal, on the mint and on the scan; the field is
located only after a refusal, so a write that is admitted still reads the
document once. A gate timeout above 2^53-1 ns is unrecordable by policy: it is
refused at the write, named by field and documented, not re-encoded.
The refusal at the switch gives the fix for each field. For a number in
metadata that is bd update --metadata or --unset-metadata, which works with
history on or off because a version is recorded from the state after the write.
For a gate timeout, which bd update cannot change, it is removing the gate with
bd delete, or setting the timeout_ns column with bd sql while history is off;
bd sql needs a server-backed store, and the text says so. It also says the
check runs once, now: a writer that does not record (an older bd, bd sql, a
pull from a clone that had history off) can add such a row afterwards, and the
first write to it then fails with the same refusal. Making the check and the
write of the setting one transaction would narrow that window, not close it.
Corrected in the comments, the docs and the changelog as well: an import is not
a path that skips the mint, since it goes through the same batch create; and
Dolt's JSON column collapses duplicate keys when it stores a document, so on a
Dolt store neither the scan nor the mint can see one, and the duplicate-key
refusal is a defence for a backend that keeps them.
* test(fix): red — the listing must answer as the as-of read does; the SDK opens must be accounted for
Three review findings on the versioned-history change and one wording fix,
tests first.
- A removed version's restriction. AsOfReadInTx answers a stored value outside
the four-value vocabulary (a NULL or empty column, "live", a hyphenated or
arbitrary string) as unknown, but ListVersionsInTx hands the column back as
stored, for every row, and the label bd versions prints passes such a string
through. A table test runs the listing and the as-of read on the same stored
value, for a version that was removed and one that was not, and expects the
same answer, and none for a version that was never removed. The label gets
the same out-of-vocabulary values and is expected to render what unknown
renders.
- The SDK's store opens. The shared construction guard now scans the repository
root as well, so the Go SDK's five opens (Open, OpenFromConfig and OpenGated,
and OpenBestAvailable in each build-tag twin) are noticed. Nothing accounts
for them yet, so both guards fail on exactly those five sites.
- A bytes bound beside the allocation-count bound on the number admission
gate. A classifier that builds the number it is asked about makes one
allocation whatever the exponent, so the count bound passes it, and the bytes
grow. The fewest bytes one call allocates for a literal with a huge exponent
must be no more than for a small one plus a margin. It passes today, because
the gate never builds the number; it fails for a gate that does.
- The refusal at the switch names the gate remedy as bd delete <id> --force,
says that without --force bd only previews, and says that removing the gate
unblocks anything it was blocking. The embedded and proxied end-to-end tests
expect all three.
* fix: green — the listing answers as the as-of read does; the SDK opens are accounted for
Three review findings on the versioned-history change and one wording fix.
A removed version's restriction. A stored removed_restriction is a free string,
and only the four values of the vocabulary are answers. The as-of read already
reported anything else (a NULL or empty column, "live", a hyphenated or
arbitrary string) as unknown, but the listing handed the column back as stored,
for every row, and the label bd versions prints passed it through.
NormalizeRemovedRestriction is now the one place that decision is made.
AsOfReadInTx calls it; ListVersionsInTx calls it for a version that was removed
and gives a version that was not removed no restriction; and restrictionLabel
renders through it. The listing, its JSON and the label now say what the as-of
read says for the same row.
The SDK's store opens. The Go SDK's five opens (Open, OpenFromConfig and
OpenGated, and OpenBestAvailable in each build-tag twin) apply neither per-store
switch, the events journal's or versioned history's, and they still do not.
Applying them would change the library's behavior for every embedder, so that
is a separate change; this one declares the boundary. The shared construction
guard now accounts for the five with one exemption reason that is true of both
switches, so a new SDK open is noticed rather than missed, and its staleness
check keeps the exemptions honest. The docs gain one bullet saying that writers
built on the SDK do not apply the switch.
The bytes bound on the number admission gate needs no production change: the
gate never builds the number, which is what the bound pins.
The refusal at the switch now names the gate remedy as bd delete <id> --force,
says that without --force bd only previews, and says that removing the gate
also unblocks anything it was blocking. The docs line says the same. For a gate
that blocks an issue, bd delete without --force prints a preview and exits 1,
and with --force the gate is removed and what it blocked is ready again.
* test(bazel): declare the root package's Go source as data for //cmd/bd:bd_test
The shared store-construction scan now reads the repository root, where the Go
SDK's opens live, but //cmd/bd:bd_test declared none of the root package's
source. Under bazel test the scan therefore saw an empty directory, reported
the five SDK exemptions as no longer matching a store construction site, and
failed the events-journal guard, while go test, which sees the whole checkout,
passed.
List the root in tools/bazel/go_srcs.py so the generator emits its managed
go_srcs filegroup there, and add that filegroup to bd_test's data. The new
block is the generator's own output and nothing else changes.
* ci: list the switch scan's proxied gate-timeout test in the 30-shard manifest
Upstream main (#7129) moved the proxied-server tier to 30 duration-balanced
shards, and TestProxiedShardManifestGeneratorNotStale requires every
TestProxiedServer*/TestServerMode* test exactly once in that block. This
branch adds TestProxiedServerVersionedHistorySwitchRefusesAnUnrecordableGateTimeout
(cmd/bd/versioned_history_switch_scan_proxied_integration_test.go), so the
block needs its line. Written by the generator itself:
python3 scripts/ci/gen_proxied_shard_manifest.py 30 --weights=duration --write
(one line, shard 8); --check exits 0 afterwards.
Rebase note (maintainer): regenerated on current main, whose proxied-server
tier uses 34 shards; the generator's incremental output
(gen_proxied_shard_manifest.py 34 --weights=duration --write) placed this
test at shard 6 of the 34-shard block.
* ci: list the PR's embedded versioned-history tests in the embedded shard manifests
#7156 made the embedded-Dolt tier's shard manifests exact-once (50 cmd
shards, 15 storage shards), so every embedded test must be listed. This PR
adds five embedded cmd tests and three embedded storage tests; this commit is
exactly what the generators write for them:
python3 scripts/ci/gen_embedded_cmd_shard_manifest.py 50 --weights=duration --write
python3 scripts/ci/gen_embedded_storage_shard_manifest.py 15 --weights=duration --write
Incremental: 8 lines added, none moved.
Rebase note (maintainer): regenerated on current main, whose embedded
manifests use 100 cmd shards and 40 storage shards; the generator's
incremental output placed these tests at cmd shards 55
(TestEmbeddedVersionedHistorySwitchScansEveryRowNotOnePage), 56
(...SwitchRoundTrip), 57 (...SwitchRefusesUnversionableMetadata), 58
(...SwitchRefusesAnUnrecordableGateTimeout) and 59
(...SetManyRefusesUnversionableMetadata) of the 100-shard block, and at
storage shards 5 (TestRecordVersionKeepsSubSecondChangeAt), 6
(TestVersionedHistoryKeepsNumbersTheStoreDistinguishesApart) and 23
(TestAsOfReadContract) of the 40-shard block.
* test: exempt OpenBestAvailableWith, where #7188 moved the SDK's store construction
Upstream #7188 split beads.OpenBestAvailable: it now delegates to the new
OpenBestAvailableWith, which builds the store. This PR's two construction
guards (TestEveryStoreConstructionActivatesTheEventsJournal and
TestEveryStoreConstructionActivatesVersionedHistory) share one exemption
list keyed by function, so after merging main they flagged
OpenBestAvailableWith as an unexempted construction site and reported the
OpenBestAvailable entries as stale. The two build-tag twins' keys now name
OpenBestAvailableWith. The reason is unchanged: it is the SDK's library
surface for embedders, and no code in the bd binary calls it. gofmt
realigned the three neighbouring entries.
* chore(schema): renumber removed_restriction to 0071 after #6943's 0070
Migrations are numbered by landing order. #6943 (participation_generation,
the versioned-history write fence) lands first and owns main-plane 0070 and
ignored/0028, so this PR's removed_restriction migration moves to the next
free slot, 0071. The rename is done here, as one maintainer commit, rather
than inside the replayed commits, so the history shows exactly what changed
relative to the PR as reviewed; the intermediate commits of the rebase carry
a duplicate 0070 and are not expected to build.
- migrations/0070_add_removed_restriction.{up,down}.sql become 0071_*, with
their header comments updated (the SQL itself is unchanged). Neither file
exists on main or on #6943, so this is not an edit to a shipped migration.
- cli_migrations.go: the CLI-bundle override is keyed to the new file name
and renamed cliMigration0071AddRemovedRestriction, and its const now sits
after 0070's.
- migration_0070_add_removed_restriction_test.go becomes
migration_0071_add_removed_restriction_test.go; its tests and messages say
0071, and it now owns the one LatestVersion pin (71).
TestLatestVersionIncludesMigration0070 in #6943's participation_generation
test is superseded by it and replaced by the usual pointer comment, and
0069's pointer comment now names the 0070 file that superseded it.
- schema_test.go hygiene comments, BUILD.bazel embedsrcs/srcs, and the
asof_read.go comment that cited the migration number.
Checked: go test ./internal/storage/schema/... (with the dolt CLI lane,
including TestAllMigrationsSQLAppliesThroughDoltCLIAndRecordsLatestVersion)
and scripts/check-migration-hygiene.sh against origin/main and against
#6943's tip.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* test(versions): reconcile #6661's tests and docs with #6943's write fence
#6943's write fence (design §16.2b) makes an update-shaped write to a legacy
record -- one whose participation_generation is NULL because it was created
while versioned history was off -- a skip, not a refusal: the fence returns
before the snapshot is canonicalized, so nothing is versioned and the mint's
admission gate never runs. Several of #6661's tests seed rows with history
off and then expect a later write to them to be versioned or refused, and
several comments say every later write to an offending row fails. On a tree
that carries both PRs those tests fail and those comments are wrong.
This ports, without changing their substance, the fence-integration commits
Jim Wordelman wrote for the donnabox integration fork, where both PRs were
already folded together:
- eff898db80 / 5d2e5a2ac4 (issueops, dolt, embeddeddolt): the mocked mint
sequence scripts the fence's participation_generation read; the number
fidelity test splits phase 2 into 2a (a legacy row is written, not
versioned, not refused, stays NULL) and 2b (a participating row is
refused and left untouched); TestRecordVersionInTxSkipsALegacyRowBefore-
TheAdmissionGate pins the fence's order against the gate.
- e0ad9d1e3c / 1528022dfa (cmd/bd): the switch round trip and the routing/env
end-to-end tests build the rows they expect a version for after the setting
is on, and assert that the pre-setting seeds gain nothing.
- 18b9015bf5 (cmd/bd): the embedded and proxied gate-timeout scan tests assert
the whole scan-vs-mint truth table (legacy offenders are named by the scan
but not refused by the mint; participating offenders are both).
- 5929ebd50c / 8ce872be03 (comments, CHANGELOG, configuration reference): the
mint's refusal binds rows that participate in history; the pre-enable scan
cannot see participation, so it over-approximates in the safe direction.
Left out on purpose: the fork's mintSkipsRow helper and defer-wake sweep
change, and its bd doctor "Versionable Issues" check and the docs that point
at it; none of those are part of #6661 or #6943.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Co-authored-by: Jim Wordelman <jim@wordelman.name>
* test(versions): adapt #6661's guards to what main changed under it
Three test-side adjustments for code that landed on main after #6661's last
merge of it; no production code changes.
- internal/storage/leg_contract_wiring_test.go: main gained an HTTP storage
leg, and TestEveryLegWiresEveryRoleContract requires every leg to name or
waive every role contract. The five R7.1 as-of read contracts this PR adds
are a storage capability the HTTP client does not serve (internal/httpclient
answers AsOf with an explicit unsupported error, and the wire has no
instant/address selector or gone/unknown refusal), so they are waived on
the http leg with that reason, as the donnabox integration fork does.
- cmd/bd/versioned_history_construction_test.go: main split
newDoltStoreFromConfig into two thin wrappers over openDoltStoreFromConfig,
which is where the activation defer now lives (this rebase's resolution of
the activation commit), so the factory guard keys on that body.
- cmd/bd/versioned_history_serve_e2e_test.go: main's
TestProxiedGatedTestsRunInTheProxiedLane requires a test that skips unless
BEADS_TEST_PROXIED_SERVER=1 to be one the proxied lane selects, so
TestVersionedHistoryServeActivatesTheProviderFromItsOwnRow becomes
TestProxiedServerVersionedHistoryServeActivatesTheProviderFromItsOwnRow,
and the 34-shard proxied manifest gains its line (written by
gen_proxied_shard_manifest.py 34 --weights=duration --write, incremental;
--check passes).
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* chore(bazel): emit go_srcs.py's managed blocks for internal/versionedhistory
Main's tools/bazel/go_srcs.py now manages a repo_files filegroup block in
every package BUILD file, lists those filegroups in the root BUILD.bazel's
aggregates, and lists every go_library in tools/bazel's release_cross_build
target. internal/versionedhistory is a package this PR adds, so after the
rebase those managed blocks were stale and TestBazelGoSrcsBlocksCurrent
(go test ./scripts/...) failed. This is the generator's own output
(python3 tools/bazel/go_srcs.py) and nothing else; --check passes
afterwards.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(versions): don't publish change_agent in bd versions --json
`bd versions <id> --json` prints storage.IssueVersion as-is, so every JSON
tag on that struct is part of a public contract. Provenance V2
(gastownhall/beads#7510, as ruled by the maintainer) removes the ad hoc
agent field in favour of an actor chain; shipping a "change_agent" key now
would make a public contract out of a field that is on its way out.
IssueVersion.ChangeAgent is now tagged json:"-". Nothing else changes: the
issue_versions.change_agent column (migration 0067) stays, ListVersionsInTx
still reads it, change_actor and change_message are still published, and
the human listing never showed the agent. No doc or golden named the key.
TestVersionsJSONDoesNotPublishChangeAgent pins the absence with a non-empty
value, so an omitempty-style regression would still fail, and pins that
change_actor and change_message are still there.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* test(issueops): pin what the unfenced test-support mint does on #6943's new paths
#6943's two fixes to the shared mint body -- (a) no issues row means no
mint and no error, and (b) a create-shaped call on a new issues-table row
flagged no-history stamps participation_generation without minting -- were
written for its two kinds. This PR's shared body has a third,
mintUnfenced, behind RecordVersionAtInTx (the R7.1 as-of fixtures'
controlled-timestamp mint). The rebase resolution decided what (a) and (b)
mean for it; this pins that decision:
- (a) applies. It is the plane rule (FR-8: the table that holds the row
decides its plane), not the fence, and the unfenced kind already honoured
the flag-based form of the same rule (IsWisp). Without it, an unfenced
mint for an unflagged wisps-table row would insert a version row that no
issues row points at. The shared body's issues-table read now runs for
all three kinds; only the update kind acts on the value it reads.
- (b) does not apply. The unfenced mint never declares participation, so a
flagged row returns right after the snapshot, as before: no read, no
stamp.
- The fence still does not apply: a legacy row is minted, and the closing
UPDATE advances current_revision alone.
TestRecordVersionAtInTxKeepsThePlaneRuleButNotTheFence scripts each of
those three sequences exactly with sqlmock.
TestTestSupportMintsStayOutsideTheShapeSplit places RecordVersionAtInTx
outside #6943's create / dual-shape / update classification explicitly (it
is the seam's exempt twin, not a mutation entry point or mint site): it must
be in none of the shape lists, stay in versionExemptions, and reach neither
RecordVersionForCreateInTx (it never stamps) nor RecordVersionInTx (whose
gate and fence would stop the as-of fixtures minting history-off rows). The
row-lock guard's exemption comment for recordVersionAtInTx already names the
stamp-only UPDATE: #6943's own wording of it (all three UPDATE issues
statements) was carried into that exemption when the as-of read commit was
replayed.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* test(storage): say exactly why the as-of read contracts stay waived on http
#6943 now runs most of its participation-generation contracts over the
served wire (internal/httpclient/served_participation_generation_test.go):
their subject is a create or an update, which the client can send, and the
fixture reads the reference store's raw columns. This checked whether the
five R7.1 as-of read contracts can be wired the same way. They cannot,
cheaply or otherwise, without a new wire operation:
- their subject is the read itself (AsOfReadFixture.Resolve), and R7.1's
read, issueops.AsOfReadInTx, is reached by no publicops role and served
by no wire operation;
- the wire carries neither selector (an instant or a served version
address) nor the gone/unknown refusal the read answers with;
- the client's only point-in-time read, DoltStorage.AsOf, is a Dolt
commit-ref read, not R7.1, and is on the client's D8 unsupported
allowlist.
Binding Resolve to the reference store behind the served env would pass,
but as a property of that store, which the store legs already pin, never
of the client. So the waiver stays; its comment and reason string now say
the above instead of the earlier shorthand ("HTTP AsOf is explicitly
unsupported"), which conflated the client's commit-ref AsOf with R7.1.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* docs(versions): describe what the write fence does to beads that predate recording
With #6943's write fence (design §16.2b) a bead that existed before
versioned history was turned on (participation_generation NULL) is legacy:
an update-shaped write to it is skipped, so it is never versioned however
often it is edited. Several user-facing strings from #6661 still described
the behaviour before the fence, and an independent review reproduced each
with a built bd (a legacy bead edited twice after enabling still lists no
versions; a legacy bead the switch refuses over is written without refusal
under BD_VERSIONED_HISTORY_ENABLED=1). Text only; no behaviour changes.
- bd versions help: only beads created while recording is on are versioned;
a bead that already existed is legacy and editing it records nothing; no
backfill. (Was: "a bead edited yesterday shows nothing until it is
edited again".)
- bd versions empty listing: drops "yet" and says why the list is empty -- a
bead created while recording is on always has its create version, so an
empty list means the bead predates recording (or was made by a writer
that was not recording), or is no-history or a wisp. The line still
starts "No versions recorded for <id>", which the switch round-trip test
pins.
- bd versions with recording off: only beads created after it is turned on
are versioned.
- bd config set versioned-history.enabled true refusal: Jim's scan stays as
conservative as he made it -- it cannot see participation, and a legacy
row can still be minted create-shaped if it re-enters the issues plane --
but the text now says a listed issue's writes are refused only if it
participates (created while history was on, or entered the issues plane
while it was on), and that legacy issues are listed because the check
cannot tell. The closing line says the same of a value a non-recording
writer adds later.
- docs/reference/configuration.md: the section opener says every accepted
change to an issue created while history is on is snapshotted, and that a
pre-existing issue is legacy; the "participates" parenthetical drops "or
written" (a write never stamps participation; only a create-shaped mint
does) and names entering the issues plane, matching the refusal text.
CHANGELOG already says "if it participates in history" and is unchanged.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(versions): keep updated_at across update-shaped version mints
The update-shaped mint ended with UPDATE issues SET current_revision = ?
WHERE id = ?. current_revision always changes there, so the column's
ON UPDATE CURRENT_TIMESTAMP clause fired: with versioned history on, every
label, dependency or import write moved issues.updated_at to the session's
wall clock (local time, read back as UTC). An import with
RejectStaleUpserts then stored the wall clock instead of the source's
updated_at, and the source's next genuine edit was rejected as stale. The
statement now assigns updated_at to itself, the rule #4298, blocked_state.go's
mark/unmark templates and the create-shaped mint statements already follow,
so history on leaves updated_at exactly where history off does. It is the
one statement every production update-shaped mint ends with.
Tests:
- TestEmbeddedMintLeavesUpdatedAtWhereHistoryOffDoes (embeddeddolt) ages a
bead, adds and removes a label and a dependency, and runs two
RejectStaleUpserts imports, with history off first as the control. With
the fix reverted, history on fails all six arms (updated_at reads the
wall clock, and the later source edit is rejected as stale); history off
passes either way.
- RunParticipationGenerationFlagOffSkipsUpdateOnParticipatingRecord, wired
on the dolt, embeddeddolt, uow and http legs: a record created with the
flag on and updated with it off mints nothing and keeps its
current_revision. Every other flag-off case uses a legacy record, which
the fence stops first, so with RecordVersionInTx's gate removed this is
the only case that fails, on all four legs. That gate is the single entry
for every production update-shaped mint, so the one update arm covers
label and close writes too.
- The sqlmock pin of the statement (version_history_preenable_scan_test.go)
and the journal-completeness exemption comment follow the new SQL.
- The createbatchequiv issues_updated_at goldens of small, depadd,
import458 and import458-reject-stale are re-recorded. They pinned the
wall-clock bump, so each row minted a second time (eq-n2; eq-db1 and
eq-dl; eq-b3 and eq-b250) had dropped out of the compared set; CI's
embedded and server legs both printed the new digests. Recorded on
embedded Dolt, the fix-reverted tree reproduces every committed golden
byte for byte, HEAD moves only these four digests, and its rows equal
the history-off rows in every scenario. GoldenDirEnv's comment lists it
as the goldens' third deliberate change.
- The new embedded test has its line in the storage shard manifest
(gen_embedded_storage_shard_manifest.py 40 --weights=duration --write),
so TestStorageEmbeddedShardManifestGeneratorNotStale stays green. It sits
after TestEmbeddedEveryAcceptedLifecycleMutationMintsOneVersion rather
than at the end of the file, where #7646 appends its own test, so the two
PRs still merge without a conflict in that file.
Docs:
- CHANGELOG: the feature's two entries under ### Fixed described fixes to a
switch no released bd has. One ### Added entry replaces them, covering
bd versions, the versioned-history.enabled switch and its per-store
semantics, the pre-enable check, the single-writer caveat, migration 0071
and the bd version <arg> refusal.
- The bd versions help, its recording-off refusal and empty-listing note,
and the opening paragraph of the configuration doc's Versioned Issue
History section now state the rule the pre-enable refusal prints: a bead
participates if it was created, or entered the issues plane (a wisp
promoted or made persistent), while recording was on.
bd version: the "did you mean bd versions" refusal now runs after the
command's metrics event is created, like the other in-RunE argument
refusals, so a mistyped bd version <id> is counted as a version invocation
instead of going uncounted.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Julian Knutsen
---------
Co-authored-by: Jim Wordelman <mayor@quad341.uk>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-authored-by: Julian Knutsen <julianknutsen@users.noreply.github.com>
Co-authored-by: Eddie the Engineer <338826946+gascity-eddie[bot]@users.noreply.github.com>
* feat(roles): issueops.Heartbeater role on the dolt, embedded and uow legs
Adds issueops.Heartbeater.Heartbeat(HeartbeatRequest{Actor, IssueID}) ->
HeartbeatResult{IssueID, Holder, HeartbeatAt, LeaseExpiresAt, Rearmed},
the lease refresh behind `bd heartbeat`, as its own role with its own
accessor.
- One body: internal/storage/issueops.ExecuteHeartbeatInTx validates
(*HeartbeatFieldError for a blank/over-long actor or empty id), refuses
a wisp, then runs RenewLeaseInTx, which is HeartbeatIssueInTx's body
reporting the renewal. HeartbeatIssueInTx is now a wrapper, so the legacy
HeartbeatIssue legs answer the same text and sentinels.
- The refresh is fenced on the holder AND on the live claim: after the
holder-fenced UPDATE, a read in the same transaction requires the issue
to be in_progress under the holder (the `update leases set` prefix and
the one IF() the Postgres dialect rewrites are unchanged; a Postgres port
should expect more serialization retries from that read). A refusal deletes the caller's orphaned lease
row, and the legs commit that refusal.
- A refresh writes only the lease row: no row_lock, version, updated_at,
event, journal entry, Dolt commit or hook. A re-arm (a live hand-doled
claim with no lease row the caller holds) is recorded as a mutation:
row_lock reminted, updated_at stamped, a lease_rearmed event, a journal
entry, a version, a Dolt commit (LeaseRearmVersionCommit) and on_update.
The remint makes a re-arm collide with a racing release or close instead
of leaving an orphaned lease on an open or closed issue (a pre-existing
race on every Dolt route). Rearmed is true only when a row was created:
a same-second refresh (0 changed rows on embedded Dolt) or a holder
spelled differently refreshes the existing row in place and keeps its
granted_at/granted_node. Reported times are rounded to whole seconds,
the stored values; the binds stay unrounded so a same-second refresh is
never a 0-row UPDATE on Dolt.
- Typed refusals: an absent id is ErrNotFound; a foreign holder is
*LeaseConflictError{Holder} wrapping ErrAlreadyClaimed; a wisp
(Ephemeral) or no live claim is *LeaseConflictError wrapping the new
ErrLeaseNotHeld, which also matches ErrNotClaimable.
- Legs: DoltStore and EmbeddedDoltStore through the issue-operation
funnel (DOLT_ADD of the named tables, then DOLT_COMMIT -m, after the SQL
commit); uow.NewHeartbeater through the new uow.RunTxScoped: a refresh or
a refusal commits with the plain SQL COMMIT (no working-set scan, no Dolt
commit, nothing another writer left uncommitted is swept), and a re-arm
commits through the new ScopedCommitter (DOLT_ADD of exactly its tables,
DOLT_COMMIT -m, never -Am). The legacy HeartbeatIssue doors commit a
re-arm the same way and keep a refusal's orphan delete, and the
proxied-server `bd heartbeat` route runs the role's body with the same
scoped commit.
- Census: storage.Storage gains Heartbeater(); HookFiringStore wraps it
(fires on_update for a re-arm only, RoleFiresHooks knows it), telemetry
wraps it, httpapi.timedProvider, uow.notifyingProvider (records a re-arm)
and externaldeps.uowProvider build it; the journal and version guards
list the heartbeat family as entry points; the httpclient unsupported
shell is regenerated and Heartbeater sits on its unsupported allowlist
until the wire lands.
Conformance: RunHeartbeater* (18 cases) on dolt, embedded dolt and uow:
refresh post-state with the stored times pinned to the result; no
row_lock/current_revision/updated_at/events/journal/issue_versions/
version-control/hook change; a guarded write with the pre-heartbeat
revision still lands; foreign holder refused against an aged lease;
refused after close/release/reclaim/status move; wisp refused; hand-doled
claim re-armed as a mutation; same-second heartbeat is not a re-arm;
orphaned leases on released, closed and reassigned issues refused and
deleted; a refresh and a refusal against a dirty working set make no
commit and leave the other writer's change uncommitted, and a re-arm
commits only its own tables; absent id; request rules; no request mutation. The http leg is
waived until the wire lands.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* feat(httpapi): POST /v0/beads/issues/{id}:heartbeat behind issues.heartbeat
Publishes issueops.Heartbeater on bd serve as heartbeatIssue, the served
lease refresh behind `bd heartbeat`.
- Spec: the operation, HeartbeatIssueRequest {actor} and
HeartbeatIssueResponse {id, holder, heartbeat_at, lease_expires_at,
rearmed}; no `revision` (a refresh writes nothing to the row) and no
expected_version (the fence is the holder and the live claim).
issues.heartbeat joins the capability vocabulary and lease_not_held
(409) the Problem.code list; `reason: ephemeral` qualifies it for a
wisp. apigen and the wire-shape golden are regenerated; the golden diff
is additive only, so wire_revision stays 2.
- Server: route row on the custom-method dispatcher, handleHeartbeat in
heartbeat.go (claim's actor rules via bodyActor, unknown member and
query refusals), Config.Heartbeater as a required role (sourceRoles,
roleSourceNames, the per-request uow.HeartbeaterSource accessor).
failHeartbeat maps *LeaseConflictError typed fields: a foreign holder
is the claim's conflict shape (already_claimed + assignee +
issue_status); no live claim, a wisp included, is the new
lease_not_held (+ issue_status, + reason: ephemeral for a wisp), matched
before the generic arms so ErrLeaseNotHeld's ErrNotClaimable never
surfaces as not_claimable. Its detail names the one state the refusing
transaction found (closed, open and not claimed, an ephemeral wisp, ...).
- bd serve wires the role from its peeled store (serveRoleSource gains
Heartbeater); the serve stub stores, the corpus and e2e harnesses, the
served harness and the encode oracle bind it.
- Wire client vocabulary: OpHeartbeatIssue/issues.heartbeat and
MethodHeartbeat are CLASSIFIED (the capability set-equality gate),
ReasonEphemeral is pinned to the server's, and lease_not_held rebuilds
*LeaseConflictError{Status, Ephemeral} wrapping ErrLeaseNotHeld in the
native words (the code-table set-equality gate). No accessor yet.
Tests: heartbeat_test.go (request mapping and projection, edge refusals,
every role refusal with its code, members and state-specific detail, the
code row, the capability). The served-http Heartbeater leg
(served_heartbeater_test.go, 18 cases) runs the contract against a real
bd serve through a test-local dial over the store's own dispatch, and the
http-leg waivers are deleted.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* feat(http): bd heartbeat over http through httpclient.Heartbeater
The client leg of the served lease refresh, and `bd heartbeat` on the
role for every route.
- httpclient.Store.Heartbeater (heartbeater.go) dials POST
/v0/beads/issues/{id}:heartbeat through Store.dispatch, so
issues.heartbeat is preflighted: an older server is refused BEFORE the
dial with *wire.CapabilityError naming the token (unwraps to
*storage.ErrUnsupported{Capability: "issues.heartbeat"}); it never falls
back to a re-claim or a metadata stamp.
- The role's request rules are restated before the dial
(validateHeartbeatRequest, pinned to
storeops.ValidateHeartbeatRequest): blank/over-long actor, empty id, each
a *HeartbeatFieldError.
- Problem mapping: already_claimed (which the shared table rebuilds as the
claim's ClaimConflictError) becomes *issueops.LeaseConflictError naming
the holder and wrapping ErrAlreadyClaimed, in the native words ("issue
already claimed by <holder>"); lease_not_held already arrives as
LeaseConflictError (Ephemeral from `reason`); not_found is ErrNotFound;
invalid_argument on `actor` is the role's field error.
- Idempotent: true, the one write this client marks replayable (a repeat
only moves the expiry later; a replay after a reclaim fails the fence).
- Legacy Store.HeartbeatIssue rides the role. Both leave the generated
shell and completeness_test's unsupported allowlist.
- `bd heartbeat` takes Heartbeater() from the resolved store on the direct
routes (dolt, embedded, http) and from the provider's HeartbeaterSource
on the proxied route (exact id resolution in a read unit of work, then
the role); runHeartbeatProxiedServer and heartbeat_proxied_server.go are
deleted. Success output and exit codes are unchanged; refusal text
changes per route (see CHANGELOG).
Tests: heartbeater_test.go (stub server: preflight refusal naming the
token with no POST, request/answer projection, each refusal's typed
mapping including the wisp's reason, the 503 replay, pre-dial validation,
validator parity, the legacy door). served_heartbeater_test.go runs the
18-case contract through env.subject.Heartbeater(), with
HookedHeartbeater wired off a HookFiringStore. TestE2E_HeartbeatOverHTTP:
real bd against an in-process serve: holder ok with revision and
updated_at unchanged and a guarded write with the pre-heartbeat revision
landing; a non-holder refused against an aged lease that stays untouched;
closed, wisp and unclaimed refused, each naming its own state; an older
server's handshake refused naming issues.heartbeat with no write. Corpus
shapes gc-heartbeat, -non-holder, -closed, -wisp pending until
reference_server.json advertises the token. CHANGELOG entry for the whole
track, including the orphaned-lease race fix.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* build(bazel): auto-sync BUILD files
Applied from the bazel-sync-patch artifact of https://github.com/gastownhall/beads/actions/runs/38875641041
(`make bazel-sync`: gazelle, tools/bazel/go_srcs.py, bazel mod tidy).
Only BUILD.bazel, MODULE.bazel and MODULE.bazel.lock are ever pushed; see
scripts/bazel-autofix-push.sh.
* fix(heartbeat): roll back a no-issue refusal; restate refresh vs re-arm
Review fixes for #7600 (adopt-pr apply-fixes, iterations 1-2).
Legacy HeartbeatIssue doors commit a refusal only when it read the issue.
The dolt and embedded HeartbeatIssue callbacks committed every
LeaseRenewalRefusal, including Found=false (the issue read failed). That
refusal deletes nothing, but it can follow a fast-path UPDATE that
already extended an orphan lease row's expiry, so committing it kept the
extension. issueops.LeaseRenewalRefusalCommits now gates the commit on
Found, the rule the Heartbeater role's HeartbeatRefusalCommits applies.
New tests on both legs pin both arms: a no-issue orphan's expiry is
unchanged, and a released issue's orphan is deleted.
Refresh vs re-arm contract docs. Comments, Long help, the OpenAPI spec
and the generated apigen still said every heartbeat writes only the
lease row, makes no Dolt commit and fires no hook. A re-arm is recorded
as a mutation: it remints the revision, records an event and a version
entry, commits once (LeaseRearmVersionCommit) and fires on_update
through the wrapping hook decorator. Restated in domain, uow, issueops,
storage.go (why RoleFiresHooks answers true, so bd serve takes the
heartbeater off a peeled store), cmd/bd heartbeat and serve, httpapi,
httpclient, the spec (apigen regenerated), and the conformance and
contract-test docs.
Minor review findings:
- The 409 already_claimed and lease_not_held details now end "nothing
on the issue was written": the refusal may have deleted and committed
the caller's orphan lease row.
- docs/multi-agent/federation.md and the CHANGELOG entry describe the
spelling-mismatch heartbeat: the row is refreshed in place and keeps
granted_at and granted_node; only a re-arm stamps this node. The
embedded spelling test pins both columns, and the lease.go comments
say "refreshed in place" instead of "re-arms".
- The refusal's orphan delete judges the holder under actorMatches, as
the in-place refresh does (iteration 2). It matched holder = ? on the
actor as sent, so a dead claim's orphan held under another spelling
of the caller (gastown.mayor, heartbeat as gastown__mayor) survived
the refusal until TTL. The refused closure now reads the row's holder
and deletes that stored holder only when actorMatches(holder, actor).
Both TestHeartbeatIssueCommitsARefusalOnlyWhenItReadTheIssue twins
gain a cross-spelling arm (row deleted) and a control: another
identity's row (gastown.dog-3) survives.
Not changed: `bd heartbeat --json` still omits `rearmed`, since adding
it changes a CLI JSON contract (follow-up). The federation.md paragraph
post-dates the v1.2.2 docs pin, so documenting this main-only behaviour
there is a maintainer call under
engdocs/decisions/2026-07-17-docs-release-pin.md section 1.
Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(uow): run the scoped re-arm's Dolt commit after the SQL commit
The proxied-server heartbeat commits a re-arm with doltServerTx.CommitScoped,
which ran DOLT_ADD per table and DOLT_COMMIT('-m') INSIDE the open
transaction, before the SQL COMMIT. DOLT_ADD stages whole tables from the
session's transaction root, so that Dolt commit was built from the re-arm's
start snapshot: an issues row another session changed while the re-arm was
open (a write still only in the working set, as in batch mode or before that
writer's own Dolt commit) was staged at its old value, and HEAD disagreed
with the rows every reader sees. This is the LatentLabsSpace/NEXUS#92
ordering the DoltStore funnel (runIssueOperationTxWithMessage) already
avoids, and the review's major finding on this PR.
CommitScoped now commits the SQL transaction first, then stages exactly the
named tables (plus the versioned-history tables) and makes the Dolt commit on
the same pinned connection, the uow twin of doltAddAndCommitPostTx:
- a serialization failure of the SQL COMMIT is still returned, so
RunTxScoped replays the unit of work;
- the Dolt commit runs detached on its own budget and replays only conflicts
that leave nothing behind: serialization failures and Dolt's 1105
"@autocommit transaction rolled back" (new isDoltAutocommitRollbackError,
mirroring the DoltStore classifier of the same name);
- nothing staged, or "nothing to commit", is not an error: a concurrent
writer's Dolt commit already took the row. A "nothing to commit" past the
staged check is logged, as the funnel logs it, so the missing audit line
is explicable;
- any other failure is logged, never returned. The data is committed, and
returning it would make RunTxScoped replay a committed re-arm, which would
then report a refresh. The session is poisoned rather than pooled, since
its state is unknown. uow records no metrics, so that log line is the
drop's only signal; bd.db.post_tx_commit_dropped counts only the funnel's.
Statements go through schema.DrainCall, retiring the local drainCall fork
(review nit).
Tests: five sqlmock tests pin the order (SQL COMMIT before any DOLT_ADD),
the swallow-and-poison path, the 1105 retry, the returned serialization
failure and the empty-commit tolerance; each fails against the previous
CommitScoped. TestIsDoltAutocommitRollbackError carries the DoltStore
classifier's table over to the uow copy, plus the prefix boundary; dropping
the prefix branch, the prefix's period, the 1105 check or the type check
each fails a case. TestHeartbeaterRearmKeepsAConcurrentWrite is the
real-Dolt regression: a change to another issues row made while the
re-arm's transaction is open must be at HEAD after the re-arm's Dolt
commit. Its working-set-only writer fails on the old ordering (dolt
2.1.8); the writer that Dolt-commits its own change passes on both and is
kept as coverage.
Review follow-ups folded in (comments, a file move and a test; the
absorption log line above is the only behaviour change among them):
- the freshRowLock invariant and its row_lock_guard_test.go mirror name the
re-arm as the one deliberate remint without a lifecycle-field change,
load-bearing for the release/close collision;
- httpclient: "a write is never retried" (wire/client.go, stall_retry.go)
and "only a read's answer is yes" (dispatch.go) now allow for the
Idempotent heartbeat, and httpHeartbeater and issueops.HeartbeatResult
document that a replayed heartbeat can report Rearmed false after a
committed re-arm, with the guarded write's revision check as the backstop;
- the proxied route moves back to cmd/bd/heartbeat_proxied_server.go, the
file family cmd/bd/AGENTS.md prescribes;
- the ScopedCommitter and RunTxScoped docs no longer say every other
writer's uncommitted change stays out of the commit: a staged table is
committed whole, so such a change to a named table rides in the re-arm's
commit, as it does in the funnel, and only other tables keep theirs;
- commitStagedTables says its drop is log-only, the absorption is logged,
and the uow classifier gets its table test (see Tests).
Not folded in: the base-owned IssueUseCase.Heartbeat /
IssueSQLRepository.HeartbeatIssue door, dead in production since the
proxied route moved to the Heartbeater role. Its one caller is the
notifying hook-parity test (uow/notifying_test.go), and moving that case
onto the Heartbeater means re-deriving its RenewLease hook semantics, so it
is left for a follow-up.
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: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: Eddie the Engineer <338826946+gascity-eddie[bot]@users.noreply.github.com>
* fix(mol): route bond operand resolution like show/update/close (closes#4714)
bd mol bond resolved operands with utils.ResolvePartialID against the local
store only, so a bead that lived in a routed store failed with
"'<id>' not found (not an issue ID or formula name)" — even though bd show
resolved the same ID. This broke `gt sling <bead> <rig>`, which cooks the
default formula and bonds it to a rig-routed bead.
- Resolve operands through resolveAndGetIssueForMutation, the same routing
fallback bd show/update/close use (local, then prefix-routed rig via
routes.jsonl, then contributor auto-routing). Write-intent so a prefix-routed
target opens writable and the bond commits where the bead lives.
- Run the bond mutation against the store that owns the resolved issue instead
of the global local store; reject a bond whose two operands resolve to
different stores rather than writing to the wrong database.
- Route the --dry-run preview read-only so it previews routed operands too.
- Add TestResolveMolBondOperandRouting covering local and routed resolution.
Same routing-parity fix as #3608/#3609 for bd close.
* fix(mol): fail fast on read-only routed stores, share same-rig bond handles
Address the two structural issues from the #4720 review beyond the rebase
itself (the rebase already preserves main's unconditional formula fallback
from #3874 instead of reintroducing the looksLikeFormulaName gate):
- Routed operands resolve but couldn't be bonded: contributor auto-routing
deliberately opens stores read-only (they hydrate foreign projects that
must never be mutated), yet the bond selected that store and dispatched
mutations that only failed at the store layer. Operand resolution now
mirrors resolveCloseTargets explicitly (local, then prefix-routed
write-intent, then the shared auto-routed read-only handle) and records
writability per operand; pickBondStore rejects a bond pinned to a
read-only store with a clear message before any mutation is attempted.
TestMolBondPrefixRoutedWriteThrough now verifies the actual dependency
write commits in the routed database, not just resolution, and
TestMolBondAutoRoutedReadOnlyFailsFast covers the fail-fast path.
- Same routed database compared as two different stores: pickBondStore
compared Go handle identity, but each route-open constructs a fresh store
in server mode, so two operands in the same routed rig were wrongly
rejected as cross-store. Both operands of a bond now share one routed
handle (an already-opened routed store is tried before opening another),
and sameBondStore falls back to StoreLocator identity (CLIDir pins the
concrete database) for separately-opened handles onto the same database.
TestSameBondStoreSeparateHandles covers the two-handle case directly.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* fix(mol): validate routed bond homes before mutation
Discover bond operands read-only, enforce dry-run parity and cross-store policy before writable reopen, unwrap decorated store identities, preserve actionable route failures, and verify the accepted home after reopen.
Co-authored-by: Johan Snyman <johan.snyman@orange.com>
Agent-Signature: codex-gpt-5.6-sol-high on behalf of matt wilkie
* fix(mol): reconcile routed bond discovery with #5253 var validation
The rebase onto current main carried two silent regressions the Aug 16
review named: the discovery-based resolution (which replaced
resolveOrDescribe on the direct-store path) never validated --var values,
so `bd mol bond --dry-run <formula> <x> --var bad=...` previewed success
for a bond execution refuses — exactly the false preview #5253 fixed —
and materializeMolBondOperand wrapped every cook error as
"'%s' not found as issue or formula", re-introducing the ErrVarValidation
double-wrap #5253 removed from resolveOrCookToSubgraph.
discoverMolBondOperand now takes the provided vars and runs
formula.ValidateProvidedVars on its formula fallback, so --dry-run and
execution reject the bond identically, before any writable reopen.
materializeMolBondOperand passes formula.ErrVarValidation through
unwrapped, matching resolveOrCookToSubgraph and pour/wisp.
Agent-Signature: claude-fable-5 on behalf of R0SEWT
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* fix(mol): review polish — fs.ErrNotExist, hook-isolated test repos, auto-route coverage
Three non-blocking notes from the Aug 16 review:
- routed.go: errors.Is(err, fs.ErrNotExist) instead of the legacy
os.IsNotExist, so the not-found check keeps working if loadPrefixRoutes
ever starts wrapping its open error.
- mol_bond_routing_test.go: pin core.hooksPath to .git/hooks after each
git init (the initGitRepoAt convention), so a developer or CI box with a
global hooksPath override never runs foreign hooks inside test repos.
- The widened openAutoRoutedStore behavior (maintainer/default auto-routes
open writable for any validated write-intent resolver, not just mol bond)
now has both the CHANGELOG sentence and a write-through test:
TestMaintainerAutoRouteMutationWritesThrough drives
resolveAndGetIssueForMutation — the bd update resolver — through a
maintainer auto-route, commits a real update there, and re-reads it via a
fresh routed read.
Agent-Signature: claude-fable-5 on behalf of R0SEWT
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* fix(mol): carry main's #5761 formula validation into routed bond discovery
Rebase adaptation for #4720 onto main b303d494df. The PR moved the direct
(non-proxied) `bd mol bond` path off resolveOrDescribe and
resolveOrCookToSubgraph onto discoverMolBondOperand and
materializeMolBondOperand. Main's #5761 meanwhile fixed the old pair so a
--dry-run fails on exactly what the real bond fails on; the new pair did not
have that fix:
- discoverMolBondOperand loaded the formula with parser.LoadByName, which
never runs Formula.Validate, so a --dry-run previewed a successful bond for
a formula the cook rejects (e.g. a waits_for gate with no spawner). It also
validated --var values against the unmerged formula, so a var whose enum is
declared only in a parent went unchecked. Discovery now resolves the
formula with parser.Resolve first, the way resolveAndCookFormulaWithVars
does, and wraps both failures the way the cook does, so --dry-run and
execution report the same message.
- materializeMolBondOperand passed only formula.ErrVarValidation through
unwrapped. A formula that fails validation was reported as "not found as
issue or formula". formula.ErrValidation now passes through too, as in
main's resolveOrCookToSubgraph.
TestDiscoverMolBondOperandRejectsWhatMaterializeRejects and
TestDiscoverMolBondOperandValidatesVarsAgainstTheMergedFormula assert the two
phases against each other, like main's TestBondDryRun* pair does for the
proxied route.
Also:
- The PR's routing tests now pass the `exact` argument that main's #5393
added to resolveViaPrefixRoutingWithAccess. They pass false, which keeps
the partial-ID resolution the tests were written against.
- The PR's three new cgo test files are added to the bd_test srcs. This is
`make bazel-sync` output on the merged tree, and it touches nothing else.
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: Rody Vilchez <102562850+R0SEWT@users.noreply.github.com>
* test(mol): rebuild the RepoContext cache in the PR's role-routing tests
Rebase adaptation for #4720 onto main b303d494df. Main's #5243 moved
auto-routing role detection onto beads.GetRepoContext(), which caches the
repo context once per process; before it, role detection ran
routing.DetectUserRole(".") on every call. The PR's auto-routing tests chdir
into a fresh repo and set beads.role there, so after the rebase they read
the context an earlier test built for its own, now-deleted repo. There
beads.role is unset, and the remote-URL fallback finds no origin and answers
maintainer:
- TestMolBondAutoRoutedReadOnlyFailsFast fails whenever a role-routing test
ran before it in the same binary (reproducible alone with -count=2):
discovery looks for the contributor operand in the local store and reports
it not found.
- TestDiscoverMolBondOperandRouting/maintainer_routed_issue and
TestMaintainerAutoRouteMutationWritesThrough still pass, but only because
that fallback is also maintainer; they never read the beads.role they
configure.
Each test now calls resetRepoContextCachesForTest after its chdir, as #5243
did for main's own role-routing tests (TestResolveCloseTargets, which
TestDiscoverMolBondOperandRouting mirrors, and the routing_read tests).
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: Rody Vilchez <102562850+R0SEWT@users.noreply.github.com>
* fix(routing): open maintainer auto-routes writable for exact-match writes
#5393 landed after this PR was written. It moved `bd comment` and
`bd comments add` off resolveAndGetIssueForMutation onto a new
resolveAndGetIssueForMutationExact. This PR widens the former's auto-route
tier for write intent: a maintainer/default target opens writable, while a
contributor target stays read-only and MutationForbidden. On the PR's
original base that widening covered comment writes. After the rebase the
exact resolver still opened every auto-route read-only, so comment writes
lost it and the CHANGELOG's "any validated write-intent resolver" no longer
held.
The exact resolver is meant to keep the mutation resolver's routing
fallbacks and only tighten matching (#5393: it "keeps the existing
cross-rig prefix-routing and contributor auto-routing fallbacks intact").
Its auto tier now takes the same write-intent path. Matching stays exact,
and the abbreviation-refusal precedence is unchanged.
TestMaintainerAutoRouteExactMutationWritesThrough pins the change: the
routed store must not be read-only, and a comment written through it must
commit in the planning database. Without this change the read-only check
fails. The write itself still succeeds, because a server-mode read-only
open does not refuse it.
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: Rody Vilchez <102562850+R0SEWT@users.noreply.github.com>
* fix(routing): harden routed writes and surface routing failures
Review fixes for #4720.
bd close resolved its batch's shared auto-route through
openRoutedReadStore, so the route opened read-only even though every
other write-intent resolver opened it writable. The shared handle now
opens through openAutoRoutedStore with write intent, so the close commits
where the issue lives.
A contributor auto-route now opens writable for write-intent callers, as
maintainer and default routes do. The refusal the previous revision added
(errContributorRouteMutationForbidden, contributorRouteRefusal,
RoutedResult.MutationForbidden) is gone. A contributor's route target is
their own planning repository, the one bd create writes to:
docs/multi-agent/multi-repo-migration.md and
examples/contributor-workflow/README.md have the contributor claim and
close planning issues from the fork, and GH#2345, beads-0km and GH#3608
made bd show, update and close reach those issues. The read-only rule
came from #4389's review fixes (e8ae7a291a), which kept "contributor
auto-routing" read-only to preserve the bd-6dnrw.32/GH#3231 guarantee
that "routed reads never mutate a foreign project's history". That
guarantee is about reads, and the planning repository is not a foreign
project. Base therefore split by backend: a server-mode bd update, close
or comment of a planning issue committed, because a read-only server
store accepts the write, while the embedded store refused it with "store
is read-only". Refusing in every resolver would have broken the
documented workflow on both backends. bd mol bond was the only command
that checked MutationForbidden, so its check goes too, and a bond of
planning issues commits in the planning repository like any other routed
write. Reads through every route stay read-only. This reverses the
previous revision's stance and is flagged here as a maintainer call.
bd unclaim now resolves its issue through resolveAndGetIssueForMutation,
as bd update --claim does, so a routed issue opens writable; with the
read resolver an embedded routed target refused the release with "store
is read-only". Like bd close, it commits a routed change itself
(commitPendingIfEmbedded), since the post-run auto-commit covers only the
local store. bd human respond and dismiss already opened their target
writable but never committed it, so on an embedded workspace the close
sat uncommitted in the routed repository's working set; they now commit
it the same way. resolveAndGetIssueWithRoutingAccess's
writablePrefixRoute parameter is renamed writable, since it now governs
auto routes too.
A routed commit that fails no longer looks like success, and a retry
commits it. bd unclaim printed "Unclaimed" (or listed the issue in its
--json output) even when the release's routed commit failed; it now
reports the commit error and leaves the issue out. The failed commit
leaves the release, or the close human respond and dismiss make, in the
routed repository's working set. There a retry finds the issue
unassigned or already closed and refuses before it reaches its commit,
and nothing else commits a routed target. On that refusal unclaim,
respond and dismiss now commit the pending write before reporting it,
through commitRoutedWrite, which their success paths share.
A routed write never creates the target's database. The routed open runs
before the lookup it serves, so an embedded open of a repository that had
not been bootstrapped yet created an empty database that outlived an id
that missed; bd bootstrap then took it for the real one and skipped the
clone from sync.remote. openRoutedTargetStore's writable branch now opens
through newExistingDoltStoreFromConfig, which refuses an embedded
workspace without a database (embeddeddolt.HasRepository) before the
sanitize migration can rewrite anything there. A server-mode open already
never creates one.
resolveAndGetIssueForMutation already returned a routing failure (an
unreadable routes.jsonl, a routed store that fails to open) as itself. The
exact resolver and bd close still fell through to "no issue found
matching", which misstates why the lookup missed. All of them now share
isRoutingFailure. The exact resolver checks its abbreviation refusal first,
so the auto tier still gets its chance at an exact match. A prefix route
whose target has no usable metadata.json now names the route and the file
and says why the file could not be used.
An auto-routed store now opens the target's own dolt_database, as a prefix
route already did. Otherwise BEADS_DOLT_SERVER_DATABASE, which names the
launching workspace's database, would point a server-mode open at the wrong
database on a shared server. openRoutedTargetStore holds that override for
both route kinds. A write refuses a target whose metadata.json cannot be
read or parsed or names no dolt_database (autoRouteTargetDatabase) instead
of falling back to that variable. A target with no metadata.json at all
opens, read or written, the only embedded database it holds
(embeddeddolt.Databases), or the default database
(configfile.DefaultDoltDatabase) when it holds none or several.
Contributor setup leaves the planning repository without one until the
first routed bd create writes it, and names its database the way any
workspace without metadata.json does, BEADS_DOLT_SERVER_DATABASE first.
The open would otherwise resolve that name again from the launcher's
variable, so when the two differed a read that missed failed with
"database not found" and a write that missed created a database beside
the one setup created. A server-mode target holds no embedded database,
so with the variable set such a route now opens the default database
rather than the launcher's, which is what it opens without the variable.
A read of a target whose metadata.json is unreadable or names no
database keeps the lenient lookup it had.
bd mol bond's routed home now gets the external-dependency policy and
nothing else, as wireExternalDependencyPolicy asks of routed stores. The
launching workspace's hooks and telemetry no longer wrap writes into
another rig. runMolBond's tail is split into planMolBond, openMolBondHome,
materializeMolBondOperands and bondMolBondOperands, which takes it from
cyclomatic 26 down to 10 or less per function. getIssueWithRouting and the
resolveViaAutoRouting wrapper had no callers left and are removed.
Tests:
- TestMaintainerAutoRouteMutationWritesThrough now checks that the routed
store is writable. Without that check it passes even against a read-only
open, because a server-mode read-only store accepts the write.
- TestAutoRouteCloseTargetWriteIntent covers bd close's write intent for a
maintainer route.
- TestContributorAutoRouteWritesThrough replaces
TestContributorAutoRouteRefusesWriteIntent: an update, a comment and a
close through a contributor route each open the target writable and
commit, a read through the same route stays read-only, and a missing id
stays a plain not-found.
- TestEmbeddedContributorRoutedWritesCommitInPlanning runs bd update
--claim, unclaim, comment, close, human respond and human dismiss
through the bd binary in a contributor checkout. Each advances the
planning database's HEAD, and the issues end up closed there and absent
from the fork's database. The embedded shard manifest gains the test.
- TestMolBondContributorAutoRoutedWriteThrough replaces
TestMolBondAutoRoutedReadOnlyFailsFast: bd mol bond's pipeline bonds two
planning issues through a contributor route, and a fresh routed read
sees the dependency; setupAutoRoute now seeds extra planning issues for
it. TestDiscoverMolBondOperandRouting's contributor case now expects the
writable reopen.
- TestResolveCloseTargets keeps base's contributor cases (beads-0km); the
previous revision had moved them to routing.maintainer.
- TestRoutedWriteDoesNotCreateTargetDatabase (in-process) and
TestEmbeddedRoutedWriteMissDoesNotCreateTargetDatabase (the bd binary)
check that a missed write through a prefix route and through a
maintainer auto-route leaves an embedded target that has not been
bootstrapped without an embeddeddolt directory. The embedded shard
manifest gains the test.
- TestRoutedMutationResolversReportRoutingFailures runs each write-intent
resolver against an auto route whose store fails to open, an auto route
whose target's metadata.json names no dolt_database while
BEADS_DOLT_SERVER_DATABASE names the launcher's, and a prefix route
whose target cannot load.
- TestAutoRouteTargetDatabase covers a write and a read of a target whose
metadata.json names a database, is missing, names none, or cannot be
parsed; a missing one yields the target's only embedded database, or
the default database when it holds none or several, either way.
TestDatabases covers the listing, which applies HasRepository's .dolt
marker probe to each database.
- TestAutoRouteMissWithoutMetadataIgnoresEnv runs a missed read and a
missed write through an auto-route to a target that has one database
but no metadata.json: the default database while
BEADS_DOLT_SERVER_DATABASE names the launcher's, and a database named
after the launcher's with the variable set and unset at use. Each miss
must report not found and leave the target holding only its database.
- TestRoutedWriteRetryCommitsFailedCommit fails the routed commit of bd
unclaim (text and --json), human respond and human dismiss with an
invalid --dolt-auto-commit. The run must fail with nothing on stdout and
leave the routed repository's HEAD as it was; a retry must report its
refusal and commit the write there.
- TestAutoRouteOpensTargetDatabaseDespiteEnv checks the target-database
change.
- The auto-routing tests clear BEADS_ROUTING_MODE and BD_ROUTING_MODE
through neutralizeRoutingModeEnv. Viper ranks them above the
routing.mode the tests write, so a host that exports either var never
routes. bdEnv, which builds the bd binary's environment in the
embedded tests, now drops BD_ROUTING_MODE as it drops BEADS_*; agent
hosts export it, and TestEmbeddedContributorRoutedWritesCommitInPlanning
failed on such a host.
TestEmbeddedRoutedWriteMissDoesNotCreateTargetDatabase no longer needs
its own envWithout.
- Reverting each fix turns its test red: the contributor read-only clamp
(the contributor tests above), unclaim's resolver or commit and the
respond and dismiss commits (the matching step of the embedded test),
and each autoRouteTargetDatabase rule. So does dropping unclaim's,
respond's or dismiss's retry commit, or unclaim's skip of a release
whose commit failed (TestRoutedWriteRetryCommitsFailedCommit); either
earlier no-metadata.json rule, the variable, which leaves the stray
database the review reported, or a fixed default database, which fails
the read of a target setup named after the variable
(TestAutoRouteMissWithoutMetadataIgnoresEnv and
TestAutoRouteTargetDatabase), and taking the first of several databases
(TestAutoRouteTargetDatabase); and bdEnv's BD_ROUTING_MODE drop, on a
host that exports BD_ROUTING_MODE=off (both embedded tests).
The CHANGELOG entry now records that every auto-route opens writable for
the commands that change an existing issue, the unclaim and human
respond/dismiss commits, that a routed write never creates the target's
database, and the target-database and routing-failure changes.
docs/multi-agent/routing.md says that write commands follow every route,
contributor, maintainer and default alike, never create the routed
repository's database, and refuse a target whose metadata.json is
unreadable or names no dolt_database. Both say that an auto-route opens
a target with no metadata.json at the one embedded database it holds, or
its default database when it holds none or several, while a prefix route
always needs the target's dolt_database. That page documents
behavior that is not in a release yet, which the docs release-pin
decision (engdocs/decisions/2026-07-17-docs-release-pin.md §1) would
leave undocumented. The review asked for docs that match the behavior,
as feature PRs #6508, #5855, #5997 and #5092 also did, so it is flagged
here as a maintainer call.
Open, and not changed here. bd close has the same retry gap on base: a
re-close of an issue that a failed routed commit left closed counts as
already closed and never commits that store (mutatedStores).
commitPendingIfEmbedded gates on the launcher's mode (isEmbeddedMode),
not the routed store's, so a server-mode launcher that opens an embedded
routed repository would leave the write uncommitted there. That gate is
shared by every routed write command and is not exercised here.
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: Rody Vilchez <102562850+R0SEWT@users.noreply.github.com>
* ci(shards): list TestDatabases in the 40-shard embedded storage manifest
The routed-write hardening added TestDatabases to
internal/storage/embeddeddolt/detection_test.go without a slot in the
Bazel-only 40-shard block of .github/scripts/embedded-storage-test-shards.txt,
so gen_embedded_storage_shard_manifest.py 40 --weights=duration --check
reported it missing and TestStorageEmbeddedShardManifestGeneratorNotStale
(go test ./scripts) failed.
Regenerated with the repository command
(gen_embedded_storage_shard_manifest.py 40 --weights=duration --write);
the incremental pack adds exactly one line, on shard 25.
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: Rody Vilchez <102562850+R0SEWT@users.noreply.github.com>
---------
Co-authored-by: Rody Vilchez <102562850+R0SEWT@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Co-authored-by: matt wilkie <maphew@gmail.com>
Co-authored-by: Eddie the Engineer <julianknutsen@users.noreply.github.com>
Co-authored-by: Eddie the Engineer <338826946+gascity-eddie[bot]@users.noreply.github.com>
* 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>
* test(delete): pin that a stale id never deletes the issue it prefixes (be-ksd)
bd delete resolves each id through the abbreviation-tolerant resolver
(resolveAndGetIssueForMutation -> utils.ResolvePartialID). When the exact
id is absent, that resolver falls through to leading-prefix abbreviation,
so an id that was already deleted resolves to a different issue whose id
it happens to begin, and --force deletes that issue.
The shape is ordinary: hash length is adaptive (3 to 8 characters) so a
grown store holds short ids beside longer ones, --id makes any shape, and
a hierarchical child's id always extends its parent's. On a fixture, after
fx-t00003 was deleted, bd delete fx-t00003 resolved to fx-t000031; a
re-run of a finished --from-file list with --force --quiet deleted two
issues it never named, silently.
The test drives deleteCmd in-process against a stub DoltStorage (no cgo,
no Dolt server) and records every request handed to the Deleter role. It
covers the single-id --force path, the preview, a deleted parent's id with
an orphaned child, the --from-file batch path, and an abbreviation of one
and of two live issues; each refusal must say delete needs the full id
and name the ids the input matches. An over-refusal guard checks that
exact ids (full, bare hash, child, batch) still delete exactly what they
name. The six refusal cases fail at this commit; the guard passes.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Agent-Signature: claude-code-claude-opus-5-5 on behalf of A3Ackerman
* fix(delete): resolve ids exactly, never by prefix abbreviation (be-ksd)
bd delete's direct route resolved each id with the abbreviation-tolerant
resolver, so an id that no longer exists resolved to the surviving issue
whose id it begins, and --force deleted that issue. Both of its resolution
sites now use resolveAndGetIssueForMutationExact (#5393's exact sibling,
until now used only by bd comment): the inline single-id path and
deleteBatch, which --from-file, multiple ids and --cascade take.
The resolver cannot tell a stale full id from an abbreviation. Hash length
is adaptive with store size, so one store holds 3- to 8-character ids side
by side and "fx-t00003" is both a valid full id and a valid abbreviation
of "fx-t000031". The rule therefore has to be per command, the way #5393
made it for bd comment. Delete is exact on both preview and --force: the
preview prints the next command to run ("To proceed, run: bd delete
fx-t000031 --force"), so a tolerant preview hands the caller the wrong
deletion to confirm.
This matches the team-server route, which passes ids to issueops.Deleter
unresolved, and DeleteRequest.IDs' own contract ("IDs ARE EXACT"). The
partial-ID notice (#6302) did not protect this path: --quiet silences it,
and a --force --quiet re-run of a finished --from-file list deleted two
issues it never named.
The refusal says what to do: "bd delete needs the full issue id: no issue
has the id "t000", which is the start of fx-t000031". To name the matches,
ResolvePartialIDExact now returns *utils.AbbreviatedIDError, which carries
the input and the sorted matches, wraps ErrAbbreviatedIDNotAllowed and
keeps the old error text, so bd comment's errors.Is checks and messages
are unchanged.
Cost: bd delete <abbreviation> is refused, naming the full ids, so the
caller retypes one. Exact ids, bare full hashes, child, cross-prefix and
routed ids resolve as before. The other deleteBatch callers (cleanup, wisp
gc, mol burn) pass full ids read from the store, so nothing changes for
them except under a race, where they now refuse instead of reaching a
neighbor. Reads and other writes keep abbreviation.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Agent-Signature: claude-code-claude-opus-5-5 on behalf of A3Ackerman
* docs(ids): say bd delete requires the full id, like bd comment (be-ksd)
The Working with IDs section named bd comment as the one command that
refuses abbreviations and said every other mutation keeps them. bd delete
now requires the exact id too, so the section covers both, says why a
delete reaches the wrong issue so easily (an already-deleted id is still
the start of its child's id, or of a longer hash), and adds the bd delete
lines to the example block. Best Practices #1 names both commands.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Agent-Signature: claude-code-claude-opus-5-5 on behalf of A3Ackerman
* docs(changelog): link the bd delete exact-id entry to #7375 (be-ksd)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Agent-Signature: claude-code-claude-opus-5-5 on behalf of A3Ackerman
* fix(delete): report a gone parent's id as a lost race under --if-revision (be-ksd)
Review-loop iteration 1 for #7375: a maintainer fixup on top of the
contributor's branch.
Major (codex+claude): a guarded `bd delete --if-revision` whose target
was deleted, and whose id is still the start of a surviving id (a gone
parent with a live <parent>.1 child), exited 1 with the abbreviation
refusal. Any other gone target gets the documented lost race
(precondition_failed, exit 13), and gascity's conditional deletes
switch on that code, so a benign race read as a hard failure.
- reportIfRevisionTargetGone (the single-id path) also takes
utils.ErrAbbreviatedIDNotAllowed as a gone target: under delete's
exact resolution that id names no row either.
- The refusal is a typed error, deleteAbbreviationError, that unwraps
to storage.ErrNotFound beside the *utils.AbbreviatedIDError, so the
--cascade caller of deleteBatch classifies it through
reportIfRevisionFailure the same way. errors.New(msg) dropped every
sentinel.
Minor (claude), taken: the refusal leads with the not-found fact,
`issue "t000" not found: bd delete needs the full issue id, and "t000"
is only the start of fx-t000031`, so gascity's isBdNotFound reads an
already-gone full id that begins a survivor's id as the idempotent
not-found it reads for any other gone id. The CHANGELOG entry quotes
the new text and the --if-revision outcome.
Minor (gemini), declined: threading the source command into the
refusal's wording. deleteBatch's other callers (bd cleanup, wisp gc,
mol burn) pass store-minted full ids that no user retypes, and the text
now leads with "issue X not found", which holds for every caller.
Tests:
- TestDeleteIfRevisionGoneIDThatPrefixesAnotherIssue: single id,
--json, --cascade and --cascade --json each exit 13 with "precondition
failed: issue no longer exists" and the precondition_failed body,
never the refusal text, and the guarded write never runs. Two
no-survivor rows are the plain gone id they must match.
- TestReportIfRevisionTargetGone: abbreviation rows, guarded and not.
- TestDeleteRefusesStaleIDThatPrefixesAnotherIssue also asserts the
refusal says "not found".
- TestEmbeddedIfRevisionDeletePreflightGoneParentIsPreconditionFailed,
end to end on embedded Dolt: delete a parent, its child survives and
`bd show <parent>` resolves to it; a guarded delete of the parent
exits 13 on the single-id and --cascade paths and leaves the child.
The TestEmbedded name is what puts it in a CI lane; its line in
embedded-cmd-test-shards.txt is the generator's incremental --write.
Mutation checks, each reverted afterwards: dropping the
ErrAbbreviatedIDNotAllowed match fails the single-id cases and the
abbreviation_guarded row; dropping ErrNotFound from Unwrap fails the
--cascade cases; dropping "not found" from the text fails every
refusal case; reverting both fixes fails both embedded legs (exit 1,
the refusal text, no "precondition failed").
Validation: the focused delete and if-revision tests; the embedded pair
under BEADS_TEST_EMBEDDED_DOLT=1; the scripts shard-manifest policy
tests and the generator's --check; gofmt; git diff --check. The full
./cmd/bd and ./internal/utils packages (-short, BEADS_TEST_SKIP=dolt)
pass but for TestRunApplyAllOK, which fails only because this worktree
sets core.hooksPath=/dev/null ("mkdir /dev/null: not a directory") and
passes with core.hooksPath overridden.
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: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Eddie the Engineer <julianknutsen@users.noreply.github.com>
Claude Code merges a project's hook settings into every session started in that
checkout, including an orchestrator's agent sessions, which get their own
briefing. A higher-precedence settings file cannot remove a lower one's hook, so
such sessions run `bd prime` whether it helps them or not. The only per-session
channel their host controls is the environment.
prime.disabled (BD_PRIME_DISABLED) makes bd prime print nothing, the same as
outside a workspace (an empty envelope under --hook-json), whatever its other
flags. It returns before any workspace or store access. Like the prime memory
caps it is a yaml-only key, and it is validated with strconv.ParseBool, the set
that viper's GetBool reads.
Measured on a copy of a 751-memory store, bytes a hook injects:
- bd prime: 1,251,189 (the default is unchanged);
- BD_PRIME_DISABLED=true bd prime, --full, --memories-only: 0;
- BD_PRIME_DISABLED=true bd prime --hook-json: the empty envelope.
In the Gas City deployment that owns that store, 637 agent sessions in 48 hours
fired the inherited hook 1,271 times. Each firing injected a 2.3 KB preview after
host truncation. On top of that, the sessions read 1.81 MB of the persisted
output. That is about 4.8 MB of context these sessions do not use.
Tests:
- TestPrimeDisabledReadsTheConfigKey.
- TestPrimeDisabledPrintsNothingInAWorkspace. A staged workspace's briefing
prints when the key is off; the test fails if the early return is removed.
- TestValidateYamlConfigValue_PrimeDisabled.
- The embedded TestEmbeddedPrime/prime_disabled_env and
/prime_disabled_config subtests.
Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Julian Knutsen
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* perf(http): answer a command's repeated reads from one response (port of bd-enterprise e626072b8)
Over an http workspace, bd show <id> --json made three identical
GET /v0/beads/issues/<id> requests: the id resolver's exact probe,
routed.go's GetIssue and show's detail read all build the same URL. Text
show made six. Over a gateway each one is a sequential round trip, so the
request count is the command's latency floor (mc-5dkzp).
This ports bd-enterprise e626072b8 (bts-xpw.3.14.6, #217) verbatim, except
cmd/bd/main.go, where OSS still opens the identity preview inline, and
bd-enterprise's httpgw dialer test, which has no OSS counterpart:
- httpclient.WithSharedConnections: the identity-gate preview and the real
open share one transport, so a write makes one handshake.
- httpclient.WithReadMemo and a wire.Client read memo, for one-shot
commands only (not bd serve, --watch or --follow): identical getIssue,
getSetting and listSettings reads are answered from the response already
received. An entry ages from the server's answer (5 s), any write clears
the memo, a read that overlapped a write is not stored, and expired
entries are swept.
- bd list's three vocabulary reads come from one memoized listSettings.
- bd update --status / --if-status skips the custom-status read for a
built-in status.
- The hook decorator skips its post-write re-reads when no executable hook
exists for the event.
- bd dep add reads its confirmation titles before the write, from the memo.
Against a loopback bd serve: show --json goes from 3 requests to 1, text
show 6 to 3, update 5 to 3, close 6 to 4. Dolt and the other registered
backends receive the same ctx and ignore it.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* feat(http): BD_HTTP_READ_MEMO=0 turns the per-command read memo off
An operator who suspects a stale read can rule the memo out without a
rebuild. Any other value, or none, leaves the default.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* test(http): pin bd show to one fetch per issue (mc-5dkzp)
TestE2E_PerCommandRequestBudget allowed show two requests, and a read
that drifts to a URL of its own (a mutant whose reader spells
brief_deps=false) fits that ceiling on both handshake shapes. These guards
pin the single fetch instead:
- TestE2E_ShowFetchesTheIssueOnce: the exact requests, path and query, of
show --json, show --json --id, show --short, show of two ids and text
show, against both handshake shapes, plus a BD_HTTP_READ_MEMO=0 step
that must read the row more than once.
- TestDefaultIssueReadsShareOneMemoKey: the resolver's exact probe,
GetIssue, GetDependenciesWithMetadata, GetLabels and IssueReader().Get
build one URL, checked without a server.
- TestE2E_CloseRereadsItsOwnWrite: against the MC handshake, closing a
lone molecule re-reads its own closed row from the server after the
write, and prints no false "completed molecule" note.
- Corpus shapes can pin `requests:`, counted on the served run alone (not
setup, verify or {rev:ID} reads). The seven gc and mc show shapes pin
1, 4, 1, 1, 3, 1 and 3.
Also: TestReadMemoOptInReadsTheRealPollingFlags holds the opt-in to the
real show/list --watch and -w, events tail --follow and bd serve; the
show budget drops from 2 to 1; requestCounter records each request's
query; and ledger row L-read-memo records the memo's bounded difference
from local reads.
Mutation runs against this tree: brief_deps=true on GetIssue and
brief_deps=false on the reader's Get each fail the e2e list and the unit
test; show opting out of the memo fails the e2e list; writes that leave
the memo standing fail the read-your-own-write e2e; a memo keyed by path
alone fails the e2e list; dropping the kill switch fails its unit test
and the e2e step.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* docs(config): list BD_HTTP_READ_MEMO
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(http): memoize a read's answer only once it has decoded
wire.Client.Do stored a memoable read's 2xx before it checked the body,
so an empty or undecodable 200 would have answered every identical read
in the command for the memo's whole TTL with the same failure, instead
of asking the server again. The answer is now stored only after it
decodes; a read that decodes nothing (out == nil) is not stored, and
every memoable read in this package decodes its answer.
TestReadMemoKeepsOnlyAnswersThatDecoded pins it (empty body, truncated
body, undecoded answer). Ledger row L-read-memo says so.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* test(http): pin the read memo's 5xx, write-method, per-client, in-flight-write and hook-gate behavior
Review follow-ups for the per-command read memo (mc-5dkzp):
- TestReadMemoNeverKeepsA5xx: a 503, 500 or 502 is not memoized and the
2xx after it is. TestDispatchRetryOfABusyMemoizedReadAsksTheServer
holds the same through dispatch's retry loop over a real wire.Client:
the retry reaches the server instead of replaying the 503.
- TestReadMemoIsDroppedByAnyWrite covers POST, PUT and DELETE, not just
PATCH.
- TestReadMemoIsPerClient: in either order, one client's read is never
answered from another's memo, and opting one client in opts in no
other. (A shared memo was otherwise caught only by test-order
pollution.)
- TestReadMemoDropsAnAnswerReadWhileAWriteWasInFlight pins the clear on
the write's way back: a read that starts and ends while the write is
on the wire is not answered again once the write has returned.
- TestHookFiringStoreReReadsOnlyForAnEventWithAHook pins hookConfigured's
probe: the decorator asks the runner about the event it fires, and
re-reads the row to build a payload only when a hook for that event
exists, through a probing double and through a real hooks.Runner.
Each was run against a mutant of the code it pins and fails there:
5xx stored before the status check; only PATCH clearing; one memo
shared by every client; no clear after the write returns;
hookConfigured answering true, false, or about the wrong event.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* docs(changelog): note the per-command http read memo
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(create): let a remote backend mint the --parent child id
`bd create --parent` always called the raw GetNextChildID first, which the
http backend does not serve, so every child create on a remote workspace
refused before writing anything. The Lifecycle role already mints
<parent>.<n> for a create that carries a ParentID and no id of its own, on
every backend and inside the create's own transaction; conformance
RunIssueOperationsCreateUnderAParentMintsTheNextChildID pins it on every leg,
the served one included (and the bd-enterprise postgres leg the MC server
runs). So the create route needs no new capability token: on a registered
Remote backend the client skips the raw reservation and lets the server mint.
The local route keeps its reservation so its Dolt commit staging is
unchanged, and an explicit --id beside --parent is still refused up front.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(mol): molecule reads, auto-close and close --continue over issueops roles
Over the http backend three molecule paths failed, and two of them
silently:
- `bd mol current` / `bd mol progress` without an id answered "no molecules"
because the in_progress listing (a raw SearchIssues shape) and the parent
walk (raw GetDependencyRecordsForIssues) were refused and the refusal was
swallowed; with an id they refused on raw GetMoleculeProgress.
- The molecule auto-close after `bd close` never ran: findParentMolecules
swallowed the same refused edge read into "not part of a molecule".
- `bd close --continue` claimed the next step in a raw RunInTransaction.
The direct route now reads molecules through roleMolStore, which answers
through roles every backend serves: EdgeReader (batched at the wire's 100
anchors) for the parent walk, BatchGetter for the roots (Get per id where a
server does not publish issues.batchGet), Relations for the step rows (full
rows; the raw dependents read over http is getIssue's shallow projection,
which zeroed step assignees) and the progress counts, and Reader.List for the
in_progress/hooked listings. The auto-close closes the root through
Lifecycle.Close, and the --continue claim is one Lifecycle.Update guarded by
ExpectedStatus=open.
No refusal is swallowed any more: findParentMolecules, the molecule finders
and the hooked scan return their errors; `mol current/progress` report them;
the auto-close stays best effort but warns on stderr; AdvanceToNextStep only
moves on to the next ready step when the claim LOST a race (status mismatch,
not claimable, already claimed) and returns anything else. The one heuristic
still skipped is the id-pattern heal in loadDescendants, and only for an
ErrUnsupported backend that cannot express an id-prefix search; other
failures now surface. `mol current`/`mol progress` leave the
types.IssueFilter forbidigo hole, since they no longer build a filter.
gc does not depend on bd's molecule auto-close: it runs its own
(cmd/gc/molecule_autoclose.go, from the bd on_close hook and the
controller's bead-close events). Its worker prompts do run `bd mol current`.
Served e2e (TestE2E_MoleculesOverHTTP): create --parent mints <root>.1/.2,
mol current <id> is non-empty with the full in-progress step, mol progress
counts, close --continue auto-advances, closing the last step auto-closes
the root. `mol current` without an id now refuses out loud on this stack
(asserted: never an empty list); its non-empty assertion is skipped until
S6c (externaldeps reader passthrough) is underneath.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(mol): list molecule candidates with the four wire knobs, drop the S6c skip
On top of S6c the in_progress listing behind 'bd mol current' (no id)
reaches the v0 wire encoder, which refuses ListRequest.IncludeAllTypes.
Ask for templates, gates, infra and ephemeral rows explicitly, which the
wire publishes, and run the 'mol current without an id' served case.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* feat(issueops): one library entry each for molecule auto-close, advance and reads
The molecule rules lived only in cmd/bd, in copies that disagreed: two
auto-close implementations that closed the root through different
library entries outside the step close's transaction, a `close
--continue` claim that set no assignee and could take a step another
agent held on the direct and http routes, and three progress counts.
Every molecule rule now has one implementation in the public issueops
package, composed over three roles every backend serves (BatchGetter,
Relations, EdgeReader): MoleculeRoots, LoadMolecule, AnalyzeMolecule,
ViewMolecule, ReadMoleculeProgress, ActiveMoleculeIDs,
CompletedMolecule. Membership is the parent-child edge.
Auto-close: CloseRequest.AutoCloseMolecule and
CloseBatchRequest.AutoCloseMolecule (opt-in, so gc's own auto-close is
not doubled) close the molecule root a close completed IN THE SAME
TRANSACTION, unforced and guarded on the root revision read there:
storageissueops.CloseCompletedMoleculeInTx on the store backends (the
role bodies bound to the caller's tx, TxMoleculeReader) and
uow.CloseCompletedMoleculeInUOW on the unit of work. It replays on an
idempotent re-close, reports the root on CloseResult/CloseOutcome
.AutoClosedMolecule, and a root its own close policy refuses stays open
and is reported (MoleculeAutoCloseRefusal) without failing the step.
Advance: a new MoleculeStepper role (storage.DoltStorage accessor,
uow.MoleculeStepperSource) whose one implementation,
issueops.NewMoleculeStepper, claims the next ready step through the
Claimer (Lifecycle.Update's Claim for a wisp step): assignee set, a step
another actor holds skipped, never taken.
HTTP: closeIssue/batchCloseIssues carry auto_close_molecule behind the
issues.close.autoCloseMolecule behavior token, and POST
/v0/beads/issues/{id}:advanceMolecule (issues.advanceMolecule) serves
the stepper. Handlers only decode, call the role and encode. The client
sends the member and dials the operation only where advertised; against
an older server it DEGRADES rather than refuses — it runs the same
library rule over its own roles (issueops.CloseCompletedMolecule after
the close, NewMoleculeStepper for the advance), so the outcome is the
same in more round trips. The capability fallbacks that lived in
cmd/bd move into the client: BatchGetter answers one getIssue per id
without issues.batchGet, and EdgeReader splits past the operation's 100
anchors.
Conformance: RunMolecule* on dolt, embedded, uow and http (the http leg
twice: served, and against a server with the tokens struck out).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* refactor(cmd/bd): molecule commands and create --parent through the library entries
`bd close`, `bd close --continue`, `bd mol current`, `bd mol progress`,
`bd ready --mol` and `bd create --parent` now call the one library entry
for each rule on every route (direct, proxied server, remote):
- close (batch, --if-revision, proxied) sets CloseRequest/
CloseBatchRequest.AutoCloseMolecule and only reports what the library
closed in the step close's transaction. autoCloseCompletedMolecule,
autoCloseProxiedCompletedMolecule and closeCompletedMoleculeRoot are
gone, and so is the separate post-close write.
- --continue is the route's MoleculeStepper role: a real claim (the
assignee is set) that skips a step another actor holds. Before, the
direct and http routes flipped the status only and could take it.
AdvanceToNextStep, ClaimStepIfOpen and its two implementations are
gone.
- mol current / mol progress / ready --mol read through
issueops.ViewMolecule, ReadMoleculeProgress, ActiveMoleculeIDs and
LoadMolecule/AnalyzeMolecule over the route's roles. Over http this
fixes the missing step assignee on `ready --mol` (corpus mark
mc-ready-mol). The proxied route's SearchIssues fallback, the role
store, the third progress count and the cmd/bd copy of the readiness
analysis are deleted; only presentation stays here.
- create --parent asks the create role to mint the child id on every
route (the local CLI reservation is gone) and to inherit the parent's
labels (InheritLabelsFromParent) inside the create. The dry-run
preview still shows the labels, and a failed label read there is
reported, not swallowed.
TestProxiedServerMoleculeLifecycleAgreesOnEveryRoute runs one molecule
lifecycle through the real binary on the direct, proxied and remote
(`bd connect` to `bd serve`) routes and requires the same rows and the
same JSON on all three. The served e2e now also pins the held-step skip,
the claimed step's assignee and the full rows of `ready --mol`.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(httpclient): refuse molecule auto-close and advance before dialing an older server
The client used to DEGRADE against a server without
issues.close.autoCloseMolecule / issues.advanceMolecule: it closed the step
without the member and ran a second, client-side copy of the auto-close
(issueops.CloseCompletedMolecule) in its own transactions, and composed the
stepper over its own roles. That kept two executions of each rule alive.
Now the rule runs in ONE place, the server's library: a close or batch close
that sets AutoCloseMolecule, and an Advance, refuse before anything is dialed
with the typed capability error (storage.ErrUnsupported, Capability naming the
token). The composed single-item batch leg now carries the member too.
- issueops.CloseCompletedMolecule (the role-composed form) is gone.
MoleculeRootClose is the one root close request (unforced, the auto-close
reason, the session, guarded on the root revision read), and both
in-transaction bodies (storage issueops CloseCompletedMoleculeInTx, uow
CloseCompletedMoleculeInUOW) build from it.
- MoleculeView.Ready is `bd ready --mol`'s list (every analysis-ready node,
hydrated), so ready --mol and mol current derive from ViewMolecule alone.
Tests: unit pre-dial refusal and member pins (httpclient molecule_test.go),
TestServedMoleculeRefusesAgainstAnOlderServer (step stays open, nothing
claimed) replacing the degraded contract arm.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(cmd/bd): ask for the molecule auto-close only where the route serves it
The refuse-before-dialing client made every `bd close` over http fail
against a server that does not advertise issues.close.autoCloseMolecule
(an older bd serve, or the MC server shape, whose orchestrator owns the
molecule lifecycle): the CLI always set AutoCloseMolecule.
storage.ServesMoleculeAutoClose answers, through every decorator, whether a
store's closes may carry the flag (MoleculeAutoCloseProber, implemented by
httpclient.Store from its handshake; every local backend serves it). The
direct batch close and the --if-revision close set the flag from it; the
proxied route always serves it. Against a silent server the close goes out
without the member and the server's side owns the auto-close.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* test(backend/http): scope the advertised-policy check to reads before the close
The close policy check is the client-side policy's last chance: it runs
before the close request, so only the reads up to that request count. A
read after the close (the old-server molecule notice reads the closed
step's edges) is not the external-dependency policy.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* test(backend/http/corpus): drop the six marks S16 and S19 retire
With the molecule library entries underneath, mol current (with and
without an id, json and text), mol progress and ready --mol read through
issueops.LoadMolecule over the roles, and create --parent lets the server
mint the child id. Those six shapes pass on the reference profile.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(cmd/bd): never silent against a server without the molecule tokens
Against a server that advertises neither issues.close.autoCloseMolecule
nor issues.advanceMolecule (an older bd serve, or one whose orchestrator
owns the molecule lifecycle):
- `bd close --continue` closed the step and only then found the advance
refused, leaving the step closed and the next step unclaimed. It now
asks storage.ServesMoleculeAdvance (a MoleculeAdvanceProber the http
store answers from its handshake; local backends always serve it)
BEFORE the close and refuses up front, saying nothing was closed.
- `bd close` went out without auto_close_molecule and said nothing. When
the closed step belongs to a molecule (issueops.MoleculeRoot), a notice
on stderr now names the molecule and the missing token: its auto-close
is the server's to run. The batch and --if-revision closes both say it.
The served e2e masks both tokens out of the handshake and checks the
up-front refusal (the step stays open) and the notice; the httpclient
unit test pins ServesMoleculeAdvance to the handshake.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* refactor(cmd/bd): mol show through issueops.LoadMolecule on every route
`bd mol show` still loaded the molecule through cmd/bd's
loadTemplateSubgraph (raw GetIssue, GetDependentsWithMetadata and
GetDependencyRecords, plus an id-pattern child probe), while mol current,
mol progress and ready --mol read through the library. It now loads
through issueops.LoadMolecule over the route's molecule roles (the direct
store's, or the proxied provider's), so membership is the parent-child
edge everywhere and the http route reads through roles the server serves.
The served e2e checks mol show's root and step count.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* docs: the molecule auto-close fails the step's close on a non-policy error; stale comments
CloseRequest.AutoCloseMolecule and CloseCompletedMoleculeInTx now say what
changed when the auto-close moved into the close's transaction: a root
close the close policy refuses still leaves the root open and is reported,
but any other failure (a storage error, a lost race on the root's revision)
fails the step's close with it, where the CLI used to close the root
afterwards and only warn.
Stale: the advanceMolecule vocabulary entry said the client composes the
stepper over its own roles when unserved (it refuses before dialing), and
the graph-create collision probe called itself best-effort by transport
(the http GetIssue miss is storage.ErrNotFound like every other store's).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* docs(changelog): the molecule tokens and the S16/S19 behaviours
Entries for issues.close.autoCloseMolecule and issues.advanceMolecule, the
issueops molecule entries, the auto-close inside the step's close (and a
non-policy failure of it failing the close), the real claim behind
close --continue, the molecule reads on every route, the notice and the
up-front --continue refusal against a server without the tokens, and
create --parent / mol reads over http.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(httpclient): regenerate unsupported_gen.go for MoleculeStepper
The PR adds MoleculeStepper() to storage.DoltStorage (200 -> 201
methods). httpclient implements it by hand, but the generated shell's
trailer still counted 200, so
//internal/storage/unsupportedgen:unsupportedgen_test
(TestGeneratedShellIsFresh) failed in Bazel / test and
Bazel / integration, turning CI Gate / Required red.
Regenerated with `go generate ./internal/httpclient`; the only change
is the trailer count (143 of 201 methods generated; 58 left).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(molecule): auto-close refusals, write skew, close --json, docs
Review fixes for #7513, numbered as in each iteration's review
synthesis.
Iteration 1:
F1: a close guard's refusal of the root (TemplateReadOnlyError,
PinnedError, CloseNotAssigneeError) is an auto-close refusal, like the
close policy's: the root stays open and is reported, and the step's
close stands. Pinned by the new conformance case
RunMoleculeGuardedRootKeepsTheStepClose on dolt, embedded, uow and the
served http client.
F2: two closes that finish a molecule's last two steps in concurrent
transactions each read the other's step as open, so neither closed the
root and both committed. Every auto-close now rewrites the root's
coordination cell before it decides the root (local_metadata
molecule-coordination/v1/<shard>, the dependency coordination idiom and
sharding with a FreshRowLock value), in both twins
(CloseCompletedMoleculesInTx and CloseCompletedMoleculesInUOW). Two
deciders of one root now conflict at commit (1213), and the retry reads
the winner's close and closes the root. This is the synthesis's option
(c), applied through a coordination cell instead of the root row; it
needs no post-commit second transaction and no engine lock. The
deterministic two-transaction regression fails without the touch and
passes with it on dolt and uow; the concurrent-close tests end with the
root closed in every round, reported by exactly one close.
F3: the auto-close checks the root's eligibility before walking any
step, MoleculeStepsClosed stops at the first open step, and a batch
decides each root once and reports it on the first item under it.
F4: ErrVersionMismatch on the root is not a refusal; it fails the
step's close with it. The classifier unit test pins this. A conformance
case cannot stage that race deterministically through the public roles.
F5: storage.ServesMoleculeAdvance answers (bool, error), and bd close
--continue refuses before closing anything when the handshake cannot be
read.
F6: the CHANGELOG and the stepper and batch-closer doc comments say
what the code does.
F7: the unserved-auto-close notice fires only when the close left an
auto-closing molecule with every step closed and its root open
(issueops.CompletedMolecule): again on a re-close, once per root in a
batch, never for a step under an ordinary epic or an unfinished
molecule. Proxied mol show, mol current and mol progress again report a
read unit of work that cannot be opened as itself, not as a molecule
that was not found.
F8: the write-ledger comment says the close is refused before dialing.
The dead FirstClosed/LastClosed guards in mol progress pre-exist on main
and are left as they are.
Iteration 2:
F1: on the proxied route, bd ready --mol reported a read unit
of work it could not open twice: once as itself, then as "molecule
'<id>' not found", which under --json is a second error document on
stdout. It now returns moleculeNotResolved, as mol show, mol current and
mol progress do. TestProxiedReadyMolReportsAnUnopenableReadOnce drives
runMoleculeReady with a provider whose NewUOW fails and wants one Error:
line, or one JSON document; both subtests fail with the old return.
F2: the coordination cell serializes every concurrent close of a step
under an open auto-closing root, not only the closes that finish the
molecule. That is the price of deciding the root in the step's
transaction, so it is documented (TouchMoleculeCoordinationInTx, the
UOW twin, CloseRequest.AutoCloseMolecule, the CHANGELOG) and pinned on
dolt and uow: two sibling closes with a third step still open conflict
(both commit when the touch is removed, on either twin), and a six-step
fan-out closes every step through the store's retry, with the root
closed and reported by exactly one close. The synthesis's alternative,
a post-commit recheck by any close that read a step open, is not taken:
it is a second, best-effort transaction after the step's commit, the
shape this PR exists to remove.
F3: MoleculeRootClose's doc no longer promises that a step reopened
between the completion read and the root close fails the step's close.
The guard is the root's RowVersion, which a step reopen never writes;
the doc now says what the guard covers and that this race goes
undetected (it is inherited from the CLI's old post-commit auto-close).
F4: the user docs describe the auto-close. docs/workflows/molecules.md
replaces "Closing the last child does not close the molecule root"
with which roots close and which stay open, the refusal warning, the
unserved-server note and the --json members, and documents the claiming
--continue and parent-child step membership;
docs/reference/json-schema.md gains a bd close --json section. These
are main-only behaviors on pages pinned to v1.2.2 (docs/cli-docs.pin):
a maintainer call against §1 of
engdocs/decisions/2026-07-17-docs-release-pin.md, as in #6508, #5855,
#5997 and #5092. The auto-close itself shipped in v1.2.2
(cmd/bd/close.go autoCloseCompletedMolecule), so the old sentence was
already wrong at the pin. docs/cli-reference/ is generated from the
pinned release and is not hand-edited; the bd close and bd mol show
help texts carry the same facts and reach it at the next pin bump.
F5: bd close --json reports the auto-close. The entry of a close that
completed a molecule gains auto_closed_molecule (the root it closed) or
molecule_auto_close_refusal (why the root stayed open), the HTTP API's
names, on the direct, proxied and --if-revision routes. The members sit
beside the issue's own rather than wrapping the output in an object the
way --suggest-next does: an object would change the output's shape
exactly when a close completes a molecule and break every consumer that
reads an array, while members leave each entry decoding as the closed
issue, compose with `closed` under the flag objects, and leave a plain
close's bytes unchanged. Pinned on the embedded and proxied tiers
(TestEmbeddedCloseJSONReportsMoleculeAutoClose, TestProxiedServerClose2B
json_reports_*, and both --if-revision replay tests), all red without
the change.
F6: cmd/bd's BeadsTemplateLabel is issueops.MoleculeTemplateLabel, so
the template commands and molecule membership cannot drift apart.
F7: the UOW twin's revision probe says that it writes nothing,
and the BatchCloseRequest.auto_close_molecule spec description has its
verb back (apigen regenerated, no drift).
Iteration 3:
F1: on the unit-of-work route (bd serve, the proxied CLI), a refused
root's molecule_auto_close_refusal and warning carried the use case's
and repository's wrapping ("close <id>: db:
IssueSQLRepository.CloseChecked <id>: ...") around the refusal, where
the tx twin and the docs give the refusal alone. Both twins now report
it through RefusedMoleculeAutoClose, which answers the refusing guard's
or policy's own sentence. RunMoleculeRefusedRootKeepsTheStepClose,
RunMoleculeGuardedRootKeepsTheStepClose and the embedded and proxied
close --json tests want that exact sentence; the uow conformance leg
and the proxied test fail without the unwrap.
F2: the docs no longer promise ErrVersionMismatch for a write to the
root that races its auto-close. The root's read and its revision check
share one transaction snapshot, so that write conflicts with the root
close at commit and the retry decides the root again; the close fails
only if it still conflicts when its retry budget runs out
(MoleculeRootClose, IsMoleculeAutoCloseRefusal,
CloseRequest.AutoCloseMolecule, the tx twin's comment, the CHANGELOG
and the OpenAPI description, apigen regenerated).
F3: TestEmbeddedCloseJSONReportsMoleculeAutoClose moves above
TestEmbeddedCloseConcurrent's doc comment, which documents its own test
again.
F4: bd mol progress counting direct steps while the auto-close counts
every descendant predates this PR; it is left for a follow-up.
F5: cmd/bd's molReader drops GetMoleculeProgress, which nothing called
once mol progress read through issueops.ReadMoleculeProgress.
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: Claude Opus 5.5 <noreply@anthropic.com>
* fix(schema,uow): route the proxied data-behind open to the #6575 stop with topology-correct guidance (port of #6695)
Port of the release/1.3.x commit bb03a310a9 (PR #6695) to main, where it
never landed: v1.3.1 is cut from a release branch that is not an ancestor
of main.
The proxied / `bd serve` open path never reached the #6575 data-behind
stop. doltSQLProvider.initSchemaAttempt passed a nil adopter to
CheckSharedStoreMigrateGate, so localDataBehind short-circuited and the
router could never emit smartDataBehind. A proxied store that was level
on schema and behind in data reported `shared-store` instead, whose body
is the designated-migrator recipe -- `bd migrate --force` then
`bd dolt push` -- which in that state is exactly the #6368 wedge the
stop exists to prevent. The refusal was always safe (the shared arm
suppresses the auto-migrate either way); the guidance was not.
- uow: wire a dataBehindAdopter with AheadBehind only
(versioncontrolops.LocalAheadBehind). IsStrictAncestor/WorkingSetClean
stay nil so the remote-ahead arm keeps its plain adopt directive, and
FastForward stays nil because it would promote the schema for every
co-resident client. Read-only proxied opens print the pull-first block
instead of the shared-consent template.
- uow.WithProxiedServerMode(), set only by openProxiedServerUOWProvider,
marks the refusal Proxied: the same provider serves `bd serve` on a
SERVER-mode workspace, where `bd dolt pull` works.
- schema: a Proxied refusal names the server host as where the pull runs
(`bd dolt pull` is refused at the proxied front door,
proxy.dolt_pull.unsupported), the option id becomes
pull-first-on-server-host, and the guidance says the forced
`bd migrate schema --force` consent step IS runnable from the proxied
workspace (the capability registry permits `migrate schema`), so it must
wait for the pull, and that BD_ALLOW_REMOTE_MIGRATE=1 is reachable too.
- cmd/bd: the --json `expected` field carries the same location
qualifier (dataBehindExpectedField).
Not ported, because main already has it: the release PR's F-B half (the
shared data-behind consent step naming `bd migrate schema --force` and
its --global twin, the printGlobalDatabaseConsentHint retarget, and the
shared_migrate_consent_test.go changes) landed on main as #6692.
Adapted to main: the release line's proxyMaintenanceRefusals table is
main's capability registry, so TestProxyMaintenanceAllowsTheSharedConsentVerb
drives validateProxyRegistryBeforeProvider for every proxied topology and
also pins that `bd dolt pull` and the bare `bd migrate` are refused; the
CHANGELOG paragraph is appended to main's existing #6575 entry.
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* docs(upgrading): where the proxied data-behind pull runs; pin its plumbing
Review fixes for the proxied data-behind stop: the one major of review
attempt 1, the cheap minors, and the nit, plus the wording minor of
attempt 2.
- Clone behind the remote, the docs section the gate's payload links
to, prescribed `bd dolt pull` with no topology qualifier: the remedy a
proxied-server workspace refuses at its front door. Its intro now says
so, and a proxied-server step pair puts the pull (and any conflict
resolution) on the server host, from a workspace with direct database
access, then `bd migrate schema --force` in the proxied workspace. It
also warns that nothing there enforces that order: `--force` and
BD_ALLOW_REMOTE_MIGRATE=1 are honored before the stop is reached, so
the stop never sees them. The warning ends on the payload's own
instruction, not to reach for either to get past the stop, rather than
a negation ("neither is a way past it") that read as the topology
blocking the wedge. The pending-migration exception above the section,
the proxied-server list under Shared servers (now three differences)
and the init-safety ordering rule say the same. The heading, and with
it the anchor the gate links, is unchanged.
- The option plumbing that carries the fix is pinned link by link.
TestApplyProviderOptions covers WithProxiedServerMode (it sets that
field and no open posture). The cmd/bd append moves into
proxiedProviderOptions, which TestProxiedProviderOptions holds to
exactly one added option on a fresh slice. And
TestNewDoltServerUOWProvider_CarriesProxiedServerMode opens two real
providers on one server, with and without the option, and reads the
field the gate copies; openAndInitSchema's provider literal and the
shared test open helpers are left as they were.
- TestProxyMaintenanceAllowsTheSharedConsentVerb also pins `bd dolt
push` and `bd conflicts resolve` as refused, the rest of the list the
proxied refusal body recites. `dolt push` is refused as unimplemented,
the kind of row that flips to allowed once a route lands.
- localDataBehind's doc comment is re-wrapped so the IsStrictAncestor
sentence no longer breaks across the inserted parenthetical.
- The CHANGELOG entry notes the docs change.
Each new pin is red with its link reverted: the option dropped from the
cmd/bd append, the append made in place, the field copy deleted from
the provider literal, the constructor dropping its options, the option
also setting preview, and the push and conflicts codes changed. Still
unpinned: which option the cmd/bd append adds (options are opaque
outside uow) and that `bd serve`'s server-mode open passes none; both
need a seam in cmd/bd.
Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
* fix(gate): resolve a bead gate whose awaited bead no longer exists (wy-dgfuiu)
A gate with await_type=bead whose awaited bead has been purged could never
resolve: GetIssue returns storage.ErrNotFound (or a wrapped sql.ErrNoRows)
against real storage, checkBeadGate returned (false, "bead gate %q: %v"), the
bead arm of evaluateGates never sets r.err, and applyGateCheckResults fell to
the "pending" arm with exit 0. The gate stayed pending forever.
Treat a missing bead as resolution, reusing the existing gateProxiedNotFound
predicate so a genuine backend or transport failure still stays pending.
close.go shares checkBeadGate and inherits the fix.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MjQHZQoR8qZTaNj2QTZokr
* fix(gate): resolve a deleted bead gate target only after a local sighting
Review fixes for #6395 (adopt-pr iterations 1 to 5).
The PR resolves a bead gate when its awaited bead no longer exists, but
the lookups it relies on turned a routing failure into not-found: the
direct getter (getIssueWithRouting) and the proxied getter both returned
the local miss when a prefix-routed rig could not be read, so an OPEN
bead in an unreachable rig resolved its gate and unblocked the step. An
await_id that never named a real bead (a typo, a short ID) also resolved
on the first check.
- A miss outside this rig's own store is errBeadGateTargetUnconfirmed: a
matched routes.jsonl route whose rig fails or does not return the bead,
an unreadable routes.jsonl, or the contributor auto-routed store. The
gate stays pending and the reason names the cause. inspectBeadGate
tests it before not-found, because the wrapped routing error can itself
be a not-found. Only this rig's own absence counts as gone.
- bd gate check resolves a gone target only if an earlier check saw it in
this rig. The first local sighting stamps await_seen=<await_id> in the
gate's metadata (an OpSetMetadata merge, so other keys survive, and
retargeting the gate invalidates it). A target that is gone and was
never seen stays pending with "no earlier gate check saw it; check the
await_id, or close the gate with bd gate resolve". A bead read through
a route is never stamped, so a misdirected route cannot arm a later
local miss. A failed stamp write is an error row, like a failed gh:run
await_id persist.
- The proxied getter reads the target with workapi.GetIssueOrWisp (the
issue use case alone never returns a wisp), stamps inside the apply
transaction, and never auto-routes.
- bd close applies the same rule (evaluateBeadGate, recording no
sighting): a gone bead satisfies the gate only if an earlier check saw
it, so closing a gate on a typo'd await_id still needs --force.
- bd close reads the awaited bead from the store that owns the gate
(RoutedResult.Store), as bd gate check in that rig would. Read from the
launcher's store, a routed gate whose awaited bead only its own rig can
reach (no route for it from the launcher) saw that open bead as missing
and, its sighting recorded, closed without --force. The proxied-server
route keeps the fresh-read getter (#5861).
- bd rename and bd rename-prefix (both the rename loop and --repair) point
a bead gate at its bead's new ID, keeping a <rig>: prefix and carrying
the sighting. UpdateIssueID rewrites text references but never
await_id, so a seen bead's rename read as a deletion and resolved the
gate on its next check.
- UpdateIssueID also commits on its own, so a retarget written after it
left a window, or after a failure a lasting state, where the gate held
a sighting of an ID that no longer existed and resolved while its bead
was open under the new ID. All three paths now rename through
renameIssueKeepingBeadGates, which orders the writes so no state in
between resolves a gate: it moves await_id to the new ID while the
sighting still names the old one (dropping, in the same write, a
sighting that already names the new ID), renames the bead, and then
records the sighting under the new ID. A check in between finds a
never-seen ID and stays pending. If moving a gate or renaming the bead
fails, the gates are pointed back at the old ID without a sighting,
since a failed write may still have landed, and the rename fails:
bd rename exits non-zero instead of warning from its text-reference
loop. Losing only the final sighting write is a warning; the next
check records the sighting again.
- A check lists the gate before it looks the bead up, so a rename landing
in between left it holding a copy that still waited on the old ID with
its sighting: the old ID was gone, and the check closed the gate while
the bead was open under its new ID. Once the bead is found gone,
evaluateBeadGate reads the gate back from its own store
(rereadBeadGate) and resolves only if the stored gate still waits on
the same await_id and still records the sighting. The rename moves the
gate before the bead takes the new ID, so a read made after the miss
sees the move. This covers bd gate check, its proxied route and
bd close; a gate that cannot be read back, or is found only through a
route, stays pending.
- checkBeadGate, the target lookup without the sighting rule, had no
production caller left and read like the bead-gate rule, which is how
bd close came to skip the sighting. It moves into the tests;
inspectBeadGate carries the lookup contract and points callers at
evaluateBeadGate.
- The gate check help, docs/workflows/gates.md and the CHANGELOG describe
the rule, including that a rename does not read as a deletion to a
check or bd close that read the gate before it, and that a rename that
fails partway leaves the gate pending without a sighting; the #6404
entry no longer says a routed read failure reads as not-found. The
CHANGELOG also warns that a rename by an older bd does not move the
gate, so once a check has seen the bead, the next check or bd close
after that rename closes the gate while the bead is still open:
upgrade the clients that rename beads together with the ones that
check gates. docs/cli-reference is pinned to v1.2.2, so it is
unchanged (generate-cli-docs.sh --check passes).
Tests: TestCheckBeadGate_UnconfirmedMissStaysPending,
TestEvaluateGates_BeadGateSightingRule, TestEvaluateBeadGate_*,
TestBeadGateSeenUpdate_KeepsOtherMetadata, TestBeadGateTargetSeen,
TestProxiedFreshReadGetter_LocalMissFollowsRoutes,
TestRoutedBeadGateGetter_ReportsWhereTheAnswerCameFrom,
TestCheckGateSatisfaction_BeadGateNeedsASighting,
TestCloseDirectPreflight_BeadGateReadsTheGatesOwnStore,
TestCloseBeadGateGetter_RouteSelection, TestBeadGateRetargetUpdate,
TestPlanBeadGateMoves, TestRenameIssueKeepingBeadGates and
TestRenameIssueKeepingBeadGates_FailedWritesResolveNoGate, which fails
each write of a rename in turn, landed or not, and evaluates every gate
after each write, both as stored and as a concurrent check listed it
before the rename (unit); the unreadable-rig step of
TestCheckBeadGateCrossRigPrefixRoute,
TestRepairPrefixesRetargetsBeadGates (gates renamed before and after
their bead) and TestRenameFailureLeavesBeadGatesPending (bd rename,
--repair and rename-prefix with a failing UpdateIssueID, landed or not)
(cgo);
TestEmbeddedGateCreate/check_bead_gate_resolves_only_a_missing_target_it_saw
and /rename_keeps_a_bead_gate_on_its_target (embedded);
TestProxiedServerGateCheck/bead_gate_resolves_when_seen_target_is_deleted
and /bead_gate_never_seen_target_stays_pending (proxied). Reordering the
unconfirmed case after not-found, dropping the sighting condition,
swallowing the routed error, stamping routed sightings, or matching any
stamp regardless of await_id each fails these tests, as do closing with
the sighting-blind lookup, reading the launcher's store on close,
dropping the carried sighting or the rig prefix on a retarget, dropping
the retarget from bd rename, the rename-prefix loop or --repair,
renaming the bead before moving its gates, keeping the sighting when
moving a gate back, keeping a stale sighting of the new ID, skipping
the final sighting write, resolving a gone bead without reading the gate
back or from a gate read back that moved, lost its sighting or was found
only through a route, or reporting an unconfirmed read-back as an error
or an unreadable gate as pending.
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: Claude Fable 5.1 <noreply@anthropic.com>
Co-authored-by: Eddie the Engineer <adopt-pr@gascity.com>
* wy-j2upyy: render the derived GATED decoration on bd show and bd list
A bead an open gate blocks is excluded from `bd ready` but rendered
`[P2 · OPEN]` by `bd show` and with a plain ○ by `bd list`, so the human
surfaces disagreed with the readiness query.
The decoration is DERIVED, never stored: no status write, no --status
filter change, no existing JSON field reshaped.
- internal/types/gated.go: IsActiveGate, the ONE predicate — a gate-typed
dependency reached over a blocking edge (blocks / conditional-blocks /
waits-for) whose status is neither closed nor pinned. That is the
is_blocked recompute's blocking leg restricted to gates, so a rendered
GATED and a `bd ready` exclusion cannot disagree. GateDescription /
GateReason own the reason's round trip with `bd gate create`.
- bd show: `[P2 · OPEN · GATED]` plus one `Gated by: <id> (<type>[:
<reason>][, awaiting <await-id>])` line per gate, beside Deferred:. The
dependency read the DEPENDS ON section already made is hoisted, so the
decoration costs no extra query.
- bd list: ⊘ in the glyph column (circle family, distinct from ○ and ❄),
and a legend entry when the page carries one. Batched by id set —
at most two extra queries per listing, one in the tree view where the
edge map is already loaded.
- --json: additive `gated_by: [{id,type,reason}]` on the detail view,
omitted when empty; documented in the OpenAPI IssueDetails schema.
Tests (red first): cmd/bd/gated_render_embedded_test.go drives real
bd show/list/--json over an embedded rig — gated, resolved, deferred+gated,
JSON additivity — plus pure unit tests for the predicate and formatters.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* wy-j2upyy: document the additive gated_by field in the JSON schema reference
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* wy-j2upyy: cover the flat list route's own batched gate read
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* wy-j2upyy: make GATED the readiness rule's gate clause, both halves
The adversarial review found the "one predicate shared with bd ready" claim
false on two axes, and both were reproducible by hand:
BLOCKER 1 — waits-for is not the status rule. The is_blocked recompute applies
"target not closed and not pinned" only to its blocks / conditional-blocks
legs; the waits-for leg goes through waitsForGateBlockedSQL, a fanout over the
target's open parent-child children (or an also_blocks spawner). A plain
`bd dep add X G -t waits-for` onto an open childless gate therefore leaves X
in `bd ready` while every new surface called it GATED. Mirroring that leg in
Go would be a second implementation of a rule the database owns, so the edge
clause now names the two legs it really mirrors (types.IsGateEdge) and the
test that pinned the wrong direction is flipped.
BLOCKER 2 — the subject half was missing and spelled three different ways.
unmarkAllBlockedSQL forces is_blocked=0 for a closed or pinned subject
whatever its edges say, so `bd ready` never withholds one on a gate's account;
show and workapi filtered nothing, cmd/bd/gated.go filtered closed only, and
list_format.go filtered closed at two more sites. A force-closed bead rendered
[CLOSED · GATED] with gated_by on show while list showed a plain row — show
and list disagreeing about one bead, which is the drift this was meant to
prevent. The clause is now types.SubjectCanBeGated, asked once in
types.GatesHolding (which replaces ActiveGates and takes the subject) and once
in the listing helper that has no hydrated deps; the formatters re-ask the SAME
exported predicate rather than inventing a fourth spelling.
SHOULD 3 — agent mode computed the gate reads and threw them away, in every
CLAUDE_CODE seat, i.e. the population that filed the bug. Decorating it is the
real fix, so gatesByIssueID now returns the gate IDS and formatAgentIssue
carries "gated by: <id>" in the parenthetical it already prints. A gate is
also a blocker, so its id appears under both "blocked by" and "gated by": the
first says what to wait on, the second says which of those nobody can clear by
doing more work. --long and --format render no gate and no longer pay for the
reads.
NOTE 5 — a pinned+gated row kept ⊘ instead of 📌; with the subject clause a
pinned bead is not gated at all, so the pin survives by construction.
NOTE 6 — the cost comments claimed "two queries" / "exactly ONE"; the id-set
readers are a few round trips each. The bound that is real (per page, never
per row) is what the comments now say.
Tests, red-first: the flipped waits-for case; TestGatesHoldingSubjectStatus and
TestSubjectCanBeGated (open/in_progress/deferred yes, closed/pinned/nil no);
TestFormatIssueCompactGated and TestFormatAgentIssueGated; and four embedded
arms — a waits-for edge that bd ready lists and no surface decorates, a
force-closed subject and a pinned subject that render nothing and publish no
gated_by, and the agent line naming its gate. Each was watched to fail against
the pre-fix predicate before it passed.
Ran: go test ./internal/types/ -run 'TestGateIsHolding|TestGatesHolding|
TestSubjectCanBeGated|TestGateDescriptionRoundTrip|TestGateRefsProjection';
go test ./cmd/bd/ -run 'TestFormat*Gated|TestFormatIssueCompact*|
TestFormatDependencyInfoWithParent|TestListRoles*|TestDisplayPrettyList*';
BEADS_TEST_EMBEDDED_DOLT=1 go test ./cmd/bd/ -run TestEmbeddedGatedRendering
(11/11 subtests); gofmt -l (empty), go vet and golangci-lint on cmd/bd,
internal/types, internal/ui, internal/workapi; scripts/ci/pr-policy.sh.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* wy-j2upyy: render GATED on the proxied `bd show` text route
SHOULD 4 of the review, and required for this rig: the constellation runs
proxied-server, where `bd show --json` already carried gated_by (uow
issue_reader -> workapi.BuildIssueDetails) while the TEXT renderer called the
plain formatters. The same bead read two ways from the same server disagreed.
proxiedRenderIssue now hoists the outgoing-edge read it already did for the
DEPENDS ON section above the header — the gates are the gate-typed subset of
that very set, so the decoration costs no extra query — and passes them to
formatIssueHeaderWithGates / formatIssueMetadataWithGates. The proxied LIST
routes were wired in the previous commit.
TestProxiedServerGatedRendering covers all five text surfaces plus the JSON
one beside them (header + Gated by line, pretty glyph, compact glyph + "gated
by", agent line, and a closed subject that renders nothing). Watched red first
with the proxied decoration stubbed out: four of six subtests failed, and the
--json arm passed, which is exactly the asymmetry the review reported.
Ran: BEADS_TEST_PROXIED_SERVER=1 go test ./cmd/bd/
-run TestProxiedServerGatedRendering -count=1 (6/6, 37.8s).
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* wy-j2upyy: put cmd/bd/state.go on the shared "Reason:" marker
NOTE 7 of the review: types' gateReasonMarker was not gate-private —
cmd/bd/state.go wrote the same "\n\nReason: " into state-change EVENT
descriptions from its own literal. No live collision (events are not
gate-typed), but the constant's doc claimed GateReason returns "" for every
gate not made by `bd gate create`, and that is false for any description
carrying the marker.
The previous commit exported the constant as types.ReasonMarker, reworded
GateReason to say what the pair really guarantees (a round trip, not a
provenance check) and pinned the honest behavior in
TestGateDescriptionRoundTrip. This commit is the second writer: state.go now
builds its event description from the same constant, so the two cannot drift
apart by accident.
Ran: go build ./...; go test ./internal/types/ -run TestGateDescriptionRoundTrip
-count=1; gofmt -l cmd/bd/state.go (empty); go vet ./cmd/bd/.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* wy-j2upyy: alias types.GateRef in package backend
gated_by on IssueDetails makes GateRef reachable from the public backend
contract; TestPublicSurfaceComplete requires every such type to carry an
alias here.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
* wy-j2upyy: build(bazel): register gated.go and its tests in cmd/bd and internal/types
The rebase onto e766da5ed carried the new source files but not their
BUILD.bazel entries, so every Bazel lane failed to compile internal/types
(undefined: GateRef). This is CI's own bazel-sync patch for 9ad7eb96c3,
applied unchanged.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
* wy-j2upyy: compute gated_by AFTER the dependencies read in BuildIssueDetails
The be-lpi merge (#6352) moved src.Dependencies() below the cardinality
counts so the unresolvable-edge delta reads count-first. That hunk merged
cleanly, which left details.GatedBy computed on the still-nil slice, and
both CI shards' show_json…carries_gated_by subtests went red (PR Risk
Embedded Dolt Cmd 20/20, Proxied Dolt Cmd 4/15 at d21237f3dc).
Move the GatedBy line to directly after details.Dependencies = deps, still
before the BriefDeps trim that rewrites the slice, and pin the ordering with
a workapi unit test over both DetailSource seams and BriefDeps on/off (red
on the pre-fix code, green after).
Ran: go test ./internal/workapi; go vet ./internal/workapi;
BEADS_TEST_EMBEDDED_DOLT=1 go test ./cmd/bd -run TestEmbeddedGatedRendering;
BEADS_TEST_PROXIED_SERVER=1 go test ./cmd/bd -run TestProxiedServerGatedRendering.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
* ci: register #6606's gated-rendering tests and gated_by wire shape with main's generated gates
Maintainer fixup for adopt-pr #6606. The adopted head merges the PR head
(c43eb567d2) into main (800d43eb8d). The PR's merge-base (02f05340f6)
predates three generated artifacts on main that every PR adding a cmd/bd
tier test or a wire member has to keep current, so the merged tree is red
on them even though the PR's own CI cannot see them:
- .github/scripts/embedded-cmd-test-shards.txt: the Bazel-only 50-shard
block must name every TestEmbedded* test exactly once, or
TestCmdEmbeddedShardManifestGeneratorNotStale fails `go test ./scripts/`.
`gen_embedded_cmd_shard_manifest.py 50 --weights=duration --write`
(incremental) placed TestEmbeddedGatedRendering on shard 16 and moved
no existing assignment; the frozen 20-shard block is untouched.
- .github/scripts/proxied-cmd-test-shards.txt: likewise for the 30-shard
block and TestProxiedServerGatedRendering (shard 2), via
`gen_proxied_shard_manifest.py 30 --weights=duration --write`, so
TestProxiedShardManifestGeneratorNotStale passes.
- internal/httpapi/wireshape/testdata/golden.json: TestWireShapeDigest
(#7182) pins every response member. `go run
./internal/httpapi/wireshape/cmd/gendigest` recorded the PR's new
IssueDetails.gated_by array and its id/type/reason members as four pure
additions (+25/-0), so no wire_revision bump is owed.
The PR's own files are unchanged.
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(gated): state gated_by one way, mark --watch as undecorated, fix stale refs
Review follow-ups for #6606. Comment and doc text only; no behavior change.
- gated_by is now documented in one direction. internal/types/types.go,
internal/types/gated.go and docs/reference/json-schema.md said the list
is nonempty EXACTLY when `bd ready` withholds the issue on a gate's
account. Only one direction holds: the is_blocked recompute also blocks
a child whose parent is blocked (its parent-child legs), so a child of a
gated parent leaves `bd ready` with an empty gated_by. All three now say
"nonempty means withheld", as the OpenAPI text already did, and name the
parent-child case.
- bd list --watch passes a nil gated map on both routes
(runListProxiedWatch, displayWatchedIssueList), so a bead the one-shot
listing marks with the gated glyph keeps its plain status glyph while
watched. Watch is out of this PR's scope; the three call sites now say
so instead of reading as a forgotten argument.
- show_format.go named types.ActiveGates, which does not exist; the
predicate is types.GatesHolding.
- gated.go's best-effort note compared the gate read with `bd list`'s
blocking annotation, which only the direct route swallows. It now scopes
that comparison to the direct route and names the proxied route's
failing read (A-blk-1).
- proxiedGatedIssueIDsOwnUOW now notes that its unit of work is a second
snapshot, so one render can name a just-resolved gate under "blocked by:"
but not "gated by:".
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>
* fix(list): hydrate proxied gate candidates from both planes (bd-p8k7dm)
The proxied list resolved gate candidates through the use case's
GetIssuesByIDs, which reads the issues table only, while the edges it
resolved came from GetForIssueIDs, which reads both dependency tables.
A wisp gate (`bd mol wisp` clones a formula's gates as wisps, held to a
wisp step by a blocks edge) therefore hydrated to nothing. Its step
listed undecorated in pretty, --flat and agent output while `bd show`,
`--json` and `bd ready` called it gated.
Read the wisps beside the issues, the two-plane idiom
ready_proxied_server.go and uowMolReader already use. A failed wisps
read keeps the durable candidates. Correct the cost-bound comment that
claimed the id-set readers partition the planes on both routes.
Tests: a wisp-step + wisp-gate case in TestProxiedServerGatedRendering
and TestEmbeddedGatedRendering asserts the pretty, --flat and
CLAUDE_CODE=1 rows of `bd list --include-ephemeral`, and
TestProxiedGatedIssueIDsHydratesBothPlanes pins both planes plus the
failed-wisps-read fallback.
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: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-authored-by: Eddie the Engineer <adopt-pr@gascity.com>
* feat(schema): never migrate an existing database without explicit consent (bd-qhn8y)
Beads 1.2 release remediation. 1.2.0/1.2.1 auto-applied migrations 54-65 at
store open on ANY command, including reads; older binaries then refuse the
migrated database. MigrateUp now refuses pending main-sequence migrations on
an existing database before any write (dolt_ignore seeding included) unless
the operator consented: bd migrate / bd migrate schema (preview flags
withhold), bd migrate --force, or BD_ALLOW_MIGRATE=1
(BD_ALLOW_REMOTE_MIGRATE honored as an alias). Fresh init and at-latest
databases are unaffected; the #4259 remote gate keeps all its protections.
Also: freeze shipped migrations (hash-pin test, main 0001-0065 + ignored
0001-0024), retract v1.2.0/v1.2.1 in go.mod, agent-executable un-migrate
runbook (docs/recovery/unmigrate-schema-v65.md), and the upgrade smoke +
historical migration harnesses now model the consent contract and assert
the refusal carries guidance.
No version bump here by design: cutting the release stays with the release
owner.
Rebased onto main 800d43eb8d: the go.mod retract hunk is dropped -
main already retracts v1.2.0/v1.2.1 (and v1.1.1) since #5782. The
uow consent grant moves into the TestMain main added in #6441 (a
second TestMain no longer compiles), and the new files are listed
in the BUILD.bazel targets main now carries (gazelle).
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* fix(schema): cloned-workspace bootstrap carries creation-consent (bd-qhn8y)
The consent gate treated a workspace `bd init --remote` / `bd bootstrap`
just cloned into existence like a pre-existing database, refusing the
smart gate's provably-safe first-mover migration and stranding init in
the generic open-error path (bypassing the bd-4mpy7 finalize+guidance
ergonomics). Cloning IS creating: those paths now record consent
explicitly, and the #4259 remote-migrate gate still applies to them
unchanged (consent is not its designated-migrator override). Fixes CI
TestEmbeddedInit/remote_behind_schema_gate.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* test(migration): consent first in main's wisp lanes too (bd-qhn8y)
The rebase onto 800d43eb8d brought in #6049's wisp-plane lanes, which
postdate this PR's harness changes. Each one makes an ordinary candidate
command the first touch on an old-schema database, and the consent gate
refuses it:
- historical-dolt-upgrade-test.sh run_wisp_plane_upgrade opens with
`bd list` before any migrate: "candidate could not open the seeded
wisp workspace" for v1.0.1, v1.1.0, v1.1.2 and v1.2.2 (the
Migration Test Harness dolt-runtime shard).
- run_dirty_tracked_wisp_scenario (v1.1.2): the consent refusal stops
the open before MigrateUp reaches the #5816 dirty tables, so the lane
fails "without naming them".
- upgrade-smoke-test.sh "Wisp plane survives upgrade" upgrades with a
bare cand_init, so list/ready/blocked/update all hit the refusal
(4 failures each for v1.3.0 and v1.3.1, both in the PR smoke set).
Use the PR's own pattern: the explicit `bd migrate schema` is the first
candidate touch (cand_upgrade in the smoke script). Base 800d43eb8d
passes these lanes unchanged; with this fixup the full 14-version
historical corpus and all five PR smoke versions pass.
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>
* fix(schema): close consent-gate review findings (bd-qhn8y)
Review fixes for the migration-consent gate (adopt-pr review, attempts
1 and 2).
Majors:
- #4566 deadlock rebuilt one check earlier: on a database that is both
behind and dirty, the consent refusal fired before the dirty-table
guard, whose remedy (`bd dolt commit`) opens without consent. The
working-set-reconcile opens now tolerate MigrateConsentError: embedded
(toleratesConsentRefusal, WSR intent only) and server mode
(LenientOpen's warnLenientOpenRefusal) print WorkingSetWarning and
commit at the current schema; strict, read-only and RemoteSync opens
still refuse. Covered by an embedded test (a refused open writes
nothing: dolt_status, dolt_ignore and schema_migrations unchanged) and
a server-mode integration subtest.
- Bare `bd migrate` consented: isMigrateConsentCommand now matches only
the schema verb, so `bd migrate` (metadata reconcile, including
--update-repo-id, --inspect and --dry-run) no longer consents to a
one-way migration; `bd migrate schema` and --force do.
TestLocalMigrateConsentScope pins the scope through the root pre-run.
The dirty-table warnings name `bd migrate schema` accordingly.
- Runnable JSON hint: the JSON refusal follows the #4259 AgentDirective
convention, a non-runnable hint plus a migrate_consent object
(versions, pending, severity, human_decision_required, options) whose
commands are retargeted with --global for the shared global database.
The text refusal prints the same --global hint under `bd --global`.
- Freeze floor: the hash-pinned freeze now covers what v1.3.x shipped,
main 0001-0066 and ignored 0001-0026; the CHANGELOG puts new
migrations in 0070+ / 0028+.
- Fresh-bootstrap heal: MigrateUpWithLock with heal authority takes the
consent-free migrate path, so a retried bd init whose first pass left
a non-zero cursor converges; other lock callers keep the gate.
Minors: the uow team-server guards are repinned on `bd migrate schema`;
the un-migrate runbook is linked from the recovery index and
cross-linked with the 1.2.1 repair-forward doc; the CHANGELOG BREAKING
entry matches the shipped contract; harness comment grammar.
Docs: the user docs and README named bare `bd migrate` as the step that
applies schema migrations; they now say `bd migrate schema`, which also
exists in the pinned docs release (v1.2.2) and in v1.3.x. The
`bd migrate schema` help no longer claims migrations run automatically
on store open. The Go remedy that sends a remote-gate stop to bare
`bd migrate` for its migrate-or-adopt options is unchanged (pinned by
TestNoticeSharedMigrateRefusalPerDecision).
Upgrade smoke (attempt 2): the consent-gate assertion is graded only when
the old binary left a database. Releases before v1.0 have no
`init --non-interactive`, so prev_init creates nothing there and the
candidate's `bd list` fails with "no beads database found", which has no
consent guidance. Main's Bazel smoke lane (#7331) runs the newest 30
releases, 20 of them pre-1.0, under the required ci-gate; all 20 went red
on the merge. The 10 v1.x releases still take the refusal branch.
Shard manifest (pre-approval CI): the new embedded test
TestEmbeddedMigrateConsent_BehindAndDirtyWorkingSetReconcileRecovers is
listed in the Bazel 15-shard block of embedded-storage-test-shards.txt
(incremental --write; shard 15). Main's ci lane runs
TestStorageEmbeddedShardManifestGeneratorNotStale in //scripts:scripts_test,
which fails on any unlisted top-level embeddeddolt test.
Not addressed (optional): env-only consent docs for embedders, the
unparseable BD_ALLOW_REMOTE_MIGRATE alias hint, and the harness
`|| true` on `cand migrate schema`.
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: Claude Fable 5 <noreply@anthropic.com>
Co-authored-by: Eddie the Engineer <julianknutsen@users.noreply.github.com>
Co-authored-by: Eddie the Engineer <adopt-pr@gascity.com>
The page still described the rules-file-only Cursor setup from before #4649
and the old --remove scope. Rewrite it against what bd installs today:
- project setup: .cursor/rules/beads.mdc, the shared .agents/skills/beads/
skill, and .cursor/hooks.json with sessionStart/preCompact/postToolUse
hooks running `bd cursor-hook <event>` (user entries left alone)
- `bd init` runs the project setup unless --skip-agents/--stealth or bare
- --global: ~/.cursor/hooks.json + ~/.agents/skills/beads/, no rules file
- hook lifecycle: sessionStart injects bd prime; preCompact arms a refresh
marker; postToolUse re-injects once and clears it; markers live in the user
cache dir keyed by conversation_id + workspace root
- --check scope per mode and the exit/hint on a missing piece
- --remove keeps user hooks, deletes hooks.json once only `version` remains,
keeps the skill while the Codex integration still uses it
- a manual hooks.json fallback in the shape bd writes
README.md: `bd init` also installs the Cursor integration, not only
Claude Code and Codex (the default init route in cmd/bd/init.go).
Follow-up to #7268 (bd-gy483w, the README line from bd-erf5vx).
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
* feat(gate): bd gate create --repo names the repository a gh:run/gh:pr gate is checked in
A gh:pr gate for a PR in another repository could only be pointed there
through the blocked issue's metadata.repo; with none, `bd gate check`
resolved the bare number against the current repository and escalated
"pull request not found" on every check, with nothing in the text saying
which repository it had looked in. Five gates armed that way on 2026-10-03
never released after their PRs merged.
- `--repo OWNER/REPO` (or HOST/OWNER/REPO) on `bd gate create`: an
explicit value wins over the inherited one; it goes through the same
validator as metadata.repo (now `validateGitHubRepo`, split out of
`githubRepoFromIssue`); it is refused on human/timer/bead gates, where
nothing would read it. Both create routes call one helper,
`gateMetadataForCreate`, so the flag cannot drift between them.
- The gh:pr not-found escalation reason names the repository the number
was resolved against ("pull request not found: #42 in owner/repo" or
"... in the current repository").
- Help text, docs/workflows/gates.md and the plugin's ASYNC_GATES.md say
when the flag is needed. docs/cli-reference is pinned to the release
and regenerates on its own.
Tests: TestGateMetadataForCreateExplicitRepo, TestCheckGHPRNotFoundNamesTheRepository
(unit); TestEmbeddedGateCreate/create_gate_with_repo + /repo_flag_on_human_gate_is_refused
(embedded); TestProxiedServerGateCreateInheritsRepoMetadata/explicit_repo_flag_wins_over_inherited
(proxied).
Refs ghosttrack/wyvern wy-2jh4v5.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
* fix(gate): keep the create --repo workspace bypass off bd gate create
The root pre-run bypass for `bd create --repo` (GH#3686) matched the leaf
name "create", so `bd gate create --repo` outside a workspace took it: an
OWNER/REPO slug opened a stray ./OWNER/REPO/.beads workspace under the cwd
and failed with "issue not found", and an https:// URL skipped store wiring
and panicked on the nil store. Key the bypass on the command path, as
proxy_capability.go already does; gate create now fails with "no beads
database found" outside a workspace like every other command, and top-level
create --repo (local path and remote URL) still takes the bypass.
Also name the repository in the gh:run not-found escalation, as the gh:pr
one already does. Only stderr with a lowercase "not found" reaches that
arm: real gh reports a missing run as "HTTP 404: Not Found (<api url>)",
which takes the existing error path, and that URL already names the
repository. The match stays case-sensitive because a token without access
to the repository gets the same 404.
Tests: TestEmbeddedCreateRepoFromNonBeadsCwd/gate_create_repo_flag_is_not_a_workspace
(slug and URL forms, built binary run from an empty cwd) and the
cross_repo/current_repo subtests of TestCheckGHRunNotFoundNamesTheRepository
fail with the fixes reverted. Its real_gh_404_names_the_repository subtest
feeds gh's real 404 stderr and fails if the match is widened.
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: Claude Fable 5.1 <noreply@anthropic.com>
Co-authored-by: Eddie the Engineer <julianknutsen@users.noreply.github.com>
* fix(close): verify bead gates on the proxied-server route (wy-j48b3y)
The close pre-check built its bead-gate lookup on the local store, which
the proxied-server route never opens (the root pre-run short-circuits to
uowProvider). So `bd close <gate>` on a bead gate refused with
"no local store available" there even after the awaited bead had closed,
while `bd gate check` resolved the same gate through its fresh-read
getter. Item 1 of #5861.
The pre-check now picks the getter by route: proxied-server reads through
the same proxiedFreshReadGetter gate check uses (local read, then prefix
routes); direct and embedded keep the store-backed routed getter.
Tests: a proxied integration test covers the open-target refusal (which
now names the target's status), the closed-target close, and --force;
against the old code it fails with the exact upstream refusal. A unit
test pins the route selection. Docs and CHANGELOG drop the limitation.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
* ci(shards): list TestProxiedServerCloseBeadGate in the proxied 30-shard manifest
#7129 turned the Bazel 30-shard block of
.github/scripts/proxied-cmd-test-shards.txt into an exact-once coverage
gate (TestProxiedShardManifestGeneratorNotStale in scripts/). This PR's
merge-base predates that gate, so after the rebase onto current main the
gate fails with "missing (1): TestProxiedServerCloseBeadGate", the
proxied integration test this PR adds.
Generated with the gate's own fix command,
`python3 scripts/ci/gen_proxied_shard_manifest.py 30 --weights=duration --write`.
The write is incremental: it puts the one name on the lightest shard (2)
and moves no existing assignment. The frozen 15-shard block is untouched.
Agent-Signature: claude-code-unknown-model-max on behalf of Eddie the Engineer
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
Co-authored-by: Eddie the Engineer <adopt-pr@gascity.com>
* feat(remember): opt-in memories.budget-chars — refuse a write that crosses the corpus budget (wy-2pox7y)
The wheelhouse-side tripwire only REPORTS the memory-corpus size, so the corpus
re-trips red every few days and nothing has ever stopped the write that crossed
the line. This is the stop.
New config key `memories.budget-chars` (integer, default 0 = OFF), wired exactly
like `prime.max-memory-chars`: recognized in cmd/bd/config.go, routed to yaml in
internal/config YamlOnlyKeys (it is read through viper, so a DB-backed write
would be accepted and then never read), validated non-negative at set time, and
documented in docs/reference/configuration.md.
With the budget ON, `bd remember` measures the corpus as the sum over every
memory of len(key)+len(content) — BYTES, the same unit `bd prime`'s
--max-memory-chars counts in — projected to AFTER the write would apply. An
overwrite replaces that key's old content in the sum rather than adding to it,
so a memory near the ceiling can still be edited.
- over budget -> refused, nothing written, exit 1, one line on stderr
- over budget + --force -> written, and the crossing is still announced
- >= 80% and within -> written, then warned
- below 80%, or budget 0 -> silent; with the budget off the corpus is not even
read, so behavior is byte-identical to before
Every line goes to STDERR, so --json output is never corrupted; a --json refusal
additionally gets the normal machine-readable error object on stdout.
The whole decision is one pure function (rememberBudgetVerdict), which is what
lets the branches be pinned without a database.
Tests run (targeted, never ./...):
go build ./... rc 0
go vet ./cmd/bd/ ./internal/config/ rc 0
go test ./cmd/bd/ -run 'Memor|Remember|Prime|Budget' -count=1 rc 0
go test ./internal/config/ -count=1 rc 0
BEADS_TEST_EMBEDDED_DOLT=1 go test ./cmd/bd/ \
-run TestEmbeddedMemoryCorpusBudget -count=1 -v rc 0 (6/6 subtests)
golangci-lint run --config=.golangci.yml --build-tags=gms_pure_go \
./cmd/bd/... ./internal/config/... 0 issues in touched
files (one
pre-existing gosec
G304 in
internal/config/permissions_open_nonlinux.go)
New tests: cmd/bd/memory_budget_pure_test.go (byte unit incl. multibyte,
overwrite delta, budget-off silence, config read + negative clamp, the
at-budget/one-over boundary, --force, the 80% warn band and its edges,
unclamped percentage, single-line contract);
cmd/bd/memory_embedded_test.go TestEmbeddedMemoryCorpusBudget (the same five
spec points end to end against a real embedded-Dolt store, through
`bd config set`, asserting the exact stderr lines, the nonzero exit, and that a
refused write leaves the old content intact);
internal/config/yaml_config_test.go validation + yaml-only routing.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013XmKxqKuXTaKivDiCoBwBV
* fix(remember): one --json refusal line, ceil on the over-budget percentage (wy-2pox7y)
Review fixes on ca9f14d65d. Three items; one review item turned out to be a
false alarm and is recorded here rather than acted on.
- BLOCKER 1 (CLI docs regeneration) — NO CHANGE NEEDED, and that is the
finding. docs/cli-reference/ and docs/CLI_REFERENCE.md are not generated
from this checkout: docs/cli-docs.pin pins them to release tag v1.2.2, and
scripts/generate-cli-docs.sh, check-cli-docs-drift.sh and check-doc-flags.sh
all resolve that pin (resolve-docs-bd.sh) and build bd from the TAG, because
the published docs site describes the latest release, not main's source. No
CI path sets BD_DOCS_IGNORE_PIN. So changing `bd remember`'s help surface on
main cannot move the generated docs, and it did not:
./scripts/generate-cli-docs.sh ran to completion ("Generated CLI docs from:
bd version 1.2.2 (dev)") and left the tree clean — zero diff. The gate is
green at this commit and was green at ca9f14d65d. The --force flag and the
Corpus budget paragraph reach the docs when the pin is bumped at release.
- NIT 1: the --json refusal said the same sentence twice, prose on stderr AND
the envelope on stdout. It now says it ONCE, the way
HandleErrorWithHintRespectJSON does it: --json gets only the stdout
envelope, every other route gets the bare sentence on stderr. New subtest
TestEmbeddedMemoryCorpusBudget/json_refusal_is_said_once asserts a nonzero
exit, EXACTLY one JSON document on stdout (a second Decode must be io.EOF),
the refusal sentence inside the envelope, a stderr with no "memory corpus"
in it, and that the refused write left the old content intact.
- NIT 2: floor arithmetic made the refusal at 201 of 200 read "(100%)" — the
exactly-at-budget value this code deliberately ALLOWS, so the refusal wore
the number of the case it is not. The percentage now CEILINGS over the
budget (101%) and still FLOORS within it. The split is on the VALUE, not on
--force, so one projection cannot report two different percentages
depending on a flag; that is why the forced over-budget line moved too.
TestRememberBudgetVerdictBoundary, TestRememberBudgetVerdictForceWrites and
TestMemoryBudgetLinePercentIsUnclamped updated; the warn band gains a
999-of-1000 case pinning the floor inside the budget, so "100%" can only
ever mean at-budget.
- NIT 5: one comment at the List/Remember seam saying the budget is ADVISORY
and not atomic — the two are separate transactions, so concurrent writers
can both measure inside the budget and both land. No locking.
Nits 3 (primeConfigInt duplication) and 4 were left alone by instruction.
Gates run from the worktree:
go build ./... rc 0
go vet ./cmd/bd/ ./internal/config/ rc 0
go test ./cmd/bd/ -run 'Memor|Remember|Prime|Budget' -count=1 rc 0
go test ./internal/config/ -count=1 rc 0
BEADS_TEST_EMBEDDED_DOLT=1 go test ./cmd/bd/ \
-run TestEmbeddedMemoryCorpusBudget -count=1 -v rc 0 (7/7)
gofmt -l cmd/bd internal/config no output
golangci-lint run ./cmd/bd/ ./internal/config/ 1 issue, all
pre-existing: gosec G304 in internal/config/permissions_open_nonlinux.go
(last touched f4d496fed, not by this branch)
./scripts/check-cli-docs-drift.sh rc 0
./scripts/check-doc-flags.sh rc 0
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JFSKdUYCTyuhBM97tHyoye
* ci: list the PR's tests in the embedded shard manifest and cmd/bd BUILD.bazel
#7156 made the embedded-Dolt shard manifests exact-once, and Bazel equivalence
requires every test file in the go_test srcs. Adds TestEmbeddedMemoryCorpusBudget
(generator output, incremental) and memory_budget_pure_test.go (the line CI's
bazel-sync patch printed).
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
* fix(remember): budget the key ResolveKey writes; hint on stderr too
Review fixes for #6508 (apply-fixes iteration 1; all minor or nit):
- The budget credits an overwrite under memoryapi.ResolveKey's key, the
one rule every Remember implementation writes under, instead of a
parallel flag-else-derived copy of it. A write ResolveKey refuses
skips the budget, so a whitespace-only --key gets the role's "memory
key must not be empty" instead of an over-budget refusal that points
at --force.
- The stderr refusal now carries the same hint as the --json envelope
(raise the budget, forget a memory, or --force), printed the way
HandleErrorWithHintRespectJSON prints one.
- The memoryCorpusChars comment and `bd remember --help` no longer
imply that a budget equal to prime.max-memory-chars keeps prime from
eliding memories: the unit (bytes) is the same, but prime counts each
memory as rendered, markup included, so the budget has to sit below
that cap for that.
- New embedded pins: a write without --key that crosses the budget is
refused with exit 1 and writes nothing; a blank --key gets the
validation error; the Hint line is on stderr and not under --json.
Each pin was checked red against a mutant of the code it guards.
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: 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>
The Last reviewed marker (2026-07-10) passes the 90-day limit in
scripts/check-doc-freshness.sh at 2026-10-09 00:00 UTC, when the required
"Check doc flags freshness" job would fail on every PR and merge-group
run, as it did for ERROR_HANDLING.md (#7266).
Re-reviewed against cmd/bd/setup.go, cmd/bd/setup/ and internal/recipes/
at e72cd8b31 and corrected what had drifted:
- bd setup cursor installs the agent skill and .cursor/hooks.json
(sessionStart, preCompact, postToolUse) besides the rules file, and
takes --global (hooks and skill only).
- bd setup claude writes its managed section to AGENTS.md when
CLAUDE.md is an @AGENTS.md import stub.
- bd setup codex takes --global.
- bd init runs the Claude Code, Codex and Cursor project setup, not
Codex alone.
The marker is 2026-10-05, not the UTC date, because the script rejects a
future date and a Pacific shell still reads 10-05.
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
#7301 scoped the pre-migration read failure on a shared server to schemas
that "predate 1.2.0". That misses 1.2.2, the recovery re-release of the
1.1 line: its migrations stop at 0053 with no lease migrations, so a 1.2.2
server sits at v53 like 1.1.x. Upgrading such a server's clients to 1.3.1
without `bd migrate schema` makes `bd list`, `bd show` and `bd ready` fail
with `table not found: leases`.
Key the caveat to schema v53 or older, naming 1.1.x and 1.2.2, which
matches the section's own "A 1.2.2 or 1.1.x database sits at schema v53".
Refs #6929, #7284, #7301
* docs(upgrading): scope the shared-server read failure to pre-1.2.0 schemas
#7284 said most reads fail between upgrading a shared server's clients
and running `bd migrate schema`. That only holds for a schema older than
1.2.0: the leases table ships with main migration 0055 and ignored 0012
and 0016, all in v1.2.0. From 1.2.x, reads keep working and only writes
are refused (probed against a 1.2.1 server with 1.3.1 and main builds).
Restore the original wording and add the pre-1.2.0 caveat, naming only
the observed `bd list` failure from #6929.
Refs #6929
* docs: add beads-viewer (Paseo plugin) to community tools
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit ad28cf00ba)
* Add LazyBeads (lb) to community tools
- List lesliesrussell/lazybeads under Terminal UIs
- Note that it is unrelated to the earlier lazybeads under Historical
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 1aa2b645e2)
* docs(community-tools): update the beads-web entry
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit aa177110b3)
* docs(community-tools): mention the beads-web tree view
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QebAVaD36wUemAsdBx8wwJ
(cherry picked from commit e0eb482a11)
* Updated community tools documentation with Beads Tracker
Applied changes from BB to 1 file
Files modified:
- docs/community-tools.md
Updated community tools documentation
Applied changes from BB to 1 file
Files modified:
- docs/community-tools.md
Updated community tools documentation
Applied changes from BB to 1 file
Files modified:
- docs/community-tools.md
(cherry picked from commit 75d0f8de0c)
* docs: add b9s to community tools (TUI and web UI)
(cherry picked from commit 8bb6ab6913)
* docs: add btui to community tools (btui-bb2)
Agent-Signature: codex-unknown-model-unknown-reasoning on behalf of Andreas Dellrud
(cherry picked from commit 81da372c63)
* docs: mention released btui Beads 1.3 support (btui-0fm)
Agent-Signature: codex-unknown-model-unknown-reasoning on behalf of Andreas Dellrud
(cherry picked from commit 8f27445bee)
* docs: add beadside to community tools
(cherry picked from commit 2c2cb1fd5c)
* docs: add Beads for Obsidian to community tools
(cherry picked from commit cb82d067d8)
---------
Co-authored-by: cuongntr <cuongntr@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Leslie Russell <leslierussell@gmail.com>
Co-authored-by: weselow <598746@gmail.com>
Co-authored-by: Beyond Better <git@beyondbetter.app>
Co-authored-by: vanderheijden86 <vanderheijden86@gmail.com>
Co-authored-by: Andreas Dellrud <andreas.dellrud@gmail.com>
Co-authored-by: michal.psencik <misa.psencik@gmail.com>
Co-authored-by: Rome-1 <romethorstenson@gmail.com>
The shared-server upgrade steps said an upgraded client keeps reading the
old schema and only has writes refused. In practice most reads fail as
well: bd list, bd show and bd ready stop with "table not found: leases"
because 1.3 reads expect tables the old schema lacks. Say so, and tell
operators to run the migration as soon as the clients are upgraded
rather than treating the window as merely degraded.
Refs #6929, #7038
The upgrade docs told every non-migrating clone to adopt the migrated
database with `bd bootstrap`, claiming it replaces the local database.
On a clone that already has one, bootstrap prints "Nothing to do." and
exits 0, leaving the clone on the old schema (#6687).
Document the flow that works: every clone backs up with the old binary,
other clones `bd dolt pull` on the old binary after the migrator pushes
and then upgrade; a clone that already upgraded moves its local database
aside, re-clones with `bd bootstrap`, and re-imports the backup. Align
the gate description, shared-server note, and init-safety summary.
Also add a post-migration step to run `bd recompute-blocked` once per
database, since migration 0059 can over-set is_blocked and silently hide
ready work (#7037).
Refs #6687, #7037
Makes the repo's agent and contributor surface describe developing beads, not using bd, and requires every PR to link a documented issue.
- Contributor-only root AGENTS.md with a routing table; cmd/bd/AGENTS.md and engdocs/AGENTS.md seam files; CLAUDE.md symlinks so Claude Code loads nested files.
- Bug and feature issue forms, a PR template that requires Closes #, CONTRIBUTING sections for the triage and pipeline labels, and the opt-in fork-cache during dev setup.
- ROADMAP.md for 1.4: versioned beads (#6132), Graph Preview 2 (#7170), contributor onboarding (#7228).
- docsync guards: root AGENTS.md at or under 20 KB; every AGENTS.md symlinked, routed, and with resolving links, paths, and guard-test names.
Agent-Signature: claude-code-claude-opus-5-5-high on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(gate): ordinary commands wait out maintenance, with writer fairness
Ordinary bd commands take the workspace (and physical-root) gate SHARED and
never waited for it, so while another process held it EXCLUSIVELY — bd init
(~8s), backup restore, migrate, bootstrap — they failed at once with "a
maintenance operation is running". In shared-server mode every project
shares one physical-root gate, so another project's bd init broke every bd
command on the machine for its duration.
Ordinary commands now wait:
- up to 15s by default; BEADS_GATE_WAIT_TIMEOUT (Go duration or bare
seconds, same convention as BEADS_INIT_GATE_TIMEOUT) overrides it, and 0
restores fail-fast;
- one "waiting for another bd process ..." notice after 2s (shared with bd
init's notice);
- Ctrl-C aborts the wait. A canceled wait used to fall through to the
shared fail-open path ("continuing ungated"); it is now a hard error;
- past the bound, the same error naming the holder, the wait, and the knob.
Git hooks stay fail-fast: `bd hooks run` and the bd export/import children
the hooks spawn run with BD_GIT_HOOK=1, treat failure as a warning, and must
not stall a commit or checkout for 15s.
Writer fairness (internal/workspacegate). flock/LockFileEx give no queueing,
and acquisition is non-blocking polling, so a steady stream of overlapping
shared holders could keep a waiting exclusive acquirer (bd init) out past
its bound. A per-gate intent lock (<gate>.intent) fixes that: a waiting
exclusive acquirer whose first try is busy takes the intent lock
exclusively while it polls, and waiting shared acquirers probe it before
every attempt and wait while it is held. The exclusive waiter then waits
only for in-flight holders to drain. The intent is an OS lock, so a crashed
waiter's intent dies with it; its advisory sidecar is ignored when the lock
is free, and intent-lock errors other than "busy" degrade to the old
behavior. Fail-fast acquisitions (Wait <= 0) ignore the queue entirely, so
hooks and BEADS_GATE_WAIT_TIMEOUT=0 behave exactly as before. The intent
lock is taken only while acquiring its gate, directly before it in
AcquireAll's sorted order, so it adds no lock-order cycles.
Nested bd (bd orphans running bd close, hooks fired by git that bd runs)
would deadlock against the queue: the child queues behind an exclusive
waiter that is waiting for the child's parent. A bd process holding its
gates shared exports BEADS_GATE_SHARED_HOLDER_PID; a child whose recorded
ancestor is alive skips the queue (it cannot help the waiter anyway).
Tests: workspacegate fairness (a continuous shared stream no longer starves
an exclusive waiter; verified to fail without the queue), intent lifecycle,
stale intent from a SIGKILLed process, cancellation while queued,
InheritedSharedHold. cmd/bd: holder released after ~3s lets a command
through with one notice; past-bound error text; fail-fast modes (0, hooks);
Ctrl-C is not fail-open; a new command queues behind a waiting bd init
while a child of a shared holder does not; env parsing.
TestSharedServerConcurrent runs a late bd init of a new project during the
client workloads, so both directions are exercised against a real server.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(gate): a queued exclusive waiter may delay shared commands, never fail them
Review follow-up (B1). A doomed exclusive waiter — bd init or restore
blocked behind a long-lived shared holder such as `bd list --watch`,
`bd events tail --follow`, an open `bd edit` editor, or a beads.OpenGated
embedder — held the writer-fairness intent lock for its whole budget, so
every NEW ordinary command deferred to it and failed with "queued for
exclusive access" even though nothing held the gate exclusively. Before
the fairness change those commands ran normally.
Two bounds fix it while keeping the fairness win:
- An exclusive waiter drops the intent lock after maxIntentHold (10s)
without getting the gate and keeps polling unqueued. In-flight ordinary
commands drain far faster than that.
- The final attempt of a waiting shared acquisition tries the gate even
while intent is held, so a shared acquisition fails only when the gate
itself is held exclusively.
With the final attempt ignoring intent, AcquireAll's 1ns floor for an
exhausted budget is dead code (a Wait-0 attempt behaves the same), so it is
back to 0. queuedDetail drops an intent sidecar left by a dead process (on
Windows its removal can fail while another process is reading it).
Tests: the doomed-waiter scenario (both bounds; each fails with its bound
removed), intent lock order across a two-gate set in both directions, an
exhausted AcquireAll budget, two exclusive waiters handing off the intent,
and BEADS_GATE_SHARED_HOLDER_PID inherited through a real subprocess.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(gate): 30s shared wait, 60s init wait, accurate errors, hook pinning
Review follow-ups for the shared gate wait (S1-S5 and nits), on top of the
workspacegate fix that keeps a queued exclusive waiter from failing
ordinary commands.
- Ordinary commands wait up to 30s by default (was 15s). Queued
maintenance operations run one after another (two inits fanned out
across shared-server projects hold the gate back to back, 10-15s each
under load) and a waiting command waits for all of them. Documented in
configuration.md and CHANGELOG, including BEADS_GATE_WAIT_TIMEOUT=0 for
scripts that relied on fail-fast.
- bd init waits up to 60s by default (was 30s). Safe only now that a
waiting init stops queueing others after 10s.
- Error text: a shared acquisition now fails only when the gate is held
exclusively, so "running" is accurate; in shared-server mode it says
"the shared server (possibly from another project)", and the detail
still names the holder when known.
- hooks.go: the hookSubprocessEnv / bd import comments listed BD_GIT_HOOK's
consumers without the gate wait, which now reads it to stay fail-fast.
TestHookSubprocessEnvKeepsGateFailFast pins that hook subprocesses carry
it and therefore never wait on the gate.
- bd edit's $EDITOR (which can outlive bd by hours) no longer inherits
BEADS_GATE_SHARED_HOLDER_PID.
- Test hygiene: the cmd/bd test binary never advertises the marker
(in-process command tests run beside tests that spawn bd) and clears any
inherited one in TestMain; the notice-delay test runs in 1s, not 3s.
- TestSharedServerConcurrent's late init keeps a 30s bound so the 60s
default cannot mask a fairness regression.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
In shared-server mode every project's physical root is the one shared dolt
data dir, and bd init holds that dir's gate EXCLUSIVELY for its whole run
(~8s). It waited only exclusiveGateWait (5s) for it, so two concurrent
`bd init --shared-server` runs in different projects, or an init during
another project's long command, failed with "bd init refuses to run over
live bd activity".
acquireInitMutationGate now uses its own acquisition options:
- Wait: 30s by default, overridable with BEADS_INIT_GATE_TIMEOUT (Go
duration or bare seconds, same convention as BEADS_PRIME_TIMEOUT and
BEADS_FSCK_TIMEOUT); ctx cancellation still aborts the wait.
- One stderr notice ("waiting for another bd process on the shared
server (...)...") once the wait passes 2s, instead of immediately.
- Past the bound, the same refusal, now naming the budget and the knob.
Exclusivity is unchanged. The 5s exclusiveGateWait is also used by
backup restore, bootstrap, migrate and the backup lock; those keep it, so
the change is scoped to init via acquireExclusiveWorkspaceGatesWithOptions.
TestSharedServerConcurrent goes back to fully concurrent inits (manual runs
with many dirs raise BEADS_INIT_GATE_TIMEOUT to match). New unit tests: a
holder released after 6s lets init through with one notice; a holder past
the bound gives the clear ErrBusy error; cancellation; env parsing.
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
The PAUSED warning, the `bd backup status` PAUSED line, CHANGELOG and
configuration.md told operators to switch to a fresh destination with
`bd backup init <new-path>`. That never ends the pause: backupDir()
reads only backup.git-repo, while `bd backup init` registers the
separate destination that manual `bd backup sync` pushes to, so
auto-backup keeps targeting the over-cap directory and stays paused.
Name the two levers that do end it: raise backup.size-cap-mb, or point
backup.git-repo at a different git repository. Also correct the
backup.git-repo row in configuration.md, which called it a repo URL
although backupDir() requires a local path containing .git (anything
else falls back to .beads/backup/), so the new advice is actionable.
TestPauseAutoBackupForSizeCap_RemediationAdvice and the status PAUSED
line now require backup.git-repo and reject `bd backup init`.
TestMaybeAutoBackup_RemediationLevers runs all three for real: raising
the cap and switching backup.git-repo each resume a sync, while
`bd backup init` leaves auto-backup paused.
Post-merge review follow-up to #6071.
Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Gas City Adopt-PR
Co-authored-by: Eddie the Engineer <adopt-pr@gascity.local>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
* fix(init): name --recreate-missing in the refusal without a paste-ready command
The missing-server-database refusal added in #5791 ended with a complete
`bd init --recreate-missing --prefix <prefix>` line. ADR 0002 Invariant 4
keeps complete destructive invocations out of bd error output, and this
refusal also fires when the server merely could not be reached: a stopped
server, a wrong port and a wrong data dir all look the same from here, and
recreating in any of them strands the real data behind an empty database of
the same name. The line also echoed the raw --prefix flag value, so a run
without --prefix printed `--prefix ` with nothing after it.
The refusal now names the flag and points to `bd help init-safety`, which
keeps the full invocation behind the diagnosis it requires. The unused
prefix parameter stays as `_` so the guard call sites are unchanged.
Also:
- --force / --reinit-local flag help, `bd help init-safety` and the init
guard comment now say neither flag authorizes recreating a missing
server-mode database; the --recreate-missing stanza says to rule out a
stopped server or wrong port/data dir and restore first.
- bootstrap.go comments no longer describe #5791 as open and unmerged.
- TestInitGuardMissingServerDBMessage_RefusalTextNoEcho pins the wording
for both evidence arms, with and without a prefix.
- TestInitGuard_RecreateMissingE2ECreatesMissingServerDB runs the real
binary against a live server lacking the database: refused without the
flag, created with it. The unit tests flip initAllowRecreateMissing
directly, so nothing exercised the documented command end to end.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* docs(recovery): init-missing-server-db covers both evidence arms and the flag limits
The init-missing-server-db section described only the project_id arm of the
guard. Under --reinit-local or --force a workspace that predates project_id
is also refused when its local Dolt data directory survives, and the refusal
then cites that directory instead of metadata.json. "What happened" now
covers both arms.
"Limits worth knowing" replaces the stale "fails open" bullet with a table
of which local state meets the refusal under bd init and under
--reinit-local / --force, and what --recreate-missing changes. The
init-force-refused section now says --force / --reinit-local bypass only the
local data-safety guard, not this refusal or the remote one, and step 3 says
why the refusal names --recreate-missing without printing the command
(ADR 0002 Invariant 4).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* docs(adr): mark ADR 0004 Accepted now that #5791 has landed
ADR 0004 (the missing-database guard signal) still read "Proposed" after the
guards implementing it merged in #5791, and its Consequences said
checkExistingBeadsDataAt "does not change" although the same PR gave it the
Tier 1 probe ahead of project_id. Record the acceptance and say what the PR
already changed; DOC_INVENTORY.md follows the status.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Eddie the Engineer <adopt-pr@gascity.local>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
* Refuse reserved words and fuzzy id matches on bd comment writes
bd comment <id> [text...] treated its first argument as an id via the
same abbreviation-tolerant resolver used everywhere else, with no
protection against the id slot holding something that was never meant
to be an id. Two related failure modes came from that:
- "bd comment list <id>", a typo for "bd comments list" (or "bd
comments <id>"), silently ran with id="list" and text="<id>" instead
of erroring.
- If "list" (or any other stray first word) happened to be a
leading-prefix abbreviation of some unrelated issue's hash, the
resolver picked that issue and the comment landed there instead of
failing with "not found". This is exactly what happened in
production: 15+ automated sessions made the "bd comment list <id>"
typo over two days, and because "list" was a leading-prefix
abbreviation of an unrelated wisp's hash ("list3t0"), every one of
them wrote a garbage comment onto that wisp.
Fixes both, independently:
- checkCommentIDNotReservedWord rejects list/add/rm/delete as the id
argument before any resolution is attempted, mirroring the existing
"bd comments list" misplaced-subcommand guard.
- ResolvePartialIDExact (internal/utils) is an exact-match sibling of
ResolvePartialID: identical exact-ID and exact-hash matching
(including a wisp's hash with its "wisp-" infix stripped), but never
falls through to leading-prefix abbreviation matching. bd comment
now resolves through this via a new resolveAndGetIssueForMutationExact,
which keeps the existing cross-rig prefix-routing and contributor
auto-routing fallbacks intact (tightened to exact matching too) so
cross-repo comment writes by full id are unaffected.
Every other caller of the touched shared functions (ResolvePartialID,
resolveAndGetIssueForMutation, resolveViaPrefixRoutingWithAccess,
resolveViaAutoRouting) keeps its exact current behavior — the new exact
variants are additive, and existing call sites were updated to pass an
explicit "false" for the new parameter rather than changing behavior.
Testing: go build/go vet pass across the whole module. The new pure-Go
guard test and a hand-rolled in-memory PartialIDResolverStore test both
run and pass without Docker or a live Dolt server, and the latter
reproduces the original collision (ResolvePartialID) before asserting
the fix (ResolvePartialIDExact) in the same test, so the fixture is
proven to exercise the real failure mode rather than trivially passing.
The Dolt-container-backed table tests (mirroring the existing
TestResolvePartialID_Wisp / TestResolvePartialID suites) could not be
run locally (no Docker in this environment) — they compile and skip
cleanly the same way the pre-existing suite does, and will run for real
in CI.
* fix(ga-wpdum): address steveyegge's PR #5393 review items b/c/d
Review (2026-08-07, posted as a PR comment, not a formal GitHub review —
hence reviewDecision stayed empty) asked for four things before merge; (a)
rebase onto #5369 was already done (2026-09-07, see PR history). This
addresses the rest:
(c) MAJOR — comment writes require an exact id, but a REAL abbreviated id
was refused with "no issue found matching %q", which is false: the issue
exists, only the abbreviation was rejected. ResolvePartialIDExact now
distinguishes the two failure modes via a new sentinel,
ErrAbbreviatedIDNotAllowed, wrapped only when the input would have resolved
via leading-prefix abbreviation. bd comment's RunE checks errors.Is against
it and returns a truthful, actionable message pointing at `bd show <id>`
instead of claiming the issue is missing. Docs (hash-ids.md) and CHANGELOG
updated with the read/write carve-out this creates.
(b) MAJOR — investigated whether the proxied-server comment path needed the
same exact-match treatment. It doesn't: resolveCommentTargetProxied resolves
via workapi.GetIssueOrWisp with the raw id, which bottoms out in
issueSQLRepositoryImpl.Get's plain "WHERE id = ?" — SQL exact equality, with
no abbreviation-matching layer anywhere in that call chain (unlike the
embedded path's utils.ResolvePartialID). Comment writes over the proxied
server were already exact-id-only before this PR. Per the review's own
fallback ("extend exact matching to that path, or document/test the gap
explicitly"), added a regression test locking this in rather than leaving it
implicit.
(d) Added CLI-level (cobra-dispatch, in-process rootCmd.Execute) tests for:
- "rm"/"delete" reserved-word rejection, the two words the #5369-inherited
tests don't cover (only "list"/"add" have hand-written cases).
- The new (c) abbreviation-refusal message end-to-end, including a
same-abbreviation sanity check against `bd show` to prove it's a real,
resolvable abbreviation and not a fixture accident.
Plus a Docker-free fake-store test in internal/utils pinning
ErrAbbreviatedIDNotAllowed's distinguishability from a genuine not-found.
Fixed in the same pass, same class of defect as (c): checkCommentIDNotReservedWord's
message claimed every reserved word is a "misplaced bd comments subcommand" —
true for "list"/"add", false for "rm"/"delete" (no such subcommand exists;
bd has "delete" as a top-level command and "rm" as an alias elsewhere, e.g.
"dep rm"). Message now says "reserved word" generically, true for all four.
Testing: go vet (plain and -tags=integration) clean on cmd/bd and
internal/utils. go test ./internal/utils/... passes including the new
ErrAbbreviatedIDNotAllowed test. go test ./cmd/bd/. (non-integration tag)
passes including both reserved-word cases. The new CLI-level and
proxied-server integration tests need a Dolt test container (Docker) this
environment doesn't have — same limitation the original commit's own
Dolt-backed tests already disclosed; they compile clean under
-tags=integration and skip cleanly the same way the pre-existing suite does.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* fix(ga-wpdum): address bee-ghosttrack's R1 review (M1 + the flagged MINOR)
R1 (aec6de4ad, REQUEST-CHANGES) found that CHANGELOG.md and hash-ids.md
claim `bd comments add` is guarded against abbreviated ids and reserved
words exactly like `bd comment`, but the code never extended the guard
to the plural form — `commentsAddCmd` had no Args validator and resolved
through the abbreviation-tolerant `resolveAndGetIssueForMutation`. Per
the reviewer's preferred fix (option ii), extend the guard instead of
softening the docs:
- Add `validateCommentsAddArgs` (mirrors `comment`'s `validateCommentArgs`
minus the singular/plural-confusion special cases) and wire it as
`commentsAddCmd.Args`, so a reserved-word id is refused before either
dispatch branch.
- Switch the embedded-path resolution from `resolveAndGetIssueForMutation`
to `resolveAndGetIssueForMutationExact`, with the same
`errors.Is(ErrAbbreviatedIDNotAllowed)` truthful-message mapping
`comment` already has. (The proxied path already resolved exactly —
it shares `addCommentProxied`/`resolveCommentTargetProxied` with
`comment` — so this closes the embedded-path gap only.)
- Update the one pre-existing test that asserted the old, now-removed
behavior (`PartialIDWithCommentsAdd` expected a genuine abbreviation to
succeed) to assert the refusal instead, and add a CLI-level regression
test mirroring `TestCLI_CommentAbbreviatedIDRejectedWithTruthfulMessage`.
- Add `TestValidateCommentsAddArgs`, a pure Args-validator unit test
(no store/Docker needed) mirroring `TestValidateCommentArgs`.
Also treats the one MINOR the review flagged as an actual gap (not just
a suggestion): the wisp-branch abbrevOnly tracking in id_parser.go had no
test pinning it — P3 (making the wisp-branch abbrevOnly append a no-op)
went uncaught. Strengthened
TestResolvePartialIDExact_FakeStore_ReproducesReportedIncident's "list"
assertion from a bare `err != nil` to `errors.Is(err,
ErrAbbreviatedIDNotAllowed)`, which is exactly the incident's own shape
in the wisp branch.
CI (PR Core / wrapper timing) is failing on this branch, but independently
confirmed pre-existing and unrelated: `ci-pr-core.sh` runs `go test -race
./...` with no `-timeout` override, so cmd/bd (a large package under
-race) hits Go's default 10-minute per-package ceiling; same-hour green
runs on other PRs measured 11-13.5 min total job time, already at the
edge, and the actively-running test at the deadline
(TestWhereCommand_ReadsPrefixFromEmbeddedStore) is unrelated to this
diff. R1 independently measured the same thing (541.6s/387.0s on other
green runs vs. 600.9s here). Needs a green re-run, not a code fix.
Verified locally (no Docker in this environment, so the two integration-
tagged CLI tests above compile-check clean via `go vet -tags=integration,
gms_pure_go` but run as SKIP rather than PASS; will run for real in CI):
- go build ./...; go vet ./cmd/bd/ ./internal/utils/: clean
- go vet -tags=integration,gms_pure_go ./cmd/bd/: clean
- gofmt -l on all 4 changed/added files: clean
- go test ./internal/utils/... -run ResolvePartialID: PASS
- go test ./cmd/bd/. -run 'TestValidateCommentsAddArgs|TestValidateCommentArgs|TestCheckCommentIDNotReservedWord': PASS
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* fix(ga-wpdum): address bee-ghosttrack's R2 review (dead-red fixture + cobra-dispatch wiring test)
R2 (a639234a0, CHANGES_REQUESTED): TestCLI_CommentsAddShortID/PartialIDWithCommentsAdd
was dead-red in its own setup — it only truncated the fixture hash to a
4-char abbreviation when len(hash) > 4, but fresh test DBs mint 3-char
hashes (min_hash_length unset), so shortID always equaled the full hash
and the t.Fatalf guard fired before any of the subtest's real assertions
ran. That meant mutation P-B (reverting comments.go's exact resolver back
to the abbreviation-tolerant one) went uncaught.
Fix: derive the abbreviation as a strict, one-character-shorter leading
prefix of the real hash (hash[:len(hash)-1]), the same derivation
comment_proxied_integration_test.go already uses — correct regardless of
fixture hash length, with a length>=2 guard instead of the old
always-true-in-practice one.
Also closes R2's recommended "NEW MINOR — the guard's wiring is
untested": comments_add_test.go drives validateCommentsAddArgs directly
(catches a gutted body, mutation P-C) but nothing exercised
commentsAddCmd's Args field through real cobra dispatch, so unwiring it
back to cobra.MinimumNArgs(1) left every test green (mutation P-D). Added
TestCLI_CommentsAddReservedWordRejectedThroughCobraDispatch, which runs
`bd comments add <reserved-word> ...` through actual rootCmd.Execute()
dispatch for all four reserved words and asserts the bystander issue
receives no comment.
Not touched, per R2: the carried-over m1 (cross-rig abbreviation error
message) — reviewer marked "Not a blocker" — and the CI race-default
timeout on cmd/bd, already diagnosed (R2 + prior PR comment) as
pre-existing infra flakiness needing a fresh run, not a code change.
Verified in this environment (no Docker/testcontainers available, same
disclosed limitation as prior rounds): gofmt clean; go vet -tags=integration
./cmd/bd/... clean (requires CGO_CPPFLAGS/CGO_LDFLAGS/PKG_CONFIG_PATH
pointed at the keg-only icu4c@78 install); go test -tags=integration
-run 'TestCLI_CommentsAddShortID|TestCLI_CommentsAddReservedWordRejectedThroughCobraDispatch'
./cmd/bd/ -v passes with all Dolt-backed subtests skipping cleanly
(Docker not available) rather than panicking — confirms both tests compile
and execute up to the container-availability skip. The actual fixture-hash
logic under test only runs where a Dolt container exists (CI); it has not
been exercised against a real container here.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* chore(bazel): enumerate the PR's 4 new test files in BUILD.bazel (adopt-pr rebase gate)
Base added cmd/bd/BUILD.bazel and internal/utils/BUILD.bazel enumerates
go_test srcs explicitly, so PR #5393's four new test files were unlisted.
Output of 'make bazel-sync' (gazelle + go_srcs.py + mod tidy), verbatim and
idempotent. Measured: the unrepaired //internal/utils:utils_test binary lists
0 of the PR's 5 TestResolvePartialIDExact* tests while still building green
(a fake green); repaired it lists 5/5.
* fix(review): surface a routed-tier abbreviation refusal on comment writes
Review-loop fixup for PR #5393 (iteration 1). The review approved with no
required changes; these are the non-gating minor plus one of the two nits,
taken because the minor is a user-visible false message on this PR's own
headline contract.
[minor] Contract & Interface Fidelity. resolveAndGetIssueForMutationExact
passes exact=true to all three tiers, so the cross-rig and auto-routed tiers
can mint utils.ErrAbbreviatedIDNotAllowed too -- and both wrappers propagate it
unwrapped (routed.go:303-305) -- but each routed error was bound inside an `if`
statement and discarded, and `return nil, err` returned the LOCAL error. The
consumers' errors.Is (comment.go:158, comments.go:238) was therefore
structurally unable to observe a routed-tier refusal, so `bd comment hr-8wn
"text"` printed `no issue found matching "hr-8wn"` for an issue a routed rig
demonstrably holds -- the exact falsehood the sentinel's own doc condemns, at
the caller that doc names (internal/utils/id_parser.go:33). Both tiers' errors
are now captured and the first abbreviation refusal is returned in preference to
the local not-found. The wrong write was already refused on every tier; only
the message contract was unmet.
The new pin cmd/bd/comment_routed_exact_test.go drives the real seam (local
town store + routed rig + routes.jsonl, mirroring
TestCheckBeadGateCrossRigPrefixRoute) in both directions, because either
assertion alone passes for the wrong reason: an abbreviation of a routed issue
must select the ROUTED refusal, and an id absent everywhere must stay a plain
not-found. Proven non-vacuous by mutation -- dropping only the selection reds
direction 1 with `no issue found matching "gt-abcdefg"`, the original symptom
verbatim, while direction 2 still passes.
[nit] Test Evidence Quality. The proxied regression test asserted only
strings.Contains(stdout+stderr, id), which passes identically on the false and
the truthful message and so locked the local/proxied message asymmetry in where
the suite could not see it. It now asserts the whole message (verified
empirically: `Error: issue pa-2u not found`) and empty stdout, matching the
exact-message norm of the sibling missing-ID subtest. The asymmetry itself is
deliberate and stays: the proxied route resolves through one exact
`WHERE id = ?` and cannot distinguish an abbreviation of a real issue from an
absent id without adding back the abbreviation probing this PR exists to remove
from write paths.
[nit] Release Safety -- DECLINED, measured. The prescribed `### Changed` bullet
belongs at the top of the first `### Changed` block in `## [Unreleased]` (base
CHANGELOG.md:383), and main has since inserted its own bullet at exactly that
anchor (`@@ -384,0 +492,16`, the #6111 entry). Adding it would mint a second
CHANGELOG add/add conflict for the finalize base-refresh on top of the
`### Fixed` re-conflict already predicted by the rebase gate -- not worth it for
an optional nit whose own text says "No code change".
cmd/bd/BUILD.bazel gains one srcs row for the new test file (via make
bazel-sync, a no-op on a second run) so bazel.yml's "BUILD files in sync" gate
stays clean.
Validation: go build ./... rc 0; go vet ./cmd/bd/ ./internal/utils/ rc 0; gofmt
clean; git diff --check clean; cmd/bd selectors 11/11 PASS including base's own
TestMatchPrefixRoute (the GH#5048 longest-prefix union guard) and
TestResolveCloseTargets (the abbreviation-tolerant sibling path);
TestProxiedServerComment 3/3 under BEADS_TEST_PROXIED_SERVER=1.
* test(utils): pin #6215's sentinel guard to the shared resolver (#5393 base refresh)
Rebasing this PR onto current main (e7138e93af -> a1ac9f4dcb, 27 commits) hit
two conflicts. Both are recorded in .gc/reviews/<root>/base-refresh-repair.md;
this commit carries the one piece of the repair that is not simply a replayed
contributor hunk.
The substantive conflict was internal/utils/id_parser.go against ab88b20517
(#6215, "refuse a bare jq/JS sentinel ... as an issue ID", which itself says
Refs #5393). Both sides ADD at the same point -- the diff3 ancestor section is
empty -- so nothing base-owned is rewritten, and the only question is WHERE
#6215's guard lands now that this PR splits the resolver into ResolvePartialID
(abbreviation-tolerant) and ResolvePartialIDExact (exact-only) over a shared
resolvePartialID.
It belongs in the shared body. #6215 put it in ResolvePartialID only because
that was then the repository's single ID-resolution entry point ("One guard
covers the direct, embedded and proxied-server paths uniformly"); this PR adds
a second. Its changelog entry on main states the guarantee directly -- "bd
update null, bd comment null and every other command that resolves an ID now
fail before any lookup, because the guard sits in the shared resolver" -- and
bd comment is precisely what this PR routes through the exact-only path. The
relocation costs no patch delta: the guard re-anchors as unchanged context
after the PR's insertion, so the content-line diff of (old base..old head) vs
(new base..new head) is empty, and the PR's stat is 16 files +1212/-31 before
and after.
Nothing covered that choice, which is why this test exists. #6215's own
id_parser_sentinel_test.go exercises only ResolvePartialID, so the naive
textual resolution -- guard left in the exported wrapper -- keeps every one of
its assertions green while a sentinel reaching the exact path degrades into
`id is a valid abbreviation, but exact-match resolution is required here:
"null" (matches [hq-null3t0])`: it names an unrelated decoy issue and tells
the caller to use the full id, when in truth their selector matched nothing.
Mutation-proved in both directions: with the guard moved into the wrapper
alone, #6215's two tests still PASS and this test FAILs; with the guard deleted
outright, #6215's refusal test and this one both FAIL (so neither is vacuous).
The over-refusal arm mirrors #6215's accepted-inputs test through the exact
path, so hq-null3t0 and the bare hash null3t0 must still resolve.
No new file, so no BUILD.bazel srcs row is owed. 61 PASS / 0 FAIL / 0 SKIP for
-run 'Sentinel|ResolvePartialID' against a real Dolt container.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
* docs: add beadcyte to community tools (Web UIs)
Local web app that draws bead history and a projected future: a
historical-median estimator, a greedy WIP-cap scheduler, and an
eight-signal triage score, each with its own uncertainty. Reads and
writes only through the bd CLI.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* docs: correct beadcyte storage-access claim and normalize emphasis
The beadcyte entry said the tool "reads and writes exclusively through
the `bd` CLI ... never the Dolt files or `.beads/issues.jsonl`". The
first half is false for the shipped package. Measured against
beadcyte@0.9.0, the latest published version (tarball sha1
93964d9632cc1b1cc846f5d84f0dfa8a79a4ef57, matching the registry
shasum):
- The package starts exactly one process that is not `bd`:
`spawn("dolt", ["sql", "-r", "json", "-q", sql], ...)` with cwd
<project>/.beads/embeddeddolt (src/history-sql.mjs:250,
`doltSqlRunner`).
- `beadcyte freeze` reaches it through `readDoltDates`
(src/freeze-cli.mjs:110). `freeze` is a dispatched subcommand
(bin/beadcyte.mjs:37, 63-65). The path is on by default:
freeze-cli.mjs:33 sets `dolt: true`, and `--no-dolt` (:38) turns
it off.
- The author's own comment agrees: "`beadcyte freeze` is the ONE
place beadcyte reads Dolt directly ... read-only"
(src/history-sql.mjs:42-44).
Correcting an over-broad claim can easily introduce a new one, so each
clause of the replacement was checked:
- "reads and writes through the `bd` CLI": every other process the
package starts is `bd`. Writes go through `bd update`, including
freeze's own write-back (freeze-cli.mjs:127), and through
`bd dolt pull`/`push` (src/serve.mjs:498, 509).
- "read-only": `QUERIES` (history-sql.mjs:115-124) holds 4
statements, all SELECT. Every SQL call site passes one of them
(history-sql.mjs:302-303, 467-470).
- "never `.beads/issues.jsonl`": the package contains zero `jsonl`
references, so the entry still meets the page's compatibility bar
(docs/community-tools.md:8-11).
Emphasis: 51 of the page's 52 entries carry exactly one bold span, the
linked name. beadcyte carried three. Removing the bold from "happened"
and "expects to happen" brings it to 52/52.
Length: the correction adds 74 characters, bringing the entry to 1073.
That is still the longest of the 7 Web UIs entries, and 3rd on the
page after Beadazzle (1579) and Beads Dashboard (1300). Review
suggested trimming it to a feature summary. That suggestion is
optional and does not gate the review, and how the product is
described is the contributor's call, so this commit does not make it.
Gates: git diff --cached --check is clean. check-doc-flags.sh returns
rc=0 against the pinned v1.2.2 bd. check-doc-freshness.sh reports 68
PASS / 0 FAIL. go test ./test/docsync passes 8/8.
go test -tags integration -run TestDocFreshness ./scripts gives
37 pass / 0 fail / 1 skip.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-authored-by: Eddie the Engineer <adopt-pr@gascity.local>
* fix(bd): cap auto-backup destination size to stop unbounded growth (ga-y6gjv)
ga-y6gjv asked for 4 fixes to bd's auto-backup subsystem. Three are already
merged and deployed (verified via git merge-base --is-ancestor against the
commit that built the currently-deployed ~/.local/bin/bd):
- interval throttle persists on failure too, per-workspace: 5f685959c
- default-off in sql-server/shared mode: 5f685959c, refined by 8b9429153
- `bd config get backup.enabled` reports the effective value: 5f685959c
This commit is only the fourth, still-open item: "prune/cap backup
archives." BackupSync/CALL DOLT_BACKUP('sync', ...) only ever transfers new
chunks into the destination — it never prunes ones that became unreachable
on the source DB (history rewrites, superseded data) — so even with the
interval fix slowing the frequency of syncs, the destination can still only
grow, never shrink. This was the actual disk-filling mechanism in the
2026-06-19 outage (43GB backup dir from a 1.7GB store).
I first tried wiring `dolt gc` into the post-sync path (mirroring
runCompactDolt's exec.Command("dolt", "gc", ...) pattern in compact.go).
That does not work: a backup destination is a bare Dolt chunk-store
directory with no .dolt repo-root marker, so the standalone dolt CLI can't
open it ("not a valid dolt repository") no matter what its working
directory is set to, and dolt_backup.go's SQL procedures only expose
add/sync/restore — never gc — for a backup destination. Confirmed this
empirically (a real dolt gc attempt against a real backup dir, outside any
test) before shipping anything, not just reasoned about it.
Given no supported way to prune a backup destination in place, this adds a
hard size cap instead: once the destination exceeds backup.size-cap-mb
(default 2048MB), maybeAutoBackup skips the sync attempt entirely rather
than letting it grow further, and prints a throttled warning
(backup.size-warn-interval, default 24h) telling the operator to free space
or raise the cap. This directly bounds the failure mode that caused the
outage — unbounded growth — without risking any operation against the
backup store's on-disk format.
Tests (cmd/bd/backup_cap_test.go): threshold check against a real
directory, warning-throttle persistence (mirrors the existing throttle
persisted on backup failure, backup_export.go), and end-to-end proof that
maybeAutoBackup never attempts BackupDatabase once capped. Confirmed each
new test fails against the pre-fix code (wiring temporarily reverted,
re-verified, restored) before treating it as green.
Verified: go build ./... clean, gofmt clean, go vet clean, full
cmd/bd + internal/config test run green (backup/config-focused subset run
with -v; no regressions in the wider package test runs either).
* fix(bd): address PR #6071 review feedback on backup size-cap (ga-y6gjv)
bee-ghosttrack's 2026-09-03 review of the size-cap fix (3d27d7a98) requested
changes before merge -- 4 major, 2 minor, all about the pause being
invisible rather than the cap mechanism itself. This addresses all six.
Major:
1. backup.size-cap-mb: 0 now means "no cap", not "use the 2048MB default."
effectiveSizeCapMB() centralizes the <=0-is-disabled interpretation;
backupSizeCapExceeded and the new status helpers all go through it.
Viper already registers a 2048 default for this key
(internal/config/config.go), so GetInt only returns <=0 when the
operator explicitly set 0 (or an unparseable value) -- the old code's
own `if capMB <= 0 { capMB = 2048 }` was silently overriding that
explicit choice, leaving no off switch for a legitimately larger
destination.
2. `bd backup status` (and --json) now report a `size_cap` object
(enabled, cap_mb, current_bytes, exceeded), and the human-text Config:
line grows a "Size cap: PAUSED (cap exceeded) -- X / Y..." line when
paused. Previously the pause was stderr-only and throttled to 24h, so
an agent/CI caller on --json or --quiet had no way to see that
auto-backup had silently and permanently stopped syncing.
3. The remediation message no longer says "delete the backup directory."
Nothing in this codebase demonstrates a deleted destination is cleanly
recreated by the next sync (the server-side Dolt backup remote stays
registered against that path), and following the old advice would
leave a zero-backup window while the next sync is itself
interval-throttled. It now points at backup.size-cap-mb / `bd backup
init <new-path>`.
4. docs/reference/configuration.md gains rows for both new keys plus an
expanded Auto-backup section (the cap mechanism, the pause, manual
backup staying uncapped, bd backup status reporting the pause);
CHANGELOG.md gets an [Unreleased]/Fixed entry referencing #6071.
Minor:
5. maybeWarnBackupSizeCap's throttle timestamp is now also cached in an
in-process map (capWarnFallback, keyed by dir) alongside the persisted
backup_state.json. The persist write targets the directory the cap
just declared full, so in the disk-full case this cap exists for, that
write fails and the timestamp never sticks -- a long-lived bd process
that keeps calling maybeAutoBackup for the same destination (e.g.
internal/storage/dbproxy's server mode) would otherwise re-warn on
every single call. The map is keyed by dir specifically so unrelated
destinations -- and unrelated tests -- never share a throttle.
6. The size-cap directory walk (getDirSize's filepath.Walk) now runs
after the interval throttle in maybeAutoBackup, not before. The
reviewer measured 65-100ms per bd invocation at 20k files in the
backup dir when the walk ran unconditionally on every command; moving
it below the throttle makes it free on the common (throttled) path and
only pays the walk cost once per interval, exactly when a sync attempt
would occur anyway.
Also noted by the reviewer: manual `bd backup` / `bd backup sync` stay
uncapped -- now documented in configuration.md.
Tests (cmd/bd/backup_cap_test.go, cmd/bd/backup_status_test.go): one new
test per review point. Each was confirmed to fail against the pre-fix code
for the expected reason before implementing -- including catching a
vacuous pass in my own first draft of the "disabled cap" JSON assertion
(zero-value Enabled:false matched whether the size_cap key existed at all
or not; fixed to assert key presence first). The disabled-cap test uses a
sparse file (Truncate, not a real write) to cross the legacy 2048MB
threshold without allocating 2GB of real disk or memory. The reordering
test is detected indirectly: if the cap check ran despite the throttle, it
would persist LastCapWarnAt; the interval-fresh case proves it does not.
Verified: go build ./cmd/bd/... clean, gofmt clean, go vet ./cmd/bd/...
clean, golangci-lint run ./cmd/bd/... -> 0 issues, targeted backup/status
test subset green (20/20, including every pre-existing backup test -- no
regressions).
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* fix(bazel): add backup_cap sources to //cmd/bd srcs lists
The contributor branched before `cmd/bd/BUILD.bazel` existed, so the two
files this PR adds were never enumerated there. After rebasing onto a base
that hand-maintains explicit srcs lists, `//cmd/bd:bd_lib` omits
`backup_cap.go` while still compiling `backup.go` and `backup_auto.go`,
which reference four symbols it defines:
backup.go:93 undefined: showSizeCapStatusJSON
backup.go:141 undefined: showSizeCapStatus
backup_auto.go:200 undefined: backupSizeCapExceeded
backup_auto.go:203 undefined: maybeWarnBackupSizeCap
`backup_cap_test.go` was likewise absent from `//cmd/bd:bd_test`, leaving
seven of the PR's nine new tests unreachable under Bazel.
`make bazel-sync-check` does not catch this: `tools/bazel/go_srcs.py --check`
only validates the `go_srcs` filegroup globs, not the `go_library`/`go_test`
srcs enumerations.
Four unrelated test files (config_leaked_secret_test.go, init_role_*_test.go,
init_git_bootstrap_routing_test.go) are also unlisted, but they are unlisted
on the base too, so they are left alone as pre-existing.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* fix(backup): stop the size-cap walk from running on every bd command (#6071 review)
Maintainer review fixup for PR #6071 (ga-y6gjv), iterations 1 and 2.
The gating finding, filed independently by both review lanes and confirmed
empirically: the fixup that moved the getDirSize walk behind the interval
throttle does not deliver its claimed property, because state.Timestamp —
the only thing that re-arms that throttle — is written in exactly two
places, both inside runBackupExport. The two steady states that skip
before reaching it therefore pass the throttle on every single bd
invocation and pay the full filepath.Walk forever:
IDLE no new Dolt commit; the walk runs, then change detection skips
and writes nothing.
PAUSED cap exceeded; the walk has already happened by the time
maybeWarnBackupSizeCap persists LastCapWarnAt, which is the only
field it wrote.
PAUSED is the pathological case: an over-cap destination is by definition
the largest one, so the feature's terminal state was its most expensive,
persisting until an operator intervened. This landed on read-only
commands too, i.e. the 65-100ms/command agent-polling regression the walk
was moved to avoid.
Both halves of the documented remedy:
- Move the cap check after change detection, the order
docs/reference/configuration.md already describes ("If data changed and
the throttle interval has passed, bd checks the destination
directory's on-disk size"). This makes that sentence true and closes
the docs finding with no docs edit.
- Re-arm the interval throttle (state.Timestamp) on the cap-exceeded
skip, leaving LastDoltCommit untouched exactly as runBackupExport's own
failure path does, so change detection still sees pending work once the
cap is raised.
Neither half suffices alone: the reorder still walks every command in a
PAUSED workspace where data IS changing, and the persist alone still walks
forever when IDLE. Persisting on the idle skip instead would add up to one
backup.interval of backup latency, which this pairing avoids.
Also from the same review, all non-gating:
- The cap-check error path failed open behind a debug-only line, so one
unreadable entry could silently restore unbounded growth while
`bd backup status --json` reported the very same error. It now warns on
stderr, throttled by the backup interval and deliberately not by the
LastCapWarnAt slot: spending that slot here would suppress the more
important PAUSED notice for a full warn interval.
- The warn timestamp is now recorded only when the message was actually
printed, so --json/--quiet agent calls stop consuming the 24h slot
silently.
- Dropped capWarnFallback (map, mutex, two accessors). No reachable
production path can read it: both call sites are in PersistentPostRunE,
which runs once per CLI process, and the proxy child installs an empty
PersistentPostRun. Its pinning test is repurposed to the contract that
is real — a persist failure must not block the already-decided skip.
- Registered backup.size-cap-mb / backup.size-warn-interval in
YamlOnlyKeys, so the backup block is a complete inventory again.
Functionally inert: the map has no enumerator and its one predicate
consumer already matches on the "backup." prefix.
- `bd backup status` prints "Size cap: unavailable (<err>)" instead of
dropping the line, and the JSON error object carries an explicit null
`exceeded` so a consumer cannot read a missing key as "not exceeded".
The CHANGELOG's cost claim is corrected to match the shipped order; it
described the throttle as sufficient, which is the defect above.
Iteration 2, all non-gating (that review approved):
- The walk-error path re-arms the interval throttle itself before
proceeding uncapped. Iteration 1 relied on the fall-through into
runBackupExport to bound that warning to once per backup.interval,
but not every runBackupExport exit persists state.Timestamp: a failed
post-sync GetCurrentCommit returns without saving state, so the walk,
the warning and the sync itself repeated on every command. The doc
comment now states the bound the code has: once per interval whenever
backup_state.json can be written.
- `bd backup status` echoes the configured backup.size-cap-mb when the
cap is disabled instead of a literal 0. viper's GetInt also resolves
an unparseable value ("2048MB") to 0, so the line asserted a value the
operator never wrote.
- The status readers count only a destination that does not exist yet
as empty. getDirSize aborts on the first per-entry error, so a chunk
file removed mid-walk read as 0 bytes, i.e. `"exceeded": false` for a
destination that may be over its cap. It is now reported as
unavailable, like any other walk error.
- docs/reference/configuration.md no longer says `--json` reports the
string `PAUSED (cap exceeded)`; it reports `size_cap.exceeded: true`.
- TestMaybeAutoBackup_CapCheckSkippedWhenThrottled seeded the same commit
as its watermark, so after iteration 1's reorder change detection
alone stopped the walk: it passed with the interval throttle deleted,
and so did every other Backup/Throttle/Auto test in cmd/bd. It now
seeds a changed commit, and its comment names the renamed
pauseAutoBackupForSizeCap.
Tests: iteration 1's four new/updated pins are each mutation-proved.
Dropping the throttle re-arm reds the three throttle pins and leaves the
idle pin green; restoring the original ordering reds only the idle pin;
reverting both reds all four. Iteration 2's three new pins each go red
under their own mutation only: dropping the walk-error re-arm, restoring
the literal `=0`, and swallowing a walk ENOENT (dropping the root stat
reds the missing-destination case instead). Disabling the interval
throttle now reds the throttle test.
Base refresh before approval (rebased onto main 3f9561db2b, which had
made the PR CONFLICTING):
- main 8269a88cbf (#6327) moved compact onto storeSizeBytes and
deleted getDirSize from compact.go, leaving backup_cap.go its only
caller, so the merged tree failed to build (undefined: getDirSize)
although only CHANGELOG.md and backup_auto.go conflicted textually.
getDirSize is restored verbatim in backup_cap.go (plus the
path/filepath import), and the two comments that described it as
shared with, or exercised by, compact.go are corrected.
- main 4e4ebdb443 (#6879) added acquireBackupLock where this commit
places the size-cap check. Both are kept, the cap check first, as
its comment asks: a skip should not first take the lock.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
Co-authored-by: Julian Knutsen <julianknutsen@users.noreply.github.com>
Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
* test(feat): red — Add soft watchdog warning for long-running schema migrations (refs be-yyzzs)
* feat: green — Add soft watchdog warning for long-running schema migrations (refs be-yyzzs)
* fix(schema): address review follow-ups on migration watchdog doc citation (refs be-yyzzs, review be-sogif)
Round 1 review (be-sogif) flagged criterion 7: the soft-watchdog comment
at schema.go cited engdocs/plans/be-m65rs-migration-watchdog-scoping.md,
which was never landed to any reachable ref (only exists on PM's own
unmerged worktree branch). Replace the dangling file citation with an
inline summary of the rationale plus reachable citations: the existing
initSchema comment in store.go (migration 0047 as a concrete long-runner
example) and `bd show be-m65rs` for the full scoping decision. Comment-only
change; no functional/behavioral diff. gofmt/build/vet clean; full package
suite reconfirmed 132 PASS, 0 FAIL, 0 SKIP.
* test(schema): red — watchdog is silent off a tty, and ignores bare seconds
Both from review #5997.
TestRunMigrationsWatchdogSurvivesNonTTY drives runMigrations end to end
with a deliberately slow first migration body and a 10ms interval, with
the progress writer put in the state a non-tty caller really sees. It
fails with an empty buffer: runMigrations hands the watchdog the package
stderr var, which is io.Discard whenever os.Stderr is not a terminal, so
the warning is discarded under bd serve, systemd, CI and any piped
invocation — the exact cases where a migration running for twenty minutes
needs to be visible. On a tty it works, which is why this went unnoticed.
Asserting on the wiring rather than on a package variable, so the fix has
to actually reach the call site.
The interval table gains bare-seconds cases. store.go's parseTimeout — the
convention migrationWatchdogIntervalDuration's own doc comment claims to
follow — documents "bare numbers treated as seconds (e.g. \"90\")", and
this one does not, so an operator setting the value to 90 silently gets
5m.
Note the review's own example value, 300, cannot serve as the test input:
300s IS the 5m default, so it passes whether the value was parsed or
discarded. Using 90 and 600 instead, which distinguish.
watchdogStderr exists here but is not yet wired, so the red is behavioural
rather than a compile error.
Refs be-lotba.
* fix(schema): point the watchdog's last dangling citation at bd show be-m65rs
Review #5997 point 1. Round 2 replaced the citation on the call-site
comment but missed the one in runMigrationWithWatchdog's own doc comment,
which still named engdocs/plans/be-m65rs-migration-watchdog-scoping.md.
That path does not exist, and neither does engdocs/plans/ — so the comment
sent a reader after a file that was never committed.
Points it at bd show be-m65rs, matching what the call site already says.
This was the last engdocs/plans reference in the repo; a repo-wide grep for
that prefix is now empty, so the two comments can no longer disagree.
Refs be-lotba.
* fix(schema): send the migration watchdog WARN somewhere a non-tty caller sees
Review #5997 point 2. The package's stderr var is io.Discard whenever
os.Stderr is not a terminal (schema.go:26-37) — it was introduced for
routine per-migration progress lines, where discarding off a tty is
correct. Wiring the watchdog to it inherited that gating, so the WARN was
emitted only on an interactive terminal and silently dropped under bd
serve, systemd, CI and any piped invocation: precisely the situations
where a migration still running after twenty minutes is worth knowing
about. On a tty it worked, which is why it was not caught earlier.
Routes the watchdog through its own writer instead. This is not a new
convention for the package — remote_migrate_gate.go, smart_remote_migrate
_gate.go and both schema-skew notices in this file already write operator
warnings straight to os.Stderr, ungated, for the same reason. stderr keeps
its terminal gating and its progress lines.
Chose the writer over the alternative the review offered (scoping the doc
comment to "interactive runs"), since the feature's stated purpose in
be-m65rs is telling an operator reading logs that a migration is still
working — and logs are the non-tty case.
Turns TestRunMigrationsWatchdogSurvivesNonTTY green; it asserts through
runMigrations rather than on the package var, so the wiring at the call
site is what is under test.
Refs be-lotba.
* fix(schema): accept a bare-seconds watchdog interval, matching parseTimeout
Review #5997 nit. BEADS_MIGRATION_WATCHDOG_INTERVAL=300 fell back to the
5m default instead of meaning 300s, so an operator changing the value got
the number they were trying to change and no diagnostic.
The doc comment claimed to follow internal/storage/dolt/store.go's
timeoutFromEnv, but only its unset/invalid-falls-back shape. timeoutFromEnv
is a one-line wrapper; the contract lives in parseTimeout below it, which
retries an unparsable value as raw+"s" so bare numbers mean seconds. This
function skipped that half, so the comment promised a convention the code
did not implement. Now mirrors parseTimeout's full shape — including its
non-positive handling on both branches — and cites parseTimeout by name,
since that is where the behavior being mirrored actually is.
On the review's related note that d > 0 is the only floor: that is
deliberate and is also parseTimeout's only floor. Diverging here would
make the two disagree again, which is what produced this nit. Happy to add
a minimum on both together if you want one.
Not reused directly because parseTimeout is unexported in another package.
The interval table gains bare-seconds cases; 90 and 600 rather than the
review's 300, since 300s is the 5m default and so cannot distinguish
"parsed as seconds" from "fell back".
Refs be-lotba.
* docs(changelog): add the migration watchdog to Unreleased
Review #5997 nit: a new user-facing env var and a new WARN line earn an
Deliberately CHANGELOG only, not docs/reference/configuration.md — even
though BEADS_FSCK_TIMEOUT, the sibling this env var's parsing mirrors, has
a row in that page's table. docs/ describes the pinned release
(docs/cli-docs.pin is v1.2.2, which does not contain this feature) rather
than main, per engdocs/decisions/2026-07-17-docs-release-pin.md. The table
row belongs with the pin bump at release time; adding it now would
document a flag no released bd accepts.
Refs be-lotba.
* fix(bazel): list migration_watchdog_test.go in the schema go_test srcs
Base added internal/storage/schema/BUILD.bazel after this PR's merge base,
enumerating go_test srcs file by file. The PR's new migration_watchdog_test.go
was therefore absent from it, so under Bazel the target reported
"Executed 1 out of 1 test: 1 test passes" while running NONE of the new tests
("testing: warning: no tests to run") -- a silent green.
Measured both ways on the adopted head: without this entry 0 watchdog tests
run; with it, all 7 tests and 8 subtests execute and pass
(bazel test //internal/storage/schema:schema_test). The enumeration is
maintained at 100% repo-wide -- all 56 unlisted test files are
//go:build-tagged -- so this file would have been the only untagged omission.
Maintainer fixup applied during PR adoption's rebase gate. No contributor
code changed; the contributor could not have seen this file, which did not
exist at the merge base.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* fix(schema): scope the watchdog promise to the migration body, stop the warner on panic
Maintainer fixup applied during PR adoption's review loop (iteration 1),
addressing the one major plus the three non-gating findings in the review
synthesis. No contributor commit was rewritten.
Major -- Change Impact / Blast Radius (scope). The watchdog wraps only
execMigrationBody, while a migration step also runs the dirty-table snapshot,
preMigrationRepair, the cursor INSERT and commitMigrationStep -- and this file
already says the per-step DOLT_ADD/DOLT_COMMIT is "the expensive, fallible part
of this step on the production embedded path". The CHANGELOG therefore
over-promised: it told users a wedged migration no longer "looked identical from
outside", which is false for a wedge in that commit. The synthesis offered two
arms and said explicitly not to do both. Taking the minimal-sufficient arm:
CHANGELOG.md now scopes the guarantee to the migration body and states that a
stall in the per-step commit is still quiet, and a comment at the call site
records that the narrow boundary is deliberate, and why. The extension arm was
declined on cost: widening the wrap means moving the snapshot/commit ordering
that carries this loop's atomic-commit contract (#4566, #4690), under a
strict-ordered sqlmock expectation set and the cross-package
migrateStepFaultHook tests -- more risk than an observability-only change should
carry. Measured: this fix leaves runMigrations at gocyclo 16 / gocognit 29,
byte-identical to before, whereas nesting the whole step in a closure would have
driven the cognitive score well past its current band.
Minor -- Resource Lifecycle & Cleanup. close(done)/wg.Wait() moved into a defer.
A panic out of fn skipped the straight-line close and orphaned the ticker
goroutine, which then went on warning about a migration that was no longer
running, for the life of the process, on the deliberately un-gated
watchdogStderr. Reachability is open rather than proven
(internal/httpapi/server.go:1406 recovers everything but http.ErrAbortHandler
and keeps serving), which is the argument for taking the one-keyword fix. Pinned
by a new test: against the pre-fix schema.go it reds with "3 WARN lines when the
panic unwound, 8 after a further 50ms"; with the defer it passes under -race.
Minor -- Test Evidence Quality. TestMigrationWatchdogIntervalDuration's
"unset_defaults_to_5m" arm never unset anything, so the ambient environment flowed
straight into the call. Two-arm control: with BEADS_MIGRATION_WATCHDOG_INTERVAL=600
exported the old arm reds ("= 10m0s; want 5m0s") and the fixed arm passes, with the
subtest confirmed to have actually run rather than being filtered out.
Nit -- Contract & Interface Fidelity. BEADS_MIGRATION_WATCHDOG_INTERVAL added to
docs/reference/configuration.md's env table, beside the BEADS_FSCK_TIMEOUT row
whose duration contract it mirrors.
Validation: go test ./internal/storage/schema/ -count=1 green (41s); 8 watchdog
tests + 8 subtests PASS, 0 SKIP, 0 FAIL; gofmt clean; go vet clean; git diff
--check clean; ./scripts/check-doc-freshness.sh PASSED.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* fix(bazel): list golang.org/x/term in the schema go_test deps
migration_watchdog_test.go imports golang.org/x/term directly. Under Bazel
it compiled only through embed = [":schema"], but gazelle lists a test
file's own imports in the go_test's deps, so `bazel run //:gazelle`
rewrites this BUILD file. Since the base now gates PRs on the Bazel lanes,
BAZEL_TEST's "BUILD files in sync (gazelle, go_srcs, MODULE.bazel)" step
would fail on exactly this one line. This is the line gazelle produces.
Measured on the adopted head refreshed onto current main: the whole CI sync
step run locally (go_srcs.py --check, bazel run //:gazelle, go_srcs.py,
bazel mod tidy) leaves this line as the only drift in the repository.
With it, bazel test //internal/storage/schema:schema_test --config=ci
passes: 433 test cases, 0 failures, all 16 watchdog cases run (0 skipped),
and tools/bazel/check_testcases.py plus equivalence.py report no schema
divergence.
Maintainer fixup applied during PR adoption's pre-approval CI repair. No
contributor code changed.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Julian Knutsen <julianknutsen@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
* 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>
* fix(formula): substitute vars in step assignee, labels, and metadata
Cook and pour substituted title/description/notes/gate but copied
assignee, labels, and metadata through raw, so a poured bead carried
literal `{{var}}` text in all three.
- labels: every label-based query, filter, and automation silently stops
matching, and nothing errors (GH#5110).
- metadata: general keys came through literal; only a top-level "repo"
key on a gh:* gate was substituted (GH#5110).
- assignee: worse than cosmetic - close refuses when the actor doesn't
match the assignee, so every step of a poured molecule is unclosable
and the molecule can never advance (GH#5754).
internal/formula/expand.go already substituted assignee and labels on
the inline-expansion path, so the two paths disagreed on the same
fields; Step.Assignee is documented as "supports substitution" and
ExtractVariables already scanned it, meaning pour hard-failed demanding
a variable it then refused to resolve.
Both call sites are fixed together: runtime-mode cook feeds the proto
that pour clones, so a field left literal in either path ships a
placeholder onto the bead. Fixing cloneSubgraphInto covers pour, wisp,
bond, and the proxied-server paths, which all funnel through it.
substituteMetadataRepo is generalized to substituteMetadataVars, which
resolves every string leaf of the metadata JSON at any depth. This drops
the earlier gh:*-gate-only restriction (SF2/SF4): reading a `repo` key
AS a GitHub selector is only correct on a gh:* gate, but resolving a
{{var}} in it interprets the key not at all. The walk still decodes into
json.RawMessage, so untouched values stay byte-identical, and object
keys are never rewritten (a rewritten key could collide with a sibling).
The variable scan is widened to match: extractAllVariables (pour) and
ExtractVariables (cook) now cover assignee, labels, metadata strings,
notes, and await ID, so pour demands exactly the variables it resolves.
Undeclared handlebars are still filtered out by VarDefs.
Regression coverage asserts on a poured bead, and checks the assignee
via validation.AssigneeMatches rather than a string compare - a
substitution-only assertion would pass while the unclosable symptom
persisted.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* chore(formula): regenerate schema_gen.go after the types.go doc edits
TestSchemaGenIsCurrent holds schema_gen.go to a byte-for-byte rerun of
the generator over types.go, and the field docs are part of the
generated output — so the Labels/Metadata comment updates made it stale.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* fix(mol bond): resolve vars like pour instead of demanding every handlebar
buildAttachCloneOpts demanded every variable extractAllVariables found in
the proto subgraph and applied no declared defaults, unlike pour
(cmd/bd/pour.go) and wisp (cmd/bd/wisp.go). Widening the scanned field set
to assignee, labels and metadata therefore widened bond's hard refusal
along with it: a proto whose label or metadata carried an undeclared
documentation handlebar, or a declared var carrying only a default, made
`bd mol bond` fail with "missing required variables" where it previously
succeeded.
Run applyVariableDefaults + extractRequiredVariables there, matching the
sibling call sites. extractRequiredVariables returns the unfiltered list
when VarDefs is nil, so a legacy template still requires every var it
mentions; the change is strictly a reduction in false failures. Applying
the defaults also puts them in opts.Vars, which is the map
cloneSubgraphInto actually substitutes from.
Also from review:
- docs/workflows/gates.md no longer enumerates a stale three-field list for
where `{{var}}` substitution applies.
- maxMetadataSubstitutionDepth's doc names walkJSONStrings (not the
long-gone substituteJSONVars) and says plainly that hitting the bound
deliberately ships a literal placeholder rather than erroring.
Reported-by: 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>
* build(bazel): add the validation dep to the bd_test go_test (make bazel-sync)
mol_embedded_test.go and template_test.go now import internal/validation
directly (validation.AssigneeMatches, to check the substituted step
assignee), so gazelle emits //internal/validation on bd_test. bd_lib
already carries the dep, so bd_test compiles through embed, but gazelle
lists every direct test import on the go_test itself. cmd/bd/BUILD.bazel
landed on main after this PR branched, so the PR could not carry the
line; without it, bazel.yml's "BUILD files in sync" step fails in the
required Bazel / test lane. Generated by `make bazel-sync`.
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: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-authored-by: Eddie the Engineer <adopt-pr@gascity.local>
* test(doltserver): red — ResolveServerMode ignores BEADS_DOLT_SERVER_PORT/BEADS_DOLT_PORT (refs be-9i0yq.1)
* feat(doltserver): green — ResolveServerMode honors BEADS_DOLT_SERVER_PORT/BEADS_DOLT_PORT (refs be-9i0yq.1)
* test(doltserver): isolate BEADS_DOLT_SERVER_PORT/BEADS_DOLT_PORT in ambient-blind tests (refs be-lbnk8)
TestResolveServerMode_Default, _EmbeddedMode, and _EmbeddedHonoredWithoutServerEnv
cleared BEADS_DOLT_SHARED_SERVER/BEADS_DOLT_SERVER_MODE via t.Setenv but never
cleared BEADS_DOLT_SERVER_PORT/BEADS_DOLT_PORT, so they silently depended on
ambient absence of those two vars. That held in clean CI but not in this rig
(BEADS_DOLT_SERVER_PORT=28231 ambient), where round-1's new env-port-aware
step 2c in ResolveServerMode correctly fired and these three regressed.
servermode.go is unchanged: its precedence logic was already correct, and the
round-1 tests (EnvPortImpliesExternal, EnvPortOverridesStaleEmbedded) already
prove it. This is a test-hermeticity fix matching the isolation pattern those
two tests already follow.
* fix(doltserver): green — killStaleServersForDir ignores ambient BEADS_DOLT_SERVER_PORT (refs be-lbnk8)
killStaleServersForDir's orphan-cleanup guard (GH#2430) called the public
ResolveServerMode, which treats an ambient BEADS_DOLT_SERVER_PORT/
BEADS_DOLT_PORT (set fleet-wide on multi-agent rigs purely to route bd's
own client connections) the same as a genuine "not my server" declaration
(explicit shared-server/host/port config). That collapsed connection-
routing into lifecycle-ownership, so the guard silently skipped orphan
cleanup for directories beads still owns whenever the ambient var was set.
Split ResolveServerMode into a shared resolveServerMode(dir, honorPortEnv)
implementation:
- ResolveServerMode(dir) = resolveServerMode(dir, true) — unchanged
behavior for all existing callers.
- resolveServerModeIgnoringPortEnv(dir) = resolveServerMode(dir, false) —
skips only the ambient-port-var check, used solely by
killStaleServersForDir's guard.
Audited the other three production ResolveServerMode call sites
(internal/storage/dolt/open.go:47+182, cmd/bd/bootstrap.go:914); all three
correctly want the ambient port var included (auto-start suppression and
clone-strategy selection both need to route to an already-running server),
so they are left calling the public ResolveServerMode unchanged. A fourth
call site (internal/storage/dolt/store.go:1602) already independently
short-circuits on the same env vars before it would ever reach
ResolveServerMode, so it was unaffected by construction. Audit findings
recorded in be-lbnk8's notes.
TestKillStaleServersPreservesOtherRepoServers (added in the prior round)
now passes; TestResolveServerMode_HostInferredExternal and
TestResolveServerMode_EnvHostBeatsEmbeddedMetadata remain the same two
pre-existing/unrelated failures confirmed at the parent commit (tracked
as be-wbyau).
* docs(release-gates): record be-lbnk8 gate PASS (ambient serverport scoping fix)
Deploy gate for be-mob5e (source review be-lbnk8, deploy commit
f5328d863153ecef94df9713ca2e3ed5e0ab0a95). 7/7 criteria PASS, with
two named non-blocking exceptions in the policy/lint lane (stale
.githooks/commit-msg marker check, and a stale golangci-lint
result-cache artifact referencing a deleted worktree) — both
environmental, independently verified, unrelated to the diff.
* fix(doltserver): exempt proxied-server from the port-env check, gate the carve-out
Check 2c classified any workspace with BEADS_DOLT_SERVER_PORT set as external
without either guard HostImpliesServerMode applies. The proxied-server
exemption is the one that bites: a proxied workspace reaches its server through
the proxy, so an ambient port does not describe its lifecycle, and our own
constellation runs dolt_mode: proxied-server with that variable set. 2c now
mirrors 2b's exemption.
The second HostImpliesServerMode guard -- any explicit non-empty DoltMode
suppresses inference -- is deliberately NOT mirrored, because
TestResolveServerMode_EnvPortOverridesStaleEmbedded pins the opposite for
dolt_mode=embedded on GH#2949 grounds. configfile.IsDoltServerMode has no port
check at all, so for that one combination the storage-mode and lifecycle
resolvers still disagree. That is a precedence question above this change, not
something to settle by picking whichever makes the tests green; the code says
so and it is tracked separately.
Adds TestKillStaleServersReapsOrphanUnderAmbientServerPort, the missing gate on
the resolveServerModeIgnoringPortEnv carve-out: it sets the port variable
itself rather than relying on the host exporting one, so it catches a
re-disabled GH#2430 anywhere. Red/green confirmed -- pointing the guard back at
the naive ResolveServerMode gives killed=[], want [222].
Two mode tests also stopped inheriting an ambient Dolt port.
TestResolveServerMode_EnvHostBeatsEmbeddedMetadata and
TestResolveServerMode_HostInferredExternal neutralize SHARED_SERVER,
SERVER_MODE and SERVER_HOST but never the port vars, so on a host that exports
one they asserted against it. The latter fails that way on origin/main too. The
whole internal/doltserver package now passes under this rig's real ambient
BEADS_DOLT_SERVER_PORT, which the previous body claimed and did not do.
Adds the CHANGELOG entry this user-visible auto-start change was missing.
(refs be-lbnk8)
* refactor(configfile): centralize the port-implies-server-mode rule
doltserver kept a private doltServerPortFromEnv plus an inline proxied-server
exemption -- a second copy of a rule that belongs beside HostImpliesServerMode.
Extract Config.PortImpliesServerMode with the same shape (proxied exemption,
then BEADS_DOLT_SERVER_PORT and the legacy BEADS_DOLT_PORT) and have
resolveServerMode's check 2c call it. No resolver changes behaviour.
Also corrects check 2c's doc comment, which was the actual defect the review
found rather than the code. It claimed the "explicit non-empty DoltMode
suppresses inference" guard was deliberately unmirrored and called that an
unresolved precedence question. HostImpliesServerMode does not work that way:
it reads BEADS_DOLT_SERVER_HOST at configfile.go:421-423 and can return there,
before the DoltMode suppression at :424-426 is ever reached. Real precedence is
env > explicit dolt_mode > persisted host, and 2c already mirrors every tier
with a port-side counterpart -- there is no persisted-port tier to guard,
because an explicit dolt_mode=embedded returns at check 3 before check 4 reads
metadata.json's dolt_server_port. Settled as be-yb2ai;
TestResolveServerMode_EnvPortOverridesStaleEmbedded keeps pinning it.
IsDoltServerMode deliberately does NOT consult the new predicate: it selects the
storage backend for every data command, a far wider blast radius than this
lifecycle-only change, and extending it needs its own call-site audit. The two
resolvers therefore still disagree for an unset/embedded dolt_mode plus a bare
port env var and no other server signal. That gap is documented at both sites
and owned by be-2nolj.
TestPortImpliesServerMode covers the new predicate directly: 14 cases over env
precedence, invalid/zero/negative ports, env-beats-explicit-dolt_mode, and the
proxied-server exemption including case-insensitivity. (refs be-lbnk8)
* docs(changelog): say the ambient port marks external, not "no longer suppresses auto-start"
The headline claimed an ambient BEADS_DOLT_SERVER_PORT "no longer suppresses
auto-start". This PR does the opposite: check 2c yields ServerModeExternal for
that var, resolveAutoStart (internal/storage/dolt/open.go:223) returns false on
External, and ensureServerRunning (internal/doltserver/doltserver.go:969-985)
refuses to start with "auto-start is suppressed because the server is
externally managed".
Only the reap clause was true. The headline now states both halves as they
behave, matching the entry's own body text.
Review round 3 blocking point 1 (bee-ghosttrack).
* docs(dolt): note that an ambient server port marks the workspace external
docs/architecture/dolt.md presented BEADS_DOLT_SERVER_PORT purely as the port
knob, in both the server-mode connection table and the environment-variable
table. Since check 2c it is also a lifecycle assertion: on a plain
non-shared, non-proxied workspace it resolves ServerModeExternal, so
auto-start is suppressed and PortSourceEnv -- documented at
internal/doltserver/doltserver.go:630 as an authoritative user assertion --
is unreachable for a bd-owned auto-start. A user setting it to pick a port
gets the "externally managed" refusal instead of a server.
Both sites now say so. proxied-server is called out as exempt; shared-server
already resolves external at check 2, before 2c is reached.
Review round 3 non-blocking point 2 (bee-ghosttrack).
* docs(servermode): cite GH#6181 for the IsDoltServerMode gap, not an invisible bead
Both cross-references for the deferred resolver-precedence gap pointed at
be-2nolj, an internal bead id maintainers cannot see -- the reason review
round 3 asked for a GitHub issue. bee-ghosttrack opened GH#6181
("doltserver: ResolveServerMode and configfile.IsDoltServerMode must share
one inference gate") from this review, which is exactly that tracker, so the
comments now name it.
Comment-only; no behavior change.
Review round 3 point 2 follow-up (bee-ghosttrack).
* feat: green — Fix: PR #5934's env-port check reclassifies bd's own server as shared, so it refuses to migrate (refs be-4yy5e)
* chore: remove leaked internal release-gate doc from PR branch
release-gates/be-lbnk8-serverport-ambient-scope-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
---------
Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
* fix(formula): reject a waits_for gate that has no spawner to wait for
waits_for = "all-children" (or "any-children") names no spawner, so
collectDependencies infers one from needs[0] and emits no dependency at
all when the step has no needs. Validation accepted that step, cooking
gave it a gate:all-children label, and the result was a step with zero
dependencies that is ready immediately — a fan-in that silently never
fans in. Only the label survived to suggest otherwise.
Reject it where the intent is still visible, naming both repairs: add
needs, or name the spawner with children-of(step-id), which carries its
own spawner and stays valid without needs. depends_on is deliberately not
accepted as a substitute, because the inference does not read it.
The fan-in example in docs/workflows/gates.md taught exactly the broken
shape — a summarize step with waits_for and no needs — so it is corrected
here alongside, with the spawner step it was missing.
* fix(formula): make a validation failure distinguishable from "not a formula"
Callers that resolve a name as a formula and fall back to a proto/issue
lookup have no way to tell the two apart, so a formula that exists and
does not validate is reported as not found and its real error is thrown
away. The spawnerless waits_for gate rejected above lands in exactly that
path.
ErrVarValidation already exists for the same reason, covering bad --var
values. Give Validate the matching sentinel; the message it produces is
unchanged. Wiring the fallbacks to it is a separate change.
* fix(mol): report an invalid formula instead of calling it not found
pour, wisp, bond and seed resolve a name as a formula first and fall back
to a proto/issue lookup. Any error from the formula path was treated as
"this is not a formula", so a formula that exists and fails validation
came back as "'<name>' not found as formula or proto ID" — with bd
formula list happily showing it. The real error was never printed, and
the advice to run bd formula list confirmed the wrong diagnosis.
Each fallback now reports a validation failure directly, the way it
already does for the bad --var values ErrVarValidation covers. A name
that really is not a formula is unaffected.
* fix(mol bond): make --dry-run validate the formula the real bond validates
resolveOrDescribe resolved a formula name with parser.LoadByName, which
never calls Formula.Validate - LoadByName -> loadFormula -> ParseFile does
not, and only parser.Resolve does. The real bond path
(resolveAndCookFormulaWithVars) calls Resolve, so the dry-run previewed
"will cook as proto" for every formula the real bond rejects, including
for the waits_for-without-a-spawner rule this branch adds. The function's
own comment already promised the opposite.
resolveOrDescribe now resolves before it validates provided vars, which
also means the --var check runs against the merged formula rather than the
unmerged one, so a var declared only in a parent is checked too. The two
error wrappings match the real path's, so the routes produce the same
message rather than merely the same exit code.
TestBdMolBondDryRun_RejectsInvalidFormulaLikeTheRealBond runs both routes
against the same invalid formula and asserts they agree - both fail, both
name waits_for, neither reports it as "not found as issue or formula". It
reproduces the gap against the old code:
dry-run previewed a bond the real bond rejects:
A: dryrun-invalid-gate (formula -> will cook as proto)
Also from review:
- validation_sentinel_test.go uses strings.HasPrefix instead of a slice
that would panic with index-out-of-range rather than failing cleanly if
the message ever shortened.
- Step.WaitsFor's field doc now states the needs requirement, and
schema_gen.go is regenerated from it, so the generated schema documents
the rule the validator enforces. docs/workflows/gates.md already said it.
The condition-filtering follow-up is filed as GH#6437: Validate runs
inside parser.Resolve, before FilterStepsByCondition, so a spawner dropped
by a false condition still reaches collectDependencies as a dangling
reference and is skipped silently - the same zero-dependency gate, past
the new check.
Reported-by: 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>
* test(mol bond): assert the dry-run gap in process, not through a subprocess
The regression test spawned an embedded bd and ran two CLI invocations,
which is the most expensive shape of test in cmd/bd - and cmd/bd already
runs 477s of its 600s budget on the macos runner, so the addition timed
the package out.
The process boundary was never what the test was about. resolveOrDescribe
and resolveOrCookToSubgraph are both reachable directly with a molReader
that answers "no such issue", and GT_ROOT puts a temp formula dir on
formula.DefaultSearchPaths without touching HOME or the working directory.
Same assertion - the two routes agree, both name waits_for, neither
reports an invalid formula as not found - in 0.03s instead of 18s.
Asserting the routes against each other rather than against a literal
message is deliberate: it is what stops a validation rule added later from
re-opening the same gap. The LoadByName control is now explicit too, since
that call still accepting the formula is the reason the bug existed; if it
ever starts validating, the comparison stops distinguishing anything and
the test says so instead of passing quietly.
Second case added while here: the dry-run validated --var values against
the UNMERGED formula, so a constraint declared only in a parent went
unchecked. Resolving first fixes that as well, and an extends chain with
the enum in the parent pins it:
dry-run accepted a var value the real bond rejects; the enum is
declared only in the parent (real bond said: formula "dryrun-child":
variable validation failed:
- variable "env": value "staging" not in allowed values [dev prod])
Agent-Signature: claude-code-opus-5-unknown-reasoning on behalf of Harry Miller
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* docs(changelog): move this PR's entry under [Unreleased]
The 1.3.0 cut renamed the old [Unreleased] block, so the entry this branch
added there now merges cleanly into the released [1.3.0] section (#6643).
Agent-Signature: claude-code-opus-5-5-unknown-reasoning on behalf of Harry Miller
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* chore(bazel): enumerate the PR's two new test files in go_test srcs
Base added cmd/bd/BUILD.bazel and internal/formula/BUILD.bazel after this
branch's merge base, so the two untagged _test.go files this PR adds were
absent from their go_test srcs lists. Generated by 'make bazel-sync'
(bazel run //:gazelle); no hand edits. A second sync is a no-op.
* docs(formula): correct the waits_for spawner doc and the dry-run parity claim
Maintainer review fixup for the adoption of #5761 (review iteration 1
pre-merge checklist). Wording only -- no control flow changes.
internal/formula/types.go: the new Step.WaitsFor doc said "Requires needs
(or depends_on)", but Formula.Validate receives only step.Needs and cook
infers the spawner solely from Needs[0] (cmd/bd/cook.go:961-962) -- the
DependsOn loop never feeds waitsForSpawnerStepID, and the struct doc's
"merged during cooking" happens after Validate. A depends_on-only bare gate
is therefore correctly rejected: the code and the error message are right,
only the comment was wrong, and it shipped into the generated schema surface
agents read. docs/workflows/gates.md already states it correctly.
Regenerated schema_gen.go with `go generate ./internal/formula/`.
CHANGELOG.md: "so it fails on exactly what the real bond fails on" was an
overclaim. The dry-run now resolves and validates the way the real bond
does, but five later real-path failure surfaces (inline expansions,
expansions, aspect load/type, condition filtering) stay outside the preview.
Named that boundary rather than claiming total parity.
Contributor commits untouched.
---------
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
* storage: add RenameLabel primitive with merge semantics
Add a storage primitive that renames a label across every issue and
wisp that carries it, in one transaction per store. An issue that
already carries the new label is a merge - the stale old-label row is
dropped rather than raising a duplicate-key error - and the call
reports renamed/merged counts plus every touched id.
- internal/storage/issueops/labels.go: RenameLabelInTx sweeps the
labels and wisp_labels tables (INSERT IGNORE then DELETE, so the
merge never errors), emitting one EventLabelRenamed plus the usual
full-snapshot journal row per touched issue/wisp, matching
AddLabelInTx/RemoveLabelInTx's journal shape. A single batch event
was considered and rejected: the journal-completeness guard requires
every touched row to carry its own journal entry.
- internal/storage/storage.go: RenameLabel added to the Storage
interface, next to AddLabel/RemoveLabel/GetIssuesByLabel.
- internal/storage/dolt, internal/storage/embeddeddolt: direct
implementations. The dolt commit targets the fixed events/labels
table pair; doltAddAndCommit's own HasStagedChanges guard skips it
when the rename touched wisps only (wisp tables are dolt-ignored,
same as AddLabel/RemoveLabel).
- internal/storage/hook_decorator.go: HookFiringStore.RenameLabel
fires on_update per touched issue, matching AddLabel/RemoveLabel.
- internal/types/types.go: new EventLabelRenamed event type. Unlike
EventLabelAdded/EventLabelRemoved, one rename produces exactly one
of these per touched row, never a paired add+remove.
- internal/jira/tracker_test.go: mock stub for the new interface
method.
Tests: internal/storage/dolt/label_rename_test.go, against a real
dolt-sql-server container - basic rename, merge, wisp sweep,
zero-carrier no-op, over-length refusal, event assertion. All green.
Also verified TestEveryBeadMutatorJournalsOrIsExempt still passes.
Gates: gofmt clean, go vet ./... clean, CGO_ENABLED=0 go test -tags
gms_pure_go -c -o /dev/null ./cmd/bd clean, go build ./... clean.
* storage: refuse RenameLabel(x, x) instead of wiping the label
RenameLabelInTx's merge branch treats every carrier of oldLabel as
already carrying newLabel when the two names collide (they are the
same string): the batched INSERT IGNORE no-ops on every row, and the
unconditional DELETE FROM <table> WHERE label = ? that follows then
removes every row for that label plane. A self-rename silently wiped
the label instead of leaving it untouched.
Reject oldLabel == newLabel (compared after trimming, case-sensitive)
before any write, returning the new ErrRenameLabelSameName. Verified
red->green: TestRenameLabel_SameNameRefused and
TestRenameLabel_SameNameAfterTrimRefused both fail (GetLabels returns
[] on both the labels and wisp_labels planes) against the pre-fix
code, and pass against the fix. Full TestRenameLabel* suite in
internal/storage/dolt still green.
* telemetry: instrument InstrumentedStorage.RenameLabel
AddLabel and RemoveLabel already get OTel spans/metrics through
InstrumentedStorage; RenameLabel had no override and so fell through
to the embedded storage.DoltStorage passthrough, invisible to
storage.* tracing. Add the override, mirroring the AddLabel/RemoveLabel
shape: span attributes for the old/new label pair (bd.label.old,
bd.label.new, matching the existing bd.dep.from/bd.dep.to pairing
convention), and on success a bd.result.count / bd.merged.count pair
following the SearchIssues-style "set result attributes after a
successful call" pattern already used elsewhere in this file.
* storage: document the O(N) round-trip cost of RenameLabelInTx's event loop
renameLabelInPlane's per-issue loop (InsertDerivedEvent + RecordEventInTx)
is O(len(oldIDs)) SQL round trips inside one transaction, up to four per
touched issue. On a huge label population that lengthens the transaction
and raises the odds an optimistic-concurrency retry has to redo the whole
rename from scratch.
No batching added: InsertDerivedEvent's dedup SELECT is a real
cross-replica convergence check (Protocol v0.1 C2.3), not a redundant one
this transaction could skip, and no batch primitive for this shape exists
anywhere in this package - building one here would be new shared
infrastructure grown for a single caller. AddLabelInTx/RemoveLabelInTx
already pay the identical per-call cost for their one issue; this loop is
that cost repeated once per touched issue. Documented inline as a
disclosed limitation rather than silently left unremarked.
* bda-lbjv: derive rename merge count from rows-affected, not a prior read
renameLabelInPlane computed merged from a snapshot SELECT of newLabel's
carriers taken before the INSERT IGNORE - a check-then-insert whose
result is used. A concurrent AddLabel(issue, newLabel) committing between
snapshot and insert made the reported count schedule-dependent while the
stored data stayed correct (cross-model finding: the Opus panel cleared
A1, codex flipped it to NOT-SAFE on exactly this line).
Now the count is a measurement: INSERT IGNORE reports one affected row
per id actually inserted, so merged = len(oldIDs) - inserted, and the
newLabel pre-read is gone entirely.
Tests: sqlmock scripts the racing schedule (insert sees a row the
snapshot read could not); mutation control confirms the old
implementation fails the new test. Full issueops package + live-store
TestRenameLabel_* green.
* bda-c77s: first-party coverage for EmbeddedDoltStore.RenameLabel
The embedded impl had zero tests while DoltStore.RenameLabel carries a
dedicated suite; AddLabel/RemoveLabel both have parallel embedded
coverage by convention. Four wiring cases (basic, merge, zero-carrier
no-op, same-name refusal) - the deep semantics stay pinned by the shared
issueops suite and the dolt-side tests against the same implementation.
BEADS_TEST_EMBEDDED_DOLT=1: 5 RUN, all green, 2.8s.
* storage: scope the rename delete to the ids the sweep captured
An unrestricted DELETE ... WHERE label = ? makes the sweep's blast radius
engine-dependent: under current-read DELETE semantics a row a concurrent
AddLabel(oldLabel) committed after this transaction's snapshot would be
removed without ever being renamed, counted or journaled. Restricting the
delete to the captured ids touches exactly the rows the INSERT IGNORE above
accounted for on every engine; a concurrent add outside the snapshot now
deterministically SURVIVES the rename - the same observable state as that
add landing after the rename committed, which is the only order-independent
reading of the race.
sqlmock WithArgs pins the id-scoped statement shape; the embedded-Dolt
lifecycle set stays green (5/5).
* cmd/bd: add `bd label rename <old> <new>` with dry-run preview
Wire the storage.RenameLabel primitive (previous commit) into a CLI
command that renames a label everywhere it appears in one call instead
of a per-issue add-then-remove loop.
- cmd/bd/label.go: `bd label rename <old> <new> [--dry-run]`.
validateLabelRename refuses empty/identical labels and the
'provides:' reserved prefix before any store call - it is a pure
function so those rules are testable without a store. --dry-run
previews the blast radius (count plus the first issues) read-only,
via a path kept separate from the write path so it can never reach a
transaction.
- cmd/bd/label_proxied_server.go: the proxied-server route composes
the existing per-issue LabelUseCase.AddLabel/RemoveLabel (and wisp
twins) in one uow.RunTx, the same fan-out shape label propagate
already uses on this route. It journals as an add/remove pair per
issue rather than the direct route's single EventLabelRenamed,
because LabelUseCase has no rename-shaped event; the rename
semantics (merge-on-collision, honest zero-carrier no-op, dry-run
preview) are identical on both routes.
- docs/core-concepts/labels.md: documents rename, dry-run, and merge
semantics under Label Management.
Tests: cmd/bd/label_rename_test.go (pure argument-validation table
test, no store needed) plus new subtests in
cmd/bd/label_embedded_test.go covering the full CLI path - basic
rename, merge, dry-run writes nothing, zero-carrier no-op,
identical/empty/reserved-prefix refusals. All green.
Gates: gofmt clean, go vet ./... clean, CGO_ENABLED=0 go test -tags
gms_pure_go -c -o /dev/null ./cmd/bd clean, go build ./... clean.
* cmd/bd,domain: emit label_renamed on the proxied route, not add+remove
runLabelRenameProxiedServer used to fan a rename out into a per-issue
AddLabel-then-RemoveLabel pair, journaling label_added/label_removed
instead of one EventLabelRenamed - a divergence from the direct
DoltStore/EmbeddedDoltStore route the upstream reviewer has already
rejected for another PR touching the same class of proxied/direct
split.
Add domain.LabelUseCase.RenameLabel and domain.LabelSQLRepository.
RenameLabel. The repository method delegates straight to
issueops.RenameLabelInTx (r.runner satisfies issueops.DBTX
structurally), so the proxied route is not merely the same SQL SHAPE
as the direct one, it is the same function: identical merge semantics,
the same ErrRenameLabelSameName refusal, and one EventLabelRenamed per
touched issue. runLabelRenameProxiedServer now just calls
uw.LabelUseCase().RenameLabel(...) inside its existing uow.RunTx.
Declare recordingLabelUC.RenameLabel so the notifying unit of work
records one update per touched issue/wisp (mirroring
HookFiringStore.RenameLabel on the direct route) instead of silently
recording nothing through the embedded interface - caught by the
existing structural parity guard, TestRecordingLabelUseCaseCoversItsSurface,
which fails on any domain.LabelUseCase method neither declared on
recordingLabelUC nor exempted with a reason.
Tests, verified red->green:
- internal/storage/domain/db: TestLabelUseCase/RenameLabel adds 5
subtests. EmitsOneRenamedEventPerIssue is the direct regression
test - reverting RenameLabel to a simulated add-then-remove
fan-out reproduces exactly the pre-fix event counts (renamed=0,
added=2, removed=1) it now asserts against (renamed=1, added=1,
removed=0).
- cmd/bd/label_proxied_integration_test.go: new "rename" subtest
exercises `bd label rename` end to end through the real proxied
server and asserts the same label_renamed/added/removed counts
directly against the events table.
- internal/storage/uow: TestRecordingLabelUseCaseCoversItsSurface
goes red (RenameLabel inherited, records nothing) without the
recordingLabelUC override and green with it.
Full internal/storage/uow suite (287s) and the new domain/db and
cmd/bd tests all pass.
* cmd/bd: record commandDidWrite before the rename error return
runLabelRename read renamed>0 into commandDidWrite only after the
`if err != nil` early return, so a rename whose SQL side committed but
whose store call also returned an error - the Dolt publication step
failing after the working-set write landed - never marked the command
as having written. The caller's deferred auto-commit would then skip
creating a Dolt commit for a write that, on disk, actually happened.
Move the commandDidWrite.Store(true) check ahead of the error check,
matching applyLabelEdit's existing per-issue marking a few lines above
in the same file.
New test: TestRunLabelRename_CommandDidWriteSetBeforeErrorReturn wraps
a real *dolt.DoltStore in a spy whose RenameLabel reports a publish
failure (renamed>0, err!=nil) after delegating to the real rename, and
asserts commandDidWrite is set despite the returned error. Verified
red->green: reverting the ordering reproduces the exact failure this
guards against.
* bda-bnid: nolint:forbidigo on proxied bulk rename call
The route delegates to domain.LabelUseCase.RenameLabel deliberately: one
EventLabelRenamed per issue with identical merge semantics to the direct
route. Patch.Labels (the lint's suggested remedy) would reintroduce the
per-issue add/remove event divergence this delegation replaced. Matches
the file's own convention (4 sibling nolints, same shape).
Negative control: without the nolint golangci-lint forbidigo reports
exactly this line; with it, 0 issues.
* cmd/bd: address review on label rename (CHANGELOG entry, dry-run caveat, partial-failure count)
Two blocking items from review (bee-ghosttrack, PR #6009):
- Add the CHANGELOG entry for `bd label rename`, in the house voice used
by the neighboring bd-label entries (bold lead sentence, PR link, dense
explanatory prose on the merge/dry-run/partial-failure contract).
- The `--dry-run` merged count is a plain snapshot intersection of two
independent reads - exactly the check-then-count shape
renameLabelInPlane's own comment documents rejecting for the write
path, because it is schedule-dependent under a concurrent
AddLabel/RemoveLabel. That is an acceptable estimate for a preview, but
nothing said so: the command's Long text, the --dry-run flag help, and
an inline comment at the computation site now all say the number is
not authoritative.
One non-blocking nit fixed (the other - hydrating full issue rows in the
direct dry-run just to print 10 titles - is left alone; see below):
- On a partial rename failure (renamed>0, err!=nil - e.g. a Dolt
publication failure after the SQL side already committed) the command
now reports how many issues were renamed and merged before the
failure, instead of only the error. Mirrors the existing shape in
conflicts.go's ResolveConflictRows handling ("resolved %d of %d
conflict(s) before failing").
Left alone, and why: the GetIssuesByIDs-hydration nit. GetIssuesByLabel
hydrates every matching issue via GetIssuesByIDs on both the old-label
and new-label reads, which is wasteful on a label carrying 10k issues
when the text-mode preview only prints 10. But the JSON-mode contract
already returns every matching issue's id+title (not capped at the
preview limit), so avoiding hydration only helps the text-mode path and
would branch the two output modes apart for a marginal win on an
uncommon case (a rename dry-run over a 10k-issue label). Not clean
enough to do inline without its own test coverage and a decision about
whether the JSON contract should change too - flagged in the review as
skippable, so skipping it here.
Verification:
- go build ./... - clean
- go vet ./cmd/bd/... - clean
- gofmt -l cmd/bd/label.go - clean
- go test ./cmd/bd/... -run 'Label|LabelRename' - all pass
- BEADS_TEST_EMBEDDED_DOLT=1 go test ./cmd/bd/... -run 'TestEmbeddedLabel$' -v
- all pass, including label_rename_basic/merge/dry_run_writes_nothing
- BEADS_TEST_PROXIED_SERVER=1 BEADS_TEST_EMBEDDED_DOLT=1 go test ./cmd/bd/...
-run TestProxiedServerLabel -v - all pass, including the "rename" subtest
- BEADS_TEST_EMBEDDED_DOLT=1 go test ./internal/storage/issueops/... -run Rename -v
- BEADS_TEST_EMBEDDED_DOLT=1 go test ./internal/storage/dolt/... -run Rename -v (live dolt-sql-server)
- BEADS_TEST_EMBEDDED_DOLT=1 go test ./internal/storage/embeddeddolt/... -run Rename -v
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* cmd/bd: report an upper bound on a failed rename, not a landed count
The partial-failure message asserted that renamed>0 means the SQL side committed. On both routes the counts are assigned inside the transaction closure (label_proxied_server.go RunTx, dolt/labels.go withRetryTx), so a Commit failure or retry exhaustion returns them holding the rolled-back attempt numbers - nothing landed, and the user read 'renamed 6 issue(s) before failing'. Retry exhaustion under a busy server is the likely failure for a bulk rename, so it misreported exactly when it fired. Now reports an upper bound. commandDidWrite keeps the same premise deliberately: it is fail-safe in the other direction.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* cmd/bd: pin the partial-failure wording, and hedge the merged count too
Round-3 review: the r2 correction rode unpinned. Nothing in the suite drives
a failing rename with renamed > 0, so the whole TestEmbeddedLabel suite passed
with the hunk reverted - the fix was unfalsifiable, which is the same defect
class the correction itself was about.
Extracts the sentence into labelRenamePartialFailureMessage, a pure function a
test can assert on without inducing a mid-transaction failure, and pins it:
the hedged phrasings must be present AND the two pre-correction phrasings must
be absent. Mutation-checked - restoring the old wording turns it red on three
assertions.
Also the round-3 nit: (%d merged) was the one unhedged clause in a hedged
sentence. It now reads (of which up to %d merged), so no number in the message
asserts a write that may never have landed.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* docs: retire the landed-count premise from the CHANGELOG too
Round-4 review, MAJOR: the code retracted a premise and the CHANGELOG kept
publishing it. The entry still said a partway failure 'reports how many issues
were renamed and merged before the failure' - a landed count - while
labelRenamePartialFailureMessage had already become an upper bound.
The sentence carried the premise TWICE and the review named one: besides the
count, its parenthetical offered 'a Dolt publication failure after the SQL side
already committed' as the case, when the whole point of the correction is that
renamed > 0 cannot distinguish that from a rollback. Rewrote both halves: the
bound is explicit, and the two failure shapes are named as indistinguishable
from the count alone.
Also round-4 MINOR: the helper had been inserted between reportLabelRename's
doc comment and its func, so the comment headed the wrong function and
reportLabelRename was left undocumented. Moved back down.
Not done, deliberately: the round-4 NIT that the pin covers the helper and not
the call site. It is marked 'noting, not asking', and an unrequested fix is the
one that ships a defect - this PR already demonstrated that.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* CHANGELOG: move this PR's entry under [Unreleased]
The 1.3.0 cut renamed the old [Unreleased] block, so these lines
merged cleanly into a released section (gastownhall/beads#6643).
Moved 31 line(s); the code is unchanged.
* cmd/bd: register label rename in the proxied capability registry
TestProxyCapabilityRegistryCoversCommandTree requires every command path to
carry a proxied-server row. label rename has a proxied route (RunE hands the
rename to runLabelRenameProxiedServer and the --dry-run preview to a proxied
read UOW), so it joins its label siblings in proxyPermittedPaths.
* storage: mint a version for every bead a label rename touches
TestEveryBeadMutatorMintsOrIsExempt (added with #6650) fails on this PR:
RenameLabelInTx writes the labels table but never reached
RecordVersionInTx. A rename changes the label set - part of the durable
snapshot - of every issue that carried oldLabel, whether it gained
newLabel or already had it (merge), so each touched issue now mints one
version row, the same gate AddLabelInTx/RemoveLabelInTx draw on a row
that landed. RecordVersionInTx is already a no-op for wisps and when
versioned history is disabled, and a rename nobody carries touches no
id, so the no-op shape mints nothing.
TestRenameLabelMintsOneVersionPerTouchedBead is the runtime twin of the
static guard: plain rename +1, merge +1, untouched bead +0, a second
rename with no carriers +0, current_revision equal to the row count.
* build(bazel): list this PR's six new test files in their go_test srcs
Generated-artifact drift repair, produced by the repository's own command
(`make bazel-sync`) and inspected before committing, not hand-written.
The PR adds six `_test.go` files and none were listed in their package's
`go_test` srcs, so Bazel compiled each of those packages' test targets without
them - green by omission. That was invisible on the pre-merge head because its
CI predates the Bazel lanes entirely (zero `Bazel /` rows). This merge brings in
e1b2e79484 (#6941), which makes those lanes feed the required gate, so the
omission would now surface as a real red.
Purely additive: 6 insertions, 0 deletions, `go_test` srcs only. No `go_library`
srcs change is needed because every added file is a test, which is also why this
cannot break the build the way a missing production source would.
Verified: `make bazel-sync` is now a no-op against this tree (empty porcelain),
and `bazel build //cmd/bd/... //internal/storage/... //internal/types/...
//internal/telemetry/...` completes successfully - 3429 actions, 0 errors.
---------
Co-authored-by: Marco Del Pin <marco@omniaevo.it>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
Add beads-pm-kit to the orchestration section: ten PM skills for running
a Beads board (split, estimate, take, loop, fleet, pm-loop, report,
forecast, audit, handoff), installable with
`npx skills add cuongbphv/beads-pm-kit`. The entry is sized to match its
neighbours in the section.
An implementation of the mail.delegate seam that gives any beads repo a
working bd mail. aweb is an open-source communication layer for agents:
durable mail and chat, wake-up events, local (team) or global
(cross-organization, federated) identities, signed and verified senders;
self-hostable or hosted. Guide and recording:
https://aweb.ai/docs/beads-mail/
Co-authored-by: Juan Reyero <juan@thestarmaps.com>
* fix(doctor): detect test binaries with testing.Testing(), not the file name
getBdBinary refuses to return a test binary as "bd" so fix tests cannot
fork-bomb by re-running themselves. The guard matched only the `go test`
naming (<pkg>.test). Bazel names test binaries <target>_test, so under
`bazel test` every fix that shells out to bd re-ran the whole fix_test suite,
recursively (~60 levels), until the 300s timeout.
testing.Testing() is true for any binary linked as a test by `go test` or
rules_go (both set testing.testBinary=1), whatever its name. The name check
stays as a fallback. bd already links package testing, so the product binary
gains no dependency. Behavior under `go test` is unchanged.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* test(bazel): tag taxonomy, docker lane, and green //scripts targets (slice B5)
`bazel test //... --config=ci` is now fully green, locally and with
--config=remote-exec.
- scripts_test declares what it reads and runs: this package's own tree
(:scripts_files), .github/** (//:workflow_files, widened from the
workflows), and .buildflags/.test-skip for scripts/test.sh. The complexity
diff test builds a one-commit git fixture instead of git-archiving the
real checkout's HEAD. Under Bazel it skips the whole-repo testing.Short()
scan (it would pass vacuously over the runfiles) and the two release
formula tests (.beads is in .bazelignore). Tagged host-tools +
no-remote-exec: it runs the host's git/python3/coreutils and some subtests
skip without git.
- prlintmake_test resolves fmt-check.sh through bazeltest.CallerDir and
declares it; it needs only bash (gofmt is shimmed), so it stays untagged
and runs remotely.
- //cmd/bd/doctor/fix:fix_docker_test reruns the fix_test binary (no second
compile, tools/bazel/go_test_variant.sh) with BEADS_FIX_REQUIRE_DOLT=1, like
pr.yml's container-backed doctor/fix job. Tagged requires-docker +
no-remote-exec; `--config=docker` selects it (race, no -short, no
BEADS_TEST_SKIP=dolt). fix_test itself stays untagged: under prcore it
skips the Dolt-backed tests exactly as pr-core's `go test` does.
- scripts/bazel_policy_test.go: every BUILD `tags` value must be in the
taxonomy, be named in the comment above its rule, and host-bound tags must
come with no-remote-exec; test:prcore must exclude requires-docker,
embedded and manual.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* test(bd): reset git's cwd cache in TestContextRoutesNameOneWorkspaceTheSameWay
The test chdirs into a fresh git repo but reset only beads' caches. git
caches the cwd's repository context process-wide, so when an earlier test in
the same process had resolved it from a non-repo directory (for example
TestCollectMetadataEntriesNoBeadsDir), GetMainRepoRoot kept answering "not a
git repository". Test order hid it under `go test ./cmd/bd`; Bazel sharding
reorders tests and exposed it. Reproduces with plain go test:
go test -run '^(TestCollectMetadataEntriesNoBeadsDir|TestContextRoutesNameOneWorkspaceTheSameWay)$' ./cmd/bd
The cache is reset on entry only. Resetting it again in cleanup changes what
later tests inherit, and TestCreateRemoteRepoSkipsLocalDatabaseGuard (which
never resets it) then fails under the unsharded go test order.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* test(bazel): shard bd_test and embeddeddolt_test; keep test re-execs shard-free (slice B6)
- //cmd/bd:bd_test shard_count = 16, //internal/storage/embeddeddolt:
embeddeddolt_test shard_count = 8. Remote -race under --config=ci: bd_test
max shard 61-82s (unsharded 252-264s), embeddeddolt max shard 84-122s
(unsharded 207-377s). The embeddeddolt max is a single test
(TestWithPeerAuth, ~93s), so more shards would not lower it. Every shard
runs tests (bd 161-172 top-level tests each, embeddeddolt 15-20).
protocol (4s), legacysqlite (4s) and dbproxy/server (22s) stay unsharded.
- Tests that re-exec their own binary now pass bazeltest.ShardFreeEnv
(a no-op under go test), so a helper child does not inherit
TEST_SHARD_INDEX/TEST_TOTAL_SHARDS/TEST_SHARD_STATUS_FILE and filter away
the one test it was asked to run: dolt suite_leak_linux, dbproxy
force_stop_linux, workspacegate (3 helpers), metrics spawn_reap, bd
worktree_remove, conformance role_bundle, linear synclock (windows).
scripts/test_script_test.go (child env built from scratch) and
repro-dolt-prod-timeouts (copies the binary, never runs it) need nothing.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* test(bazel): keep sharded bd_test off ~/.beads and keep its stdio leak guard
Two things sharding //cmd/bd:bd_test exposed:
- config.Initialize walks up from the test's cwd for .beads/config.yaml and,
under BEADS_TEST_IGNORE_REPO_CONFIG, stops at the module root (go.mod).
The runfiles tree had no go.mod, so the walk left it; with the output base
under $HOME it loaded the developer's ~/.beads/config.yaml (here
dolt.shared-server: true) and two embedded-mode autocommit tests failed
locally, though not on remote workers. bd_test now declares //:go.mod, so
the walk stops at the runfiles root as it stops at the checkout under go
test. Unsharded runs hid this: an earlier test re-initialized config first.
- TestZZStdioNotLeaked skipped in every shard, because the baseline test is
always in shard 1 and the guard in another. Without a baseline it now
checks the descriptors instead (a leaked capture leaves a pipe where fd 1
or 2 was). Under go test the baseline is always captured, so nothing
changes there.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* chore(bazel): sync BUILD files with test files added on main
Gazelle picks up cmd/bd and internal/notion tests that landed on main after
the last sync (make bazel-sync).
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(discovery): add BEADS_CEILING_DIRECTORIES; bound bazel tests' walks
bd finds its workspace by walking up from the working directory for .beads
and .beads/config.yaml. Under `bazel test` the working directory is in the
runfiles tree under the output base, usually below the developer's HOME, so
the walks left the sandbox: tests read the developer's ~/.beads/config.yaml
(results depended on it) and wrote into ~/.beads (interactions.jsonl from the
audit log, .local_version from version tracking).
BEADS_CEILING_DIRECTORIES takes git's GIT_CEILING_DIRECTORIES form (a PATH-
style list of absolute directories): a search starting inside a ceiling never
examines the ceiling or anything above it; the start itself is always
examined. Unset, nothing changes. Honored by every upward .beads/config
search: beads.AncestorDirWalk (all FindBeadsDir walks), config.Initialize
(the go.mod and config.yaml walks, and the worktree-fallback git probe, whose
routing scrub drops GIT_CEILING_DIRECTORIES), findProjectBeadsDir, the legacy
upgrade guard, the --db beads-dir walk, store reopen and findBeadsRepoRoot.
The migration-freeze marker walk is left alone on purpose: it is a write
safety gate, and BD_MIGRATION_FREEZE_FILE is already its explicit override.
tools/bazel/test_env.sh sets BEADS_CEILING_DIRECTORIES and
GIT_CEILING_DIRECTORIES to the runfiles root, TEST_TMPDIR and its own temp
root. It does not fail on an ancestor .beads: a live ~/.beads above the
output base is normal on a developer machine. bd_test no longer needs
//:go.mod as a walk stop.
Canary check: with an invalid-YAML .beads above a scratch --output_base,
compact, issueops, validation and bd_test pass under --config=ci and nothing
is written there; the previous wrapper fails on it and writes
interactions.jsonl into it.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* test(bd): check for leaked stdio after m.Run in every process
TestZZStdioNotLeaked only sees the tests that ran before it in the same
process. Under Bazel's 16-way sharding that is ~1/16 of bd_test: the baseline
test is in shard 1, the guard in another shard, and leaks in the other shards
were never checked.
TestMain now compares os.Stdout/os.Stderr after m.Run with the streams from
before it (runTestsAndSweep, so every shard and every go test run) and fails
the process on a leak. The one allowed change is the framework's own
os.Stderr = os.Stdout under -json. TestZZStdioNotLeaked stays for its go test
report and skips when it has no baseline; the descriptor fallback added for
sharding is gone.
Verified: a test that leaks os.Stdout fails `go test -run` for it alone, with
and without -json; a clean -json run passes.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* test(bazel): keep host-tools results out of the remote cache; tighten tag policy
- //scripts:scripts_test (host-tools, no-remote-exec) ran locally but its
result was still uploaded to the remote cache and served to other clients,
though the action key does not cover the host's git/python3/bash. It is now
also tagged no-remote-cache (neither read nor uploaded). Checked: after a
--config=remote-exec run and `bazel clean`, a rerun without the disk cache
executes the test again instead of taking a remote cache hit.
- Under Bazel a missing git or bash now fails those tests instead of
skipping (the host-tools tag promises them); under go test they still skip.
- Tag policy: host-tools requires no-remote-exec and no-remote-cache;
`tags = [...] + X` is rejected as non-literal; every --test_tag_filters set
by test:prcore or a config that expands it (test:ci, transitively) must
exclude requires-docker/embedded/manual, not only the first prcore line.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(bazel): run go_test variants from their package directory
rules_go gives a go_test GO_TEST_RUN_FROM_BAZEL=1 (and its `env`) through
RunEnvironmentInfo; an sh_test that reruns the binary gets neither, so the
binary skipped its chdir into the package directory and ran from the
runfiles root. go_test_variant.sh now exports GO_TEST_RUN_FROM_BAZEL=1, and
its header says the variant target must repeat the go_test's `env`.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* test(bazel): docker-lane variants for domain/db, uow and protocol
--config=docker only ran doctor/fix. pr.yml's container jobs also run
internal/storage/domain/... + uow/... (race, no -short, Dolt image pulled)
and cmd/bd/protocol (BEADS_PROTOCOL_REQUIRE_DOLT=1). Under --config=ci those
container suites skip (BEADS_TEST_SKIP=dolt), so without variants their
coverage would vanish if Bazel replaced those jobs.
- testutil: BEADS_TEST_REQUIRE_DOLT_CONTAINER=1 makes RequireDoltContainer
and StartIsolatedDoltContainer(Handle) fail instead of skip when the Dolt
container is unavailable (the generic form of BEADS_FIX_REQUIRE_DOLT).
- db_docker_test, uow_docker_test (4 shards) and protocol_docker_test
(8 shards, BEADS_PROTOCOL_REQUIRE_DOLT=1) rerun the go_test binaries via
go_test_variant.sh, repeating their `env`; tagged requires-docker +
no-remote-exec. The other domain/tracker packages have no container tests
and already run under --config=ci.
`bazel test //... --config=docker --test_arg=-test.v`: 4/4 PASS; db 908
PASS / 0 SKIP, uow 985 PASS / 32 SKIP (conformance capabilities the backend
does not implement, as under go test), protocol 151 PASS / 2 SKIP (tracked
known gaps). With --test_env=BEADS_TEST_SKIP=dolt, db_docker_test fails.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* test: shard-free env for the embeddeddolt concurrency helper; 2m bd init timeout
- concurrency_test re-execs its test binary with -test.run=^TestHelperProcess$
inside the now-sharded embeddeddolt_test; pass bazeltest.ShardFreeEnv so a
child cannot inherit TEST_SHARD_* and filter its one test away (it is
gated by BEADS_TEST_EMBEDDED_DOLT=1, so dark today).
- initBeadsWorkspace / runBDStdout (TestClose_UpdatesLastTouched and the
gemini prime hook tests) allowed 30s per bd subprocess. A -race bd on a
loaded host exceeded that for a single `bd init` (killed at 30.18s in 1 of
3 sharded remote runs; the whole test otherwise passes in ~21s), so allow
2 minutes.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* test(bd): give TestCreateRemoteRepoSkipsLocalDatabaseGuard its own git state
The test chdirs into a fresh non-repo temp dir but used whatever git/beads
cwd caches earlier tests left. When an earlier test had reset git's cache and
a later one refilled it from the package directory, workspace discovery in
the test returned the checkout's .beads (from a git worktree: the MAIN
checkout's live .beads via the worktree fallback) and `bd create` tried to
open it, so it failed with "could not verify workspace identity" instead of
the expected downstream error. It passed only on stale state (a cache
pointing at a deleted temp repo).
It now resets the git and beads caches after its chdir and again in cleanup,
so it neither depends on nor leaks cwd state. With that fixed,
TestContextRoutesNameOneWorkspaceTheSameWay also resets git's cache in
cleanup. Reproduced with the context-test cleanup reset in place, running
every cmd/bd test declared up to this one (the failing go test order); now
passes there, alone, with the two context tests, and under -shuffle seeds
1-5 (other pre-existing order dependencies show up under shuffle; this test
is not among them).
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* build(bazel): re-sync BUILD files with main
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* test(bazel): pin BD_MIGRATION_FREEZE_FILE in test_env
The freeze-marker ancestor walk is intentionally not ceiling-bounded; an
explicit BD_MIGRATION_FREEZE_FILE replaces the walk, so a MIGRATION-FREEZE
above the output base can no longer change test results.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* test(scripts): give the complexity diff fixture a Go package
complexity.sh expands "${analyzer_paths[@]}" under set -u; with an empty
fixture tree that is an unbound-variable error on bash 3.2 (macOS runners).
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(worktree): scrub inherited Git routing state
Establish CWD as the worktree repository boundary before discovery can consume inherited Git routing. Fence the startup config probe, clear routing in-process before root pre-run discovery, and retain command-owned subprocess scrubbing as defense in depth without changing PID or signal semantics.
Fixes#5531
Agent-Signature: codex-gpt-5-unknown-reasoning on behalf of Ewen Cuthiell
* refactor(worktree): explain owned filtering and remove an unused shim
Document why filtering the fresh routing slice in place is safe and call
the shared routing-key classifier directly from tests. Retain the two
forwarders used by production worktree subprocess/removal paths.
Review: https://github.com/gastownhall/beads/pull/5623#pullrequestreview-5098421671
Bead: saa-cgh.23
Agent-Signature: unknown-model/unknown-reasoning
* fix(config): isolate identity and tracked-file Git probes from routing
Reuse the worktree routing owner for GetIdentity and isGitTracked so
explicit cwd/path selection is not displaced by inherited repository,
index or injected config state. Preserve identity precedence and the
tracked-secret refusal contract, with real target/decoy regressions.
Follow-up: https://github.com/gastownhall/beads/issues/6222
Dependency: https://github.com/gastownhall/beads/pull/5623
Reported-by: bee-ghosttrack
Bead: saa-cgh.93
Agent-Signature: unknown-model/unknown-reasoning
* fix(config): share subprocess key identity for Git routing (saa-cgh.93)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* fix(exec): match Windows environment key identity (#5618)
Centralize os/exec-compatible environment-key comparison and use it for credential, metrics, Git-hook, trace, and repro subprocess filters. Preserve exact Unix semantics and Unicode near-collisions.
Agent-Signature: codex-gpt-5-unknown-reasoning on behalf of Ewen Cuthiell
Signed-off-by: Ewen Cuthiell <ewencuthiell@gmail.com>
* test(execenv): exercise every environment operation under both host rules
Thread the host choice through narrow private helpers behind the existing
exported functions. Keep one normalization owner and retain native wrapper
tests; the additional table covers both host branches for equality, prefix
matching, last-wins lookup, filtering and input preservation.
Review: https://github.com/gastownhall/beads/pull/5672#pullrequestreview-5096948965
Bead: saa-cgh.78
Agent-Signature: unknown-model/unknown-reasoning
* test(execenv): exercise exported host policy wiring (saa-cgh.78)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* docs(worktree): explain startup Git environment scope (saa-cgh.23)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* fix(config): isolate role commands from Git routing (saa-cgh.99)
Follow-up to bee-ghosttrack's review of gastownhall/beads#6322; refs #6357.
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* test(env): exercise shared key helpers on native Windows (saa-cgh.78)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* refactor(gitenv): share key parsing and normalize routing membership once (saa-cgh.93)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* docs(config): explain role command routing policy (saa-cgh.99)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* fix(git): isolate domain role configuration from inherited routing (saa-cgh.109.5)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* fix(init): probe the selected repository before configuring roles (saa-cgh.109.8)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* docs(init): explain role probe discovery ceiling behavior (saa-cgh.109.8)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* fix(init): bind proxied tail Git operations to selected directory (saa-cgh.109.14)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* fix(gitignore): preserve CRLF when appending project rules (saa-cgh.96)
Reported by bee-ghosttrack in gastownhall/beads#6343.
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* test(gitignore): pin detector edge cases and clarify append behavior (saa-cgh.96)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* fix(gitignore): preserve line endings in Git exclude appends (saa-cgh.104)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* test(gitignore): clarify exclude fixture path variable (saa-cgh.104)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* fix(gitignore): refuse exclude writes after read errors (saa-cgh.110)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* refactor(gitignore): share append byte composition (saa-cgh.105)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* docs(gitignore): explain append aliasing and trailing CR completion (saa-cgh.105)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* refactor(gitignore): use shared composition for exclude rules (saa-cgh.111)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* fix(gitignore): omit the empty exclude leading separator (saa-cgh.112)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* fix(init): bind exclude writers to the selected Git directory (saa-cgh.109.16)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* fix(hooks): isolate tracked-file guard from Git routing (saa-cgh.98)
Follow-up to bee-ghosttrack's review of gastownhall/beads#6322; refs #6356.
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* fix(hooks): retain legitimate inherited tracking context (saa-cgh.98)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* test(hooks): isolate trusted global configuration fixture (saa-cgh.98)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* docs(hooks): explain conservative tracked-file guard (saa-cgh.98)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* refactor(git): resolve hooks paths in an explicit read-only context (saa-cgh.109.17.1)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* Bind init hook operations to the selected repository (saa-cgh.109.17)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* Give the hooks tail fixture an explicit remote context (saa-cgh.109.17)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* test(git): canonicalize the hooks fixture repository root (saa-cgh.109.17.1)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* fix(init): complete selected hook options and alias handling (saa-cgh.120)
Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell
* Clarify hooks resolver ownership and preserve work-tree diagnostics (saa-cgh.120)
Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell
* Explain restoration of absent routing variables in selected exclude tests (saa-cgh.120)
Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell
* Keep init role operations on the captured selected Git context (saa-cgh.120)
Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell
* Align selected-tail fixtures with captured role authority (saa-cgh.120)
Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell
* Identify the Git index behind tracked-hook refusals (saa-cgh.120.13)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* fix(review): repair work-tree-less hook install and the fail-open secret guard
Maintainer adoption-review fixes for #6457 (iterations 1 and 2).
Blocking:
- cmd/bd, internal/git: `bd init` in a repository with no work tree stopped
installing hooks and printed "Failed to resolve git hooks".
git.ResolveHooksContext requires a work tree and deliberately errors without
one, so routing the selected-init path through it lost a capability base had
via beads.FindBeadsDir(). Add git.ResolveWorkTreelessHooksContext as the
explicit counterpart (empty RepoRoot/MainRepoRoot, relative core.hooksPath
anchored to the common directory) and fall back to it, so the install keeps
the selected, scrubbed context rather than the inherited one. It keys on "the
common directory resolved but the work tree did not", so it covers a bare
repository and a cwd inside a repository's own .git alike, and still refuses
non-repositories and directories inside a work tree. The `bare` and
`git_dir_cwd` rows in the hooks table test pin both shapes and assert the
install lands in the selected storage and configures the selected repository.
- internal/config: isGitTracked scrubbed Git routing with no fallback, so in a
checkout reachable only through legitimate GIT_DIR/GIT_WORK_TREE routing the
probe found no repository at all, the guard concluded "untracked", and
`bd config set <secret-key>` wrote the credential into a git-tracked
config.yaml where base refused. Give it the same two-probe shape as
hooks.gitTrackedFileContextWithEnv, with a legitimate-routing test.
- internal/config, internal/gitenv, docs: state the GIT_CEILING_DIRECTORIES
widening plainly rather than pairing it with a containment clause that is
false at every live call site. `-C`/cmd.Dir fixes where discovery starts, not
where it stops, so with the ceiling scrubbed the walk can reach a containing
repository above cwd; all three gitDirsForRepo call sites pass the process
working directory, which need not be a repository root. This mirrors the
wording init_proxied_server.go already had, so the tree no longer holds
contradictory statements about the same primitive.
- cmd/bd/config.go: the policy comment claimed all role commands ignore
inherited Git routing. Name the scrubbed paths without asserting a closed set
-- `bd config set/get/unset/set-many beads.role`, and the proxied-init role
tail, which goes through domain.GitUseCase.BeadsRole/SetBeadsRole and is
scrubbed on both of that repository's constructor arms -- and say that a path
which does not scrub still goes through the inherited environment: such readers
include internal/routing.roleFromGitConfig, RepoContext.Role,
doctor.CheckBeadsRole, `bd config show` and init.getBeadsRole; such writers
include init.setBeadsRole, `bd init --contributor` and `bd hooks --uninstall`.
The earlier wording framed the exception as role *resolution* only, which reads
as isolating the write plane when it is not isolated; a quantifier over "every
other" reader and writer goes stale in the opposite direction, since set-many
and the proxied-init tail are scrubbed, so neither list is exhaustive here.
Non-blocking:
- Scope the worktrees.md paragraph to the one startup probe that is scrubbed.
- Replace normalizeWorktreeGitEnvKey's ToUpper fold with execenv.KeyEqualForOS
so one subprocess key identity survives the PR.
- Compare beads.role against domain.BeadsRoleConfigKey with strings.ToLower
rather than strings.EqualFold, matching execenv.keyIdentityForWindows and
git's ASCII-only key folding, and pin it with Beads.Role/BEADS.ROLE rows
through GetConfig/SetConfig.
- Share the HooksContext workDir anchoring and symlink/case normalization
between both resolvers, so no producer of that type emits a spelling the
others do not.
- Branch the tracked-hook remediation hint on the proof label, so the inherited
case points at the routing rather than at `git rm --cached`.
- Restore the hook-status gate on the pure-JJ alias hint (base parity).
- Note that the boolean tracked-file wrappers are test-only.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* fix(review): reconcile the beads.role scrub with base #6477 on the refreshed base
Refreshing onto main 511849496 pulled in cf683435e (#6477), which makes
domain/git GetConfig propagate Git's exit error instead of mapping every
*exec.ExitError to absence. That collides with this stack's beads.role scrub in
both directions, and neither lane's CI could see it: the PR lane builds against
a base where #6477's test does not exist, and main's lane never has the PR.
Only the merged tree fails (each half passes on its own side alone).
The test half is taken byte-identically from stack parent #6464, which already
pushed this resolution against the same base commit (head 0fe936944). Both PRs
target main with every parent still open, so a divergent-but-equivalent fix here
would collide in the same file when the stack lands; copying theirs means the two
auto-merge. Re-validated and re-mutation-proven here rather than assumed:
- TestConfig_ReadFailuresAreNotMissing drops its "invalid_routing_boolean" row,
whose poisoned GIT_CONFIG_NOSYSTEM can no longer reach git for beads.role
(IsRoutingKeyForOS scrubs the whole GIT_CONFIG* prefix for that key), and gains
TestConfig_BeadsRoleScrubsInheritedRoutingEnv, which pins both halves: the role
key ignores the poison, and a key outside the scrub (user.name) still surfaces
it as exit 128 rather than as an absent key. #6477's read-failure contract for
beads.role itself is untouched, still proved by malformed_config through the
repository's own config file.
- TestInitGitRepositoryUsesSelectedDirectory/captured_home asserted
require.NoError with the comment "The existing reader maps Git exit errors to
absence" -- the premise #6477 deleted. It now requires the exit-128 error,
which is itself the proof that the generic constructor read the *current*
caller environment: only that environment can see the planted .gitconfig.
Mutation proofs at this head: deleting the beads.role carve-out reds
TestConfig_BeadsRoleScrubsInheritedRoutingEnv; reverting #6477's classification
reds both that test and captured_home. So neither retargeted fixture is vacuous.
Also silence two gosec G702 findings that only appear with this branch present.
Unscoped `make ci-pr-lint` at CI's v2.10.1 pin scores 0 on the old base and 0 on
current main, 1 on the pre-refresh adopted head (cmd/bd/worktree.go:22) and 2 on
the refreshed head (+ cmd/bd/hooks.go:1823). pr.yml scopes golangci-lint to the
PR's own diff so it can never report them, but main.yml deliberately sweeps the
whole tree, so they would red main's Lint job on the first push after merge.
Production reachability is identical on all three trees, so this is taint
widening rather than a new call path. Both sinks run a fixed "git" binary with
constant subcommands, matching the justification at init_stealth.go:84.
cmd/bd/worktree.go is the only file this adds beyond the branch's own 50; #6464
does not touch it, so the annotation cannot collide with the parent either.
---------
Signed-off-by: Ewen Cuthiell <ewencuthiell@gmail.com>
Co-authored-by: Julian Knutsen <julianknutsen@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
* fix(exec): match Windows environment key identity (#5618)
Centralize os/exec-compatible environment-key comparison and use it for credential, metrics, Git-hook, trace, and repro subprocess filters. Preserve exact Unix semantics and Unicode near-collisions.
Agent-Signature: codex-gpt-5-unknown-reasoning on behalf of Ewen Cuthiell
Signed-off-by: Ewen Cuthiell <ewencuthiell@gmail.com>
* fix(worktree): scrub inherited Git routing state
Establish CWD as the worktree repository boundary before discovery can consume inherited Git routing. Fence the startup config probe, clear routing in-process before root pre-run discovery, and retain command-owned subprocess scrubbing as defense in depth without changing PID or signal semantics.
Fixes#5531
Agent-Signature: codex-gpt-5-unknown-reasoning on behalf of Ewen Cuthiell
* refactor(worktree): explain owned filtering and remove an unused shim
Document why filtering the fresh routing slice in place is safe and call
the shared routing-key classifier directly from tests. Retain the two
forwarders used by production worktree subprocess/removal paths.
Review: https://github.com/gastownhall/beads/pull/5623#pullrequestreview-5098421671
Bead: saa-cgh.23
Agent-Signature: unknown-model/unknown-reasoning
* fix(config): isolate identity and tracked-file Git probes from routing
Reuse the worktree routing owner for GetIdentity and isGitTracked so
explicit cwd/path selection is not displaced by inherited repository,
index or injected config state. Preserve identity precedence and the
tracked-secret refusal contract, with real target/decoy regressions.
Follow-up: https://github.com/gastownhall/beads/issues/6222
Dependency: https://github.com/gastownhall/beads/pull/5623
Reported-by: bee-ghosttrack
Bead: saa-cgh.93
Agent-Signature: unknown-model/unknown-reasoning
* test(execenv): exercise every environment operation under both host rules
Thread the host choice through narrow private helpers behind the existing
exported functions. Keep one normalization owner and retain native wrapper
tests; the additional table covers both host branches for equality, prefix
matching, last-wins lookup, filtering and input preservation.
Review: https://github.com/gastownhall/beads/pull/5672#pullrequestreview-5096948965
Bead: saa-cgh.78
Agent-Signature: unknown-model/unknown-reasoning
* docs(worktree): explain startup Git environment scope (saa-cgh.23)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* test(execenv): exercise exported host policy wiring (saa-cgh.78)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* fix(config): share subprocess key identity for Git routing (saa-cgh.93)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* fix(config): isolate role commands from Git routing (saa-cgh.99)
Follow-up to bee-ghosttrack's review of gastownhall/beads#6322; refs #6357.
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* test(env): exercise shared key helpers on native Windows (saa-cgh.78)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* refactor(gitenv): share key parsing and normalize routing membership once (saa-cgh.93)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* docs(config): explain role command routing policy (saa-cgh.99)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* fix(config): isolate role readers from inherited Git routing (saa-cgh.109.1)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* fix(doctor): isolate role lookups from inherited Git routing (saa-cgh.109.2)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* fix(git): isolate domain role configuration from inherited routing (saa-cgh.109.5)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* fix(doctor): isolate explicit-path worktree fallback from Git routing (saa-cgh.109.6)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* fix(init): probe the selected repository before configuring roles (saa-cgh.109.8)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* test(beads): cover common-directory role routing (saa-cgh.109.1)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* test(git): explain system config routing flags (saa-cgh.109.6)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* docs(init): explain role probe discovery ceiling behavior (saa-cgh.109.8)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* fix(beads): scope stable worktree probes to selected path (saa-cgh.109.13)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* fix(init): bind proxied tail Git operations to selected directory (saa-cgh.109.14)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* Clarify selected discovery probes and cover separate routing vectors (saa-cgh.120)
Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell
* Keep init role operations on the captured selected Git context (saa-cgh.120)
Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell
* Observe inline Git configuration directly in linked-worktree fixture (saa-cgh.120)
Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell
* Align selected-tail fixtures with captured role authority (saa-cgh.120)
Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell
* fix(beads): select explicit directory discovery context (GH#6384) (saa-cgh.120.6)
Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell
* fix(gitenv): retain explicit Git config suppression (saa-cgh.120.7)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* test(config): pin identity under null config suppression (saa-cgh.120.7)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* fix(gitenv): keep role authority off inherited config suppression
Maintainer review fixes for PR #6461 (adopt-pr iterations 1-2). Addresses the
three major findings raised against the contributor branch, plus the major,
three minors and nit that iteration 2 raised against the first fixup; each fix
is pinned by a test that was mutation-proved against the pre-fix source.
F1 (major, security) — the leaf exempts GIT_CONFIG_GLOBAL=/dev/null,
GIT_CONFIG_SYSTEM=/dev/null and GIT_CONFIG_NOSYSTEM from ScrubRouting. Null
suppression cannot redirect a read, but it can blind one, and DetectUserRole
answers a missed read with detectFromURL, whose no-remote and SSH arms both
return Maintainer. Reproduced on this branch: a global beads.role=contributor
with GIT_CONFIG_GLOBAL=/dev/null resolved to maintainer, where the leaf's
parent fb7a93ad4 scrubbed the entry and read contributor.
Taken the synthesis's alternative arm (a): keep the exemption where the value
has no authority, drop it where it does. New ScrubRoutingAndSuppression
applies at every beads.role reader — internal/routing, doctor/role.go,
config_show.go, RepoContext.Role, bd config get/set/unset/set-many, and the
domain adapter's key-specific arms (see A1: iteration 1 claimed that last site
and did not actually reach it). Arm (b), making roleFromGitConfig's miss
non-permissive, was declined: "no beads.role and no remote implies maintainer"
is documented base behavior for local projects, so closing it there would
reclassify every such user rather than the blinded slice this PR introduced.
F2 (major, blast radius) — the stack hardened every role reader and left four
writer/reader sites fully inherited, a divergence that did not exist at base:
an inherited GIT_DIR sends setBeadsRole's write to another repository while
the scrubbed readers look at the one the user is standing in. All four now
share the same boundary (init.go's getBeadsRole/setBeadsRole,
init_contributor.go, hooks.go's uninstall --get/--unset pair).
The required fix also asked for cmd.Dir = repoRoot on the init.go pair. Still
not taken, but not on the grounds iteration 1 recorded (see A2). What holds is
the measurement against the vector the fix targets: with GIT_DIR, GIT_WORK_TREE
and GIT_COMMON_DIR gone, no production path chdirs away from the invocation
directory — `grep -rn 'os\.Chdir' --include='*.go'` over production cmd/bd
returns nothing and `bd init` takes no path argument — so threading a repoRoot
through both signatures and their eight call sites buys no behavior change
against a redirect.
F3 (major, security) — this PR converted internal/config's isGitTracked probe
from inherited to scrub-only. The guard is fail-open by construction, so in a
legitimately routed checkout (bare repo.git, GIT_DIR/GIT_WORK_TREE exported,
no in-tree .git) the probe stopped answering and `bd config set
linear.api_key` would have written the credential into a tracked file.
Restored the two-probe shape sibling #6464 applied to the structural twin:
scrubbed probe first, inherited second, either "tracked" refuses.
F5 (minor) — disclose that scrubbing GIT_CEILING_DIRECTORIES widens upward
discovery rather than bounding it, in the worktree comment and the docs
paragraph that asserted only the narrowing effect. F2's fix extends that
trade-off to two more sites, so the disclosure is now load-bearing.
F7 (minor) — renamed isConfigSuppression to isConfigSuppressionControl and
documented why the NOSYSTEM arm is deliberately value-blind. Took the
rename/document arm rather than restricting the arm to git-true values, which
would have contradicted the PR's own pinned table.
F10 (nit) — pinned both suppression tables in the windows-latest required
list; verified each name matches the gate's grep exactly once.
--- Iteration 2 ---
The first fixup's F1 census named a site it did not reach, and its cmd.Dir
rationale named a mechanism that does not hold. Both are corrected here.
A1 (major, security) — the domain adapter's key-specific arm was guarded by
`key == "beads.role" && r.env == nil`, which is dead on the only production
role path: runInitProxiedServerTail rebinds the use case to
NewInitGitRepository whenever t.workDir != "" (its sole construction site
passes cwd), and that constructor captures ScrubRouting(os.Environ()) —
non-nil, suppression retained. The nil-env constructor has no
BeadsRole/SetBeadsRole caller, so the arm could only fire from tests, while
`bd init` under an inherited GIT_CONFIG_GLOBAL=/dev/null still missed a global
role, took hasRole=false, and persisted beads.role=maintainer into
repository-local config, where it outranks the global value for every later
read in a clean environment. Iteration 1 therefore left F1's escalation not
just alive but durable, on the one path the fix was supposed to close.
Fixed by keying the strict scrub on the config key alone and applying it to
whichever environment the repository already carries (roleAuthorityEnv). That
preserves capture semantics — NewInitGitRepository keeps its captured HOME,
the property git_test.go's captured_home case pins — and removes only the
suppression entries. Codex's alternative of rebuilding the constructor's whole
env was declined: it moves every key for no gain on this finding.
A2 (minor, contract fidelity) — iteration 1 justified declining cmd.Dir with
"repository selection is left to the working directory — the one input the
scrub keeps". That is false, and false in the file a future reader consults
before deciding whether to bound the pair: GIT_CEILING_DIRECTORIES is a routing
key too, so the scrub removes a bound rather than installing one. Measured from
a non-repository directory nested under a repository: `git config beads.role
<value>` fails "not in a git directory" while a ceiling below that repository is
inherited, and writes that repository's local config once the ceiling is
scrubbed. The decline itself stands, since the measurement behind it was made
against the GIT_DIR vector; getBeadsRole now records selection as the working
directory *or a containing ancestor*, which is also what makes
clearWorktreeGitRoutingEnv's existing cross-reference to "init's role probe"
true.
A3 (minor, consistency) — `bd config unset beads.role` and `bd config set-many
beads.role=` were the two spellings of that mutation still on ScrubRouting, in
the same file as the two that moved. Both measured inert: `git config <key>
<value>` and `--unset <key>` target the repository-local file, which the
suppression variables cannot select. Moved for parity rather than annotated,
because a divergence inside one file is how the next one starts.
Test evidence (minor) — the writer pair's two subtests both pass on the
redirect alone, so downgrading getBeadsRole back to ScrubRouting left them
green even though suppression is the load-bearing half at those sites
(init.go treats a getBeadsRole miss as permission to write a default role).
Added a global_null blinding subtest with the same unblinded fixture guard.
A4 (nit) — doctor/role.go's isGitRepo was the last probe in that file on the
suppression-retaining scrub, and it gates the "beads.role not configured"
warning. rev-parse is config-sensitive through safe.directory, which lives in
global config, so a retained GIT_CONFIG_GLOBAL=/dev/null can downgrade that
warning to "N/A (not a git repository)". Moved onto the same boundary as its
two siblings. As the finding records, the safe.directory precondition was not
reproduced end to end; the change is uniformity within the file.
Tests. Every pin reds only on its own defect:
- routing: reverting to ScrubRouting reds only the blinded-read subtest; the
unblinded fixture guard and the PR's inject-vector table stay green.
- gitenv: keeping suppression reds 10 of 16 new subtests, none of the PR's.
- cmd/bd: restoring the inherited env reds both redirect subtests and names
both halves ("the write did not land where bd is standing" / "an inherited
GIT_DIR captured the write"), while the PR's own role roundtrip stays green
— it followed the same redirect on both sides, so it never saw this.
- config: the two arms are proved separately. Scrub-only reds only the
legitimate-routing subtest; inherited-only reds only the poisoned-routing
subtest, so the new fallback cannot be read as a way around the scrub.
- domain/git (A1): restoring the r.env == nil provenance guard reds
global_null only; unblinded stays green, and no other test in the package
moves — which is the same measurement that confirms the arm had no coverage
before this iteration.
Deferred to follow-up, recorded for the approval summary: F4 (delete
isRoleGitRepo and resolve the dead else-if), F6 (user.name degrading to
hostname, which needs the PR's own subtest re-pointed), F8 (execenv fold
divergence), F9 and F11 (GetIdentity hostname degradation under inherited
suppression). F9's mechanism is confirmed — identity supplied only via
GIT_CONFIG_COUNT is lost when GIT_CONFIG_* is stripped, git reports "Please
tell me who you are", while GIT_AUTHOR_*/GIT_COMMITTER_* survive — but its
"leave artifact commits on the inherited environment" arm would re-open the
GIT_DIR redirect this PR's tail swap closed, and the non-regressing arm
(re-injecting inline identity pre-scrub) is a design change with no observed
victim in this repo.
Validation (iteration 2): internal/{gitenv,routing,storage/domain/git} full
packages green; cmd/bd/doctor full package run; targeted cmd/bd run over the
role, config and init blast radius green at 54 tests; go build ./... clean; go
vet plus CGO_ENABLED=0 and GOOS=windows CGO_ENABLED=0 vet clean on every
changed package. Remaining local reds are base-parity, each matching the
recorded cause: cmd/bd/doctor's seven (the launcher's global
beads.role=maintainer short-circuits CheckBeadsRole before isGitRepo is
reached, plus Dolt server availability) and
TestInitContributorSetsBeadsRoleContributor ("--contributor requires
interactive prompts", this session's stdin is not a TTY).
--- Iteration 3 ---
Iteration 3 reviewed 0220eed32 and approved it: claude filed no findings,
codex's six fix validations all came back correct, synthesis recorded
Decision: approve, and the scorecard scored 881/1000 with Required Changes:
None. The residual was two minors and a nit, none of them merge gates. All
three are taken here because they are comment-and-constant scope, so nothing
in the approved behavior moves.
B1 (minor, blast radius; codex filed it as major, demoted at synthesis) — the
isGitRepo() gate that decides whether the role pair runs is still fully
inherited while the pair it guards is now strict, so from a non-repository
directory with an inherited GIT_DIR the gate opens, the scrubbed read misses,
and the safety-net write fails "not in a git directory". Recorded at the
GH#2950 safety net rather than restructured, for the three reasons the
demotion rests on. The achievable outcome is base parity: sync_git.go is
byte-identical at base and the pair was inherited there too, so a GIT_DIR
holder already reached Maintainer before this PR — more directly, by pointing
at a repository whose beads.role is maintainer. The failure is not silent:
init prints "Warning: failed to set beads.role" unless --quiet, and every
later detection prints "beads.role not configured (GH#2950)" with two Fix
lines. And the prescribed roleRepoAvailable() gate provably does not close it:
all five gate sites are bare `if isGitRepo()` with no else, so a strict gate
answers false in exactly the described band, nothing is written, the role
stays unset, and detection still falls to detectFromURL. The optional
hardening is therefore declined rather than deferred — it would delete a
warning and change no role — and the comment says so, so the next reader does
not mistake a gate change for closing the fail-open path.
B2 (minor, contract fidelity) — the getBeadsRole rationale iteration 2 wrote
to close A2 introduced a new overstatement in its closing sentence: "bd init
takes no path argument — the residual is upward discovery from an unintended
cwd, not a redirect". `bd -C <dir>` is a redirect and takes no path argument.
Verified in tree rather than from the finding: applyChangeDirSelection
(main.go) resolves the target's .beads dir and sets BEADS_DIR with no chdir,
it runs from the root PersistentPreRunE ahead of every init-related early
return in that hook, and init honors BEADS_DIR for workspace selection — so
`bd -C other init` acts on other/.beads while the pair reads and writes
beads.role in the invocation repository. init.go's own "PersistentPreRun
doesn't run for init command" note is about the later skipsStoreInit return,
not about -C, which is what made this vector easy to miss twice. Reachability
is bounded: -C requires an existing beads project at the target, so the
pairing arises on re-init rather than first init. Comment narrowed to name the
residual; threading init's resolved project root through the pair is the
stronger arm and stays out of scope as a behavior change.
B3 (nit, architectural consistency) — the adapter selected the role-authority
boundary on a bare "beads.role" literal while the use case passed the
unexported beadsRoleConfigKey, two spellings of one contract the compiler
could not couple. Exported it as domain.BeadsRoleConfigKey and compared
against it at both adapter arms; no new import edge, since package git already
imports domain. Mutation-proved rather than asserted: replacing the
comparison with the case-variant "Beads.Role" the finding names reds
TestInitGitRepositoryRoleIgnoresInheritedConfigSuppression/global_null alone
while unblinded stays green, so the drift the nit describes is caught by an
existing pin. The comparison is still exact, not case-folded: git config names
are case-insensitive, so a caller hand-writing a variant spelling would bypass
roleAuthorityEnv, but folding widens which keys take the strict environment
and no production caller passes anything but the const — a behavior change the
nit did not ask for.
Validation (iteration 3): go build ./... clean; go vet plus CGO_ENABLED=0 and
GOOS=windows CGO_ENABLED=0 vet clean on cmd/bd, cmd/bd/doctor,
internal/storage/domain, internal/storage/domain/git and internal/gitenv;
internal/storage/domain/... full packages green (domain, db, fs, git); targeted
cmd/bd role run green at 19 subtests with no skips
(TestBeadsRoleCommandsIgnoreInheritedGitRouting and
TestBeadsRoleWriterIgnoresInheritedGitRouting, including the suppression
subtest added in iteration 2); gofmt and git diff --check clean. Full cmd/bd is
still not run locally: it times out at base as well. The iteration-1 deferrals
are unchanged and still owed follow-up bead ids at finalize (F4, F6/F11, F8,
F9).
---------
Signed-off-by: Ewen Cuthiell <ewencuthiell@gmail.com>
Co-authored-by: Bee <bee@ghosttrack.com>
Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
Co-authored-by: Julian Knutsen <julianknutsen@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
* fix(worktree): scrub inherited Git routing state
Establish CWD as the worktree repository boundary before discovery can consume inherited Git routing. Fence the startup config probe, clear routing in-process before root pre-run discovery, and retain command-owned subprocess scrubbing as defense in depth without changing PID or signal semantics.
Fixes#5531
Agent-Signature: codex-gpt-5-unknown-reasoning on behalf of Ewen Cuthiell
* refactor(worktree): explain owned filtering and remove an unused shim
Document why filtering the fresh routing slice in place is safe and call
the shared routing-key classifier directly from tests. Retain the two
forwarders used by production worktree subprocess/removal paths.
Review: https://github.com/gastownhall/beads/pull/5623#pullrequestreview-5098421671
Bead: saa-cgh.23
Agent-Signature: unknown-model/unknown-reasoning
* fix(config): isolate identity and tracked-file Git probes from routing
Reuse the worktree routing owner for GetIdentity and isGitTracked so
explicit cwd/path selection is not displaced by inherited repository,
index or injected config state. Preserve identity precedence and the
tracked-secret refusal contract, with real target/decoy regressions.
Follow-up: https://github.com/gastownhall/beads/issues/6222
Dependency: https://github.com/gastownhall/beads/pull/5623
Reported-by: bee-ghosttrack
Bead: saa-cgh.93
Agent-Signature: unknown-model/unknown-reasoning
* fix(config): share subprocess key identity for Git routing (saa-cgh.93)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* fix(exec): match Windows environment key identity (#5618)
Centralize os/exec-compatible environment-key comparison and use it for credential, metrics, Git-hook, trace, and repro subprocess filters. Preserve exact Unix semantics and Unicode near-collisions.
Agent-Signature: codex-gpt-5-unknown-reasoning on behalf of Ewen Cuthiell
Signed-off-by: Ewen Cuthiell <ewencuthiell@gmail.com>
* test(execenv): exercise every environment operation under both host rules
Thread the host choice through narrow private helpers behind the existing
exported functions. Keep one normalization owner and retain native wrapper
tests; the additional table covers both host branches for equality, prefix
matching, last-wins lookup, filtering and input preservation.
Review: https://github.com/gastownhall/beads/pull/5672#pullrequestreview-5096948965
Bead: saa-cgh.78
Agent-Signature: unknown-model/unknown-reasoning
* test(execenv): exercise exported host policy wiring (saa-cgh.78)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* docs(worktree): explain startup Git environment scope (saa-cgh.23)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* fix(config): isolate role commands from Git routing (saa-cgh.99)
Follow-up to bee-ghosttrack's review of gastownhall/beads#6322; refs #6357.
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* test(env): exercise shared key helpers on native Windows (saa-cgh.78)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* refactor(gitenv): share key parsing and normalize routing membership once (saa-cgh.93)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* docs(config): explain role command routing policy (saa-cgh.99)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* fix(init): isolate role configuration from inherited Git routing (saa-cgh.109.3)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* fix(init): use the selected origin in contributor setup (saa-cgh.109.7)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* fix(init): isolate Git writes in planning repositories (saa-cgh.109.9)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* test(init): retain inherited planning commit author (saa-cgh.109.9)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* fix(init): align embedded role gates with selected Git context (saa-cgh.109.12)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* fix(init): scope embedded artifact Git operations to selected directory (saa-cgh.109.15)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* test(init): cover selected optional artifacts and explain refused commits (saa-cgh.120)
Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell
* Honor role-probe cancellation and exercise actual fork planning (saa-cgh.120)
Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell
* fix(init): warn when automatic contributor role write fails (saa-cgh.109.3)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* test(init): cover successful nonquiet contributor role writes (saa-cgh.120)
Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell
* Assert the automatic contributor setup banner alongside warnings (saa-cgh.120)
Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell
* test(init): read persisted role routing from the store (saa-cgh.120)
Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell
* fix(git): isolate domain role configuration from inherited routing (saa-cgh.109.5)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* fix(init): probe the selected repository before configuring roles (saa-cgh.109.8)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* docs(init): explain role probe discovery ceiling behavior (saa-cgh.109.8)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* fix(init): bind proxied tail Git operations to selected directory (saa-cgh.109.14)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* fix(gitignore): preserve CRLF when appending project rules (saa-cgh.96)
Reported by bee-ghosttrack in gastownhall/beads#6343.
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* test(gitignore): pin detector edge cases and clarify append behavior (saa-cgh.96)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* fix(gitignore): preserve line endings in Git exclude appends (saa-cgh.104)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* test(gitignore): clarify exclude fixture path variable (saa-cgh.104)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* fix(gitignore): refuse exclude writes after read errors (saa-cgh.110)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* refactor(gitignore): share append byte composition (saa-cgh.105)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* docs(gitignore): explain append aliasing and trailing CR completion (saa-cgh.105)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* refactor(gitignore): use shared composition for exclude rules (saa-cgh.111)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* fix(gitignore): omit the empty exclude leading separator (saa-cgh.112)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* fix(init): bind exclude writers to the selected Git directory (saa-cgh.109.16)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* Explain restoration of absent routing variables in selected exclude tests (saa-cgh.120)
Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell
* Keep init role operations on the captured selected Git context (saa-cgh.120)
Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell
* Align selected-tail fixtures with captured role authority (saa-cgh.120)
Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell
* fix(init): write embedded excludes in the selected project (saa-cgh.120.11)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* fix(init): scrub the fork auto-detect gate; scope the startup-scrub claims
Maintainer review fixup for PR #6462 (adoption review iterations 1-2).
Gating major — hardened startup probe with an unhardened twin
------------------------------------------------------------
config.gitDirsForRepo (internal/config/config.go:419-424) is scrubbed by this
stack, but its byte-identical database-path twin
beads.worktreeFallbackBeadsDirForRepo (internal/beads/beads.go:1054-1058) runs
the same `git -C <repoPath> rev-parse --git-dir --git-common-dir` for the same
purpose and is not. Two claims added in this range asserted the boundary was
universal:
- docs/reference/worktrees.md:15 "Startup Git discovery probes for every `bd`
command scrub inherited Git routing variables" (false universal)
- cmd/bd/worktree_cmd.go:712 "Startup config discovery applies the same
boundary to its one pre-hook Git probe" (false singular)
Both are narrowed here to name only the plane that is actually scrubbed, and to
state that the `.beads` database-discovery probes still honor inherited routing.
The review offered a code arm (scrub beads.gitOutput,
beads.worktreeFallbackBeadsDirForRepo, and internal/git/gitdir.go:32) as the
alternative. That arm is DECLINED for this leaf, measured rather than assumed:
- Open sibling PR #6461 already carries it. At refs/pull/6461/head,
internal/beads/beads.go:293 routes gitOutput through
gitOutputEnv(gitenv.ScrubRouting(os.Environ())) and :1069 sets
cmd.Env = gitenv.ScrubRouting(os.Environ()) in the ResolveBeadsDirForRepo
twin, with internal/beads/{beads,context}_test.go coverage. Our head has
zero gitenv references under internal/beads (grep control).
- internal/git/gitdir.go is restructured wholesale by open sibling PR #6464
(loadGitContext/ResolveHooksContext), which documents "Routing variables are
honored, not filtered" as a deliberate choice.
- internal/beads/ and internal/git/ are not among this PR's 47 files, so the
code arm would rewrite two functions an open, non-ancestor sibling is
already rewriting in files this PR does not otherwise touch.
The twin is filed as bd-p4che with the failure scenario, the three unhardened
sites, the required decoy test, and the #6461 merge-order note, so the work is
tracked whether or not #6461 lands.
Minor — fork auto-detect gate left on inherited routing
------------------------------------------------------
cmd/bd/init.go:2002 gated the fork auto-detect block on the unscrubbed
isGitRepo() while the same single hunk hardened three setupForkExcludeAt(cwd, …)
call sites around it, and five sibling role gates in this PR already use the
scrubbed isInitRoleGitRepo(ctx). Under the invalid inherited GIT_DIR this PR's
own matrix uses, that gate returns false in a real fork clone and silently
suppresses the whole block — prompt, non-interactive auto-configure, and the
hardened writer at :2007/:2019. Switched to isInitRoleGitRepo(ctx) (same argv,
plus the scrub).
Pinned by a new fork_auto_invalid row in
TestEmbeddedInitSelectedExcludeRouting: it drops --setup-exclude so the exclude
write is reachable only through the gate, adds an upstream remote so the
already-scrubbed detectForkSetup reports a fork, and keeps --role=maintainer so
autoConfigureForkContributor stays an early return and the gate is the only path
that can add the pattern. The row carries the same fixture guard the sibling
role test uses, asserting the inherited probe really is refused.
Mutation-proved: with the gate reverted to isGitRepo() and the row in place,
only fork_auto_invalid fails ("selected exclude = "# owned project
exclude\nkeep-me/\n"; want ... "**/RECOVERY*.md"") while all six incumbent
subtests stay green — so the row adds coverage rather than duplicating an
existing fixture.
Not taken (non-gating, recorded so the next pass grades the call rather than
re-filing it)
----------------------------------------------------------------------------
- per-key `beads.role` scrub inside the generic accessor
(internal/storage/domain/git/git.go:110,133): the constructor contract it
straddles is owned by the parent legs; #6464 also edits this file.
- splitting gitenv.routingKeys into redirect vs fence sets
(internal/gitenv/routing.go): the class was filed on the parent PRs and the
set is shared by the whole family; changing it here would fork a primitive
five open branches consume.
- deleting the three zero-caller wrappers in cmd/bd/init_stealth.go:
cmd/bd/init_stealth.go is concurrently rewritten by open sibling #6461,
which does not carry this leg's setupStealthModeAt/setupGitExcludeAt split
(base 566c84ba8 greps 0 for those names; this head greps 5), so deleting
them here would conflict that rewrite.
Correction (iteration 2): the earlier reason for this bullet — "the file is
byte-identical across the open siblings at this head" — does not reproduce
and is withdrawn. git diff --name-only HEAD refs/adopt/pr6461 --
cmd/bd/init_stealth.go is NON-empty precisely because this PR created the
...At split; byte-identity with a sibling is only obtainable for siblings
that already carry this leg (empty against refs/adopt-pr-probe/6464). The
decision stands on the concurrent-rewrite reason above.
- nit, non-git `bd init` note (cmd/bd/init.go): no code change is owed on the
merits, which is its own reason rather than the execenv one it previously
borrowed. commitEmbeddedInitArtifacts (cmd/bd/init.go:3477-3483)
re-establishes the dropped repo gate as its own SCRUBBED
`rev-parse --git-dir` probe via initArtifactGitCommand (:3537-3541); only
the added stderr line is new.
- nit, unexporting execenv.KeyHasPrefixForOS: internal/execenv/execenv.go is
byte-identical to both siblings resolvable at this head
(refs/adopt/pr6461 and refs/adopt-pr-probe/6464 both diff empty), so
unexporting it here would fork a file they share.
Correction (iteration 2): the earlier "across all four open siblings"
quantifier overstated what is measurable — iteration 1's other two probe
refs no longer exist in this worktree, so the claim is scoped to two.
Iteration 2 (non-gating cleanup; no code, test, or behavior change)
------------------------------------------------------------------
The iteration-2 review found zero blockers and zero majors in this fixup's
delta and the quality scorecard decided approve. All three of its items were
documentation or record-keeping and are discharged here:
- Contract fidelity nit: the narrowed worktrees.md sentence had fixed WHICH
PLANE scrubs but kept the original's unconditional frequency ("on every
`bd` command"), while the probe its appositive names —
worktreeFallbackConfigPath — runs only under
`primaryConfigPath == "" && beadsEnvConfigPath == ""`
(internal/config/config.go:183). Reworded to separate the two: the scrub is
unconditional FOR THAT PROBE, and the probe itself is a fallback that runs
only when nothing earlier in startup already resolved a config path, with
an ancestor .beads/config.yaml or an explicit BEADS_DIR as the
short-circuits. Stated as a general condition plus examples rather than
swapping one unconditional claim for another. The review's suggested
wording cited internal/config/config.go:183; the line number is dropped
because no file under docs/reference cites Go line numbers (6 Go-path
mentions across that tree, none with :NNN) and a line citation in a doc
rots. The file reference is kept so the claim stays checkable.
- Release-safety minor: bd-p4che's required-fix section now also names the
two PROSE sites that assert the unhardened state (this worktrees.md
paragraph and clearWorktreeGitRoutingEnv's doc comment), with a
drift-proof `git grep "still honor inherited routing"` anchor, because its
close-out instruction previously named only the three code sites. If #6461
merges first, it adds the byte-for-byte pre-image of this paragraph at the
same location, so this fixup's hunk applies CLEANLY and would leave the
falsified wording behind silently; nothing in CI pins the file (absent from
scripts/check_doc_freshness_test.go). Only that merge order is silent, and
the direction is safe either way since stale wording under-claims
protection.
- Debuggability nit: the two "Not taken" bullets above are corrected, see the
inline "Correction (iteration 2)" notes.
Validation
----------
- git diff --check clean; go build + go vet ./cmd/bd ./internal/config green.
- 25 blast-radius cmd/bd tests green with BEADS_TEST_EMBEDDED_DOLT=1 and
BEADS_TEST_REQUIRE_EXCLUDE_PERMISSION=1 (exclude/stealth writers, fork
auto-detect, init-role and worktree routing), incl.
TestEmbeddedInitSelectedExcludeRouting 7/7. The one skip
(TestInitPromptNonGitRepo) is the pre-existing "Dolt test server not
running" opt-in.
- An initial run showed 21 reds at 0.00s from a concurrent session sweeping
the shared /tmp/beads-bd-tests-* root; all pass under an isolated TMPDIR.
- Iteration 2 touches one Markdown file and no Go source, so the code
validation above still stands at this tree: git diff --name-only for the
iteration-2 delta is docs/reference/worktrees.md alone. git diff --check
clean. worktrees.md is not in scripts/check_doc_freshness_test.go's
freshnessDocuments and is named by no workflow, Makefile target, or test,
so no gate covers it.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* fix(git): reconcile role-config tests with the preserved read-error contract
Base advanced 11 commits during finalize and #6477 ("preserve config read
errors instead of treating them as absent", cf683435e) landed in the one
package this PR co-edits, internal/storage/domain/git. The rebase was clean
and no production code conflicts, but the two changes falsify each other's
test expectations in opposite directions:
- #6477's invalid_routing_boolean row injects GIT_CONFIG_NOSYSTEM to force a
beads.role read failure. This PR scrubs routing for beads.role, and
gitenv.IsRoutingKeyForOS classifies every GIT_CONFIG* key as routing, so the
injector can no longer reach that read. Retarget the row to test.marker so it
still proves a routing-induced failure is surfaced rather than swallowed, and
narrow the BeadsRole propagation assertion to malformed_config, which breaks
the repository's own config and is therefore immune to the scrub. Add a
positive pin that beads.role now resolves as absent without error under the
same poison.
- This PR's captured_home asserted NoError on the strength of "the existing
reader maps Git exit errors to absence", which is exactly the contract #6477
removed. Expect the error instead, matching the adjacent assertion that the
inherited writer fails on the same broken HOME.
#6477's guarantee is unchanged: the merged GetConfig keeps its classification
block and still uses cmd.Output(), which is what populates exitErr.Stderr.
Only this one injector for this one key stopped producing a failure.
internal/storage/domain/git 45/45 pass; removing the scrub from GetConfig makes
the new pin fail, so it is non-vacuous. cmd/bd blast radius 28/28 pass with
BEADS_TEST_EMBEDDED_DOLT=1, covering all six base-added init/temp-root tests.
---------
Signed-off-by: Ewen Cuthiell <ewencuthiell@gmail.com>
Co-authored-by: Julian Knutsen <julianknutsen@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
* fix(notion): keep notion.token out of the Dolt database (#6676)
notion.token was missing from YamlOnlyKeys, so `bd config set
notion.token` (the command `bd notion status` recommends) wrote the
token to the Dolt config table, whose contents `bd dolt push` sends to
the remote. The git-tracked-config guard never fired for it either,
because checkSecretGitTracked only considers yaml-only keys.
- Add notion.token to YamlOnlyKeys, next to github.token, gitlab.token,
jira.api_token and ado.pat, so `bd config set` writes it to
config.yaml and refuses a git-tracked config.yaml.
- Map notion.token to NOTION_TOKEN in secretKeyEnvVarHints so that
refusal suggests the variable bd actually reads, not BD_NOTION_TOKEN.
- notion.ResolveAuth now reads config.yaml first, then the database,
then NOTION_TOKEN. The database read is kept only so a token stored
by an older bd keeps authenticating after an upgrade.
- resolveNotionAuth's no-store fallback goes through ResolveAuth, so a
config.yaml token is found even when no store is open.
- The proxied `bd serve` settings integration test used notion.token as
its credential-bearing key and read it back with `bd config get`,
which now reads config.yaml; it uses notes.api_token instead.
- The DB-backed-secret guard test used notion.token as its example of a
non-yaml secret key; it uses custom.api_token instead.
- Docs list notion.token with the other yaml-only secrets, and the
quickstart leads with NOTION_TOKEN because `bd init` in a git repo
leaves config.yaml tracked.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(config,notion): delete leaked secret rows on unset; name the legacy auth source
Maintainer review fixes for #6724 (GH#6676).
Finding 1 (major, PR-introduced): moving notion.token into YamlOnlyKeys made
`bd config unset notion.token` return before the store, so a workspace that had
already leaked the token into the pushed config table lost its only bd-side
remover — exactly the population the PR exists to protect. configUnsetCmd now
best-effort deletes the database row for yaml-only SECRET keys and reports which
copies it removed. It is keyed on IsYamlOnlyKey+IsSecretKey rather than on
notion.token, so it closes the gap for the whole class; measured, that is at
least ado.pat, github.token, gitlab.token, jira.api_token, linear.api_key,
linear.oauth_client_secret and notion.token, plus whatever the prefix rules
(`ai.`, `sync.`, `federation.`, ...) admit. Non-secret yaml-only keys are gated
out before the store is opened, so an ordinary `bd config unset routing.mode`
still costs no database open. It reads before deleting because DeleteConfig
reports no miss, so the common never-leaked workspace stays silent instead of
announcing a removal that did not happen.
Finding 2 (major, pre-existing class): internal/notion/auth.go asserted "It must
never be written to the database" as an unqualified invariant while
PUT /v0/beads/config/notion.token still writes that row with no refusal. Scoped
the comment to the CLI door and named the HTTP/dashboard door as the known
remaining hole. Closing that door is deliberately NOT attempted here: it is a
cross-tracker change at workapi.ValidateSettingWrite/SetSetting on a
pre-existing surface, and belongs where every tracker credential gets the rule
at once.
Finding 3 (minor): the config.yaml token and the legacy row both reported
`config_token`, collapsing the safe case with the leaked one. Added
AuthSourceDatabaseLegacy plus a `bd notion status` rotation warning — the only
signal that gives the CHANGELOG's rotation advice an addressee.
Finding 4 (minor): pinned the end-to-end shape `bd config set` actually writes.
The finding cited internal/config/config.go:653 (setNestedKey), which is
SaveConfigValue's writer and not on this path — SetYamlConfig routes through
updateYamlKey/updateNestedYamlKey — but its conclusion held: the written shape
is nested. The new test drives the real writer rather than a second fixture, and
both its assertions were proven live by mutation (breaking the config.yaml read
trips the round-trip; forcing the flat fallback trips the non-vacuity guard,
while the round-trip alone still passed, which is why that guard exists).
Finding 5 (nit): both "not configured" errors led with `bd config set
notion.token`, which the new git-tracked refusal rejects in the default
post-`bd init` layout. They now lead with `export NOTION_TOKEN`, matching the
quickstart's ordering.
Also corrected the CHANGELOG, which still claimed unset clears config.yaml only.
Validation: ./internal/notion and ./internal/config green under `env -u
BEADS_DIR`. The cmd/bd notion/config tests are green except
TestConfigValidateReadOnlyIsHermetic and
TestGetNotionConfigReadsDBPathWhenStoreUnset, which fail identically at the PR
head with these fixes stashed (A/B in this same worktree) — ambient, not
introduced here.
--- Iteration 2 review fixes (one major, three minors, one nit) ---
Finding 1 (major, introduced by the iteration-1 fixup above): the cleanup
reached the store through openWorkspaceConfig -> ensureDirectMode ->
ensureStoreActive, which is open-OR-CREATE. So `bd config unset <yaml-only
secret>` in a workspace holding only .beads/config.yaml created a 2.1 MB
embedded Dolt database and flipped it out of db-less mode for every later
command -- from a command whose contract is "edit a YAML file", silently and
with exit 0. It also contradicted configCommandCanRunWithoutStore, which
classifies this exact invocation as runnable with no store precisely when
beads.FindDatabasePath() is empty. unsetLeakedSecretRow now returns early
rather than reach an open-OR-CREATE store in a workspace that has no database to
reach. The proxied route is exempt rather than gated --
proxiedWorkspaceConfig reaches an already-connected provider and creates
nothing, and a server-mode workspace legitimately has no local database
directory for FindDatabasePath to find, so gating it on the local path would
silently disable the cleanup exactly where the row is most replicated. Iteration 3 finishes
that thought: the same is true of the DIRECT server-mode route, which this gate
still skipped.
Finding 2 (minor): the remover ran only if the YAML unset succeeded first,
which skipped it for the population it exists for -- no config.yaml, or a shape
UnsetYamlConfig refuses. Base deleted the row there and the fixup did not, while
`bd notion status` names this very command as the remover. The cleanup now runs
either way, and a failed YAML unset carries the row's fate in its error instead
of telling the user to run `bd init` while a credential sits in the pushed
table.
Finding 3 (minor): a failed DELETE of a row the read had found was rendered as
"Could not check the database ..." under a JSON key asserting unreachability --
the one outcome that is certain, reported as the inconclusive one.
removeStoredSecretRow now returns the found bit alongside the error, and the
delete-failure case gets its own message and its own JSON keys
(database_row_present / database_delete_failed), carrying the rotation warning.
Finding 4 (minor): nothing pinned the command -> cleanup wiring; deleting the
call left every test green. The yaml-only branch is now runConfigUnsetYamlOnly
and four new tests drive configUnsetCmd itself against a recording settings
surface: the row is read, deleted and reported; a non-secret yaml-only key
touches the config plane zero times; --json carries the new keys; and .beads/ is
byte-unchanged (config.yaml aside) after unsetting a secret with no database
present.
Finding 5 (nit): CHANGELOG and docs/reference/configuration.md described the
dual removal unconditionally. Both now say the database half is best effort and
name the cases where it is skipped or refused.
Every new pin proven by mutation, one at a time, each failing only with its fix
removed: dropping the FindDatabasePath gate takes the no-database test into
embeddeddolt.OpenSQL (it really does provision); re-gating the cleanup behind
the YAML unset leaves the row undeleted and unmentioned; replacing the command's
cleanup call with a zero value drops the report and the --json field; returning
false for `present` on a failed delete puts database_unreachable back.
Complexity ledger flat by construction: worst_changed stays
showConfigYAMLOverrides at cyclomatic 17 / cognitive 29, which this PR does not
touch and which measures identically at the base blob. The extracted
runConfigUnsetYamlOnly is 6/9 and the three report helpers are at most 5/2.
Iteration 2 validation: ./internal/notion and ./internal/config green under
`env -u BEADS_DIR`; all nine cmd/bd leaked-secret/notion-auth tests green, one
-run per invocation (a batched regex shares rootCmd and produces false reds);
the CGO_ENABLED=0 gms_pure_go cmd/bd test binary still compiles (the new test
file is untagged, so it carries its own tree-snapshot helper rather than the
cgo-tagged twin); scripts/check-doc-flags.sh and `go test -tags=gms_pure_go
./test/docsync` pass for the docs edit.
--- Iteration 3 review fixes (two minors, both on the gate itself) ---
Finding 1 (minor, introduced by the iteration-2 gate above): "not proxied and no
local database directory" over-fires. findDatabaseInBeadsDir answers on
metadata.json plus embeddeddolt/ and dolt/, and it skips the stat for server mode
only when metadata.json is present -- so a metadata-less server workspace, whose
host comes from config.yaml or BEADS_DOLT_SERVER_HOST (main.go, GH#3545, the
shape gc provisions on every `gc-beads-bd start`), reports "" while its row sits
on the shared server, replicated to every remote it pushed to. The skip was not
buying anything there either: PersistentPreRun has already CONNECTED that
workspace's store, and ensureStoreActive early-returns on an active store without
opening or creating anything. For notion.token this was a narrow regression of a
base capability -- at base that key was not yaml-only, so `bd config unset
notion.token` took the database branch and deleted the row. The seven
pre-existing yaml-only secrets never had a remover at base, so for them the skip
withheld only new coverage, which is what holds this at minor. The gate is now
mayProvisionDatabase, which asks about the store before the disk; each arm that
returns false is a route where the database is already open -- proxied, or a
store already active and tracked, which is provably non-provisioning because it
is ensureStoreActive's own no-op arm.
Finding 2 (minor): neither arm of that gate had a behavioral test. Deleting the
!usesProxiedServer() clause left all four command-level tests green, and it is
the only thing keeping the cleanup alive for proxied workspaces, which have no
local database directory by construction -- the clause a later simplification is
most likely to read as redundant was the one clause nothing defended.
TestConfigUnsetCleansTheRowWithNoLocalDatabaseDirectory now pins both arms as the
mirror of TestConfigUnsetDoesNotProvisionADatabase: "no local database directory"
is the state all three share, so the route to the database is the only thing that
distinguishes them.
Both arms mutation-proved, one at a time, each red on exactly one subtest while
the four pre-existing command-level tests stayed green under both mutations:
deleting the active-store arm reproduces the finding verbatim (GetSetting calls =
[], UnsetSetting calls = [] for a connected server workspace, exit 0); deleting
the !usesProxiedServer() arm leaves the proxied workspace's row never looked for.
That second half -- the pre-existing suite staying green -- is the claim Finding 2
rests on, and only a run under the mutation can state it.
The CHANGELOG's "skipped where there is no database to hold a row" and the
matching sentence in docs/reference/configuration.md asserted exactly what the
gate got wrong; both now say it is skipped only where reaching the row would mean
creating a database, and that a server-mode or proxied workspace whose database
is simply not on local disk still gets the cleanup.
Complexity ledger still flat: worst_changed stays showConfigYAMLOverrides at
cyclomatic 17 / cognitive 29 (untouched, identical at the base blob), and
extracting the gate took unsetLeakedSecretRow from 6/5 to 5/4 with
mayProvisionDatabase at 4/3.
Iteration 3 validation: gofmt clean, `go build ./cmd/bd/`, `go vet ./cmd/bd/` and
`git diff --check` clean; the six leaked-secret/notion-auth tests and the four
command-level tests all green against the real fix, one -run per invocation under
a private TMPDIR (a batched regex shares rootCmd and produces false reds; a
sibling suite's sweep deletes shared temp roots mid-run); the CGO_ENABLED=0
gms_pure_go cmd/bd test binary still compiles; scripts/check-doc-flags.sh,
scripts/check-doc-freshness.sh and `go test -tags=gms_pure_go ./test/docsync`
pass for the docs edit (no new links, anchors or headings, so the render check
does not apply).
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Julian Knutsen <julianknutsen@users.noreply.github.com>
* fix(worktree): scrub inherited Git routing state
Establish CWD as the worktree repository boundary before discovery can consume inherited Git routing. Fence the startup config probe, clear routing in-process before root pre-run discovery, and retain command-owned subprocess scrubbing as defense in depth without changing PID or signal semantics.
Fixes#5531
Agent-Signature: codex-gpt-5-unknown-reasoning on behalf of Ewen Cuthiell
* refactor(worktree): explain owned filtering and remove an unused shim
Document why filtering the fresh routing slice in place is safe and call
the shared routing-key classifier directly from tests. Retain the two
forwarders used by production worktree subprocess/removal paths.
Review: https://github.com/gastownhall/beads/pull/5623#pullrequestreview-5098421671
Bead: saa-cgh.23
Agent-Signature: unknown-model/unknown-reasoning
* fix(config): isolate identity and tracked-file Git probes from routing
Reuse the worktree routing owner for GetIdentity and isGitTracked so
explicit cwd/path selection is not displaced by inherited repository,
index or injected config state. Preserve identity precedence and the
tracked-secret refusal contract, with real target/decoy regressions.
Follow-up: https://github.com/gastownhall/beads/issues/6222
Dependency: https://github.com/gastownhall/beads/pull/5623
Reported-by: bee-ghosttrack
Bead: saa-cgh.93
Agent-Signature: unknown-model/unknown-reasoning
* fix(config): share subprocess key identity for Git routing (saa-cgh.93)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* fix(exec): match Windows environment key identity (#5618)
Centralize os/exec-compatible environment-key comparison and use it for credential, metrics, Git-hook, trace, and repro subprocess filters. Preserve exact Unix semantics and Unicode near-collisions.
Agent-Signature: codex-gpt-5-unknown-reasoning on behalf of Ewen Cuthiell
Signed-off-by: Ewen Cuthiell <ewencuthiell@gmail.com>
* test(execenv): exercise every environment operation under both host rules
Thread the host choice through narrow private helpers behind the existing
exported functions. Keep one normalization owner and retain native wrapper
tests; the additional table covers both host branches for equality, prefix
matching, last-wins lookup, filtering and input preservation.
Review: https://github.com/gastownhall/beads/pull/5672#pullrequestreview-5096948965
Bead: saa-cgh.78
Agent-Signature: unknown-model/unknown-reasoning
* test(execenv): exercise exported host policy wiring (saa-cgh.78)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* docs(worktree): explain startup Git environment scope (saa-cgh.23)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* fix(config): isolate role commands from Git routing (saa-cgh.99)
Follow-up to bee-ghosttrack's review of gastownhall/beads#6322; refs #6357.
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* test(env): exercise shared key helpers on native Windows (saa-cgh.78)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* refactor(gitenv): share key parsing and normalize routing membership once (saa-cgh.93)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* docs(config): explain role command routing policy (saa-cgh.99)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* fix(init): isolate role configuration from inherited Git routing (saa-cgh.109.3)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* fix(init): use the selected origin in contributor setup (saa-cgh.109.7)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* fix(init): isolate Git writes in planning repositories (saa-cgh.109.9)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* test(init): retain inherited planning commit author (saa-cgh.109.9)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* fix(init): align embedded role gates with selected Git context (saa-cgh.109.12)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* fix(init): scope embedded artifact Git operations to selected directory (saa-cgh.109.15)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* test(init): cover selected optional artifacts and explain refused commits (saa-cgh.120)
Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell
* Honor role-probe cancellation and exercise actual fork planning (saa-cgh.120)
Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell
* fix(init): warn when automatic contributor role write fails (saa-cgh.109.3)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* test(init): cover successful nonquiet contributor role writes (saa-cgh.120)
Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell
* Assert the automatic contributor setup banner alongside warnings (saa-cgh.120)
Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell
* test(init): read persisted role routing from the store (saa-cgh.120)
Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell
* Bind early embedded Git bootstrap to the selected project (saa-cgh.120.9)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* Create the owned separate-storage parent in the bootstrap fixture (saa-cgh.120.9)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* fix(init,gitenv,config): maintainer fixup for #6459
Review iteration 1, blocking:
- cmd/bd/init_stealth.go: scope the fork exclude writer the way this PR
scoped the fork detector. detectForkSetup now scrubs inherited Git
routing, but resolveGitExcludePath still ran `git rev-parse
--git-common-dir` with no Dir and no Env, so with GIT_DIR inherited
toward another repository bd detected the fork in the selected repo and
then appended `.beads/`, `**/RECOVERY*.md` and `**/SESSION*.md` to the
*inherited* repository's .git/info/exclude - automatically, with no
prompt, in non-interactive mode. At base the two halves agreed (both saw
the inherited repo, found no upstream, wrote nothing), so the PR is what
creates the disagreement. Scrubbing the probe is the whole remedy: no
cmd/bd caller chdirs, so `repoPath == ""` already means the selected
project directory once inherited routing is gone. The new test asserts
both halves - the selected repo is written, the inherited one is
byte-unchanged - and reverting the scrub reds it while every existing
exclude test stays green.
- cmd/bd/config.go: the new comment claimed "All role commands ignore
inherited Git routing". Only bd config's own role paths were hardened -
routing.DetectUserRole, `bd config show`, `bd doctor` and `bd hooks
uninstall` still resolve beads.role through the inherited environment,
and beads.RepoContext.Role pins GIT_DIR/GIT_WORK_TREE last-wins but still
inherits GIT_CONFIG_*. So `bd config get beads.role` and `bd config show`
can disagree in one shell, and `bd config unset beads.role` and `bd hooks
uninstall` can target different repositories. Narrow the comment to the
command set it covers; widening the boundary to the deciders is a
separate, permissions-adjacent change. The same root cause is filed on
#6460 and #6464, where it is broader - fix it once, on whichever merges
first.
Review iteration 1, non-blocking:
- docs/reference/worktrees.md: the new prose claimed startup Git discovery
probes for every bd command scrub inherited routing. Only internal/config's
gitDirsForRepo does; internal/git's process-cached context does not. Narrow
the sentence to config discovery and name both sides.
- internal/gitenv/routing.go: say in the contract comment why
GIT_CEILING_DIRECTORIES is a routing key even though it narrows rather
than redirects, and disclose that removing it widens the upward search.
Pin the membership with a ceiling entry in the existing scrub table.
- cmd/bd/worktree_cmd.go: route the removal pass's key identity through
execenv.KeyIdentityForOS instead of the last hand-rolled fold. ToUpper is
the opposite direction from the shared primitive and provably
non-equivalent: on Windows it collapsed GıT_OPTIONAL_LOCKS (U+0131) onto
GIT_OPTIONAL_LOCKS and stripped an unrelated variable that
gitenv.ScrubRoutingForOS, one line earlier, keeps.
Validation: go build ./..., go vet, CGO_ENABLED=0 vet and
GOOS=windows CGO_ENABLED=0 vet all clean; internal/gitenv green; cmd/bd
filtered run green except TestGetNotionConfigReadsDBPathWhenStoreUnset and
TestConfigValidateReadOnlyIsHermetic, which fail identically at the
unmodified head. All three new pins mutation-proved.
Review iteration 2, non-blocking:
- internal/config/worktree_config_test.go, cmd/bd/init_git_bootstrap_routing_test.go:
finish the conditional half of iteration 1's GIT_CEILING_DIRECTORIES item.
That item offered "drop the key" or "keep it and say so - and if kept, add
a legitimate-ceiling case to the two cited tests". The docs arm was taken
but only one of the two tests got a case, and the half left unpinned is the
widening the new contract comment now promises. Both new cases set a
*legitimate* ceiling - an operator fencing off an ancestor - and assert the
scrub widens past it: startup config discovery still resolves the main
repository's shared config, and `bd init`'s bootstrap probe still resolves
the containing repository. Each carries a control that fails the test if the
ceiling did not bite, so neither can pass vacuously. Dropping
GIT_CEILING_DIRECTORIES from routingKeys reds both new pins while
TestWorktreeFallbackConfigPathIgnoresInheritedGitRouting and
TestSetupForkExcludeIgnoresInheritedGitRouting stay green, so they cover an
arm the poisoned-routing pins do not.
The review prescribed this assertion in the inverted direction ("a
fenced-off ancestor does not suppress the fresh git init"). Measured
against git 2.43.0: a ceiling at a repository root does fence off a probe
run from a subdirectory, so scrubbing it makes the ancestor visible and the
fresh `git init` is suppressed. The tests pin the measured direction.
- cmd/bd/init_stealth.go: the scrub makes resolveGitExcludePath's "not a git
repository" newly reachable from `bd init --setup-exclude` exactly where the
cause is interesting, but the probe's error was discarded. Thread git's own
reason through, reusing firstNonEmptyLine from sync_git.go, which already
exists for this failure shape. exec.ExitError.Error() is only "exit status
128", so a bare %w would have added nothing readable. The "not a git
repository" prefix is load-bearing - setupStealthMode matches it with
strings.Contains to treat this as a skip - and is preserved. Rendered:
Warning: failed to configure git exclude: not a git repository (inherited
Git routing is ignored here): fatal: not a git repository (or any of the
parent directories): .git
Validation (iteration 2): gofmt clean; go build ./...; go vet, CGO_ENABLED=0
go vet and GOOS=windows CGO_ENABLED=0 go vet clean on cmd/bd and
internal/config. Both new pins green and mutation-proved as described; the
nine existing cmd/bd exclude/routing/fold pins, the internal/config
worktree-fallback set, and the internal/gitenv and internal/execenv suites all
stay green. No production behavior change beyond the error text.
---------
Signed-off-by: Ewen Cuthiell <ewencuthiell@gmail.com>
Co-authored-by: Julian Knutsen <julianknutsen@users.noreply.github.com>
Co-authored-by: Julian Knutsen <julian@example.com>
* test(docs): red — Docs: init-safety re-clone playbook must say damaged stores go OUTSIDE data_dir and a fresh clone needs bd migrate schema (refs be-wv0d0)
* feat: green — Docs: init-safety re-clone playbook must say damaged stores go OUTSIDE data_dir and a fresh clone needs bd migrate schema (refs be-wv0d0)
- docs/recovery/init-safety.md: new re-clone-gotchas section covering both
live gotchas from ga-vrq5pu (damaged/set-aside stores must move OUTSIDE
data_dir; a fresh clone needs `bd migrate schema` for dolt-ignored
clone-local tables), with cross-reference pointers from the two existing
bd bootstrap mentions and a pointer (not a duplication) to bd doctor
--fix's automated corrupt-manifest convention. Freshness markers bumped.
- cmd/bd/init_safety_help.go: RECOVERY section of the init-safety Long help
gets a brief RE-CLONE GOTCHAS addendum with both symptom signatures and
the fix command.
- test/docsync/init_safety_recovery_test.go: retargeted
TestInitSafetyCLIReferenceCoversReCloneGotchas (written during RED) to
TestInitSafetyCLIHelpCoversReCloneGotchas, asserting on
cmd/bd/init_safety_help.go's Long field instead of the generated
docs/cli-reference/init-safety.md. That generated page is pinned to a
released bd (docs/cli-docs.pin = v1.2.2, built in a detached worktree per
scripts/resolve-docs-bd.sh) and does not pick up a Long-field edit at
HEAD until a maintainer bumps the pin at the next release — confirmed
empirically (`git show v1.2.2:cmd/bd/init_safety_help.go` still points at
the deprecated docs/RECOVERY.md path, and a full
./scripts/generate-cli-docs.sh run here produced zero diff to the
committed docs/cli-reference/). CI's own drift gate
(scripts/check-cli-docs-drift.sh) is blame-scoped for exactly this
reason. The original RED test was asserting on an artifact this PR
cannot legitimately change without fighting that pin.
* fix(docs): address review feedback on init-safety re-clone playbook
Three fixes per bee-ghosttrack's REQUEST-CHANGES on PR #6431:
- Correct Gotcha 1's "The fix" paragraph: bd doctor --fix's
corrupt-manifest repair renames the whole data_dir directory to a
sibling .<ts>.corrupt.backup path, not a backup nested inside the
database's own directory. Verified against
cmd/bd/doctor/fix/database_integrity.go and
cmd/bd/doctor/tracked_runtime.go.
- Replace the hardcoded "Schema already at v64" literal with
version-agnostic "Schema already at v<N>" in the doc and CLI help
text, and narrow the docsync test assertion to the prefix "schema
already at v" so it survives future version bumps instead of
rotting again.
- Drop the dead GitHub-issue-style link around ga-vrq5pu (a Gas City
bead id, not a GitHub issue) — keep it as plain text.
Ref: be-hobyw
* review: correct re-clone gotchas and tighten their guards (PR #6431 iters 1-2)
Maintainer review fixup for the adopted PR. This is a docs-only PR whose
entire deliverable is factual accuracy, so every finding here is about a
claim the doc makes rather than about code behaviour.
=== Iteration 1 ===
[major] Gotcha 1's "The fix" paragraph misattributed the automated repair
and pointed an operator mid-crash-loop at a path that cannot run. Verified
first-hand in the worktree:
- internal/doltserver/manifest_recovery.go:231-235 renames
<data_dir>/<db>/.dolt -> <db>/.dolt.<ts>.corrupt.backup, i.e. IN PLACE,
not the whole data_dir to a sibling as the doc claimed. It also only
fires behind nomsDirLooksCorrupt, whose own comment is "recovery only
fires when we can prove there is nothing the user would want to keep"
(:94-100) - so it never touches the superseded-but-populated store the
gotcha is about.
- The whole-data_dir -> sibling rename is a different fix:
cmd/bd/doctor/fix/database_integrity.go:35,43-45 over
getDatabasePath(beadsDir) (validation.go:15-21).
- That fix opens with serverModeIntegrityRecoveryGuard, which refuses
outright in Dolt server mode (:79-96).
Rewritten to state all three facts and to tell the reader plainly that the
move is theirs to make by hand. Kept the correct headline sentence. The
paragraph deliberately does not assert anything about where the in-place
backup lands under the legacy single-database layout (data_dir/.dolt), the
one premise the review left unproven - the wording is scoped to the standard
<data_dir>/<db>/ layout instead of minting a fresh unverified claim.
[minor] Gotcha 2's mechanism sentence ("bd's ordinary open does not recreate
them") is false for embedded mode: newStore -> initSchema (store.go:285,470)
calls schema.MigrateUp (:574), and migrationWorkNeeded returns true whenever
!ignoredSource.atLatest (schema.go:866-867) - and ignored_schema_migrations
is itself in doltIgnorePatterns, so a fresh clone always qualifies. Replaced
the universal with the actual condition. The replacement list of opens that
do NOT self-heal was itself wrong on its first item; see iteration 2 below.
The prescribed remedy was already correct and is unchanged.
[minor] The doc's prose Freshness source list gained cmd/bd/init_safety_help.go
but the enforcing DOCS array did not. Added to both scripts/check-doc-freshness.sh
and the pinned row in scripts/check_doc_freshness_test.go - a coupled pair:
editing only the script reds the pinned test with "Freshness source does not
name cmd/bd/init_safety_help.go" (verified by running exactly that mutation).
[nit] The docsync guard for the headline rule was two independent whole-file
substring checks. Scoped it to Gotcha 1's own section and matched the advice
as a phrase, and pinned both ends of the help text's #re-clone-gotchas
cross-reference, which neither markdown link checker can see because it lives
in a Go string. Five mutation legs, each reddening only its own assertion:
inverting the advice, moving the phrase outside the section, renaming the
heading, breaking the help anchor, and removing the Gotcha 1 heading. The
inversion leg is the one that matters - the file still contained "outside"
(2x) and "data_dir" (13x), so the old form stayed green on inverted advice.
[nit] Bumped Last reviewed: to the revision date.
=== Iteration 2 ===
Both lanes verified all five iteration-1 fixes. Three prose findings remained,
none a merge gate (scorecard: approve, Required Changes: none). All three are
the same defect class - a sentence that quantifies over a set the author did
not census - so each is fixed by removing the quantifier rather than by
restating it more carefully.
[minor] Gotcha 2's replacement enumeration was false on its first item: a
server, shared or proxied open DOES replay the clone-local series in this
doc's own scenario. Re-derived at head, both lanes independently:
- internal/storage/uow/dolt_sql_provider.go:267-287 calls
MigrateUpWithLock UNCONDITIONALLY on the non-team-server, non-preview
arm; p.readOnly is consulted only after a RemoteMigrateGateError comes
back (:288-296), so it cannot suppress the pass.
- The gate cannot refuse a main-current clone: PendingVersions is
mainSource.pendingVersions only (schema.go:525-527) and the gate
early-returns nil on len(pending)==0 (remote_migrate_gate.go:731-737),
so the ignored series is invisible to it.
- migrationWorkNeeded is true whenever !ignoredSource.atLatest
(schema.go:866-869), so the locked pass runs the full MigrateUp
including ignoredSource.migrate (schema.go:822). DoltStore.initSchema
reaches the same call on the writable-open path (dolt/store.go:3076).
So the positive clause is widened to any writable open (embedded, server or
proxied), and the negative clause is rewritten as a tautology plus an open
list: the open that hit the error was not self-healing, and the kinds that
skip or only verify "include" read-only/preview opens, team-server opens
(verifyTeamServerSchema only checks - dolt_sql_provider.go:342-371), the
preview-attach arm, and gate-refused opens. Each named arm was verified
individually; the list deliberately does not claim to be exhaustive, which
is what the previous wording got wrong. Nothing in docsync can enforce this
paragraph, so an open list is also the honest shape.
[minor] Gotcha 1's data_dir locator omitted the mode that overrides both
knobs it names. ResolveDoltDir checks IsSharedServerMode() FIRST and returns
SharedDoltDir() before it ever reaches projectDoltDirPath
(doltserver.go:316-330); the knobs are BEADS_DOLT_SHARED_SERVER=1|true or the
dolt.shared-server config key (:117-122), and the directory is
~/.beads/shared-server/dolt/, overridable via BEADS_SHARED_SERVER_DIR
(:248-257, :275-285). Added as its own paragraph rather than growing the
parenthetical, with the reason it matters most there: one shared data_dir
holds every project's database, so a single stray subdirectory crash-loops
the server for all of them.
[nit] "neither of bd doctor --fix's TWO Dolt-database repairs" made a numeric
claim the sentence does not need, and the count is wrong:
cmd/bd/doctor/fix/repo_fingerprint.go:135-161 os.RemoveAll's
cfg.DatabasePath(beadsDir) behind an interactive "This will DELETE %s. [y/N]",
and cleanCruftBeadsDirFiles (artifacts.go:238) can remove a .beads
subdirectory too when a redirect is expected. Dropping the word "two" would
have left "neither", which is itself a two-quantifier, so the count is
removed instead: "no bd doctor --fix repair performs this move here. The two
that come closest are:" - now a statement about the two bullets that follow,
not a census of the repairs. The operative universal survives the census
(the move-performing rename sites are only database_integrity.go:46,54; the
others delete or rename in place), so the reader's action is unchanged.
Validation (iteration 2): go test -tags=gms_pure_go ./test/docsync (8 tests,
green, zero skips, both InitSafety tests among them); go test -tags=integration
-count=1 -run Freshness ./scripts (33 pass, 1 Windows-only skip);
./scripts/check-doc-freshness.sh PASS with docs/recovery/init-safety.md at 0
days old and all five of its Freshness sources resolving; git diff --check
clean. Prose-only: no code, test or freshness-pair file changed this
iteration.
---------
Co-authored-by: Julian Knutsen <julianknutsen@users.noreply.github.com>
* Accept uutils coreutils timeout in generated hooks
The generated hook selects a timeout helper only when its --version
banner starts with "timeout (GNU coreutils) ". uutils coreutils reports
"timeout (uutils coreutils) " with the same command line and the same
exit 124 on expiry, so hosts that ship it (Ubuntu 25.10+, NixOS with
uutils-coreutils-noprefix) silently fell through to the Perl alarm, or
to the unbounded direct run when Perl is absent. Follow-up from #5522,
tracked in #5541.
- Widen the identity allowlist to uutils; the match stays by banner so
Windows timeout.exe is still never probed (#5503).
- Add a backend-selection case using the GNU stub with the uutils
banner: fails on the old shim (selects gtimeout), passes with the
widening.
- Regenerate the managed sections in the tracked .githooks/* so
TestTrackedManagedHookSectionsMatchGenerator stays green.
- Update the hook-timeout passages in docs/reference/git-integration.md
and troubleshooting.md, which described the probe as GNU-only.
Verified on NixOS with uutils 0.10.0 as /run/current-system/sw/bin/timeout:
with Perl removed from PATH and a bd that hangs, the old shim runs
"without timeout" for the full duration; the new shim expires at
BEADS_HOOK_TIMEOUT and continues.
Agent-Signature: claude-code-claude-opus-5-unknown-reasoning on behalf of Tomasz Feliksik
* Regenerate tracked .githooks managed sections with make githooks-regen
TestTrackedManagedHookSectionsMatchGenerator holds the managed section in
each tracked .githooks/* byte-equal to the cmd/bd/hooks.go generator, but
nothing regenerated them: after a generator change a contributor had to
splice the new section in by hand, and the failure only dumped both
texts. The v1.2.0 bump reddened main this way (ce20a64bb), and #6561 shipped
its first revision with the five hooks stale.
- BD_UPDATE_GOLDEN=1 makes the test rewrite the section in place, keeping
everything around the markers (the project's own hook logic) untouched.
Same switch the package's events golden already uses.
- `make githooks-regen` wraps it, next to `corpus-regen`.
- The drift failure now names that command.
- The exactly-one-section check runs before any rewrite.
Verified: drifting one byte inside .githooks/pre-push fails the test with
the hint; `make githooks-regen` restores the file to the same blob SHA;
the test is green again.
Agent-Signature: claude-code-claude-opus-5-unknown-reasoning on behalf of Tomasz Feliksik
* Check the tracked hook shims against real timeout implementations
The Go tests pin the shim's helper selection with scripted stand-ins, so
they can only encode what the author believes each real `timeout` does.
That is where the last two defects lived: uutils prints a banner the
allowlist did not know (#5541), and busybox — which #5541 suggests
adding — exits 143 on expiry rather than 124, so allowlisting it would
turn every deadline into a failed hook and a blocked push.
checks.nix adds a flake check that runs the tracked .githooks/* managed
sections (held equal to the generator by
TestTrackedManagedHookSectionsMatchGenerator) against the binaries
themselves: GNU coreutils, uutils, busybox and toybox `timeout`, each
with and without perl, under dash, bash and busybox ash, for all five
hooks — 150 cases. Expectations come from a model of the contract (the
allowlist as data), so widening it is one line here and the binaries
either agree or they do not.
A fake bd on the shim's restricted PATH blocks on a held-open fifo until
a helper kills it, records the signal and re-raises it, so each case
asserts the backend that ran (TERM from timeout, ALRM from perl's alarm)
and not merely that the shim finished. No clock: a helper that fails to
kill the fake trips the harness's own `timeout 10`. Every case asserts
exit 0, since anything else blocks the user's push. Reading .githooks/*
instead of building bd keeps it at ~1 s and off the Go build's critical
path; CI's test-nix job runs it after its existing help-text smoke test.
Mutation-checked: restoring main's GNU-only sections fails all 30 uutils
cases (15 unbounded, 15 on the perl backend); allowlisting busybox with
a loosened probe fails all 30 busybox cases with hook exit 143.
Agent-Signature: claude-code-claude-opus-5-unknown-reasoning on behalf of Tomasz Feliksik
* Run the hook-timeout check under the gtimeout candidate name too
The shim probes `timeout` and then `gtimeout`, but the matrix only ever
put a binary named `timeout` on PATH, so the second candidate was never
run against a real implementation. Whether a helper is accepted under
that name depends on what its banner does with argv[0].
Measured: the uutils multicall dispatches on the argv[0] SUFFIX
(src/bin/coreutils.rs, `binary_as_util.ends_with(util)`) and then prints
the canonical utility name — invoked as gtimeout it reports
"timeout (uutils coreutils) 0.8.0" (this flake's nixos-25.11 pin; 0.11.0
identical), which the allowlist accepts. busybox and toybox know no
gtimeout applet and fail the probe outright, rejected as before. GNU is
immune by construction: Homebrew's gtimeout is a separate binary whose
banner is the fixed "timeout (GNU coreutils) 9.11"; nixpkgs' coreutils
is a single-binary multicall that refuses a foreign name ("unknown
program 'gtimeout'"), so it gets no variant here.
Each multicall is now also installed on a case PATH as `gtimeout` ALONE
(`installs`, derived from `implementations`; `backendFor` stays keyed on
the implementation, so the model's claim is "uutils is allowlisted
whatever it is called"). 240 cases on Linux, 80 on darwin (no busybox or
toybox there, and no busybox-ash shell). The shadowed
`out=` inside run_case is `case_out` now: it only survived because every
case is a backgrounded subshell, and a de-backgrounded case would have
died on the final `touch "$out"`.
Mutation-checked: installing the variant as `xtimeout` (a name the shim
never probes) fails exactly the 30 uutils-as-gtimeout cases — 15 with
nothing killing the fake bd, 15 on the perl backend (ALRM) instead of
coreutils; restored, 240 of 240 pass. The busybox/toybox variants cannot
distinguish (their expectation is rejection either way); their weight is
that the probe does not blow up on a foreign name.
* Run the flake checks on main too, by nix flake check; docs wording
pr-risk.yml's test-nix job ran the hook-timeout check on PRs only; the
byte-identical job in main.yml never got the step, so post-merge main
never ran it. Both jobs now run `nix flake check -L`: no hardcoded
`x86_64-linux` (the step beside it, `nix run .#default`, was already
system-agnostic), and a check added to checks.nix runs without a
workflow edit. checks.aarch64-darwin and .x86_64-darwin evaluate.
Measured on ubuntu-latest with a cold Nix store (fork run 35700791032,
this tree, 240 cases): `nix flake check -L` 3.6 s including substitution
of uutils, busybox, toybox, dash and perl; 0.08 s warm — beside the
4 min 9 s the existing `nix run .#default` step spends building bd in
the same job. The 10-minute timeout is not in question.
git-integration.md: on Git for Windows the preferred deadline backend is
"a coreutils timeout (GNU or uutils)", not GNU alone, since both now
qualify. troubleshooting.md: reflow a ragged paragraph.
* review: close the duplicated contracts around the uutils timeout accept
Maintainer review fixes for #6561. No change to the shim's behavior or to the
generated/tracked hook sections.
- cmd/bd/hooks_timeout_process_test.go: the uutils fixture was built with
strings.Replace, which returns its input unchanged when the pattern is
absent, so a later edit to the GNU stub's banner would silently degenerate
the uutils case into a second copy of the GNU one — still green, no longer
testing the new accept. Hoist the derivation and fail loudly when the banner
no longer matches.
- cmd/bd/hooks_timeout_process_test.go: findHookProcessGNUTimeout held a second,
un-widened copy of the identity allowlist, so on exactly the hosts this PR
exists for (uutils timeout, no gtimeout) the only Go test that drives a real
timeout binary skipped with a reason the fix had just made false. Widen the
probe's case, rename it findHookProcessCoreutilsTimeout, and reword the skip
and the subtest. Measured against stub PATHs: uutils goes rc=1 -> rc=0, GNU
stays rc=0, a busybox banner stays rc=1.
- cmd/bd/init_hooks_test.go: TestGenerateHookSection_Timeout asserted only the
GNU alternative, so deleting the new uutils one from the generator left the
structural contract green (verified: it passes under that mutation before
this change, and reports "section missing uutils coreutils identity check"
after). Add the companion assertion.
- cmd/bd/init_hooks_test.go, Makefile: the regen arm rewrites tracked source
files, so give it its own BD_UPDATE_HOOKS_GOLDEN rather than the package's
shared BD_UPDATE_GOLDEN — an unscoped `BD_UPDATE_GOLDEN=1 go test ./cmd/bd/`
used to turn genuine hook drift into a silent working-tree rewrite that
reported PASS.
- cmd/bd/init_hooks_test.go: locate the managed section by marker prefix
instead of the versioned marker line. Tracked hooks drift both from generator
content and from the release version stamp; the exact-line lookup made the
second class fatal ("tracked hook missing ...") before the regen arm was
reachable, so `make githooks-regen` failed at exactly the moment a release
engineer reaches for it. The versioned markers are still verified — they are
part of the byte compare.
- checks.nix: the `rc -eq 124` safety-net verdict discarded both $case_out and
the already-captured $signal, so the one failure mode that is intermittent
and not locally reproducible was also the only one with no diagnostics.
Report them like the `rc -ne 0` branch below it.
- docs/reference/troubleshooting.md, docs/reference/git-integration.md: mirror
the coreutils wording across both docs this PR touches, and generalize the
re-install guidance in both. Managed sections are never reported Outdated
(getHookVersion returns IsShim for them and computeHookStatuses gates on
!IsShim), so nothing tells an existing install it is stale; the sentence was
still scoped to the older name-only check (#5503).
- CHANGELOG.md: add the [Unreleased] entry for #5541, worded to the actual
scope — with Perl installed the shim still reached the Perl alarm arm, so the
lost deadline bit uutils hosts without Perl — say that existing installs must
run `bd hooks install` once, and drop the claim that stock NixOS ships uutils
(this PR's own checks.nix takes GNU from pkgs.coreutils).
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
---------
Co-authored-by: Julian Knutsen <julianknutsen@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
* fix(exec): match Windows environment key identity (#5618)
Centralize os/exec-compatible environment-key comparison and use it for credential, metrics, Git-hook, trace, and repro subprocess filters. Preserve exact Unix semantics and Unicode near-collisions.
Agent-Signature: codex-gpt-5-unknown-reasoning on behalf of Ewen Cuthiell
Signed-off-by: Ewen Cuthiell <ewencuthiell@gmail.com>
* fix(worktree): scrub inherited Git routing state
Establish CWD as the worktree repository boundary before discovery can consume inherited Git routing. Fence the startup config probe, clear routing in-process before root pre-run discovery, and retain command-owned subprocess scrubbing as defense in depth without changing PID or signal semantics.
Fixes#5531
Agent-Signature: codex-gpt-5-unknown-reasoning on behalf of Ewen Cuthiell
* refactor(worktree): explain owned filtering and remove an unused shim
Document why filtering the fresh routing slice in place is safe and call
the shared routing-key classifier directly from tests. Retain the two
forwarders used by production worktree subprocess/removal paths.
Review: https://github.com/gastownhall/beads/pull/5623#pullrequestreview-5098421671
Bead: saa-cgh.23
Agent-Signature: unknown-model/unknown-reasoning
* fix(config): isolate identity and tracked-file Git probes from routing
Reuse the worktree routing owner for GetIdentity and isGitTracked so
explicit cwd/path selection is not displaced by inherited repository,
index or injected config state. Preserve identity precedence and the
tracked-secret refusal contract, with real target/decoy regressions.
Follow-up: https://github.com/gastownhall/beads/issues/6222
Dependency: https://github.com/gastownhall/beads/pull/5623
Reported-by: bee-ghosttrack
Bead: saa-cgh.93
Agent-Signature: unknown-model/unknown-reasoning
* test(execenv): exercise every environment operation under both host rules
Thread the host choice through narrow private helpers behind the existing
exported functions. Keep one normalization owner and retain native wrapper
tests; the additional table covers both host branches for equality, prefix
matching, last-wins lookup, filtering and input preservation.
Review: https://github.com/gastownhall/beads/pull/5672#pullrequestreview-5096948965
Bead: saa-cgh.78
Agent-Signature: unknown-model/unknown-reasoning
* docs(worktree): explain startup Git environment scope (saa-cgh.23)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* test(execenv): exercise exported host policy wiring (saa-cgh.78)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* fix(config): share subprocess key identity for Git routing (saa-cgh.93)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* fix(hooks): isolate tracked-file guard from Git routing (saa-cgh.98)
Follow-up to bee-ghosttrack's review of gastownhall/beads#6322; refs #6356.
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* fix(config): isolate role commands from Git routing (saa-cgh.99)
Follow-up to bee-ghosttrack's review of gastownhall/beads#6322; refs #6357.
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* test(env): exercise shared key helpers on native Windows (saa-cgh.78)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* refactor(gitenv): share key parsing and normalize routing membership once (saa-cgh.93)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* docs(config): explain role command routing policy (saa-cgh.99)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* fix(hooks): retain legitimate inherited tracking context (saa-cgh.98)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* test(hooks): isolate trusted global configuration fixture (saa-cgh.98)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* fix(hooks): isolate role cleanup in the selected repository (saa-cgh.109.4)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* fix(hooks): reset only common local role configuration (saa-cgh.109.10)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* fix(hooks): scope hooks-path cleanup to selected common config (saa-cgh.109.11)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* test(hooks): make worktree role preservation independent (saa-cgh.120)
Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell
* Report selected config read failures during hook reset (saa-cgh.120)
Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell
* fix(hooks): keep successful config stdout separate from diagnostics (saa-cgh.120)
Agent-Signature: Codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell
* fix(config): pin role writes to fresh common context (GH#6384) (saa-cgh.120.3)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* fix(config): retain Git diagnostics from role writes (saa-cgh.120.3)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* test(config): assert the actual Git lock diagnostic (saa-cgh.120.3)
Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
* fix(config,hooks): restore the inherited-tracking fallback in the secret guard
Maintainer review fixes for PR #6454 (adopt-pr iteration 1). The scorecard
approved at 913/1000 with no blocker or major surviving synthesis; these are
the non-gating findings that were cheap to close while the fixup was open.
Finding 1 (minor, security) is the only in-range regression in the report. The
range switched internal/config.isGitTracked from the inherited environment to
gitenv.ScrubRouting only, so a config.yaml tracked solely through legitimate
routing -- a bare repository whose work tree is named by GIT_DIR/GIT_WORK_TREE
-- reported untracked, and a secret-key write that upstream-base refused was
silently allowed. Restores the scrubbed-then-inherited union the same stack
already gave cmd/bd.isGitTrackedFile.
Finding 4 (nit) composes with it rather than conflicting, so both land as one
change: the inherited probe now runs only when the scrubbed probe failed for a
configuration reason. git's exit codes discriminate exactly -- 0 tracked, 1
repository reached but path untracked (final), 128 no reachable repository --
so the ordinary untracked-hook miss no longer spawns a second `git ls-files`
while the bare-work-tree fallback is preserved.
Finding 2 (minor). scrubWorktreeRemovalGitEnvForOS keyed its stricter
no-optional-locks policy on strings.ToUpper while the rest of the PR uses
execenv key identity. The two disagree in both directions on Windows:
GIT_OPTIONAL_LOCKS with a dotted capital I (U+0130) survived the scrub although
Git honors it, and GIT_OPTIONAL_LOCK with a long s (U+017F) was dropped
although os/exec keeps it distinct. normalizeWorktreeGitEnvKey is deleted in
favour of execenv.KeyEqualForOS. Base applied ToUpper on all platforms, so this
is a consistency fix in newly rewritten code, not a regression.
Finding 5 (nit). The comment above resetHooksPathIfBeadsManaged's probe
asserted that repoRoot and commonDir share the cached Git context. Probed
false: with cwd A and GIT_DIR=B/.git, `git rev-parse --git-common-dir
--show-toplevel` prints B/.git and A. Restated as intent.
Finding 3 (scrubGitHookEnv is a fifth, strictly weaker routing scrubber) is
deliberately not taken here: cmd/bd/export_auto.go is untouched by this range,
so the hazard is byte-identical at base, and the synthesis scoped it to a
follow-up bead rather than growing this stack.
Each fix is mutation-proved. Reverting isGitTracked reds only the new
TestSecretGitTrackingHonorsInheritedBareWorkTree -- including "refusal = <nil>",
the actual security consequence -- while the incumbent decoy test stays green,
so the pin adds coverage rather than duplicating it. Restoring ToUpper reds
only the new Windows row, showing both directions at once.
TestGuardHookWritePathHonorsInheritedRepository gains a fixture guard asserting
its scrubbed probe fails for a configuration reason rather than exit 1, so a
future fixture change cannot silently make the fallback unreachable.
scrubWorktreeRemovalGitEnvForOS had no test at all before this.
Green locally: ./internal/config, ./internal/execenv, ./internal/gitenv,
./internal/githooksenv, ./internal/gittraceenv, ./internal/metrics, ./scripts,
./internal/beads (the GIT_CONFIG_GLOBAL blast radius neither reviewer ran), and
a blast-radius cmd/bd run over the hooks, worktree, role and uninstall suites.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
---------
Signed-off-by: Ewen Cuthiell <ewencuthiell@gmail.com>
Co-authored-by: Bee <bee@ghosttrack.com>
Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
Co-authored-by: Julian Knutsen <julianknutsen@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
* fix(dolt): honor dolt.auto-commit=batch/off on the proxied-server write path (#4995)
In proxied-server mode every write minted a Dolt history commit whatever
dolt.auto-commit said. Two causes:
- cmd/bd/main.go never applied issueOpsContext(rootCtx) in the
proxiedServerMode branch of the root pre-run, so the context carried no
deferred-commit marker.
- internal/storage/uow/doltserver_tx.go: doltServerTx.Commit ignored
issueops.VersionCommitDeferred(ctx) and ran CALL DOLT_COMMIT('-Am', ?)
whenever a message was supplied.
Apply issueOpsContext to rootCtx in the proxied setup, and have
doltServerTx.Commit blank its message under a deferred context so the existing
plain-COMMIT branch persists the write to the working set without advancing
Dolt history. dolt.auto-commit=on is unchanged.
This commit alone strands batch/off writes in the working set; the explicit
flush point (`bd dolt commit`) follows in the later commits of this series.
(Originally recorded as "witness: salvage uncommitted work (ocb-ani)"; the
change itself is unmodified.)
* test(uow,cmd/bd): add regression tests for proxied dolt.auto-commit batch/off (#4995)
Add focused regression tests verifying that proxied dolt.auto-commit batch/off
defer Dolt version commits:
- cmd/bd: TestIssueOpsContextDefersByModeInProxiedServerMode verifies that
issueOpsContext defers version commits in proxied-server mode when
dolt.auto-commit is batch or off.
- internal/storage/uow: TestDoltServerTxCommitDefersDoltCommitUnderDeferredContext
and TestDoltServerTxRunTxWithDeferredContextSkipsDoltCommit verify that
doltServerTx.Commit blanks the commit message under a deferred context,
bypassing DOLT_COMMIT and status checks, and executing plain COMMIT to
persist writes into the working set without advancing Dolt history.
* fix(dolt): add the proxied flush point dolt.auto-commit=batch/off defers to (#4995)
The deferral half of this PR makes dolt.auto-commit=batch/off actually take
effect on the proxied-server write path. On its own that turns batch/off into
"never commit": proxied mode returns from the root pre-run before newDoltStore
runs, so getStore() is nil and `bd dolt commit` has no store to commit
through. Writes pile up in the sql-server working set where `dolt log`,
`dolt push` and backups never see them.
Add the missing half. cmd/bd/dolt_commit_proxied_server.go is the proxied dual
of `bd dolt commit`: it takes the uow.MaintenanceProvider route (RunNonTx) and
runs CALL DOLT_COMMIT('-Am', ?) on a pinned connection, gated on
issueops.HasPendingChanges. It deliberately does not go through
doltServerTx.Commit, which blanks its own message under the deferred context;
routing the flush through the deferral it exists to discharge would make the
flush a no-op. doltCommitCmd dispatches to it on usesProxiedServer(); the
message is built before the branch so both routes name the same default, and
the "Committed." / "Nothing to commit." contract is unchanged.
--dolt-auto-commit's help no longer claims proxied-server routes are
unaffected: it names the proxied flush point and keeps the SIGTERM/SIGHUP
flush marked embedded-only. docs/reference/configuration.md says the same.
`bd vc commit`'s proxied refusal now points at `bd dolt commit`.
Tests:
- cmd/bd/dolt_commit_proxied_integration_test.go: three batch writes leave
dolt_log unchanged and stay readable, `bd dolt commit` advances it by
exactly one, a second `bd dolt commit` reports "Nothing to commit." with
dolt_log unchanged, and one write under --dolt-auto-commit on advances it
by one. On the PR's original base it failed at the `bd dolt commit` step
with "no store available". On current main the front door refuses the
command before that code is reached, so this test is only green together
with the next commit, which moves `dolt commit` to supported in the proxy
capability registry.
- TestIssueOpsContextDefersByModeInProxiedServerMode renamed to
TestIssueOpsContextDefersByModePolicyTable and the proxiedServerMode
assignment dropped: issueOpsContext branches only on writesCommitNow(),
never on the storage mode, so the old name over-promised.
- doltserver_tx_test.go: "bd: update bd-4995" -> "bd: update GH#4995", which
no longer reads as a bead id.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* fix(proxy): move `dolt commit` from refused to supported in the capability registry
Main's proxy capability registry (added by #6269, 24a9da6cc) declares
`dolt commit` direct-only: it has a "proxy.dolt_commit.unsupported" refusal
in proxyMaintenanceRefusals (cmd/bd/proxy_capability.go) and is classed
HistoryDirectOnly in historyCapabilityMatrix (cmd/bd/history_capability.go).
The front door therefore refuses `bd dolt commit` in proxied-server mode
before dispatch, so the proxied dual added earlier in this series is
unreachable, and dolt.auto-commit=batch/off has no way to flush.
the history/VC front-door contract, and neither the registry, its tests nor
the docs explain why `dolt commit` was listed. Nothing on main implemented
`dolt commit` for the proxied route at the time, which is consistent with the
entry being a statement of what existed rather than a design decision.
This flips a capability main had declared unsupported, deliberately: the
proxied route now has an implementation (runDoltCommitProxiedServer), and
batch/off need it as their flush point (GH#4995).
Declared the same way as the other proxied-supported command,
`dolt remote remove`: HistoryProxySupported in the history matrix, and no row
in proxyMaintenanceRefusals.
Tests follow: history_capability_test.go moves `dolt commit` from the
direct-only assertions and refusal contract to the proxy-supported ones
(including the nested front-door pass-through), and
history_remote_frontdoor_matrix_test.go drops the refusal row and adds a
`dolt commit` pass-through check to TestHistoryRemoteSupportedFrontDoorParity.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* fix(proxy): exempt explicit commit points from the proxied deferral (#4995)
Maintainer review fixup for PR #6499, adopt-pr iterations 1-2.
Major (Contract & Interface Fidelity). The deferral is applied once, to
rootCtx, so it blanketed BOTH commit classes the direct route distinguishes by
which wrapper a verb picks: policy-honoring writes (transactHonoringAutoCommit,
per-verb issueOpsContext) and explicit commit points (transact, which passes
the caller's message whatever the policy says). Under dolt.auto-commit=batch a
proxied `bd batch -m "release batch"` therefore persisted the rows, discarded
the message and minted nothing, while the identical command and config on the
direct route committed it — and batch_proxied_server.go's own contract comment
rejects exactly that ("would persist these writes while silently bypassing
Dolt history"), as does batch.go's "the contract is the same on both backends".
issueops.WithImmediateVersionCommit clears the marker and cmd/bd's
explicitCommitPointContext applies it in the duals whose direct twin calls
transact. Scope is the intersection of the transact call sites with
proxyPermittedPaths: batch, mol bond/pour/squash, mol wisp create, and the
WISP half of mol burn (cook and migrate issues also call transact but are
refused in proxied mode, so they have no dual to exempt). The review sized the
radius at batch + 4 mol verbs; mol wisp create is the same class — its direct
twin reaches cloneSubgraph's transact through spawnMoleculeWithOptions — so it
is exempted with them.
Membership is per commit site, not per command (iteration 2). `bd mol burn` is
two classes on the direct route: wisps go through burnWisps -> transact, while
persistent molecules go through deleteBatch -> issueOpsContext ->
dolt/deleter.go, which returns before DOLT_COMMIT when the context defers.
Exempting the whole command minted one Dolt commit per persistent molecule
under batch/off — on a destructive verb, where the identical direct-route
command defers them all to `bd dolt commit`. runMolBurnProxiedServer now
applies the exemption to the wisp RunTxResult only, and the flag help,
configuration.md and the helper's own radius comment say so.
Minors:
- The flush passes '--author' like DoltStorage.CommitAll, so the one commit
batch mode keeps is attributed to the bd actor rather than the SQL session
user (without it dolt_log reads `root <root@localhost>`).
- runDoltCommitProxiedServer calls the shared runProxiedNonTx instead of
re-implementing its provider checks, so `bd --json dolt commit` keeps the
JSON error envelope; `dolt commit`'s RunE no longer re-wraps an
already-reported failure, and runProxiedNonTx's message gains the provider
%T the open-coded version had.
- The flag help and configuration.md drop two false claims: that the deferral
covers "every write" in proxied mode (the bd serve plane over the same
provider never touches rootCtx, so daemon writes still commit per write) and
that the SIGTERM/SIGHUP flush is "embedded-only" (flushBatchCommitOnShutdown
gates on an open store, which direct SQL-server mode has; only proxied mode
lacks one). Both surfaces now name the explicit-commit-point exemption.
- Both user-facing enumerations of that exemption are now derived from the
explicitCommitPointContext call sites rather than restated (iteration 2):
they had omitted mol wisp create, listed mol burn wholesale, and implied a
message-less `bd batch` defers when batch.go synthesizes a default message
and the dual exempts unconditionally, so every proxied batch commits.
- doltserver_tx.go's ephemeral-form comment names its second entry point —
RunTx/RunTxResult under a deferred context — where its
ONLY-dolt_ignored-state rationale stops applying.
Not done: regenerating docs/CLI_REFERENCE.md. Its --dolt-auto-commit drift is
base-preexisting, and the generated CLI docs are built from the release tag
pinned in docs/cli-docs.pin, not from this source, so touching them converts
the drift gate's inherited-drift warn-pass into a failure.
Tests. The uow blanking table gains the immediate-commit arm (tagless, so it
runs in every lane); the proxied integration test gains an explicit-batch-commit
step with a deferred plain create as its control, plus the flush attribution
assertions. Mutation-proved: reverting explicitCommitPointContext to a no-op
reds the new step (dolt_log 80 -> 80, no commit minted), and dropping
'--author' reds the attribution assertion with committer=root.
Iteration 2 adds the WIRING pin those left open — the mechanism was covered,
but deleting `ctx = explicitCommitPointContext(ctx)` from a dual was green in
every lane, which is why the mol burn over-application above was invisible.
dolt_autocommit_exemption_wiring_test.go is tagless and needs no server: a
uow.UnitOfWorkProvider that records the context RunTxResult hands NewUOW and
then refuses observes exactly the context each dual gives its transaction.
Mutation-proved per arm: neutering the exemption at batch/bond/squash reds
those three rows and only those; dropping it from the wisp RunTxResult reds
the wisp arm alone; and restoring the command-wide reassignment reds the
persistent arm alone, reproducing the defect this iteration fixes.
Validation: go build ./..., go vet (cgo and CGO_ENABLED=0), gofmt clean;
internal/storage/issueops; internal/storage/uow -run TestDoltServerTx; the
cmd/bd registry / history / policy / batch / mol / wisp / errors battery; and
the gated real-server lane BEADS_TEST_PROXIED_SERVER=1 green for both
TestProxiedServerBatchDefersThenDoltCommitAdvancesHeadOnce (41s) and
TestProxiedServerMolBurn (33s, all four subtests including the mixed
wisp+persistent burn this iteration changed).
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-authored-by: Julian Knutsen <julianknutsen@users.noreply.github.com>