Commit graph

10 commits

Author SHA1 Message Date
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