Commit graph

12 commits

Author SHA1 Message Date
Julian Knutsen
6d27a4f96e
fix(issueops): enforce the close guards on every close leg (#7425)
* fix(issueops): enforce the close guards on every close leg

The template read-only guard, the pin guard and the assignee authority
fence (be-035) lived only in cmd/bd (validateIssueClosable), so a close
through bd serve, issues:batchClose, a batch:apply close item or a library
caller of Lifecycle.Close / BatchCloser / BatchApplier closed what bd close
refused.

They now run inside the close's own transaction in CloseIssueCheckedInTx
(enforceCloseGuardsInTx), the body every checked close shares (dolt,
embedded, uow, and the server behind httpapi), for a target that is not
already closed:
- a template refuses with *issueops.TemplateReadOnlyError (no bypass);
- unless Force (CloseRequest, CloseBatchRequest, CloseItem) is set, a pinned
  issue refuses with *issueops.PinnedError and another actor's bead with
  *issueops.CloseNotAssigneeError (matches ErrNotOwner).

Wire: 409 template_read_only, issue_pinned and not_assignee (holder in
`assignee`, also on a batch-close outcome); the client rebuilds the typed
errors. The decision is one exported pure rule over the pre-image,
issueops.CheckClosable (internal/storage/issueops), which the in-tx guard
calls; bd close's direct and proxied preflights call it too, ahead of gate
satisfaction under the same already-closed skip, so bd close output, refusal
order and exit codes are unchanged (validateIssueClosable is gone). bd close
--if-revision now applies the guards too.

Conformance: RunLifecycleCloseEnforcesTheCloseGuards,
RunBatchCloserItemsAnswerToTheCloseGuards and
RunBatchApplyCloseItemsAnswerToTheCloseGuards on dolt, embedded, uow and
http, plus handler mapping tests, a CheckClosable table test, and a cmd/bd
test pinning that the guards outrank gate satisfaction.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(httpclient): send force on the raw close; scope the close guards

Review fixes for #7425 (adopt-pr bd-0h0ao4, iterations 1 and 2).

The raw close keeps parity over http. httpclient.Store.CloseIssue maps the
off-role raw close onto the role's closeIssue op and sent force=false.
With the guards in the role, a pinned or claimed target then refused (409
issue_pinned / not_assignee) on http only: dolt, embedded and proxied run
the raw close as issueops.CloseIssueInTx, which applies neither the guards
nor close policy. The molecule auto-close, `bd gate resolve`,
`bd todo done` and `bd human dismiss` all make that call, and its
signature carries no force a caller could pass. It now sends force. Over
http that also stops applying close policy to the raw close, which it did
at base and no other backend does; parity is the point, so that goes too.
The template guard has no bypass on the wire, so a template still refuses
the raw close over http where the other backends close it; no raw caller
is known to close one. TestServedRawCloseKeepsParityWithTheOtherBackends
closes both pin spellings, a held bead and a parent with an open child
through Store.CloseIssue and requires the template refusal; with force
back to false it fails on 409 issue_pinned.

The close guards stay on the close verbs. A status update that crosses
into the done category (`bd update -s closed`, PATCH, a batchApply update
item) still answers to close policy only, so it closes a pinned issue or
another actor's bead on every backend, as it did before this PR. Guarding
it changes what the update legs admit and needs its own refusal mapping on
PATCH and batchApply, so it is left for a follow-up; the update.go and
domain/db comments now say the exclusion is deliberate.

CHANGELOG: the entry moves from Fixed to Changed as BREAKING, is scoped to
the close operations, names the two paths the guards do not cover, and
adds a Migration line (send force or reclaim; templates are never
closable). Docs: the OpBatchCloseIssues item codes, the CloseIssueChecked
and CloseIssueOptions.Force docs (storage, dolt, embeddeddolt), the
oracle-a scenario strings that named the retired validateIssueClosable,
and the TestCloseCheckOne_CloseGuardsOutrankGateSatisfaction doc, which
claimed a proxied route it does not drive.

Iteration 2: the wire contract says what force waives. The OpenAPI
`force` members of CloseIssueRequest, BatchCloseRequest and ApplyCloseItem
said force bypasses close policy "and nothing else"; it also waives the
pin and the assignee guard, and never the template guard. The batchClose
"only two answers" paragraph now says the same, and types.gen.go is
regenerated (`make api-gen`). "Close guards" names the close operations
instead of "every route to a close" and adds that a status update into
the done category is not one, and the PATCH done-crossing paragraph says
a patch is never refused `issue_pinned` or `not_assignee`. The conformance
comments that quoted the old Force sentence (batch_apply_contract.go,
batch_closer_contract.go, lifecycle_close_reopen_contract.go) quote the
current docs, and the batch_apply failure message no longer says Force
does nothing else. CHANGELOG: a `close` line of `bd batch` is named among
the raw closes, and "a template is never closable" becomes "the close
operations never close a template, forced or not". The storage interface
CloseIssue gains a doc that states its HTTP exception.

TestCloseGuardRefusalsPrintTheGuardSentenceOnEveryRoute pins the sentence
`bd close` prints for each guard (template, pin, assignee) through each
printer (closeDirectRefusal, closeDirectTypedRefusal, closeProxiedRefusal,
closeProxiedTypedRefusal), with the refusal bare, wrapped by the use case
and the SQL repository, or inside a served problem envelope. One pinned
refusal also goes through closeProxiedOutcomes and closeProxiedFailures,
where the stderr line and the `--json` error field must both be the
sentence. Six overlay mutants fail it: closeGuardRefusal recognizing no
guard, or not the pin, and each of the four printers skipping its call to
closeGuardRefusal.

Not done here: a CLI test that `--if-revision` exits 1 on a guard refusal,
not ExitGuardMismatch. External PR #7372 carries per-id fence tests for
that route (6 of 7 pass at this head); they are better absorbed with
credit than rewritten.

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>
2026-10-09 18:30:42 +00:00
Bee
2cae0c1ad8
fix(storage): a parent-child edge propagates only the parent's exogenous blockedness (#6506) (#6602)
* fix(storage): parent-child cascade propagates only exogenous blockedness (wy-3eb07b, #6506)

A parent-child edge used to cascade the parent's is_blocked bit to its
children WHATEVER set it. So the "close gate on the epic" idiom — P carries
blocks edges onto its own children C1 and C2 so P cannot close before them —
darkened the very children P was waiting for. Neither child could reach
bd ready, so neither could be worked, so neither could close: a permanent
lock, and the one direction cmd/bd/dep.go does not refuse.

The contract (#6506): a parent-child edge propagates only EXOGENOUS
blockedness. P counts as blocked FOR CHILD C iff P has a blocking reason —
an open blocks/conditional-blocks target, or a live waits-for gate — whose
target is NOT one of P's own parent-child children, or P's own parent is
(recursively) exogenously blocked. P's OWN is_blocked is unchanged: it really
does depend on open children. Only the propagation narrows.

DESIGN: a second-pass predicate on the parent row, not WITH RECURSIVE.
Both parent-child legs of shouldBeBlockedIDsUnionScopedSQL keep their
p.is_blocked = 1 conjunct and gain parentCascadesBlockedSQL, which says "p's
blockedness is not solely explained by p's own children":

    EXISTS (blocking reason of p whose target is not p's child)
      OR NOT EXISTS (blocking reason of p whose target IS p's child)

The second disjunct carries the contract's recursive clause through the
EXISTING fixpoint instead of through SQL recursion: a parent that is blocked
with no child-targeted reason of its own is dark either exogenously or
because ITS parent is, and either way its children inherit — one level per
pass, exactly as the cascade always converged.

A recursive CTE was the other candidate and is rejected on cost, not on
engine support. Its seed set is the direct-exogenous set, which includes the
waits-for gate, and the seed cannot be confined by the batch scope (%[3]s)
because a batch's ancestors are by definition outside the batch. That would
put an UNSCOPED whole-table gate evaluation into every batched mark/unmark —
the statement shape #6288 removed, now on every write instead of only on the
full repair. The predicate here is correlated to a parent that is already
known blocked, so it probes idx_dependencies_issue for a handful of rows.
The scope splice, the DISTINCT waits-for barrier and the doctor-count
lockstep are all untouched.

One gap this form does not express: a parent that is BOTH blocked by its own
open child AND darkened by an exogenously blocked ancestor is not
distinguishable from one blocked only by its children, so its children stay
bright. That is an under-propagation in a corner the contract would darken;
it needs a second stored bit (or the CTE above) to see, and it cannot
recreate the lock this commit removes.

Also: AffectedByDepChange{,ForWisp}InTx now seeds the parent's other children
on a parent-child edge change (appendSiblingsUnderParentInTx). Writing that
edge reclassifies the parent's blocking reason on the new child from
exogenous to child-derived, which flips the answer for the SIBLINGS — the
close-gate epic is built one child at a time, and the second edge is what
un-darkens the first. Without it the incremental write path and the full
repair disagree, which the new tests catch as a nonzero doctor count.

Tests (internal/storage/dolt/blocked_consistency_test.go), all four seeded
through the real write path and each verified RED against the pre-fix SQL
except the control:
  - ParentBlockedOnlyByItsOwnChildren: the repro, plus a GetReadyWork
    assertion that the children are workable again.
  - ExogenousParentStillCascades: the control — the fix narrows the cascade,
    it does not remove it. Green before and after.
  - ThreeLevelChainBothWays: GP exogenous darkens P and C; GP blocked only by
    its child P darkens neither. Repaired from an inverted plane too, since
    the chain is the case that needs more than one pass.
  - WaitsForGateOverOwnChildren: a gate whose spawner is the parent's own
    child does not darken; one on an outside spawner does.

TestRecomputeAllIsBlocked_CascadesThroughParentChild is unchanged and green,
including its single-pass lower-bound count — which is why the legs keep the
p.is_blocked = 1 conjunct rather than deriving the cascade from the graph
alone.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* feat(dep): warn when a parent blocks on its own child (wy-3eb07b, #6506)

`bd dep add P C` where C is already P's parent-child child is the "close gate
on the epic" idiom: P carries a blocks edge onto its own child so P cannot
close before it. dep.go refuses the OTHER direction (a child blocking on its
dotted-ID parent, "would create a deadlock") and says nothing about this one,
which is the direction that used to deadlock for real — the cascade darkened
the child, so it could never reach bd ready, be worked, or close.

Since the cascade fix the edge is harmless, so this is an advisory, not a
refusal: it names what the edge now means (the parent stays blocked; the
child and its siblings are NOT hidden from bd ready) so an operator does not
have to rediscover the contract from a query.

It fires only for blocks/conditional-blocks, only after the edge has actually
landed and committed, and stays silent on any read error — an advisory must
not turn a successful write into an error, and must not precede a refusal for
an edge that was never written (the hierarchy and cycle guards reject this
pair whenever both edges already exist, in either order, which is why the
shape usually arrives one edge at a time or through import).

Unlike the D1 implicit-blocks warning it is NOT gated on an interactive
stderr: that one fires on the documented-default majority path, where
training callers to ignore stderr is the risk; this one fires on a rare
deliberate shape, and an agent wiring a close gate is exactly the caller who
should read what it does.

Wired into both direct paths (`bd dep add` and `bd dep --blocks`); the
proxied-server paths return earlier and are untouched.

Tests beside the existing dep-add warning tests: the predicate table
(including the two controls — right id with a blocks edge is not a child, and
the parent's other children do not match), the message content, and the type
gate proving it returns before touching the store.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* feat(doctor): report parent-blocks-on-own-child edges (wy-3eb07b, #6506)

A new "Parent Close Gates" check lists every blocking edge from a parent onto
one of its own parent-child children — the close-gate idiom, where P blocks
on C1 and C2 so P cannot close before them.

INFORMATIONAL, with no --fix and no effect on the overall result. Before the
cascade fix these edges were a trap: the parent's blocked bit propagated to
its children whatever set it, so the gate hid the very children it was
waiting for and nothing under it could become ready. The cascade now
propagates only exogenous blockedness, so the edges are legal and usually
deliberate. What an operator wants from doctor is therefore the inventory —
which beads in this store use the idiom, and where a pre-6506 store's
mysteriously invisible children came from — not a repair, and certainly not a
warning that would train people to remove a working gate.

It is the mirror of the existing "Child-Parent Dependencies" check, which
finds a CHILD blocking on its PARENT (still a deadlock, still fixable). The
two differ in how they match: that one reads dotted-ID ancestry, this one
matches real parent-child edges, because the close gate is wired between
unrelated ids.

Tests beside the child-parent ones: the empty inventory (with an ordinary
hierarchy present, which must not be mistaken for a gate), and the reported
case with two controls in the same fixture — an exogenous blocker on the
parent and an ordinary blocker on the child, neither of which may appear.

Gate note: these live in package cmd/bd/doctor, which the brief's cmd/bd
selector does not reach; `go test ./cmd/bd/doctor/` was run in full.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* revert(dep): drop the unreachable parent-blocks-own-child warning (wy-3eb07b, #6506)

This reverts 34b7f5b42. The warning it added could never print.

Its precondition is "a blocks edge from P onto C succeeded AND C is already
P's parent-child child", and the store refuses exactly that edge.
CheckBlockingHierarchyInTx (internal/storage/issueops/dependencies.go) rejects
a blocker that is the source's own descendant, and it sits OUTSIDE the
SkipCycleCheck gate, so no caller opts out of it; batch_apply.go:533 applies it
again on the DependencyEditor path `bd dep add` actually uses. Written in the
other order, the parent-child edge that closes the pair is refused as a cycle.
So the reverted code paid a GetDependentsWithMetadata read on EVERY
blocks/conditional-blocks `bd dep add` to emit something no operator could
ever see, and its 102-line test pinned a predicate instead of a behaviour.

What an operator DOES hit is the refusal — and the cascade fix left its stated
reason false. It read "blocked status cascades to descendants, so <blocker>
would inherit the block and never close". Since #6506 a parent-child edge
propagates only the parent's exogenous blockedness, so the descendant does not
inherit and nothing deadlocks. The refusal still stands, because a blocks edge
is not how the hierarchy says "I close after my children" — so the reason now
names the form that is: a waits-for gate over the children, `bd gate`.

The same false sentence was the OpenAPI description of
Problem.blocker_is_ancestor, so it is corrected there too, with types.gen.go
regenerated by `go generate ./internal/httpapi/apigen/` to keep `make
api-check` green.

The doctor "Parent Close Gates" check from 4c5f2f77b is KEPT. A warning on a
write path that refuses the write is noise; an inventory of the edges a store
already carries — from import, from merge, from the pre-refusal past — is what
an operator can act on.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(storage): the parent-child exogeneity test is over the whole SUBTREE (wy-3eb07b, #6506)

B1 of the adversarial review: 648ab0af6 tested "is this blocking reason's
target one of my own children" as a DIRECT parent-child child, but #6506's
contract is about blockedness originating outside the parent's own SUBTREE.
At depth 1 the fix worked; at depth 2 it left the permanent lock alive.

  P --blocks--> G,  pc C -> P,  pc C2 -> P,  pc G -> C

G is not P's child, so P read exogenous, so P darkened C, so C darkened G —
and G is the only row whose close can free P. Exactly the shape-1 mutual lock
the issue says no contract intends, one level down. Pinned as
TestParentChildCascade_ParentBlocksItsOwnGrandchild, verified RED at
4c5f2f77b: p/c/c2/g all blocked, all three children missing from ready work,
and the full repair changing nothing.

The test is now a real ancestor walk (subtreeWalkDepth levels of indexed
LEFT JOINs up from the reason's target), so a reason anywhere under the
blocker counts as its own.

Also B2 — the cost regression, which is the same edit, because the shape that
makes the test correct and the shape that makes it affordable are one
decision. The union's parent-child legs no longer carry a per-row correlated
EXISTS. They subtract an uncorrelated set instead:

    AND p.id NOT IN (parents explained by their own subtree)

and the UNBATCHED statements (full repair, doctor count) do not even spell
that set as a subquery: it is read ONCE per fixpoint pass and bound as ids.
A repair pass is four statements and each would otherwise derive the same set
twice; reading it once is the whole difference. The batched mark/unmark keep
the spliced subquery, where it is confined to the batch's own parents by the
existing scope splice and costs a few rows.

MEASURED, gastownhall/beads#6506 bar: full repair and doctor count <= 1.5x
origin/main, write path <= 1.2x. Committed benchmark
(internal/storage/dolt/blocked_scale_bench_test.go, -short-skipped), 1000
issues / 2870 deps / 333 blocked rows, embedded dolt 2.2.0, run INTERLEAVED
main/head to cancel machine drift, four pairs, medians:

                             origin/main 71c4cd08b   this branch   ratio
  full repair                 48 71 43 46 -> 47 ms   66 56 54 55 -> 55 ms  1.18x
  doctor count                55 62 44 53 -> 54 ms   67 61 57 57 -> 57 ms  1.06x
  write path, per CloseIssue  37 30 21 22 -> 26 ms   30 23 16 24 -> 23 ms  0.91x

All three inside the bar; the worst single PAIR is 1.38x on the repair and
1.30x on the count. The two sides disagree on blocked rows by construction
(604 on main, 333 here) — that IS the fix.

NOT inside a bar, and disclosed rather than hidden: the benchmark's fourth
timing, a 200-id RecomputeIsBlockedForIDsInTx (the bulk/import batched path,
which no metric in the review covered), is 53-63 ms on main against 400-556 ms
here — 6.9x at the medians. The cause is structural and measured: a batched
pass runs many small statements, each deriving the set twice, and the set
costs a few ms however it is written. The per-pass read that fixes the
unbatched statements makes the SMALL-batch case worse, not better (one
whole-store read costs more than the subqueries a two-id batch pays), so the
fix is a per-batch-scoped read threaded through expandBatchTemplate's
placeholder plumbing — a separate change, and the reason this timing is
committed rather than left in a scratch file.

Three shapes were built and measured before this one, all at the same scale:

  - the review's own: per-row correlated EXISTS with two more inside,
    3.3-3.7x full repair, 5.2x doctor count;
  - the set as a DISTINCT derived table LEFT JOINed on p.id, which is what B2
    recommended: ~30x. dolt plans a join operand as the inner side of a nested
    loop and rebuilds it per outer row — the correlated shape in a derived
    table's clothes. This is the one finding that contradicts the review, and
    it is why the set is subtracted with NOT IN instead;
  - WITH RECURSIVE for the ancestor walk: blew the driver read timeout on the
    full repair. A recursive CTE pays a query's overhead per ITERATION; the
    seeded walk cost 45 ms per evaluation against 6 ms for four levels of
    joins, which is why the walk has a horizon (subtreeWalkDepth = 4, epic ->
    sub-epic -> leg -> task). Past it a reason reads as exogenous, which
    propagates MORE and hides nothing the old code showed.

Seeding: AffectedByDepChange{,ForWisp}InTx now walks UP from a parent-child
edge's target, not just to it. Hanging G under C changes nothing about C and
everything about any ANCESTOR of C that blocks on G, so each such ancestor's
sibling set is reseeded — otherwise the incremental write path and the full
repair disagree, which the new test catches as a nonzero doctor count. The
walk is filtered to ancestors that carry a blocking reason at all: without
that filter a 70-deep chain reseeds every ancestor's subtree on every edge
written into it, which timed out TestGetReadyWork_ParentFilterReturnsDeepDescendants.

CHANGELOG now names the limitation the review ruled acceptable but undocumented
(a sub-epic blocked both by its own children and by an exogenously blocked
ancestor keeps its children visible), marked tracked upstream; bee files the
follow-up issue at PR time.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(doctor): rune-safe Detail truncation, Category on the N/A returns (wy-3eb07b, #6506)

The "Parent Close Gates" check joins its inventory with U+2192, three bytes
wide, and then cut the joined string at byte 200. Two of every three offsets
land mid-rune, so `bd doctor --json` could carry invalid UTF-8 in Detail — a
display nuisance in the terminal, but a value a JSON consumer has to decode.
truncateDetail walks back to a rune boundary first; the test drives every
entry count from 1 to 120 so the cut lands at all three offsets within the
arrow and asserts utf8.ValidString on each.

The same byte cut appears twice more in this file (:101, :561) on ASCII-only
details. Left alone here: they are not this bead's, and changing them would
put a behaviour change in two checks a reviewer of #6506 has no reason to be
reading.

The check's two "N/A" early returns also omitted Category, unlike its three
real returns, which drops them out of the categorised report. Both now carry
CategoryMetadata.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* perf(storage): read the batched exogeneity set once per batch, not per statement (wy-3eb07b, #6506)

D1, the PR blocker from the round-1 review. The batched mark/unmark templates
spliced parentsExplainedBySubtreeSQL — the "which blocked parents are explained
only by their own subtree" query — into both of their parent-child legs,
batch-scoped. The scope made it look cheap. It was not: dolt pays for a
`p.id NOT IN (subquery)` once per leg per STATEMENT, and a batched pass is a
mark and an unmark, so one 200-id RecomputeIsBlockedForIDsInTx derived the set
four times and measured 6.9x origin/main (53-63 ms -> 400-556 ms). That is the
bulk/import path and the cost shape #6288 removed.

The set is now READ once per batch and BOUND into both statements as ids —
the same trade the unbatched full repair already makes per pass — which is why
markBlockedTemplate/unmarkBlockedTemplate are built per batch now: the number
of bound ids is a property of the batch. In front of the read sits a cheap
indexed guard, batchParentKindsInTx: a parent KIND with no parent-child row in
the batch has an empty candidate set, hence an empty exogeneity set, so its
read is pure overhead, and the read is a ten-join walk under two CTEs that
dolt spends ~8 ms planning whether it returns rows or not. Most batches name
no wisp parent at all; a batch of roots names neither. Without the guard the
2-id case measured 1.9x, with it 0.94x.

expandBatchTemplate now WALKS the template instead of counting "%s": the batch
scope and the bound exogeneity ids alternate inside the union (leg 3's scope,
leg 3's NOT IN, leg 4's scope, leg 4's NOT IN), so only text order says where
each group goes. It returns an error on a ?/bound mismatch rather than handing
the engine an opaque argument-count failure. The %s budget is back to 6 from
8, re-pinned, with two new pins beside it: the ? group is exactly the bound
exogeneity ids (none for an empty set), and the mismatch is refused.

KEPT, on round-1's measurements: the NOT IN subtraction (the derived-table
JOIN measured ~30x in dolt) and the 4-level LEFT JOIN ancestor walk (WITH
RECURSIVE blew the driver read timeout).

MEASURED. n=1000 issues / 2870 deps / 333-604 blocked, embedded dolt 2.2.0,
TestBlockedStateScaleTiming, SIX interleaved origin/main(71c4cd08b)/head pairs,
medians, worst single pair in brackets. The bench now times three batch sizes
instead of one, because the per-statement and per-id costs pull opposite ways:

  metric                     main     head    ratio          bar
  full repair               49 ms    57 ms    1.16x [1.32x]  <= 1.5x  MET
  doctor count (consistent) 48 ms    57 ms    1.18x [1.32x]  <= 1.5x  MET
  write path, per CloseIssue 25 ms   26 ms    1.03x [2.59x]  <= 1.2x  MET
  batched recompute, 200 id 54 ms    69 ms    1.28x [1.57x]  <= 1.5x  MET
  batched recompute,  20 id 17 ms    22 ms    1.29x [1.50x]  (measured)
  batched recompute,   2 id 22 ms    21 ms    0.94x [1.03x]  (measured)

All four stated bars are met on medians. The worst-pair column is at or inside
this box's own noise: over the same six runs origin/main's OWN spread is 2.07x
on the full repair, 2.33x on the write path, 1.92x on the 2-id batch and 1.19x
on the 200-id batch, so a single pair's ratio is not evidence at this
resolution and the medians are what the bars are read off.

DISCLOSED, not a stated bar and not fixed here: the bench FIXTURE BUILD —
2870 AddDependency calls plus 240 CloseIssue through the store — is 75 s ->
102 s, 1.36x [1.61x]. That is the dependency-ADD write path, and the cost is
round 1's incremental seeding (AffectedByDepChangeInTx now walks up to every
reason-carrying ancestor and reseeds its whole sibling set), which is what
buys the incremental/full-repair agreement pinned by the lockstep test in the
next commit. Per-edge it is sub-millisecond; it shows up here because the
fixture writes the hierarchy of a 1000-issue store edge by edge.

GATE: go build ./... ; go vet ./internal/storage/issueops/ ; go test
./internal/storage/issueops/ (ok, includes the rewritten template and sqlmock
pins) ; BEADS_TEST_EMBEDDED_DOLT=1 go test ./internal/storage/dolt/ -run
'ParentChildCascade|RecomputeAllIsBlocked' (ok) ; gofmt -l clean. The full
enumerated gate is on the bead.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* test(storage): pin both sides of the subtree-walk horizon, and the incremental/full-repair lockstep (wy-3eb07b, #6506)

D2 and D3 from the round-1 supervisor ruling.

D2 — THE HORIZON IS NOW PINNED, not commented. "Inside my own subtree" is
decided by a fixed 4-level ancestor walk (subtreeWalkDepth), because a
recursive walk cost 7.5x per evaluation and blew the driver read timeout. Two
tests that differ by ONE EDGE straddle it:

  _ReasonAtTheWalkHorizon    P blocks a descendant exactly 4 pc levels down.
                             The walk reaches P, so the reason is
                             subtree-derived and the chain comes bright.
                             RED on origin/main (4 rows dark that the fix
                             brightens) — so it is not vacuous.
  _ReasonPastTheWalkHorizon  one level further. The reason reads as EXOGENOUS,
                             so the whole chain stays dark, which is
                             origin/main's own answer — and that test PASSES
                             UNCHANGED ON origin/main (verified in a temp
                             worktree at 71c4cd08b, since removed). It also
                             asserts no row of the shape appears in
                             GetReadyWork: no new dark rows AND no new visible
                             rows past the horizon, checkable rather than
                             argued. Raising the constant makes it fail and
                             name the row that changed.

Both also repair from a fully inverted plane, which is the leg that needs the
fixpoint rather than the write path's seeding. The CHANGELOG now names the
4-level horizon beside the existing limitation sentence, and the constant's own
doc names the two pins.

CAN THE HORIZON BE RAISED? Measured, and the answer is "not on this evidence".
Same bench, same box, full repair / doctor count / 20-id batch / 200-id batch:

  depth 4   57 ms /  58 ms / 21 ms /  69 ms     (shipping)
  depth 6  126 ms / 118 ms / 52 ms / 101 ms     2.2x, TWICE reproduced
  depth 8   59 ms /  74 ms / 24 ms /  68 ms     ~= depth 4, TWICE reproduced

The curve is NON-MONOTONIC: 6 falls off a cliff and 8 comes back. That is a
dolt planner artifact, not a cost model, and raising a semantics-bearing
constant on the strength of a number nobody can explain is the wrong trade —
depth 8 also makes every past-horizon shape newly bright, which is a behavior
change and not this round's business. Left at 4, with the numbers recorded for
whoever picks the knob up.

D3 — THE LOCKSTEP. _IncrementalMatchesFullRepairAcrossEdits walks one graph
through the mutations that reclassify a blocking reason WITHOUT touching the
row that carries it, and after every one asserts both the exact flags and
assertConvergedAndStable: detection counts 0 AND a full repair changes 0 rows.
An under-seeded incremental path (the AffectedByDepChange{,ForWisp}InTx
ancestor walk round 1 added) fails here as a nonzero repair over a graph the
write path just finished maintaining. The mutations: re-parent the reason's
target INTO the blocker's subtree (which is how the shape arrives — the store
refuses a blocks edge straight onto an existing own descendant, and that
refusal's reason text is what 3a5203979 corrected), close the descendant,
reopen it, re-parent it back OUT, remove the blocks edge. The
into/out-of-subtree steps are the ones that flip rows the edge does not name
(the parent's other children), which is exactly what
appendSiblingsUnderAncestorsInTx exists to seed. RED on origin/main for the
semantic values; origin/main's own incremental/full-repair agreement holds
there, so what this pins is the agreement, not the numbers.

GATE: BEADS_TEST_EMBEDDED_DOLT=1 go test ./internal/storage/dolt/ -run
'ParentChildCascade' -count=1 — 8/8 ok; gofmt -l clean; go vet clean.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(doctor): the close-gate inventory walks the same four parent-child levels as the cascade (wy-3eb07b, #6506)

The "Parent Close Gates" check listed only DIRECT parent->child gates, so the
fix's own headline shape (a parent that blocks on its grandchild) never
appeared in the inventory. The check now joins a descendant-pairs set built
to the same four parent-child levels the cascade uses for "inside my own
subtree" (issueops subtreeWalkDepth), as plain joins over the dependency
union rather than a correlated subquery, which dolt declined to plan once
rows were present. Messages say "own-descendant"; the tests add a grandchild
gate (2 listed, the exogenous edge still not) and assert Category.

CHANGELOG cites the nested-gap follow-up, gastownhall/beads#6601.

Tests run: go build ./... 0; go vet ./cmd/bd/doctor/ 0; gofmt -l clean;
env -u BEADS_ACTOR go test ./cmd/bd/doctor/ -run 'ParentBlocksOwnChild|TruncateDetail' -count=1 PASS (3/3).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* ci: allowlist TestBlockedStateScaleTiming's -short skip (wy-3eb07b, #6506)

scripts/check-testing-short.sh reserves testing.Short() for runtime, stress
and large-fixture skips and keys them by file::func. The scale-timing test
added in this PR builds a 1000-issue / ~2000-edge dolt fixture and times the
blocked-state paths over it: a large-fixture skip, and PR Core runs with
-short, so it needs the entry. One line, the same shape as the
TestUOW_ConcurrentMergeOps_NoLostUpdate row from #4732.

Local: ./scripts/ci/pr-policy.sh rc 0 (check testing.Short boundaries
succeeded; the other nine legs unchanged).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* wy-3eb07b: build(bazel): register blocked_scale_bench_test.go in internal/storage/dolt

The rebase carried the bench test but not its BUILD.bazel entry, so the
Bazel test lane's gazelle sync and Go test equivalence steps failed while
every Go lane was green. This is CI's own bazel-sync patch for 043f9c47b9,
applied unchanged.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(blocked): resolve explained parents through their ancestry; walk ancestors on hinted per-table members

Maintainer fixup for #6602 (adopt-pr review iteration 1, quality scorecard
760/1000, request_changes; amended at iteration 2, 906/1000, approve). It
fixes the review's two major findings, the doctor check's message and its
swallowed query failure, the stale core-builder doc, and the stale
test-comment names. At iteration 2 it also takes both nits and corrects a
CHANGELOG sentence this fixup had made false.

- Mixed-arm leak (major). The explained-parent read decides from a
  parent's own reason rows, and the fixpoint carries the recursive clause
  only for a parent with no reason row of its own. With Q blocked on an
  outside X, P a child of Q, and P blocking on its own child C, P read as
  explained and C came bright under an epic still gated by X, on the
  write path and in full repair alike. pruneExplainedByAncestryInTx now
  shrinks every read to the greatest set whose members' blocked parents
  are all members. A full-repair read is complete, so a blocked parent it
  did not return is unexplained. A batch-scoped read climbs instead,
  reading the blocked parents above the batch by id (explainedAmongInTx).
  The suggested one-level NOT EXISTS is not enough: put a second close
  gate between them (R blocked on X, pc Q -> R, Q blocks on P, pc P -> Q,
  P blocks on C) and P's blocked parent Q is in the set, so R's gate
  never reaches C.
- ancestorChainInTx (major) walked the derived UNION of both dependency
  tables that #7224 removed from isAncestorInTx, on every parent-child
  write and merge replay. It now walks reachabilityMembers, the hinted
  per-table recursive members split out of reachabilityQuery, with the
  reason filter kept in the outer SELECT. TestGraphWalkPlansHonorJoinHints
  (embedded) gains an ancestor-chain subtest that pins the lookup plan;
  the old walk fails it.
- New dolt tests: TestParentChildCascade_OwnGateUnderExogenousParent
  (write path, full repair, and X closed and reopened),
  _NestedGatesBothWays (the two-gate chain both ways, then a close of the
  children's own blocker, which re-evaluates them through a batch whose
  read covers nothing above their parents), and
  _WispGateUnderExogenousParent (a wisp gate under an issue epic, an
  issue gate under a wisp epic, then an explained wisp gate the walk must
  read by id above such a batch). Five mutants of the prune were each
  killed: no prune (the PR head), a one-level check, an over-prune, a
  scoped read treated as complete, and a scoped read that trusts every
  parent above it. The eight existing cascade tests pass under all five.
  Iteration 2 killed two more, each by its own section of the wisp test
  alone: dropping the lookup of a wisp parent from blockedParentEdgesInTx,
  and dropping explainedAmongInTx's wisp leg, which had survived all
  eleven cascade tests.
- The doctor check no longer says the children "stay in bd ready", and
  a failed or timed-out inventory query is now a warning carrying the
  error, as in validation.go's other checks, instead of an OK that reads
  as "no gates". TestCheckParentBlocksOwnChildDB_QueryFailureWarns pins
  it with a closed handle, and it fails with the old status. A warning
  does not touch doctor's overall result, and it can be suppressed.
- The core builder's doc no longer describes the spliced design, and
  three test comments name builders that exist.
- explainedAmongInTx says why it does not tolerate a missing table, as
  the file's wisp reads do: the prune runs only on a non-empty read,
  which came from the same core query over all four tables.
- The CHANGELOG entry no longer calls #6601's shape (a sub-epic gated on
  its own children under an exogenously blocked epic) a known limitation
  that keeps the children visible. The prune darkens them, as
  TestParentChildCascade_OwnGateUnderExogenousParent pins.

Left as-is, all non-gating: the refusal hint's "(bd gate)", an API string
pinned by the golden corpus; a parent-child add/remove timing in the
scale bench, whose 1000 issues cannot show the 50k shape (the plan pin
guards it); and hints for the explained-parent subtree walk and the
doctor query. The measured complexity major is runDiagnostics (50/66),
the same at base; the PR adds two lines to it.

Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(storage): re-pin the classic batch-apply statement count for the parent-child cascade

The B0 statement-count pins predate this PR's parent-child cascade. The
first full run of the storage tiers on the adopted head measured the
40 (classic) shape at 835 statements on both backends, against the
pinned 786 +/- 2.

All 49 extra statements are reads, seven for each of the shape's seven
distinct parent-child dep adds (its eighth repeats a pair and is a
no-op):
- appendSiblingsUnderAncestorsInTx reseeds the parent's other children:
  one ancestorChainInTx walk and four child probes, +5.
- The batched mark/unmark reads its exogeneity set first
  (batchExogeneity): the parent-kind probe and the issue-parent read, +2.

Measured by logging every statement of the classic apply on the CI base
233d151b37 (786) and on b2b93515bf (835), then diffing the two logs by
statement shape. Those seven shapes are the whole difference, each
exactly +7, and no write changed. The 356 and 712 shapes are unchanged
on both backends.

This is the deliberate re-measure and re-pin the pins' doc comment asks
for. The per-change breakdown is in pinnedEmbeddedStatementCounts.

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>
2026-10-08 08:31:34 +00:00
Julian Knutsen
37acca96db
feat(cli): add --if-revision compare-and-swap guard to update/close/assign/delete (#7203)
* feat(cli): add --if-revision compare-and-swap guard to update/close/assign/delete

Adds --if-revision <int64> to `bd update`, `bd close`, `bd assign` and
`bd delete`, reusing the existing opaque row_lock token published as
IssueDetails.Revision and the library's own ExpectedVersion compare-and-swap
support. A mismatch writes nothing and exits 13 (ExitGuardMismatch); with
--json the stderr envelope carries integer expected_revision/current_revision
fields deployed callers decode directly, never a quoted string. An
unsupported backend reports conditional_write_unsupported and exits 1
instead of silently dropping the guard. The guard composes with
--if-assignee/--if-status (every guard must hold) and is refused alongside
label or parent edits and alongside more than one id, matching the existing
--if-assignee rules. `bd assign` is newly routed through the checked
Lifecycle path to gain CAS support it previously had none of at all.

Implements Item 4 (compare-and-swap through the CLI, gastownhall/beads#4682)
from the BEADS-JOURNAL-PLAN.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* chore(bazel): regenerate cmd/bd BUILD.bazel for if_revision/close_if_revision

gazelle hadn't picked up if_revision.go, close_if_revision.go,
if_revision_test.go, and if_revision_embedded_test.go, so Bazel's bd_lib
and bd_test targets failed to build with "undefined: parseIfRevisionFlag"
and friends while plain `go build`/`go test` worked fine. Ran `make
bazel-sync` (bazel run //:gazelle; go_srcs.py; bazel mod tidy) to pick up
the new files; only cmd/bd/BUILD.bazel's srcs lists changed.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* test(cli): update update-guard parity strings for --if-revision

TestParityUpdateGuardsRequireFieldUpdate and TestParityUpdateGuardsRejectClaim
pinned the exact stderr text of update.go's pre-write guard short-circuits.
Adding --if-revision to those guard messages (update.go/update_input.go)
changed "--if-assignee/--if-status" to "--if-assignee/--if-status/--if-revision"
in both, which this PR's own change to the guard text had not updated here —
caught by CI's dolt-server tier, not by the targeted if_revision* test runs.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-04 13:38:01 -07:00
Isis Anisoptera
45a116d1a7
fix(update): fence unforced --notes overwrites behind --force across all surfaces (#5946)
* fix(update): fence unforced --notes overwrites behind --force across all surfaces

bd update --notes silently replaced existing notes, destroying handoff
history. The contract now refuses an unforced overwrite of non-empty
notes with ErrNotesOverwrite (409 notes_overwrite_refused over HTTP,
force_notes_overwrite to override), enforced inside the mutation
transaction on both the dolt and uow backends, for single updates and
batch apply alike. CAS guards keep precedence: a stale
--if-assignee/--if-status still surfaces as the exit-13 mismatch, on
both backends, before the fence speaks.

CLI: --force and --if-assignee are no longer mutually exclusive (that
exclusion made overwriting under a guard impossible); both update
routes translate the fence's sentinel into the same actionable advice
(--force to overwrite, --append-notes to preserve history), and the
post---force warning is worded as an audit statement. The shipped
plugin skill docs and bd note help now prescribe --append-notes for
handoffs instead of the newly fenced bare --notes.

The fence is the single enforcement point: no client-side pre-read
copies of the rule. Conformance contracts, unit tests for
AuthorizeNotesOverwrite, and embedded/proxied/httpapi regression
coverage included.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MAFpn9pUw8WKMfymteZHbh

* fix(update): exempt explicit clears from the notes fence; share its predicate

CI surfaced three gaps in the fence's reach:

- Clearing notes (--notes "" / patch.notes: "") was refused, diverging
  from every sibling text field's clear and from the backend behavior
  contracts. The fence now targets only its actual footgun — replacing
  non-empty notes with different non-empty content — via a single shared
  predicate, issueops.NotesReplacement, used by both the contract's
  AuthorizeNotesOverwrite and the CLI's warning path, so the two can no
  longer drift. Prose updated to match everywhere the rule is stated
  (ErrNotesOverwrite, ForceNotesOverwrite, OpenAPI spec + regenerated
  types).
- The revision-CAS integration tests' incidental concurrent writes now
  patch design instead of notes, so they no longer depend on notes-fence
  semantics at all.
- The historical-upgrade harness deliberately replaces fixture notes and
  asserts the new value; its two bd update --notes calls now pass
  --force.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MAFpn9pUw8WKMfymteZHbh

* fix(update): address review — changelog BREAKING entry, problem.go doc block, close-policy-under-guard test

Review follow-ups on #5946 (bee-ghosttrack, MERGE-AFTER-FIXES):

- CHANGELOG: BREAKING entry under [Unreleased] ### Changed for the notes
  fence on both wires (CLI exit 1, HTTP 409 notes_overwrite_refused), with
  the --force / --append-notes migration line. It also names the two
  deliberate edges: the explicit-clear exemption, and --force widening to
  the close-policy half under --if-assignee now that the flag pair is legal.
- problem.go: CodeNotesOverwrite's comment had landed inside
  CodeDependencyCycle's doc block; each const now sits under its own docs.
- assign_fence_embedded_test.go: pin the previously untested close-policy
  half of --force under --if-assignee (refused unforced, authorized forced).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JyuQ6Tjv3D7tpNqeb2WDED

* test(update): align TestWarnNotesReplacement with the post-fence warning copy

The test landed on main after this branch was cut and pins the pre-fence
wording, where the warning fired on any unforced overwrite. Since the fence,
an unforced overwrite is refused outright and warnNotesReplacement fires only
after a forced one — the audit trail for a habitual --force — so the copy it
pins is now '--force replaced existing notes'.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JyuQ6Tjv3D7tpNqeb2WDED

* docs(import): record bd import's notes-fence exemption as by-design (GH#6190)

Import consults none of the per-field live-state fences — notes overwrite,
live-claim reassign, close policy — and that is the intended shape, not an
omission: its contract is wholesale row replacement, guarded by its own
staleness check (only strictly-newer rows rewrite local state, --allow-stale
is the single deliberate-overwrite opt-in) and reported field-by-field in
updated_issues. Named in AuthorizeNotesOverwrite's enforcement-boundary
comment and in bd import's help; the published CLI docs pick the help text
up at the next release pin bump.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JyuQ6Tjv3D7tpNqeb2WDED

* fix(update): refuse --notes "" and add --clear-notes; stop --notes help reading as additive

GH#6021: an empty --notes wiped the whole notes field at exit 0 behind the
same ✓ Updated receipt as a successful write — and the empty string is
exactly what a dead command substitution collapses to. The empty value is
now refused on both CLI routes (the accident and the deliberate clear are
the same bytes at the flag layer), and the deliberate clear gets its own
verb, --clear-notes, mutually exclusive with --notes/--append-notes. A verb
rather than the proposed --allow-empty-notes opt-in: what needs authorizing
is an intent, not an input path — --allow-empty-description unblocks
stdin/file plumbing, which notes does not have — and an opt-in passed
habitually would silently disarm the guard while a habitual --clear-notes
fails loudly. --force does not bypass the refusal; the fence's clear
exemption stands, so the verb alone authorizes the erase. The HTTP API is
unchanged: patch.notes "" still clears.

GH#6272: bd update --help called --notes "Additional notes" and the prime
text said "Add supplementary notes" — both read as appending, so agents
following the injected guidance faithfully clobbered prior context. The
update help now names the operation with the --append-notes contrast at the
point of use, the shared/create help is field-named like --description and
--design, and the prime line points at bd update --append-notes.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JyuQ6Tjv3D7tpNqeb2WDED

* fix(bazel): enumerate the PR-new files in cmd/bd and issueops srcs

The base added cmd/bd/BUILD.bazel and internal/storage/issueops/BUILD.bazel
with EXPLICIT srcs lists after this branch was cut, so the three files this
PR adds were never enumerated:

  cmd/bd/update_notes_guard.go        (go_library bd_lib)
  cmd/bd/update_notes_guard_test.go   (go_test bd_test)
  internal/storage/issueops/aggregate_authorize_notes_test.go (go_test)

The go_library omission is a hard build break, not a silent skip:
update.go:215,220 and update_input.go:106,111 are enumerated and call
validateNotesUpdate / clearNotesRequested, so //cmd/bd:bd_lib compiles the
callers without the callee. bazel.yml arms unconditionally for fork PRs
(head.repo.fork == true) and builds //cmd/bd:bd + //cmd/bd:bd_test, so this
reds the lane. make bazel-sync-check cannot see it -- go_srcs.py only
validates the glob-based go_srcs filegroup, never the rule srcs lists.

Generated by make bazel-sync (gazelle), not hand-edited, so the workflow's
own BUILD-files-in-sync drift step agrees byte-for-byte.

* fix(notes): name --clear-notes in bd note's rm guidance, correct the fence boundary comment, pin both request-shape rules

Takes all three non-gating minors from the review. No behavior change: two
prose fixes and two test cases.

1. cmd/bd/note.go's rm|remove|delete branch advised
   `bd update <id> --notes "text" --force` under "To change or clear notes",
   but clearing through --notes is exactly what this PR made impossible --
   validateNotesUpdate refuses an empty value unconditionally and --force does
   not reach it. The branch now names both verbs separately: --notes --force to
   replace, --clear-notes to clear. The edit and update branches speak only of
   replacing and were already correct, so they are untouched.

2. aggregate.go's enforcement-boundary comment claimed the UpdateIssueInTx
   funnel's "one notes-replacing caller is bd edit". Under this PR's own
   NotesReplacement predicate there are at least four more (bd note's
   read-combine-write, bd defer --reason, bd rename and delete-tombstoning's
   mechanical ID rewrites, bd compact's clears). The exemption is still sound --
   every funnel writer derives its new value from the current notes -- so the
   comment now names those CLASSES instead of a single caller, which is the
   claim that is actually true and that a future fence auditor can check.

3. Both branches this PR adds to ValidateUpdateRequest were uncovered: the
   batch apply leg reaches them here and nowhere else, while the single-issue
   HTTP handler's own pre-check returns before storage. Added a sibling table
   (the existing one varies only the patch; these two rules are properties of
   the REQUEST) with a case each. Mutation-checked, disjoint: neutralizing the
   force-without-notes branch reds only the first case, neutralizing the
   notes+append branch reds only the second, and the pre-existing
   canonical-fields table stays green under both.

Not an amend of 5ffcc9c16c: that commit's message states it was generated by
make bazel-sync and not hand-edited, so folding hand-written Go into it would
falsify the claim its own BUILD-files-in-sync argument rests on. No new files,
so the srcs lists it repaired stay correct.

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
2026-10-01 05:02:40 -07:00
Julian Knutsen
4caeeffeec
feat(serve): name the blockers on a live-blocker not_closable (#6893)
* feat(issueops): type the blocked-close refusal as BlockedError

Every close-policy blocker refusal was fmt.Errorf("%w: %s is blocked by
%v", ErrCloseBlocked, ...), so the blocker list existed only as prose. A
caller reporting the refusal elsewhere (the HTTP surface) had to parse it
or drop it.

issueops.BlockedError carries IssueID, the typed []Blocker (id plus the
blocking edge type when known) and the wrapped sentinel. Its message is
byte-identical to the historical sentence, so the direct and proxied CLI
lines and failed[].error do not move, and errors.Is(ErrCloseBlocked) still
matches. The sentinel is a field rather than fixed so other "X is blocked
by Y" refusals (e.g. a blocked claim) can reuse the type.

The in-transaction guard keeps the edges typed (isBlockedByInTx, with
IsBlockedInTx formatting through Blocker.String), and the external guard
builds the error from IsBlocked's []string via ParseBlocker, the inverse
of that spelling.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* feat(httpapi): name the blockers on a live-blocker not_closable

The served close refusal said only "issue is blocked", so an HTTP client
could not tell the user what held the close, while bd close on the direct
and proxied routes prints "cannot close blocked issue: X is blocked by
[Y]".

A live-blocker not_closable now carries a `blockers` extension member,
[{id, kind: local|external, type?}], read from *issueops.BlockedError's
typed list, and a detail that opens with the direct route's sentence
built from the same list. It covers issues/{id}:close, per-item
issues:batchClose outcomes, PATCH into a done status and
issues:batchApply. The code, status and open_children discriminator are
unchanged; an error that only mentions blockers in prose keeps the old
generic detail and no member.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(issueops): test the external: prefix before the type split in ParseBlocker

Maintainer review fixup for #6893.

ParseBlocker tried the " (" / ")" split before the external: prefix
branch, so it won for any external reference whose capability ends in
")". validateExternalRef (cmd/bd/dep.go) constrains a capability to
non-empty only, so `external:remote:pay (beta)` is a legal reference
created by the sanctioned `bd dep add` path -- and it parsed to a
truncated ID of "external:remote:pay" plus Type "beta", a value outside
the documented blocks|waits-for|conditional-blocks vocabulary that
falsifies the spec's own promise that an external blocker carries no
type.

Only the structured half was wrong: the mis-split round-trips through
String(), so the prose detail and the CLI sentence stayed byte-identical
and the failure was silent on exactly the new `blockers` member this
change exists to make trustworthy.

Hoisting the prefix test is loss-free -- Blocker.Type's doc comment
already states an external reference never carries a reported type.

Pin: the ParseBlocker/String table in
TestBlockedErrorKeepsTheHistoricalSentence gains the paren-suffixed
external row; every external case tabled there was paren-free, which is
why this got through. Restoring the old ordering reds the new row.
The DeepEqual failure now prints %#v, because Blocker implements
String() and the default verbs render got and want identically for
precisely this defect.

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
2026-10-01 00:51:06 -07:00
Julian Knutsen
3b8e85bae3
Add issueops.Releaser: give a claim back, optionally only a named holder's (#5482)
* Add issueops.Releaser: give a claim back, optionally only a named holder's

Claiming has had its own role since Claimer; releasing has never had one.
`bd unclaim` reaches the raw seam directly, and everything that isn't the
CLI has had to spell the release as a patch — assignee to empty, status to
open, started_at to null — which puts the transition's definition in the
caller three fields at a time and still leaves the lease row behind. A
release is one act with a known post-state, and the lease it drops is the
part a patch cannot express at all.

It is its own role rather than a method on Claimer for the reason
Bootstrapper and InitVerifier are two: a caller entitled to give its own
work back is very often not entitled to take new work, and a surface
carrying both hands it a capability it should not be able to reach.

THE SHAPE MIRRORS THE RAW SEAM, and the two places it does not are both
refusals rather than permissions. UnclaimIssueInTx and
UnclaimIssueIfAssigneeInTx refuse an unheld row and a status the release
transition is not defined over with UNTYPED strings — "issue X is not
assigned" and, for the second, "no matching row", which explains nothing
and no caller can classify. The role reads the row first and names them:
ErrNotClaimed and ErrNotReleasable. Which requests are refused is
unchanged; the raw calls still run their own checks underneath.

ErrNotReleasable is wider than "closed" and the leaf says so out loud: the
release UPDATE is pinned to status open or in_progress, so an issue parked
in `blocked` while still holding a claim is refused. That is a limitation
of the transition, not a policy, and it is now visible instead of arriving
as "no matching row".

A RELEASE IS NOT IDEMPOTENT and this keeps it that way. An unheld row is
ErrNotClaimed with or without Force, not a Changed-false no-op — the raw
rule, and the one a reaper can errors.Is in a line it writes knowingly.
ExpectedAssignee is the compare-and-set: a match REPLACES the ownership
fence, exactly as UpdateRequest.ExpectedAssignee does for a transfer, so a
supervisor can free a named agent's claim without Force and without being
able to clobber a claim that has since moved. Force may not accompany it —
the two answer one question and disagree — and a non-nil pointer to "" is
ErrValidation rather than "expected unassigned", because releasing a row
nobody holds describes no release.

ErrNotOwner MOVES to issueops and internal/storage aliases it forward. A
refusal the public role raises has to be classifiable by a caller that
cannot import an internal package; a Go alias preserves identity in both
directions, so every existing errors.Is site keeps matching the same value.

All three legs share one body (internal/storage/issueops.ReleaseIssueInTx),
so this is one reading plus two wrapper checks rather than three backends
agreeing — and the wrapper check earned its keep again, in the same place
MetadataCAS's did. An EPHEMERAL release writes a row and versions nothing;
the unit-of-work leg's commit message is what commits its SQL transaction
as well as what versions it, so composing the message from the durable
table set rolled the write back and the wisp came out still claimed. Green
on both stores, red on the unit of work, exactly as the engdocs predicted.
The domain reach now answers Wrote and the store legs take Tables.

Eleven contract cases on all three legs. The post-state is read RAW, cell
by cell, because the whole reason to state it on the role was that a caller
should not have to reconstruct it — including the lease row, whose survival
is the failure no role-answer assertion can see. The attribution case
forces a release by someone who is NOT the holder, the only arrangement in
which stamping the holder is distinguishable from stamping the actor, and
counts entries per actor because created_at is second-granularity and an
ORDER BY would decide it on a coin toss.

The contract does NOT carry a case for a false ReleaseResult.Changed, and
says so: nothing returns it false, so the case could not fail. What can
fail is the decorator's use of it, which internal/storage/hook_releaser_test
drives with the answer the role reserves the right to give.

FACADE ONLY: no wire, spec or httpapi change, and no bd command re-pointed.
The wire half follows in the conditional-update / release wire slice per
the program's council gating.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Delete the two release pre-checks a mutation proved could not fail

Written as defence in depth, measured as dead weight. ErrNotOwner and
ErrAssigneeMismatch already come back from UnclaimIssueInTx and
UnclaimIssueIfAssigneeInTx typed, wrapped and in this same order, so
removing both copies left the whole eleven-case contract green on the
server-backed leg — the mutation-equivalence verdict that says a branch
exists to look reassuring rather than to hold anything.

What stays is the pair the raw seam answers with a bare string: an unheld
row ("issue %s is not assigned") and a status the release transition is not
defined over ("no matching row"). Those are the refusals this body is FOR,
and each one goes red when it is skipped.

The header now says which refusals this function owns and which it leaves
to the calls below, so the absence reads as a decision rather than as a
check somebody forgot.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Lint: one spelling of the holder, and drop two parameters nothing varies

golangci-lint's unparam found releaserSeedClaimed's holder and
releaserRowVersion's table taking one value at every call site. Both are now
gone, and the holder is one package constant rather than nine copies of the
same literal — which is worth more than the lint: half these cases are ABOUT
the difference between the holder and the caller, and two spellings of "the
holder" is how such a case comes to assert the wrong one.

Plus two British spellings misspell caught.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Review: say why Changed is asymmetric with Claimer's, and three prose fixes

Doc only; no behaviour changes and none intended.

THE RULING ON ReleaseResult.Changed, written where it belongs. Keeping the
unheld-row refusal was defended here as "the rule the raw seam already
has", which is an appeal to precedent rather than a reason. The reason is a
fact about the two POST-STATES. Claimer can afford an idempotent answer
because a claim's post-state IDENTIFIES THE CLAIMANT: a re-claim finds
assignee == Actor and StatusInProgress, the claim's own signature surviving
on the row, so the role can tell "you already did this" from "somebody else
holds it". A release leaves an ANONYMOUS post-state — assignee cleared,
status open, started_at gone — which is the same row whoever emptied it and
whether or not it was ever full. An idempotent release would answer Changed
false identically for "I already released this", "a reaper beat me to it"
and "nothing ever claimed it", with nothing left on the row to tell them
apart. Those three want different things from a caller, so the role refuses
and lets the caller pick. ClaimResult.Changed is now named at the
comparison rather than merely gestured at.

ExpectedAssignee compares BYTE FOR BYTE, now said out loud: " agent-a" is
not agent-a and refuses. The validator trims only far enough to tell a
blank expectation from a real one and never writes the trimmed form back,
and the no-mutation promise makes that permanent — so a padded expectation
loses every time rather than intermittently, which is the failure worth
warning about.

And the deleted-pre-checks note now states the CONSEQUENCE rather than the
shortcut: one leg was sufficient evidence BECAUSE all three legs run this
function and it reaches the same two raw entry points, so there is no
second implementation in which a deleted pre-check could still have been
load-bearing. "A mutation verdict is only true of the body you mutated" is
answered by there being one body. Where the legs DO differ is in what they
version — hence ReleaseWrite's two facts and the wisp case on all three.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Review Sim <ci@beads.test>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-09 07:48:56 -07:00
CI Bot
927f943572 feat(issueops): name the two dependency-endpoint refusals (bd-yby99.9)
DependencyEditor.AddDependencies refuses an edge whose SOURCE names no row,
and one whose TARGET names no row this database can see the absence of. Every
other refusal the role can raise hands a caller something to branch on —
ErrSelfDependency, ErrDependencyCycle, *DependencyTypeConflictError,
*DependencyHierarchyConflictError — and these two handed back "an error", with
different text on each backend. A programmatic consumer could not tell a ghost
endpoint from an infrastructure failure, and the role's own doc said so rather
than promising the anonymity would last.

Both now carry an identity: ErrDependencySourceNotFound and
ErrDependencyTargetNotFound, wrapped by a *DependencyEndpointNotFoundError that
names the refused edge and which of its endpoints was absent. Two sentinels
rather than one because the two are separate answers — a ghost source is always
a bad id, while a target is refused only where this database would have held
it. What is NOT refused is unchanged: an "external:" reference and another
repository's id are still stored as external targets.

The store-backed body and the cross-tier target precheck mint the refusal where
they already read the row. The domain repository has no such read: it learns of
the absence from a foreign-key violation, so it reads both endpoints back on
the transaction that refused, only on the refusal path, and never downgrades
the refusal to a probe's failure. Taking the identity out of the driver's
constraint name would have been the thing a typed refusal exists to avoid. One
user-visible consequence: the proxied-server path now renders "issue <id> not
found" where it used to render a raw foreign-key violation, which is what the
embedded path has always said.

The guarded create classifies the new type where it classified the raw
foreign-key signal, so a missing dependency, parent or waits-for target is
still ErrValidation wrapping ErrNotFound on every backend.

RemoveDependency is deliberately untouched. A removal that finds no edge is
Removed false with a nil error, so there is no refusal there to name.

The shared contract asserts the sentinel and the typed fields for each endpoint
in TWO POSITIONS: alone in a request, and mid-batch where the refusal competes
with the rollback of an edge already written, the half that also reads the
graph back at zero edges. Both cases were verified red on all three backends
before the production change — "issue <id> not found" untyped on the two store
paths, "Error 1452 ... Foreign key violation" on the unit-of-work path.

Agent-Signature: claude-code-claude-opus-5-unknown-reasoning on behalf of CI Bot

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-07 19:45:54 +00:00
Julian Knutsen
33e14b5c82
Move the namespace-neutral error vocabulary into its own leaf (#5395)
memoryops needed one sentinel — ErrValidation — and the value the whole repo
matches lived in issueops. So the memory leaf imported the issue package for
one errors.New and pulled internal/types in behind it, claiming memory sits
downstream of issues. It does not: the two are sibling planes over one config
table.

beadserrors now declares the vocabulary that belongs to no plane in
particular — ErrValidation, ErrNotFound, ErrNotInitialized, the ErrUnsupported
type — and issueops re-exports it by alias, exactly as internal/storage and
backend already re-export from issueops. 141 qualified ErrValidation
references across the tree, zero edited: a Go alias preserves identity.
memoryops now depends on beadserrors and context, nothing more.

What belongs down there is what a leaf for a plane nobody has written yet
would need. ErrCloseBlocked and ErrDependencyCycle name issue concepts and
stay in issueops.

beadserrors imports stdlib and nothing else, enforced by a strict depguard
rule rather than asked for in a comment, because it sits beneath every leaf
and whatever it imports is imported by all of them.

Answers Q4 from #5387.
2026-08-07 04:32:06 -07:00
CI Bot
27ffb42e1f feat(init): put bd init's identity seam behind Bootstrapper and InitVerifier (bd-zl3u8)
`bd init` had two implementations of what a workspace's identity IS. The direct
route read issue_prefix out of the config plane at init.go:1358 and _project_id
four hundred lines later, decided adopt-vs-write with two helper predicates, and
wrote both keys by name. The proxied route called domain.BootstrapUseCase, which
held its own list of which keys an identity is made of, wrote them
unconditionally, and folded the Dolt remote into the same call. The two agreed on
the key names and disagreed on the rule, and no test compared them.

ONLY THE IDENTITY SEAM IS A ROLE. Everything else init does — creating .beads/,
writing metadata.json and config.yaml, initializing git, installing hooks,
starting a Dolt server — CREATES the substrate or the workspace around it, and a
role is reached through an accessor ON a store, so it cannot be what makes the
store exist. init.go alone is 3,060 lines; this commit touches the part that
happens inside the database.

TWO ROLES, AGAINST THE VersionReconciler PRECEDENT. That one is a read and a
write on one role because they are two shapes of one question, and every word of
that is true here too. The test that separates them is different: can one caller
be entitled to the READ and not the WRITE? Here yes, and not hypothetically —
`bd init --team-server` adopts a bts-provisioned identity and is forbidden to
write one, and a gateway credential may be read-only. Those paths now hold an
InitVerifier and never obtain a Bootstrapper, which the type system checks;
with one role they would hold the writer and the suppression would stay where it
is today, in three should* predicates on the CLI.

Q8 ANSWERED IN THE ROLE. Bootstrap over an already-identified substrate is
ErrAlreadyIdentified, carried by an *AlreadyIdentifiedError naming what was
found, decided from the same read the write would have followed inside ONE
transaction. Either marker is enough: a substrate several rigs share carries a
prefix one of them chose, and overwriting it renames every id the others are
about to mint. The guard now sits below both front doors instead of in front of
one, so gateway and adopt paths inherit it, and re-identifying is something
somebody asks for rather than something init does twice.

THE ROLE OWNS THE IDENTITY AND NOTHING ELSE. BootstrapProject wrote six values;
BootstrapRequest carries two. The fingerprints, the synced-at marker and the
recorded binary version are refreshed on EVERY init, adopt or not — a fresh clone
of an already-identified database needs its own fingerprints precisely because it
bootstrapped nothing — so a refusable one-time write would mean either a refusal
that stops recording them or a write that is no longer one-time. bd_version has a
second reason: it is VersionReconciler's key. The Dolt remote left too; it is
where the database syncs to, not what it is, and putting them in one call is what
let a remote that could not be created fail a bootstrap that had already
succeeded. domain.BootstrapUseCase is DELETED and domain.ConfigUseCase gains
SetMetadata, the write half of the GetMetadata it already published, so the
unit-of-work body can read, refuse and write in one transaction.

THE DEFECT. Proxied `bd init` against a database another rig had already
identified rewrote both markers with its own derived values. It verifies and
adopts now, printing the direct route's existing line, with the role's refusal as
the backstop. The direct route's two identity reads also became one snapshot, so
the prefix it adopts and the project id it reconciles against can no longer come
from either side of a concurrent write; shouldConsultInitProjectID still gates
whether the id is USED, so which identities init adopts is unchanged.

CONFORMANCE. backend/conformance/bootstrapper_contract.go holds twelve cases —
both roles in one file, because every promise on either is a statement about the
other — run at all three implementations with ZERO PARKS and zero divergences.
They deliberately do not re-test the decision: the validator's and the refusal's
whole tables are pinned without a database in internal/workapi/bootstrap_test.go.
What only a real backend can show is asserted instead: that the identity is there
for the NEXT caller (a new transaction on the unit-of-work backend), that a
refusal and a validation failure leave the markers EXACTLY as they were, that the
verifier reports an unreadable identity as an error rather than as an empty one,
and that a bootstrap costs at most one version-control entry. Two independent
bodies plus an engine check, not three votes: dolt and embeddeddolt share
internal/storage/issueops.BootstrapInTx and VerifyIdentityInTx and differ only in
how they reach a transaction. The bodies live there rather than in an importable
store<role> package because the read and the write it qualifies must see one
snapshot, which storage.DoltStorage cannot express — so there is no constructor
for a depguard entry to deny.

NO HTTP OPERATION, and that is a decision. A server can only serve a database it
is already bound to, and binding it required the identity this role writes, so
the only caller that could reach such an endpoint would be asking a running
server to identify a workspace that is by construction already identified — which
is the refusal. Bootstrapping over an unauthenticated surface is a different risk
class from reading one. The read half already has an endpoint:
ContextResponse.project_id on GET /v0/beads/context is InitVerifier's answer, on
the wire, today. Recorded in both leaf docs and in the checklist.

USER-VISIBLE, for the wave's changelog pass: proxied init adopts instead of
overwriting on a shared database; `bd init` no longer heals a substrate carrying
a prefix and no project id, which is Q8 as written; an explicit BEADS_DIR outside
the repo now gets a project id written from its own metadata.json instead of
being left half-identified. Reasoning and the alternatives are in
/data/tmp/sd-server/AMBIGUITIES.md as A-ini-0..7.

A-ini-0 IS A FALSE PREMISE IN THE BRIEF, not a finding about the code: bd-zl3u8,
bd-jtp1h and bd-yby99 do not exist in the workspace at BEADS_DIR. Verified by two
bd binaries failing to open it and by a direct SQL read of all 5,603 issues.
Everything else the brief asserted about the code checked out, so the spec used
was the brief plus Q8 plus A2.

Verified: build, vet, gofmt clean; golangci-lint 0 issues (its unparam check is
what found resolveInitIssuePrefix's now-dead `write` return, removed here);
TestBootstrapperContract 12/12 at dolt, embeddeddolt and uow; internal/workapi,
internal/storage, internal/telemetry, internal/jira, issueops, the root layering
pins and the whole internal/storage/domain and internal/storage/uow packages
green; internal/httpapi green and `make api-check` clean with no spec or
generated diff; TestInit* and TestResolveInit*/TestApplyInitGateway* and
TestCorpusGolden and TestDoctor* green under BEADS_TEST_EMBEDDED_DOLT=1;
TestProxiedServerExternalCreate, TestProxiedServerPing and TestProxiedServerUpdate
green under BEADS_TEST_PROXIED_SERVER=1, each of which runs
`bd init --proxied-server` in its harness; TestProxiedLookup green.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-06 03:01:33 +00:00
Julian Knutsen
d801ec43dc
feat(issueops): put every issue capability behind one library surface
Beads had two implementations of most issue verbs: one for the direct route
(the CLI talking to a store it opened itself) and one for the proxied-server
route (the CLI talking through a unit of work over a running Dolt server).
They drifted — different commit messages, different transaction boundaries,
different refusals, occasionally different answers.

Seven role interfaces now live in the leaf package issueops: Lifecycle,
Reader, ReadyClaimer, BatchCloser, DependencyEditor, Commenter and Relations.
Each is reached only through a store accessor, never a constructor, because
the accessor is where the hook and telemetry decorators add their layers.
Three implementations back every role — dolt, embeddeddolt, and the
unit-of-work provider the proxied route uses. Both routes call the same role
for close, dep add/remove/list, comment, ready --claim and update.

A depguard rule (httpapi-domain-boundary) denies internal/storage/domain from
internal/httpapi, so a handler cannot reach uw.IssueUseCase() past the roles
and open a second front door one lint-clean commit at a time.

Behaviour users will notice, all in the CHANGELOG:
  - bd close a b c is one Dolt commit, not three, and --claim-next moved
    inside that transaction so it fires only when something landed
  - the open-children guard moved into the transaction and its hand-rolled
    cmd/bd copy is gone, removing a read-then-write window that made
    bd close <child> <parent> depend on argument order
  - bd dep add --file honours deferred version commit
  - embedded bd comment writes the role's message and author
  - dep verb commit messages are the role's on the direct route

Wisp-sourced dependency edges are restored. Moving bd dep add onto the role
had pinned an edge's SOURCE to the issues plane, and the two routes did not
even fail alike: direct refused with "issue <id> not found", proxied threw an
fk_dep_issue violation. The comment justifying the pin claimed the issues
plane was "the only one its unit-of-work sibling can reach" — that was false;
domain.DependencyUseCase declared a full set of wisp twins with no production
caller. All three implementations now route per edge by the edge's own
source. A mixed request stays one transaction: parent-child-first ordering
and the whole-graph cycle gate span both planes, and a refusal rolls back
both. Behind the role, three bulk add verbs collapsed into one source-routed
AddDependencies, so no plane-pinned variant is left to reach for by mistake.

Six Provenance fields with no production caller were deleted rather than
wired — CloseRequest, CloseBatchRequest, ClaimNextRequest, AddCommentRequest,
AddDependenciesRequest, RemoveDependencyRequest. Each role already composes an
id-bearing message, so a caller could only restate the default and make it
unreachable from production. Two are not caller-settable even in principle:
CloseBatchCommitMessage names what LANDED and ClaimNextCommitMessage names the
id the claim WON. UpdateRequest and ReopenRequest keep theirs; commit messages
users see are unchanged.

Verified: build, vet and gofmt clean; golangci-lint 0 issues; protocol corpus
byte-identical under BEADS_PROTOCOL_REQUIRE_DOLT=1; all twelve
DependencyEditor conformance wirings green (four contract functions against
each implementation); TestEmbeddedDepAddWispSource runs bd dep add <wisp-id>
at the front door and was demonstrated RED against the pinned routing first.
Three internal/storage/dolt failures reproduce on pristine origin/main.

Known gaps are enumerated in the PR description rather than left to be found:
comment listing is on no role, bd dep tree and bd dep cycles have no role,
bd create and bd reopen are on Lifecycle only on the direct route, per-edge
line attribution is lost in bd dep add --file, multi-store bd close
--claim-next rides only the first store's batch, and the is_blocked staging gap
(bd-2y9ke, predates this change). Seven of the eight role interfaces now have a
shared conformance contract in backend/conformance, run at all three
implementations; main's Claimer, added in parallel by #5334, is the eighth and
has none yet.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-04 12:27:56 -07:00
Julian Knutsen
0a3ff99f34
Add issueops.Claimer and route the HTTP claim through it (#5334)
The claim was the one v0 operation not covered by the public facade: the
handler reached past it into the domain layer, driving
uw.IssueUseCase().ClaimIssue directly and carrying its own conflict type,
its own refusal shaping and its own transaction protocol. That is a
handler doing the library's job.

Claim is now a role of its own beside issueops.Lifecycle and
issueops.Reader, reached by its own accessor rather than appended as a
fifth verb:

- issueops.Claimer, with ClaimRequest, ClaimResult and the typed
  ClaimConflictError, which WRAPS the refusal rather than replacing it —
  errors.Is, the refusal's exact prose and beads.ParseClaimConflict's
  fragments all survive.
- storage.Storage.IssueClaimer(), implemented by both Dolt stores over a
  shared storageissueops.ExecuteClaim, and recursed through by the hook
  and telemetry decorators.
- uow.IssueClaimerSource / uow.NewIssueClaimer, where the HTTP path's
  semantics live, retry included.

handleClaim now does argument validation, asks the provider for the role
and returns the result. The wire is unchanged: no diff under
internal/httpapi/spec or internal/httpapi/apigen, and the existing claim,
spec-parity and bijection suites pass unmodified apart from the storage
commit message, which loses its "bd serve:" prefix now that the operation
is not the server's.

ClaimResult.Issue is deliberately the bare post-state row — no labels,
dependencies or comments, unlike UpdateResult. That is what the shipped
v0 response and `bd update --claim --json` both report today, verified
against an issue that does carry labels; hydrating it here would change
an already-published body.

Breaking for out-of-tree implementations of beads.Storage, which must add
IssueClaimer() to compile. Noted in CHANGELOG.md.

Agent-Signature: claude-opus-5

Co-authored-by: CI Bot <ci@beads.test>
2026-08-04 08:40:18 -07:00
Julian Knutsen
b92442d1a3
feat(storage): one guarded issue-lifecycle surface for the CLI and linked consumers (#5191)
Adds issueops.Lifecycle — Create, Update, Close, Reopen — reached from the storage handle via
store.IssueLifecycle(), implemented once and shared by the CLI and linked library consumers. Three backends
implement it and a shared conformance suite asserts them against one spec. The bd CLI's create, update,
close and reopen now route through it.

Fixes several defects that predate this change and became visible once the write paths were forced to
agree: swallowed metadata-edit failures, a claim applied before field validation, missing value validation
on title/priority/estimate, silently dropped create edges to missing targets, infra-typed creates landing in
the wrong table, a dropped SourceRepo, closed_by_session written but never read, and a compound update
writing twice.

Behavior changes needing release notes: create with an occupied explicit id now fails instead of silently
overwriting; a compound update is one atomic operation with one hook and one version commit; reparenting
replaces all parent edges; reopening something not closed reports nothing to do.
2026-07-31 11:26:38 -07:00