* feat(http): bd blocked over bd serve (blocked.list) through issueops.BlockedLister
`bd blocked` refused against an HTTP workspace: it called the legacy
GetBlockedIssues, which the HTTP backend stubs as unsupported. It now runs
one role on every route, and bd serve publishes that role.
- Role: issueops.BlockedLister.ListBlocked(BlockedRequest{ParentID, Labels,
LabelsAny, ExcludeLabels}) -> BlockedResult{Items}. One body,
internal/storage/issueops.ExecuteListBlockedInTx over the unchanged
GetBlockedIssuesInTx; labels normalized in the role (BlockedFilter);
Items never nil and in a total order (priority, created_at desc, id).
- Legs: DoltStore (read tx), EmbeddedDoltStore (read conn), uow (read unit
of work through the use case's GetBlockedIssues, so the
external-dependency uow decorator applies). Census: storage.DoltStorage
gains BlockedLister(); HookFiringStore passes it through (a read),
telemetry wraps it, uow.notifyingProvider, externaldeps.uowProvider and
httpapi.timedProvider build it.
- externaldeps.Store.BlockedLister is built over its own GetBlockedIssues,
so local `bd blocked` output is unchanged. Over a remote store it takes
the server's listing when the server advertises
policy.external_dependencies, else decorates the server's listing here
through EdgeReader and BatchGetter (decorateBlocked, factored out of
GetBlockedIssues).
- Wire: GET /v0/beads/blocked (listBlockedIssues; parent, label,
label_any, exclude_label) answering BlockedPage {items, has_more} with
the new x-go-type-pinned BlockedIssue schema, behind the new
blocked.list token. apigen and the wire-shape golden regenerated; the
golden diff is additive only, so wire_revision stays 2.
Config.BlockedLister is a required role, wired in bd serve.
- Client: httpclient.Store.BlockedLister dials through Store.dispatch, so
an older server is refused BEFORE the dial with *wire.CapabilityError
naming blocked.list. The legacy Store.GetBlockedIssues rides the role
(page and row cap applied to its answer) and leaves the unsupported
shell. Divergence ledger row F-blocked retired.
- CLI: `bd blocked` takes BlockedLister() from the store on the direct
routes and from the provider's BlockedListerSource on the proxied route;
runBlockedProxiedServer is deleted. --json output is the same rows in
the same order, [] when empty.
Tests: backend/conformance RunBlockedLister (10 cases: direct blocker,
child attributed to its blocked parent, closed blocker, wisp plane, pinned
status, parent filter, label filters with normalization, order, empty
slice, request not mutated) on dolt, embedded, uow and the served HTTP
client; httpapi handler tests (mapping, unknown/repeated params,
projection, capability); httpclient stub tests (pre-dial refusal naming
the token, encoding, projection, legacy door paging); skew and vocabulary
counts; TestE2E_BlockedOverHTTP (served `bd blocked --json` equals the
local command's after mapping ids and timestamps, member order included,
external blocker named, older-server refusal with no dial); corpus
gc-blocked re-marked and gc-blocked-parent added, both pending until the
reference server advertises blocked.list.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(blocked): pin server-side external decoration, refuse has_more, serve the legacy door over http
Review fixes for the blocked.list slice.
- Server-side external decoration is now pinned on the compositions bd
serve answers from. TestWrapUOWProviderBlockedListerNamesExternalBlockers
lists through the wrapped unit-of-work provider's own BlockedLister
accessor (the bd serve provider path) and requires an external-only row
and a mixed row to carry their external: refs; building that lister over
the inner provider fails it. TestServedBlockedListerCarriesExternalRefs-
WhenTheServerEnforces serves the store-shaped composition
(externaldeps.Store.BlockedLister, policy advertised) and requires the
operation's own answer, through the undecorated client role, to carry the
refs, and the client's decorated chain to return it unchanged; serving
the inner store's lister fails it.
- The client refuses an answer reporting has_more with the new typed
httpclient.TruncatedListingError instead of returning a short listing:
the operation has no cursor, and a caller reads a missing row as
unblocked. The legacy door inherits it.
- externaldeps.Store.GetBlockedIssues over an http store reads the extra
sources through the served roles (EdgeReader, BatchGetter) instead of the
raw GetIssuesByIDs / GetDependencyRecordsForIssues the http backend
refuses, and the decoration skips the source read when there is nothing
to load. The legacy door on the CLI chain (bd mol stale, the wisp
commands) now answers over http in both policy modes;
TestServedLegacyGetBlockedIssuesThroughTheDecorator pins it, paging
included. bd ready --explain still refuses on its other raw reads; the
CHANGELOG says so.
- Docs: the spec and the retired F-blocked ledger row state that the
listing is unpaged, bounded by the client's 32 MiB response limit
(refused, never read in part), and that has_more is refused.
- Contract: new cases for waits-for and conditional-blocks blockers, no
type exclusions (gate, epic), and a stale flag with no nameable blocker
(on the legs that can write the column: dolt, embedded; skipped
elsewhere with the reason). Order seeds explicit created_at values with
five rows tied on priority and created_at, two of them wisps, so only the
id tiebreak orders them; dropping the tiebreak now fails every run.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* feat(blocked): bd blocked --flags, the blocked flag per id from stdin
`bd blocked --flags [--json]` reads ids from stdin, one per line (blank
lines and repeats ignored), and prints the blocked flag bd holds for each:
with --json, [{"id","is_blocked"}] in the order the ids were first given,
omitting an id that names no row on either plane, [] for no input. It is
the readiness column a consumer otherwise had to read with `bd sql`, so no
such consumer needs a local-only command.
It is the FLAG, not the listing: `bd blocked` narrows the stored flag to
rows it can name a blocker for, and --flags does not, so a row whose flag
is set with no nameable blocker reads true here and is absent from the
listing. Where the external-dependency policy applies, an unsatisfied
external: blocker sets the flag, as it keeps the row out of `bd ready`.
One library entry on every route: issueops.BlockedFlags over the route's
BlockingAnnotator (the store's accessor on dolt, embedded and HTTP, the
provider's on the proxied route). Over HTTP that is listBlockingAnnotations
with is_blocked behind dependencies.blocking.isBlocked; a server without
that token is refused before the dial, naming it. No wire change. The
listing's filter flags are refused with --flags rather than ignored.
Tests: TestE2E_BlockedFlagsOverHTTP (served JSON equals the local command's
after mapping ids to titles, unknown id omitted, repeat collapsed, [] on
empty stdin, filters refused; a stale-flagged row with no blocker reads
true and is absent from `bd blocked --json`, which fails if --flags is
derived from the listing; an older server's handshake refused naming the
token with no dial); TestProxiedServerBlocked/flags_reads_ids_from_stdin on
the proxied route; corpus gc-blocked-flags, pending until the reference
server advertises the token. CHANGELOG entry.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* feat(blocked): bd blocked --flags --raw, the stored is_blocked column
`bd blocked --flags --raw [--json]` answers the stored is_blocked column
for each id read from stdin, exactly what reading is_blocked from the issues
and wisps tables returns, without the external-dependency policy: a row
blocked only by an unsatisfied external: ref reads false (the policy-aware
--flags reads true), and a stale flag reads true either way. Same output
shape as --flags. This lets a consumer move off a `bd sql` read of the
column with no change in what it reads. The default --flags is unchanged.
The role is taken from beneath every decorator: storage.UnwrapStore on the
direct routes, uow.UnwrapProvider on the proxied route. Over HTTP the
innermost store is the http client, whose annotation read is the server's
answer: against a server that does not advertise
policy.external_dependencies that answer is the column, and --raw is
served. A server that advertises it decorates the flag it answers, the v0
wire has no member asking it for the column, and the decorated flag cannot
be turned back into the column client-side, so --raw against such a server
is refused before the annotation read, naming the token, rather than
answered with the decorated flag. --raw without --flags is refused.
Tests: TestE2E_BlockedFlagsOverHTTP/raw_is_the_stored_column (served --raw
equals local --raw; the externally-blocked-only row reads true with --flags
and false with --raw on both; locally blocked rows agree; a stale-flagged
row reads true in both modes; --raw without --flags exits 1; a server
advertising the policy refuses --raw with no annotation request);
TestProxiedServerBlocked/flags_raw_is_the_stored_column; corpus
gc-blocked-flags-raw (pending until the reference server advertises
dependencies.blocking.isBlocked). Routing --raw through the decorated
annotator fails the e2e. CHANGELOG entry.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* docs(changelog): bd blocked --flags --raw is for the local and proxied routes
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* test(blocked): give the e2e gate-kid its own priority; document --flags answers closed ids
TestE2E_BlockedOverHTTP seeded gate-parent and gate-kid at one priority, so
when both landed in the same second their order fell to the generated ids,
which differ between the local and the served workspace: the comparison
failed intermittently. gate-kid now has its own priority. Ten runs on the
embedded lane pass.
bd blocked --flags answers a closed id too, with its stored flag; a SQL read
of the column filtered on status <> 'closed' leaves it out. Said in the
command's doc and the CHANGELOG.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(blocked): apply label filters to external-only blocked rows
The external-dependency policy appends a row blocked only by an
unsatisfied external: ref after the label query has run, so --label,
--label-any and --exclude-label never judged it: bd blocked and
GET /v0/beads/blocked listed it whatever its labels, on every route.
Both decorators now filter those rows by the request's labels. The uow
decorator reads them through GetMany, chunked at MaxGetManyIDs, so their
labels are hydrated; GetIssuesByIDs left them empty, which also printed
them unlabelled on the proxied route.
Review fixes (adopt-pr apply-fixes, iteration 1):
- major #1: label filters on external-only rows in the store and uow
decorators, with absence-asserting arms in the unit, served httpclient
(server- and client-enforced policy), e2e and proxied tiers; the spec
and the role doc say such rows are narrowed like every other row.
- minor #2: the policy.external_dependencies token prose names the
blocked listing (spec, routes.go, regenerated types.gen.go).
- minor #6: SERVE_RUNBOOK and the allowUnlimited comment record the
blocked listing's unbounded whole-set answer and why.
- minor #10: BlockedLister telemetry-outermost and typed-unsupported pins
beside the ReadyCounter pair, plus the externaldeps wrap pin.
- nit #9: F-blocked names --flags --raw's refusal against a server that
applies the policy (ledger.go and the regenerated ledger doc).
- nit #11: the remote BlockedLister no longer builds a local lister it
then discards.
Review fixes (adopt-pr apply-fixes, iteration 2; the review approved at
940 with one minor and two nits, none gating):
- minor (the --flags refusal list was unpinned): the new
TestBlockedFlagsRefusesEveryListingFilter pins blockedFlagFilterFlags
to the flags blockedCmd registers, in both directions. Every
registered flag except --flags and --raw must be refused, and every
entry must name a registered flag. The test walks Flags() rather than
LocalFlags(), so it does not merge the root's persistent flags into
blockedCmd, and it skips inherited root flags and cobra's --help.
Mutants:
- four fail it: a new filter flag left off the list, a dropped
entry, a misspelled entry, and --raw added to the list;
- a simulated earlier in-process run (merged root flags plus --help)
stays green, and fails once either skip is removed.
- nit (the remote branch's span): the remote BlockedLister comment now
says why that lister is not wrapped again. The inner lister already
carries telemetry's span, so wrapping would nest a second span of the
same name. The comment also says what runs outside that span.
- nit (duplicated order comparator): left as is. finishBlockedIssues
predates this PR, so merging the two sorts would refactor existing
code with no review pass left after this one.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Gas City Adopt-PR
---------
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Co-authored-by: Eddie the Engineer <338826946+gascity-eddie[bot]@users.noreply.github.com>
* feat(roles): issueops.Heartbeater role on the dolt, embedded and uow legs
Adds issueops.Heartbeater.Heartbeat(HeartbeatRequest{Actor, IssueID}) ->
HeartbeatResult{IssueID, Holder, HeartbeatAt, LeaseExpiresAt, Rearmed},
the lease refresh behind `bd heartbeat`, as its own role with its own
accessor.
- One body: internal/storage/issueops.ExecuteHeartbeatInTx validates
(*HeartbeatFieldError for a blank/over-long actor or empty id), refuses
a wisp, then runs RenewLeaseInTx, which is HeartbeatIssueInTx's body
reporting the renewal. HeartbeatIssueInTx is now a wrapper, so the legacy
HeartbeatIssue legs answer the same text and sentinels.
- The refresh is fenced on the holder AND on the live claim: after the
holder-fenced UPDATE, a read in the same transaction requires the issue
to be in_progress under the holder (the `update leases set` prefix and
the one IF() the Postgres dialect rewrites are unchanged; a Postgres port
should expect more serialization retries from that read). A refusal deletes the caller's orphaned lease
row, and the legs commit that refusal.
- A refresh writes only the lease row: no row_lock, version, updated_at,
event, journal entry, Dolt commit or hook. A re-arm (a live hand-doled
claim with no lease row the caller holds) is recorded as a mutation:
row_lock reminted, updated_at stamped, a lease_rearmed event, a journal
entry, a version, a Dolt commit (LeaseRearmVersionCommit) and on_update.
The remint makes a re-arm collide with a racing release or close instead
of leaving an orphaned lease on an open or closed issue (a pre-existing
race on every Dolt route). Rearmed is true only when a row was created:
a same-second refresh (0 changed rows on embedded Dolt) or a holder
spelled differently refreshes the existing row in place and keeps its
granted_at/granted_node. Reported times are rounded to whole seconds,
the stored values; the binds stay unrounded so a same-second refresh is
never a 0-row UPDATE on Dolt.
- Typed refusals: an absent id is ErrNotFound; a foreign holder is
*LeaseConflictError{Holder} wrapping ErrAlreadyClaimed; a wisp
(Ephemeral) or no live claim is *LeaseConflictError wrapping the new
ErrLeaseNotHeld, which also matches ErrNotClaimable.
- Legs: DoltStore and EmbeddedDoltStore through the issue-operation
funnel (DOLT_ADD of the named tables, then DOLT_COMMIT -m, after the SQL
commit); uow.NewHeartbeater through the new uow.RunTxScoped: a refresh or
a refusal commits with the plain SQL COMMIT (no working-set scan, no Dolt
commit, nothing another writer left uncommitted is swept), and a re-arm
commits through the new ScopedCommitter (DOLT_ADD of exactly its tables,
DOLT_COMMIT -m, never -Am). The legacy HeartbeatIssue doors commit a
re-arm the same way and keep a refusal's orphan delete, and the
proxied-server `bd heartbeat` route runs the role's body with the same
scoped commit.
- Census: storage.Storage gains Heartbeater(); HookFiringStore wraps it
(fires on_update for a re-arm only, RoleFiresHooks knows it), telemetry
wraps it, httpapi.timedProvider, uow.notifyingProvider (records a re-arm)
and externaldeps.uowProvider build it; the journal and version guards
list the heartbeat family as entry points; the httpclient unsupported
shell is regenerated and Heartbeater sits on its unsupported allowlist
until the wire lands.
Conformance: RunHeartbeater* (18 cases) on dolt, embedded dolt and uow:
refresh post-state with the stored times pinned to the result; no
row_lock/current_revision/updated_at/events/journal/issue_versions/
version-control/hook change; a guarded write with the pre-heartbeat
revision still lands; foreign holder refused against an aged lease;
refused after close/release/reclaim/status move; wisp refused; hand-doled
claim re-armed as a mutation; same-second heartbeat is not a re-arm;
orphaned leases on released, closed and reassigned issues refused and
deleted; a refresh and a refusal against a dirty working set make no
commit and leave the other writer's change uncommitted, and a re-arm
commits only its own tables; absent id; request rules; no request mutation. The http leg is
waived until the wire lands.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* feat(httpapi): POST /v0/beads/issues/{id}:heartbeat behind issues.heartbeat
Publishes issueops.Heartbeater on bd serve as heartbeatIssue, the served
lease refresh behind `bd heartbeat`.
- Spec: the operation, HeartbeatIssueRequest {actor} and
HeartbeatIssueResponse {id, holder, heartbeat_at, lease_expires_at,
rearmed}; no `revision` (a refresh writes nothing to the row) and no
expected_version (the fence is the holder and the live claim).
issues.heartbeat joins the capability vocabulary and lease_not_held
(409) the Problem.code list; `reason: ephemeral` qualifies it for a
wisp. apigen and the wire-shape golden are regenerated; the golden diff
is additive only, so wire_revision stays 2.
- Server: route row on the custom-method dispatcher, handleHeartbeat in
heartbeat.go (claim's actor rules via bodyActor, unknown member and
query refusals), Config.Heartbeater as a required role (sourceRoles,
roleSourceNames, the per-request uow.HeartbeaterSource accessor).
failHeartbeat maps *LeaseConflictError typed fields: a foreign holder
is the claim's conflict shape (already_claimed + assignee +
issue_status); no live claim, a wisp included, is the new
lease_not_held (+ issue_status, + reason: ephemeral for a wisp), matched
before the generic arms so ErrLeaseNotHeld's ErrNotClaimable never
surfaces as not_claimable. Its detail names the one state the refusing
transaction found (closed, open and not claimed, an ephemeral wisp, ...).
- bd serve wires the role from its peeled store (serveRoleSource gains
Heartbeater); the serve stub stores, the corpus and e2e harnesses, the
served harness and the encode oracle bind it.
- Wire client vocabulary: OpHeartbeatIssue/issues.heartbeat and
MethodHeartbeat are CLASSIFIED (the capability set-equality gate),
ReasonEphemeral is pinned to the server's, and lease_not_held rebuilds
*LeaseConflictError{Status, Ephemeral} wrapping ErrLeaseNotHeld in the
native words (the code-table set-equality gate). No accessor yet.
Tests: heartbeat_test.go (request mapping and projection, edge refusals,
every role refusal with its code, members and state-specific detail, the
code row, the capability). The served-http Heartbeater leg
(served_heartbeater_test.go, 18 cases) runs the contract against a real
bd serve through a test-local dial over the store's own dispatch, and the
http-leg waivers are deleted.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* feat(http): bd heartbeat over http through httpclient.Heartbeater
The client leg of the served lease refresh, and `bd heartbeat` on the
role for every route.
- httpclient.Store.Heartbeater (heartbeater.go) dials POST
/v0/beads/issues/{id}:heartbeat through Store.dispatch, so
issues.heartbeat is preflighted: an older server is refused BEFORE the
dial with *wire.CapabilityError naming the token (unwraps to
*storage.ErrUnsupported{Capability: "issues.heartbeat"}); it never falls
back to a re-claim or a metadata stamp.
- The role's request rules are restated before the dial
(validateHeartbeatRequest, pinned to
storeops.ValidateHeartbeatRequest): blank/over-long actor, empty id, each
a *HeartbeatFieldError.
- Problem mapping: already_claimed (which the shared table rebuilds as the
claim's ClaimConflictError) becomes *issueops.LeaseConflictError naming
the holder and wrapping ErrAlreadyClaimed, in the native words ("issue
already claimed by <holder>"); lease_not_held already arrives as
LeaseConflictError (Ephemeral from `reason`); not_found is ErrNotFound;
invalid_argument on `actor` is the role's field error.
- Idempotent: true, the one write this client marks replayable (a repeat
only moves the expiry later; a replay after a reclaim fails the fence).
- Legacy Store.HeartbeatIssue rides the role. Both leave the generated
shell and completeness_test's unsupported allowlist.
- `bd heartbeat` takes Heartbeater() from the resolved store on the direct
routes (dolt, embedded, http) and from the provider's HeartbeaterSource
on the proxied route (exact id resolution in a read unit of work, then
the role); runHeartbeatProxiedServer and heartbeat_proxied_server.go are
deleted. Success output and exit codes are unchanged; refusal text
changes per route (see CHANGELOG).
Tests: heartbeater_test.go (stub server: preflight refusal naming the
token with no POST, request/answer projection, each refusal's typed
mapping including the wisp's reason, the 503 replay, pre-dial validation,
validator parity, the legacy door). served_heartbeater_test.go runs the
18-case contract through env.subject.Heartbeater(), with
HookedHeartbeater wired off a HookFiringStore. TestE2E_HeartbeatOverHTTP:
real bd against an in-process serve: holder ok with revision and
updated_at unchanged and a guarded write with the pre-heartbeat revision
landing; a non-holder refused against an aged lease that stays untouched;
closed, wisp and unclaimed refused, each naming its own state; an older
server's handshake refused naming issues.heartbeat with no write. Corpus
shapes gc-heartbeat, -non-holder, -closed, -wisp pending until
reference_server.json advertises the token. CHANGELOG entry for the whole
track, including the orphaned-lease race fix.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* build(bazel): auto-sync BUILD files
Applied from the bazel-sync-patch artifact of https://github.com/gastownhall/beads/actions/runs/38875641041
(`make bazel-sync`: gazelle, tools/bazel/go_srcs.py, bazel mod tidy).
Only BUILD.bazel, MODULE.bazel and MODULE.bazel.lock are ever pushed; see
scripts/bazel-autofix-push.sh.
* fix(heartbeat): roll back a no-issue refusal; restate refresh vs re-arm
Review fixes for #7600 (adopt-pr apply-fixes, iterations 1-2).
Legacy HeartbeatIssue doors commit a refusal only when it read the issue.
The dolt and embedded HeartbeatIssue callbacks committed every
LeaseRenewalRefusal, including Found=false (the issue read failed). That
refusal deletes nothing, but it can follow a fast-path UPDATE that
already extended an orphan lease row's expiry, so committing it kept the
extension. issueops.LeaseRenewalRefusalCommits now gates the commit on
Found, the rule the Heartbeater role's HeartbeatRefusalCommits applies.
New tests on both legs pin both arms: a no-issue orphan's expiry is
unchanged, and a released issue's orphan is deleted.
Refresh vs re-arm contract docs. Comments, Long help, the OpenAPI spec
and the generated apigen still said every heartbeat writes only the
lease row, makes no Dolt commit and fires no hook. A re-arm is recorded
as a mutation: it remints the revision, records an event and a version
entry, commits once (LeaseRearmVersionCommit) and fires on_update
through the wrapping hook decorator. Restated in domain, uow, issueops,
storage.go (why RoleFiresHooks answers true, so bd serve takes the
heartbeater off a peeled store), cmd/bd heartbeat and serve, httpapi,
httpclient, the spec (apigen regenerated), and the conformance and
contract-test docs.
Minor review findings:
- The 409 already_claimed and lease_not_held details now end "nothing
on the issue was written": the refusal may have deleted and committed
the caller's orphan lease row.
- docs/multi-agent/federation.md and the CHANGELOG entry describe the
spelling-mismatch heartbeat: the row is refreshed in place and keeps
granted_at and granted_node; only a re-arm stamps this node. The
embedded spelling test pins both columns, and the lease.go comments
say "refreshed in place" instead of "re-arms".
- The refusal's orphan delete judges the holder under actorMatches, as
the in-place refresh does (iteration 2). It matched holder = ? on the
actor as sent, so a dead claim's orphan held under another spelling
of the caller (gastown.mayor, heartbeat as gastown__mayor) survived
the refusal until TTL. The refused closure now reads the row's holder
and deletes that stored holder only when actorMatches(holder, actor).
Both TestHeartbeatIssueCommitsARefusalOnlyWhenItReadTheIssue twins
gain a cross-spelling arm (row deleted) and a control: another
identity's row (gastown.dog-3) survives.
Not changed: `bd heartbeat --json` still omits `rearmed`, since adding
it changes a CLI JSON contract (follow-up). The federation.md paragraph
post-dates the v1.2.2 docs pin, so documenting this main-only behaviour
there is a maintainer call under
engdocs/decisions/2026-07-17-docs-release-pin.md section 1.
Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(uow): run the scoped re-arm's Dolt commit after the SQL commit
The proxied-server heartbeat commits a re-arm with doltServerTx.CommitScoped,
which ran DOLT_ADD per table and DOLT_COMMIT('-m') INSIDE the open
transaction, before the SQL COMMIT. DOLT_ADD stages whole tables from the
session's transaction root, so that Dolt commit was built from the re-arm's
start snapshot: an issues row another session changed while the re-arm was
open (a write still only in the working set, as in batch mode or before that
writer's own Dolt commit) was staged at its old value, and HEAD disagreed
with the rows every reader sees. This is the LatentLabsSpace/NEXUS#92
ordering the DoltStore funnel (runIssueOperationTxWithMessage) already
avoids, and the review's major finding on this PR.
CommitScoped now commits the SQL transaction first, then stages exactly the
named tables (plus the versioned-history tables) and makes the Dolt commit on
the same pinned connection, the uow twin of doltAddAndCommitPostTx:
- a serialization failure of the SQL COMMIT is still returned, so
RunTxScoped replays the unit of work;
- the Dolt commit runs detached on its own budget and replays only conflicts
that leave nothing behind: serialization failures and Dolt's 1105
"@autocommit transaction rolled back" (new isDoltAutocommitRollbackError,
mirroring the DoltStore classifier of the same name);
- nothing staged, or "nothing to commit", is not an error: a concurrent
writer's Dolt commit already took the row. A "nothing to commit" past the
staged check is logged, as the funnel logs it, so the missing audit line
is explicable;
- any other failure is logged, never returned. The data is committed, and
returning it would make RunTxScoped replay a committed re-arm, which would
then report a refresh. The session is poisoned rather than pooled, since
its state is unknown. uow records no metrics, so that log line is the
drop's only signal; bd.db.post_tx_commit_dropped counts only the funnel's.
Statements go through schema.DrainCall, retiring the local drainCall fork
(review nit).
Tests: five sqlmock tests pin the order (SQL COMMIT before any DOLT_ADD),
the swallow-and-poison path, the 1105 retry, the returned serialization
failure and the empty-commit tolerance; each fails against the previous
CommitScoped. TestIsDoltAutocommitRollbackError carries the DoltStore
classifier's table over to the uow copy, plus the prefix boundary; dropping
the prefix branch, the prefix's period, the 1105 check or the type check
each fails a case. TestHeartbeaterRearmKeepsAConcurrentWrite is the
real-Dolt regression: a change to another issues row made while the
re-arm's transaction is open must be at HEAD after the re-arm's Dolt
commit. Its working-set-only writer fails on the old ordering (dolt
2.1.8); the writer that Dolt-commits its own change passes on both and is
kept as coverage.
Review follow-ups folded in (comments, a file move and a test; the
absorption log line above is the only behaviour change among them):
- the freshRowLock invariant and its row_lock_guard_test.go mirror name the
re-arm as the one deliberate remint without a lifecycle-field change,
load-bearing for the release/close collision;
- httpclient: "a write is never retried" (wire/client.go, stall_retry.go)
and "only a read's answer is yes" (dispatch.go) now allow for the
Idempotent heartbeat, and httpHeartbeater and issueops.HeartbeatResult
document that a replayed heartbeat can report Rearmed false after a
committed re-arm, with the guarded write's revision check as the backstop;
- the proxied route moves back to cmd/bd/heartbeat_proxied_server.go, the
file family cmd/bd/AGENTS.md prescribes;
- the ScopedCommitter and RunTxScoped docs no longer say every other
writer's uncommitted change stays out of the commit: a staged table is
committed whole, so such a change to a named table rides in the re-arm's
commit, as it does in the funnel, and only other tables keep theirs;
- commitStagedTables says its drop is log-only, the absorption is logged,
and the uow classifier gets its table test (see Tests).
Not folded in: the base-owned IssueUseCase.Heartbeat /
IssueSQLRepository.HeartbeatIssue door, dead in production since the
proxied route moved to the Heartbeater role. Its one caller is the
notifying hook-parity test (uow/notifying_test.go), and moving that case
onto the Heartbeater means re-deriving its RenewLease hook semantics, so it
is left for a follow-up.
Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: Eddie the Engineer <338826946+gascity-eddie[bot]@users.noreply.github.com>
* feat(roles): LeaseReclaimer role and POST issues:reclaim (S9)
Adds issueops.LeaseReclaimer.Reclaim(ReclaimRequest{Actor, OlderThan,
Filter}) -> ReclaimResult{Reclaimed []ReclaimedLease{ID, PreviousOwner,
Revision}}, the stale-lease sweep behind `bd reclaim`, on every leg:
- dolt, embedded dolt and the unit-of-work provider all run one body,
internal/storage/issueops.ExecuteReclaimInTx over
ReclaimExpiredLeasesInTx, and record one version commit per sweep that
reverted anything through the issue-operation funnel (so a deferred
version commit on the context is honored);
- each reverted row's fresh row_lock is published as its revision, so a
former holder's guarded write fails with ErrVersionMismatch;
- an id that is not a stale lease (absent, live, unheld) is left out of
Reclaimed, never an error; the id scope is capped at 1000
(*TooManyReclaimIDsError, counted as sent);
- the hook decorator fires on_update once per reverted row (and the
proxied notifying provider records one update per row); telemetry
wraps it like every role.
bd serve publishes it as POST /v0/beads/issues:reclaim behind the new
issues.reclaim capability (httpapi.Config.LeaseReclaimer, required like
every role). Spec, apigen and the wire-shape golden are regenerated;
the change is additive and wire_revision is unchanged. The HTTP client
leg dials it (wire vocabulary, capability preflight, local validation
in the role's order).
Conformance: RunLeaseReclaimer* (12 cases: revert post-state, the
revision race, live lease, grace window, id scope with absent/live ids,
empty answer, assignee/label scopes re-homed from reclaim_scope.go,
recovery event attribution, on_update once per row, refusals, the cap
boundary, no request mutation) wired on dolt, embeddeddolt, uow and the
served http leg, and so held by the leg lock. Handler tests cover the
member mapping, the projection, every handler refusal by name and the
role's refusals reaching the wire.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* feat(bd): bd reclaim runs the LeaseReclaimer role on both routes (S9)
`bd reclaim` takes issueops.LeaseReclaimer off the decorated store on the
direct route (so a connected HTTP workspace dials issues:reclaim instead
of refusing) and off the proxied provider's own accessor on the proxied
route, replacing the raw ReclaimExpiredLeases calls and
runReclaimProxiedServer. Visible changes: --json entries carry the
reverted row's new `revision`, the workspace's on_update hook fires once
per reverted row, and the version commit is the role's own
("bd: reclaim N expired lease(s)", honoring dolt.auto-commit through the
context the way bd prune does).
Tests: an embedded direct-route CLI test (scoped sweep with a live and an
absent id, revision, one version commit, on_update once) and the proxied
reclaim integration test now asserts the revision.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(roles): S9 review LOWs: one validator, field attribution, overflow bound
- The library's ValidateReclaimRequest is the one definition of a valid
reclaim: it now also refuses a blank assignee/label/label-any/exclude
entry, and every refusal but the id cap is a *issueops.ReclaimFieldError
naming its field. The httpapi handler no longer checks blank entries
itself; failReclaimErr names the member the role's error is about
(`ids` for the cap) instead of blaming `ids` for every validation. The
HTTP client's restatement matches, pinned field by field.
- older_than_seconds is refused at >= MaxInt64/1e9: that float rounds to
2^63 ns, which wrapped negative under the old > check.
- New contract case RunLeaseReclaimerRefusesABlankScopeEntry on all four
legs; handler tests for field attribution and the overflow boundary.
- CHANGELOG names the 1000-id cap on bd reclaim --id and is rewrapped; the
client's grace-window precision comment no longer claims exactness.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(roles): S9 review: regenerate the unsupported shell, cgo-tag the embedded contract, one actor spelling
- go generate ./internal/httpclient: the new accessor moves the partial-shell
trailer to 145 of 200.
- lease_reclaimer_contract_test.go gets //go:build cgo like its siblings, so
the pure-Go lane compiles.
- The library trims the actor before attributing, matching the handler, so
" alice " is attributed the same on every route.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(roles): S9 review minors: bound the reclaim actor on every leg, pin any_replica, validate before the uow
Review minors on #7412, each in code this PR adds.
- The reclaim actor lands on every reverted row's recovery event, in a
VARCHAR(255) column, but ValidateReclaimRequest never bounded it: a
256-character actor passed validation on the dolt, embedded-dolt and
unit-of-work legs and failed the sweep with the backend's own
"Error 1105: string '...' is too large for column 'actor'" on the first
row it would have reverted (all three legs answer exactly that with the
bound below removed). The shared validator now holds the trimmed actor to
types.MaxFieldLen, as claimIssueInTx does, so it is a *ReclaimFieldError
for `actor` on every leg. The HTTP client restates the rule, and the parity
test covers both sides of it. bd serve already refused it through the
claim's name rules. The role's Actor and REFUSALS docs name the bound, and
the conformance case runs it on all four legs.
- ValidateReclaimRequest's doc no longer says bd serve's handler leaves every
rule to it: it names the three wire rules the handler adds of its own.
- TestReclaimSendsAnyReplicaOnlyWhenAsked pins the one filter member that
widens a sweep: the client sends any_replica only when the caller set it.
- The unit-of-work leg validates before opening its unit of work, as the dolt
and embedded-dolt legs do; TestLeaseReclaimerRefusesBeforeOpeningAUOW pins
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>
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
* feat(roles): BatchGetter role and issues:batchGet route (S7)
Adds BatchGetter.GetMany(ids) -> {Issues, Missing}, a one-snapshot,
order-preserving, deduped, 1000-id-capped batch read, wired through all
three library legs (dolt, embedded dolt, uow) behind the existing
hook/telemetry decorator chain, plus the POST /v0/beads/issues:batchGet
HTTP route (spec, apigen, wire-shape golden, issues.batchGet capability
token). Conformance contract (RunBatchGetter*, 12 cases) passes on all
three legs against real backends. No HTTP client leg yet (waits on the
generator / PR #7247); left as a documented seam on BatchGetter's doc
comment.
CLI GetIssuesByIDs call sites are left unmigrated this slice and marked
with TODO(batchgetter) comments: every call site reads an unbounded id
list today, and GetMany's 1000-id cap has no chunking/fallback in any
caller yet, so swapping them in now would add a new, unhandled failure
mode to already-shipped CLI paths (export, import, molecule port,
ready-explain, wisp sweep).
Verified via three live-mutate guards against
internal/storage/issueops/batchget.go (disabling the cap check, dropping
the Missing append, and replacing ordered iteration with map iteration):
each turns the embedded-dolt contract red, confirming the cap, Missing
reporting, and order-preservation assertions actually catch a break.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* fix(roles): close S7 review gaps — revision on wire, BUILD sync, handler tests
Addresses the S7 Opus review's FIX-FIRST items on BatchGetter/issues:batchGet:
HIGH
- batchGetResponse now projects apigen.BatchGetIssue (types.BatchGetIssue +
NewBatchGetIssue), carrying `revision` per issue the way IssueDetails does;
spec, apigen and the wire-shape golden regenerated (additive, no
wire_revision bump).
- make bazel-sync: the 12 files missing from BUILD.bazel srcs are back in
sync across 9 BUILD.bazel files.
- New internal/httpapi/batch_get_test.go: success incl. revision, missing
ids, empty arrays not null, unknown member refused, missing/null ids
refused, query parameter refused, 1001 ids refused with the full request
reaching the role, 1000 ids accepted.
MED
- RunBatchGetterAcceptsExactlyTheCap pins the cap boundary (> vs >=).
- RunBatchGetterHydratesLabels pins Labels survive projection.
- RunBatchGetterReadsOneSnapshot renamed to
RunBatchGetterSharesOneReadStructurally with a doc that no longer
overclaims atomicity; a real interleaving test needs a hook on the frozen
roleFixtureKit, out of scope here.
- Doc comments across ExecuteGetMany, GetManyResult.Issues and the
BatchGetter interface now say hydration is labels only.
LOW
- failBatchGetErr's doc no longer claims blank entries are "already caught".
- PR #7247 references kept.
Re-ran build/vet/gofmt/lint, make api-check, make bazel-sync(-check), the
full internal/httpapi suite, and all three conformance legs (dolt via the
pinned local server, embeddeddolt, uow) plus targeted cmd/bd serve tests —
all green. Live-mutate-guard reverified: cap >=, dropping Missing from the
response, and clearing Labels each now fail the relevant test.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* fix(roles): sync client vocabulary and repo gates with issues:batchGet
The S7 route landed on the server without the sibling tables that hold
the rest of the tree set-equal with the server's surface, so five
tests and two manifest gates went red on the PR head:
- httpclient/wire: mirror batchGetIssues into the client vocabulary,
CLASSIFIED, not wired, the way the wire wave and #7250's
issues.count.scope landed: OpBatchGetIssues, its issues.batchGet
token on opCapability, its identity row, and the first-slice skew
dimension 35 -> 36 (TestCapabilityTableMatchesTheServerRouteTable).
- httpclient/wire: BatchGetIssue is the first golden.json schema with
a `revision` member that needs no legacy-integer tolerance — the
route postdates #6053 and types.BatchGetIssue declares Revision a
string, and a pre-#6053 server never advertises issues.batchGet, so
Preflight refuses before any body is decoded. Exempt it with that
reason in a new revisionSchemaExempt table rather than adding an
issues[] rewrite no legacy server can reach; the gate refuses an
entry that is both covered and exempt, a stale exemption, and an
empty reason.
- httpclient/encode: give the oracle's role set a BatchGetter stub —
httpapi.Listen requires the whole set, so all three oracle tests
failed to bind.
- storage/uow: exempt IssueUseCase.GetMany from the notifying-parity
partition as a read, the reason hook_batch_getter.go gives.
- shard manifest: place TestBatchGetterContract in the 15-shard
embedded storage block (generator --write, incremental).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* test(roles): pin the BatchGetter pure tier and the spec ids caps
Review fixes, iteration 1. The review approved with no blocker or major
finding and three minors, and this commit takes all three. It changes
tests and one comment only, and every new assertion was mutation-probed
with go test -overlay.
- storage/issueops: add batchget_test.go, the database-free tier that
FinishGetMany's doc already claimed ("pinned without a database") but
that no test supplied. It pins:
- the cap is checked before the blank scan (an over-cap request with
a blank at position 0 answers *TooManyIDsError);
- the bound is inclusive;
- dedupe keeps the first mention, does not trim, and never writes
through the caller's slice;
- Issues and Missing both follow request order;
- both slices are never nil;
- ExecuteGetMany refuses one id repeated past the cap before any
query (a sqlmock with no expectations).
Ten mutants were each killed by exactly their intended test, with the
rest of the package green: last-mention, sort, trim, in-place dedupe,
blank-before-cap, >=, nil Missing, nil Issues, dedupe-before-validate
and validate-after-query.
- httpapi: TestSpecDefaultsMatchSharedConstants now checks ids.maxItems
against the enforced bound on the two request bodies that carry an
`ids` list: batchGetIssues against issueops.MaxGetManyIDs, and
deleteIssues against maxDeleteIDs. Each body is reached through its
operation's own requestBody $ref. Setting either constant to 999 turns
only this test red. The spec's other list caps (batch
create/close/apply items, dependency edge lists) stay ungated, as
before.
- cmd/bd/serve.go: the batchGetter field comment said its accessor
"does NOT recurse through the hook decorator". HookFiringStore.
BatchGetter does recurse to the inner getter; it just doesn't wrap
the result. The comment now says that.
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 Sonnet 5 <noreply@anthropic.com>
* Add issueops.GraphCounter: how many edges, in one named direction (ga-itny5)
The graph counts are the last read on the storage surface with no role behind
them. `storage.DoltStorage` publishes CountDependents, CountDependencies and
CountDependentsByStatus as three methods that differ only in a direction and a
narrowing, and every one of them is a raw method a front door can call with no
decorator, no probe and no plane story. This is their facade.
ONE METHOD, AND THE DIRECTION IS IN THE REQUEST. The raw seam spells the
direction in the METHOD NAME, which is the one thing a request field can get
wrong, so `EdgeCountRequest.Direction` is REQUIRED and an empty one is
ErrValidation before anything is read — including for a request that names no
ids at all, which is otherwise the empty answer EdgeReader gives. There is no
`both`: the two numbers are over different edge sets, summing them
double-counts an edge between two requested anchors, and a paired answer would
make Status — which narrows by a row only the inbound direction has — govern
half an answer silently. internal/workapi's detail assembly already makes two
calls for the pair today, so nothing pays a round trip it was not paying.
STATUS IS INBOUND-ONLY AND SAYS SO RATHER THAN BEING IGNORED. Narrowing by
status means joining the far end of an edge to the row holding its status, and
an OUTBOUND edge's far end may be a row this database does not hold — an
"external:" reference or a foreign-repository id, both of which
DependencyEditor accepts. A status filter there would silently drop every
dangling edge, which is the class of edge EdgeReader exists to return verbatim.
The raw seam has the same asymmetry: CountDependentsByStatus exists and
CountDependenciesByStatus does not.
A MISSING ANCHOR IS A FLAG, NOT ErrNotFound. 0 is the common answer — most
issues have no edges in at least one direction — so an id typo would never
surface, and a batch that failed on one absent id would discard the answers for
the ids that were found. That is EdgeReader's rule, and it is what forces the
existence probe and the tally into ONE transaction.
WHAT IS EXCLUDED, since the never-append rule makes each one a decision. The
COMMENT count is genuinely consumed — `bd show` prints it beside the two edge
counts — and is still out: a comment has no direction, no type and no far end,
so every field of the request below IDs would be meaningless to it. CountEvents
has no caller in the tree at all and follows the journal. GetDependencyCounts
is expressible as two calls with Types set to the blocking type, and naming it
as a method would have added a map-shaped answer no wire operation can carry.
THREE LEGS, ONE BODY. All three reach issueops.ExecuteEdgeCount — the two
stores wrap it in their own read transaction, the unit of work reaches it
through the domain repository, whose runner publishes exactly the DBTX method
set — so the contract header says one reading plus two engine checks and three
wrapper checks, not "three backends agree". Validation moved INSIDE that body
for the same reason: with one body there is no second implementation for a
per-leg check to belong to.
FACADE ONLY. No HTTP operation: the wire half follows in the graph-counts wire
slice per the program's council gating. No `bd` command either, and that is the
larger of the two decisions — the numbers are printed today through
internal/workapi's detail seam, which an HTTP handler shares, so moving it is a
change with its own parity argument. Both absences are written into the leaf
doc beside the promises, as VersionReconciler writes down its absent HTTP half
and BatchApplier its absent CLI.
Contract: 14 cases, wired on all three legs. Mutation-checked — a constant
count reddens 7 including both per-direction cases, ignoring the direction
reddens the 4 inbound ones, and dropping the ephemeral plane reddens the 2
cross-plane ones. The pure halves (the request vocabulary, the missing-anchor
rule, the SQL shape) are pinned without a database beside the body.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Review: reattach the Importer note, cite the collision, size the id list
Three corrections, none behavioral.
The four-line note about Importer's uow-only accessor was left stranded above
the GraphCounter row by this slice's insertion, where it asserted three things
that are false of it: GraphCounter IS a storage.DoltStorage accessor, a
store-built backend CAN fill its field, and importer_contract.go's header says
nothing about it. Moved back onto the row it describes.
"Nothing in this contract's reach can produce one" reads too easily as "it
cannot happen". A cross-table id collision is real and constructed:
TestDependentRecordsCrossTableCollision seeds one logical edge into both
dependency tables and names the two production paths that make them — a wisp
promoted to durable, and two Dolt clones merged. The leaf now cites it and says
what this role promises against it (the sum) versus what
CountDependentRecords' question is (the distinct total).
And EdgeCountRequest.IDs says out loud that it carries no size cap, which
EdgeReadRequest.IDs also does not: the bound belongs to the wire operation,
where the request arrives from somewhere else and the cost of an unbounded one
is a stranger's. ApplyBatchRequest.Items makes the same split explicitly.
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>
* 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>
* Add issueops.BatchApplier: one plan, one transaction
A heterogeneous, ORDERED list of creates, updates, closes and edges applied
as one durable act. Each of BatchCreator, BatchCloser and DependencyEditor is
one verb repeated, so a caller that needs two of them needs two transactions
with a window in between; this role's unit is a PLAN.
The role, the two bodies, both decorators and the accessors on every
implementer. The wire half and the conformance contract land beside this.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Close the empty-commit-message hole a no-op batch could open
ApplyBatchCommitMessage now reads the write as well as the result. The counts
are ItemResult.Changed, which is what a CALLER observes; a request can still
write a durable row with every count at zero — a same-type edge re-add
rewrites that edge row's metadata, a re-close can settle blocked state. An
empty message for one of those is an unlabelled Dolt commit on the store legs
and a rollback of a real write on the unit-of-work leg.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Give BatchApplier the contract its two bodies justify
Thirty-nine cases over three legs and TWO independent bodies — the store legs
share issueops.ApplyBatchInTx, the unit-of-work leg cannot reach it, and the
contract header says so rather than claiming three backends agree.
The end-gate case is the one that could not have been written before: every
edge in it is legal when it is written, and only a re-validation against the
closure the whole request produced refuses the pair.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Publish batchApply on v0, and delete batchCreate's false promise
The spec first, the types from it, the handler against the types. The item
union is a TAGGED single-shape object rather than a oneOf, because the
document's x-go-type doctrine forbids composition keywords; the create item
publishes sender, metadata, status, ephemeral and no_history, none of which
batchCreateIssues has — which is why no measured caller could use that one.
The wire result stays lean: ids, changed and a revision. The hydrated
snapshot on the Go contract is what the completion hooks consume, and hooks
never fire on this surface.
OQ2: batchCreateIssues' description claimed a dependency target could name an
earlier item of the same batch. It never could — the server mints the ids and
a wire item has no name — so the paragraph is deleted rather than qualified.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Partition the two new dependency probes on the recorder's surface
The gate halves BatchApplier re-runs are repository PROBES — an ancestry walk
and a reachability walk — so recordingDepUC declares neither and the parity
test has to say so out loud rather than let embedding answer for it.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Teach the proxied topology's capability golden about batchApply
The one expectation stored as data outside the package whose gates would
otherwise have caught it — which is what its own header warns about.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Restore the CAS hook case, mint 409 already_exists, and stop over-claiming
Three fixes from review.
The rebase that brought MetadataCAS in left `case *hookMetadataCAS:` with an
EMPTY BODY: a Go type switch does not fall through, so RoleFiresHooks answered
FALSE for it and #5473's Listen refusal was silently disarmed. The compiler,
vet, lint and CI all pass on that. The case is restored and — because it had no
precondition of its own, which is why nothing caught it — serve_source_test now
pins CAS the way it pins the other four, with its peel assertion.
An occupied explicit create id becomes 409 already_exists rather than 400. The
body is well-formed and stays well-formed; what refuses it is state the client
must READ, and recovery is to look at that state. A dead 409 retires for free
where a narrowed 400 breaks clients.
Two headers claimed all three legs share the store body — every clause false,
one citing the contract header as agreeing when it says the opposite — and the
plan file gave a placement reason that is MetadataCAS's, not this role's. The
end-gate claim in ADDING_AN_ISSUEOPS_ROLE.md is narrowed to the true thing: the
two LEAF checks are shared, the orchestration around them forks.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Give the scheduling-edge set one definition, in types
Four packages walked {blocks, conditional-blocks, parent-child} under four
names — isSchedulingEdge, isSchedulingDep, isSchedulingDependency, and the
isApplySchedulingEdge this branch added as the fourth. Adding a fifth
scheduling type was four edits with nothing to catch a missed one.
It goes in internal/types rather than the issueops leaf the review named,
because internal/storage/issueops imports internal/storage/domain, so domain
cannot import back and two of the four copies would have survived there. Beside
the Dep* constants themselves, every walker reaches it: nine call sites, one
definition, one edit for a fifth type.
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>
* Add issueops.MetadataCAS: compare-and-set over one metadata key
The one coordination primitive missing at every layer. Everything the
metadata plane holds is written through Lifecycle.Update, which has no way
to say "only if", so every caller that needs a guarded write composes a
transaction, a read and an update by hand — and each one has to get the
composition right. Gas City emulates it client-side with RunInTransaction +
GetIssue + UpdateIssue for exactly that reason, and the comment it left
behind names the gap: "the upstream storage layer exposes no
conditional-UPDATE ... WHERE primitive".
The role is a state transition stated as a pair. Expected is the key's value
before, Value is its value after, and nil on either side means the key is
ABSENT there: a conditional create is (nil -> value), a conditional delete
is (value -> nil), and a caller that can take a lease can return it to the
state its own acquire tests for. Equality is canonical, so a caller cannot
lose a swap to its own formatter; numbers compare as their source literal,
because decoding through float64 equates two int64s past 2^53 and that is
the silent false match a compare-and-set exists to prevent.
A MISMATCH IS AN ANSWER, not an error: Swapped false, Current carrying the
value that refused it, nil error. That is the one place this diverges from
PROPOSAL-cas-conditional-update.md, which specifies a typed error and a loud
non-zero exit for the assignee/status guards. Its argument is a CLI one — a
swallowed refusal in a shell script is the bug class it was written for —
and a non-zero exit is the front door's enforcement, which the HTTP handler
here still owes and pays. The role's designed caller is a retry loop, for
which a lost race is the ordinary path, and an error cannot hand back
Current without a bespoke type every caller must errors.As before it can
read the one field it needs.
All three legs share one body (internal/storage/issueops), so this is one
reading plus two wrapper checks rather than three backends agreeing. The
wrapper check earned its keep: the unit-of-work leg rolled an ephemeral swap
back, because the shared body reported "no durable tables changed" and that
leg's commit message is what commits the SQL transaction as well as what
versions it. MetadataCASWrite now carries the two facts separately.
The HTTP half lands with the role per the 2026-08-05 scope decision:
POST /v0/beads/issues/{id}:casMetadata, spec first. A lost race is a 200
carrying swapped:false, so the operation has no conflict code; an omitted
`expected`/`value` member means absent and a member holding null is a value,
which is why the handler reads raw members.
No bd command yet: the primary consumer is an embedder, and a CLI front door
is additive. No .golangci.yml entry, for the reason memoryops gives — the
body is an …InTx function no front door can reach.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Review: read Current from the row, and let a client read a present null
Two shape fixes, both of which would have been expensive to change after
anyone depended on them.
A *json.RawMessage wire member cannot READ a present null: encoding/json
nils the pointer before UnmarshalJSON runs, so a generated client decoding
{"swapped":false,"current":null} gets the same value it gets for an omitted
member — and on this operation those mean opposite things. A retry loop
against a null-valued key would read "absent", swap with expected omitted,
mismatch, and livelock on a stream of 200s. x-go-type-skip-optional-pointer
makes the member a bare json.RawMessage, which is an Unmarshaler and
receives the literal; the wire is unchanged in both directions, which is
exactly why nothing else catches the regression, so the decode is now
pinned. nullable: true beside it, for the validating gateway in front of
somebody's server.
The number rule was defended in three places as protecting int64s past 2^53
from a float64 round-trip. It protects nothing: the metadata column decodes
through float64 itself — measured, 9007199254740993 stores as ...992, 1.0 as
1, -0.0 as 0, 1e300 as three hundred and one digits. The false justification
is gone from all three sites and replaced with what the probe actually
showed, plus the guidance it implies: compose an Expected from a previous
Current, and prefer a string for a coordination token.
That guidance was not true yet, because Current was the REQUEST's bytes
rather than the row's — so "what you get is what a later read sees" was
false, and a loop feeding Current back compared its own spelling against the
substrate's forever. Current is now re-read inside the deciding transaction
on every path. One extra SELECT, one statable invariant.
Three contract cases, each watched to fail: Current is the column's bytes
and a Current-driven loop converges (mutant: answer from the plan);
the history entry names the request's actor, counted per actor because
created_at is second-granularity and an ORDER BY decided this case on a coin
toss when it was first written (mutant: stamp a constant); a wisp swap
writes no durable event row, which two layers had been holding by
coincidence with nothing asserting either.
Also: the serializer-omits-null footgun in the spec (an absent `value` is a
DELETE, and Jackson/Pydantic/omitempty all omit nulls by default),
canonicalizeForContract's own float64 blind spot named in the coverage
paragraph, and the leaf now says corrupt stored metadata is an untyped error
— a 500 — because the request was well formed and the issue exists.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Close the three capability holes CI found, and one my sweep could not
All three are the same shape: a surface that loses the new role silently,
and none of them is reachable from the package tests I ran locally.
internal/storage/uow's notifying wrapper is the important one. Its
recordingIssueUC inherited CompareAndSetMetadataKey from the embedded use
case, so a swap through a notifying unit of work recorded nothing and the
hook the DoltStorage chain fires for the same write was lost. Its
notifyingProvider did not answer MetadataCAS at all, so a caller's type
assertion simply stopped matching and the wrapper dropped the capability
along with its hooks. Both are now declared, and the recorder reads the
use case's own "a row write landed" rather than inferring it from the
request — which is strictly better than what the hook decorator can do, and
snapshots anyPlane because this role resolves a wisp id itself.
cmd/bd's serveIdentityStore is the second stub store to nil-panic on the
promoted accessor, after serveRolesStore in the same commit. And
serve_proxied_integration_test.go carries a SECOND hardcoded capabilities
golden, whose own comment says two literals that must match are one literal
— it was right, and it was still missed.
My local sweep ran the metadata-cas contract on all three legs but not the
whole internal/storage/uow package, which takes nine minutes; that is where
the parity guards live. Ran it whole this time.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* docs: name the step with no number — the surfaces that EMBED
A new accessor arrives on every embedder promoted rather than declared, so
the build stays green and the first symptom is a nil dereference in somebody
else's stub. Four such places caught this role after its own slice was
green: RoleFiresHooks, both halves of uow's notifying wrapper, and two
cmd/bd stub stores. Grep for the embed, not for the interface — and run
internal/storage/uow whole, because the parity guards live there and the
package takes nine minutes.
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>
The memory commands get the treatment the sixteen issue commands got in #5378:
a role interface in a leaf package, conformance-tested at all three backends,
with the CLI routes and the HTTP handlers as thin callers over one
implementation.
memoryops is its own namespace rather than an addition to issueops. The two
planes share a config table and nothing else; a memory whose key shadows a
settings name is still a memory, and that separation is now the role's,
pinned by its contract, rather than a filter each caller reapplies.
Closes an unauthenticated disclosure found on the way: memory content was
served in cleartext on GET /v0/beads/config, and reachable through two more
doors — `bd config show` and `bd info --json`, the latter republished into
agent transcripts by MCP get_schema_info. Enumeration is now filtered at the
shared seam (workapi.FilterSettingsEnumeration); `bd config show` is left
alone deliberately, since an operator asks for it by name.
Two wire contracts were settled after the review council, recorded in full on
the PR: the search parameter is spelled `search` rather than `q`, because
issues:query already publishes `q` as a boolean expression and one surface
must not spell two questions one name; and getMemory keeps its 404, because
the status reports the distinction the front door already reports and
`bd recall` exits 1 on a miss where `bd config get` exits 0.
Ten agents over 216 files, one directory-balanced group each, working to a
rubric that named what to cut (duplication narration, restatement of the next
line, the governing rule echoed in every command file, throat-clearing) and
what to keep (traps, invariants, security, tracker ids, behaviour changes, and
the "why a naive simplification destroys this assertion" rationale).
Net 1,523 lines. Density against this repo's own per-directory norm on main:
cmd/bd 33.6% -> 27.3% (main 10.7%)
internal/storage 26.1% -> 23.1% (main 14.1%)
backend/conformance 34.0% -> 29.6% (main 22.8%)
internal/httpapi 30.9% -> 27.8% (main 30.6%, now below)
overall 34.7% -> 31.6%
Every agent landed at 18-25% rather than the 30% asked for, and every one gave
the same reason independently: what remained was on the keep list. Ten separate
judgements agreeing is the most useful result here — the prose is dense, but it
is mostly load-bearing, and the shortfall is the honest answer rather than a
failure to try.
TWO REVERTS, both to protect something worth more than the lines.
issueops/ is back to its pre-trim state, giving up 610 lines. The conformance
contracts cite the leaf docs BY LINE — "pins treewalker.go:52-66" — 155 times.
Trimming the cited files silently repointed those at whatever text moved into
those numbers, across agent boundaries so no agent could see it. A semantic
remapper recovered 141 of them, but 23 needed judgement and several landed on
struct fields. The leaf docs are the spec the contracts are written against;
they are the one place in this change where dense prose IS the deliverable, and
keeping them stable is worth more than the 610 lines. tree_walker_contract.go
and version_reconciler_contract.go went back for the same reason: an agent had
deleted a paragraph containing a citation, so positional restoration could not
align them.
After the reverts, exactly 5 citations point into a still-trimmed file and 2 of
those are weak — both in cmd/bd/config_guard_test.go, which this series never
touched and whose citations were already wrong on main (init.go:361 pointed at
a closing brace; the guard it names is at init.go:1499).
VERIFICATION. A guard strips every comment and all whitespace from each of the
193 modified files at HEAD and in the worktree and requires the two to be
byte-identical, so a code change cannot hide in a comment diff. It handles `//`
inside string and raw-string literals, and was tested against a deliberate code
change before being trusted. gofmt clean, go build, go vet, golangci-lint 0
issues, and the two AST-based tests that PARSE trimmed files — the timed
provider binding pin over claim.go and the serve database-source gate over
serve.go — both pass.
One real defect found while trimming: checkDatabaseSource's doc block ran into
`// sourceRoles is ...` with no blank line, so godoc attached thirty-one lines
of the wrong prose to func sourceRoles and left checkDatabaseSource
undocumented. Fixed by separating them.
`bd dep tree` had two implementations of one walk. The direct route resolved a
partial id, opened a prefix-routed store and called store.GetDependencyTree; the
proxied route took the id verbatim, opened a unit of work and called the use
case. Each then carried its own copy of the `both`-direction merge, the status
prune, the mermaid and human rendering and the empty-tree wording. The copies
agreed, which is the only reason nobody noticed that a `both` walk was two
independent reads with nothing spanning them. Both now build one
issueops.WalkTreeRequest and ask for the role.
THE ROLE, and both its neighbours said in advance why it had to be one.
Relations and EdgeReader each exclude the tree in the same words -- "a recursive
walk has a depth, a cycle policy and a node shape of its own" -- and all three
are on this contract: MaxDepth, the first-visit rule, TreeNode. It is not
CycleDetector either: a cycle has NO anchor and a tree is nothing but its
anchor, and the two disagree about what an edge is -- this walk follows every
type except `relates-to`, the cycle report follows `blocks` and
`conditional-blocks` only -- so one workspace can honestly have no cycles and a
tree that revisits a node.
ONE BODY, THREE LEGS, AND THAT IS ONE VOTE. Unlike every other role in
backend/conformance, all three implementations reach the same function: the two
stores wrap issueops.WalkDependencyTreeInTx in five lines around their own
transaction and the unit of work reaches it through a new domain repository
method. So TestTreeWalkerContract x 3 is one reading of the walk plus an engine
check, not three backends agreeing, and the contract file says so at the top.
What the legs still buy is the WRAPPERS, which is where every measured drift in
this graph family has actually lived -- so the refusals assert SENTINELS rather
than message text and the cap case asserts the typed error's fields. The parts
that decide what the answer MEANS are pure (ValidateWalkTreeRequest,
PruneTreeByStatus, MergeBidirectionalTree) and are pinned without a database.
TWO USER-VISIBLE CHANGES ON THE PROXIED ROUTE, both in the owner's Q11 set, both
in CHANGELOG.md.
PARTIAL IDS RESOLVE. `bd dep tree a1b2` worked on a direct workspace and
failed on a team server, because this route passed the argument to storage
verbatim. It resolves in its own short-lived read unit of work before the role
is asked for anything, so a lookup that finds nothing reports the lookup
failure rather than a provider that cannot offer a surface.
--max-rows IS HONORED. It used to be refused outright ("not supported in
proxied-server mode") because the unit-of-work path threaded no cap. The cap
is on the role's request now, so the shared body enforces it for all three
backends and the flag means the same thing wherever the command runs. It is
still POST-HOC -- a tree walk has no query filter to thread a cap through --
and both the leaf doc and --help say so. The shared --max-rows help text
forked for this (addRoutedMaxRowsFlag): the proxied-server refusal is still
true for the eight other commands that take the flag.
A DEFECT FIX NOT ON THAT LIST, recorded as AMBIGUITIES.md A-twk-1: a `both` walk
now sees ONE database state on every route, where it used to be two
unsynchronised reads that could show half an edit.
Q7 IS OBEYED. --show-all-paths stays a no-op -- accepted, ignored, and now
DOCUMENTED as ignored -- and TreeNode.Truncated stays always-false for the same
reason. The one-visit rule that makes both dead is now a stated promise
(TreeResult.Nodes) and a conformance case (RendersASharedSubtreeOnce), so
implementing either as a side effect of a later refactor fails a test instead of
shipping.
CONFORMANCE. backend/conformance/tree_walker_contract.go holds fifteen cases
citing the leaf doc by line, run at all three implementations with ZERO parks:
45 subtests green. Seeding a cycle takes raw SQL for the reason the
cycle-detector contract records -- no supported write creates one -- so that one
case uses the fixture's Exec hook.
HTTP. GET /v0/beads/dependencies/tree, spec first and the types generated
against it. TreeNode is x-go-type-pinned to internal/types, so `bd dep tree
--json` and the response body are one compatibility domain, and
DependencyTreePage's Items are pinned in pinning.go -- the trap wave 2 fell into
with DependencyEdges (bd-5o3gt), not repeated here. A root that names nothing is
a 404, which is the difference from GET /v0/beads/dependencies: one anchor
leaves no other answer to preserve. No max_rows on the wire; the cap is a CLI
circuit breaker. `capabilities` gains dependencies.tree, and TreeWalker becomes
a required field of the store-shaped httpapi.Config, which costs the in-tree
tests a line each and no shipped caller anything (bd serve builds a provider).
NOT TOUCHED: the legacy DetectCycles seam bd-5g4f2 is about. This walk reads
GetDependencyTreeInTx and never AppendBlockingGraphInTx, so the two-cycle-answers
problem is exactly where it was.
Verified: build, vet, gofmt clean; golangci-lint 0 issues; make api-check green;
TestTreeWalkerContract 15/15 at dolt, embeddeddolt and uow; internal/httpapi 0
failures including the eight new tree-route cases; the pure tree_walk tests
green; TestEmbeddedMaxRowsNonListPaths green (DepTreeMaxRows still exits 2);
BEADS_TEST_PROXIED_SERVER=1 TestProxiedServerDep2 green including the four new
Tree cases; TestProxiedLookup* green; TestCorpusGolden green.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
`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>
THE TWO ROUTES DISAGREED ABOUT WHAT --force MEANS on a destructive command.
On a local database `--force` deletes the named beads and orphans their
dependents; on a team server it deleted the whole dependent subtree, `--cascade`
was REFUSED outright ("not supported in proxied-server mode (delete always
cascades)") and Cascade was hardcoded true at both call sites. So there was no
way to delete one bead on a team server without taking everything under it, and
asking for the safer behaviour was an error.
Q1 ANSWERED IN THE ROLE. issueops.Deleter has one method, reached through
store.Deleter() and the provider's own accessor, and the three modes are request
fields: no flags refuses over a dependent the request did not name, Force
orphans it, Cascade deletes the closure. The guard is workapi's and the body's,
below every front door, for the reason Sweeper's require-a-filter gate is: a
second front door that inherited the capability without the guard would orphan a
workspace's graph by omission — which is exactly what this commit's HTTP
operation would otherwise have been.
IT IS A DIFFERENT ROLE FROM Sweeper, not a mode of it. Sweeper erases a set the
caller DESCRIBED; this erases rows the caller NAMED. That is what decides where
each one's safety lives: a description can be accidentally too wide, so Sweeper
carries a require-a-filter refusal; a list of ids cannot be, so this one's guard
is about the graph.
THE DEFECT. The direct route's batch path deleted the rows in one transaction
and then rewrote `[deleted:ID]` into the neighbours' text afterwards, discarding
every update error. A failure in the window left a workspace whose beads were
gone and whose descriptions still cited them by id. The existence probe, the
guard, the cascade expansion, the deletion and the rewrite are now one
transaction. WHAT THAT COSTS is written into the leaf beside the promise: the
transaction is as large as the deletion plus its neighbourhood, so a batch with
a very large neighbourhood fails whole. It is NOT Sweeper's trade (bd-hysee) —
the delete itself was already one transaction on every route — and the part that
is new is named rather than measured, which is recorded for sign-off.
TWO MORE DEFECTS the single call site removed. The one-id path held its own
transaction that removed each edge by hand, so it never reported labels, events
or orphans; and `domain.DeleteIssuesParams.EnforceCascadePolicy` and `.Force`
were declared, documented in fifteen lines describing exactly these three modes,
and READ BY NOTHING. They are deleted; the policy lives in the role now.
THE CONTRACT IS WHAT WAS DELETED, not what was reported.
backend/conformance/deleter_contract.go holds eleven cases, each citing the leaf
doc, run at all three backends with ZERO PARKS and zero divergences. Every case
that acts asserts row counts through QueryScalar rather than trusting the result
the delete reported about itself. They are TWO INDEPENDENT BODIES plus an engine
check: dolt and embeddeddolt share internal/storage/issueops.DeleteInTx and
differ only in how they reach a transaction, and the unit-of-work provider
reaches the same questions through the domain use cases. It does NOT duplicate
backend/conformance/audit_issue-lifecycle.go, which stays the right home for
`DeleteIssues` at the STORAGE seam: that suite's Factory hands back a bare
storage.DoltStorage, so the unit-of-work backend — where the guard did not exist
at all before this commit — can never run a case placed there.
`bd serve` gains POST /v0/beads/issues:delete, spec first. The dependents guard,
the all-or-nothing id resolution and the reference rewrite are the role's, so
the handler is argument validation and a projection. `cascade` and `force`
default false, which is the guarded mode; DeleteIssuesResult is not
x-go-type-pinned for the reason SweepResult is not, and a reflection test keeps
the projection honest. No page envelope, so nothing to pin in pinning.go.
USER-VISIBLE, and the CHANGELOG says so loudly: a team-server script relying on
the implicit cascade starts leaving orphans; `bd delete <one-id>` without
--force now refuses over an outside dependent, converging the direct route's
three paths onto the answer two of them already gave; the proxied `--json`
result gains `orphaned_issues`. Reasoning and the alternatives are in
/data/tmp/sd-server/AMBIGUITIES.md as A-del-1..6.
Verified: build, vet, gofmt clean; golangci-lint 0 issues; make api-check
(regenerate-and-diff plus the httpapi suite) green; TestDeleterContract 11/11 at
dolt, embeddeddolt and uow; the internal/workapi delete unit tests; the
internal/storage, internal/telemetry and root layering pins;
TestConformance/Audit/issue-lifecycle and the dolt TestDeleteIssues* family
(this commit refactors DeleteIssuesInTx's guard); TestEmbeddedDelete,
TestEmbeddedDeleteJSONDependencyErrorContract, TestBurnWisps,
TestWispGCProtectsActiveWisps and TestCLI_WispGCExcludeType under
BEADS_TEST_EMBEDDED_DOLT=1; TestProxiedServerDelete{,ForceOrphans,Wisp,
Concurrent}, TestProxiedServerMolBurn and TestProxiedServerWispGC under
BEADS_TEST_PROXIED_SERVER=1; and TestProxiedLookup*.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
STAGE TWO OF TWO. Stage 1 (aa10a725e) added MaxRows and SkipCounts to
ListRequest and flipped no routes; this is the flip, plus the one role the
decoration needed.
TWO PARTS, and the role first because the flip needs it.
THE ROLE. `issueops.BlockingAnnotator` answers the decoration a listing prints
beside each row — `(parent: X, blocked by: Y, blocks: Z)` — for the ids of a
page that has already been chosen. It is its own role rather than EdgeReader
growth (Q12 asked and answered two), and the distance between them is larger
than it looks: EdgeReader returns STORED ROWS of every type with targets
spelled as stored, no status consulted, and a per-anchor Missing flag from an
existence probe; this one returns a DERIVED summary of two types with closed
blockers dropped, the inbound direction included, and NO existence probe at
all. It is not Reader growth either — it has no order of its own, nothing it
returns depends on how the page was chosen, and a ListRequest field would have
implied the annotation was part of the query.
THERE IS NO MISSING FLAG, and that is a decision the leaf states rather than an
omission: an id that names nothing and an id with no live blocking edges
decorate identically, so a probe would be a read whose answer no caller can
use. One conformance case asserts that ABSENCE of a distinction.
A BLOCKER THIS DATABASE HOLDS NO ROW FOR COUNTS AS OPEN — an `external:`
reference, a foreign-repository id, a row whose issue was deleted. An
unreadable status is not `closed`, and a listing that hid a blocker it could
not resolve would report work as unblocked on the strength of a row it never
found. Both implementations already did this; it now has a sentence and a case.
THE ORDER WITHIN EACH LIST IS NOW PINNED, ascending with repeats collapsed, and
this is the commit's ONE user-visible change. Both lists are joined into one
line of output, so the query's natural order was user-visible bytes that could
move between runs. It affects only rows with two or more live blockers, and it
is recorded as A-blk-2.
TWO BODIES, NOT THREE. dolt and embeddeddolt share
storage/issueops.ExecuteBlockingAnnotation inside their own read transaction;
the unit-of-work provider is the genuinely separate one — it reads BOTH
dependency tiers for every id and merges, where the store side partitions the
ids by plane, and it resolves statuses only for the ids a row mentioned.
FinishBlockingAnnotation is what makes the SHAPE of the answer one decision
rather than two. Seventeen cases, three wirings, ZERO PARKS.
THE HTTP HALF. GET /v0/beads/dependencies/blocking, spec first, `make api-gen`
after. `IssueBlocking` is x-go-type-pinned to the role package the way `Cycle`
and `CycleMember` are, and BOTH the schema and the envelope's Items are pinned
in internal/httpapi/pinning.go — the v2.6.0 allOf trap was checked (the
generated type is a bare alias) and bd-5o3gt did not become two. The size bound
is maxDependencyAnchors, SHARED with the stored-edge read rather than given a
constant of its own: the two operations are asked about the same page of ids,
and two numbers would let a client ask one about a page the other refuses.
`dependencies.blocking` joins the capability vocabulary; `checkDatabaseSource`
grows a required role, which is the edit that reaches code this commit did not
write.
THE FLIP, one mode at a time and named as such in the code. FIRST `--json`:
the role's List runs the same LoadStoreListConfig, the same BuildListFilter and
the same workapi.FinishPage the branch ran longhand, so the page is unchanged
bytes and ErrTooManyRows still reaches handleMaxRowsError for exit 2. SECOND
every text rendering, with SkipCounts set — stage 1 added that field for this
arrival, and without it the flip would trade a plain scan for three aggregate
joins on the most-run command in the tree. THIRD the decoration.
WHAT STAYS OFF THE ROLE is --watch and the hierarchical --parent tree, the two
modes that consume the FILTER as a value. The bead also named --deps and
--format, and its stated reason — "reach no epilogue on either route" — is
false for both: they run FinishPage and printTruncationHint today. What is
genuinely off-role in those two is the WHOLE-GRAPH dependency-record load they
perform, which is neither a page nor the blocking decoration; their page comes
from the role like every other mode's. Recorded as A-blk-3 with the reading
this commit proceeded under, which is also the reading stage 1's own message
states ("stage 2 moves bd list's TEXT path onto the role").
The proxied route loses `runListProxiedReady`: --ready is ListRequest.ReadyFlag
and picking the ready query from it is the role's job on both routes. Two
functions differing only in which use-case method they called is the drift this
replaces.
PROVABLY INERT AT THE CLI, measured rather than argued: 31 `bd list` / `bd
children` invocations — every output mode, both cap knobs, --ready, --parent,
--format, --deps — run against a binary built from integration/facade-wave-3
and one built from this commit, over ONE shared workspace, differ on exactly
the two multi-blocker lines A-blk-2 predicts and nothing else in 687 lines. A
base-against-base run isolates the one other moving line as the
once-per-period install tip.
The forbidigo exception list did NOT shrink, and the count in
issueops/reader.go's claim is unchanged. cmd/bd/list.go and
list_proxied_server.go were never on it; cmd/bd/list_show_filter_modes.go still
is, because the tree walk, the watch loop, the proxied builder call and `bd
show --current` all still name the type. Said in the config rather than implied
by silence.
Verified: build, vet, gofmt clean; golangci-lint 0 issues; the seventeen new
cases at dolt, embeddeddolt (BEADS_TEST_EMBEDDED_DOLT=1) and uow, all green
with no skips; internal/httpapi and make api-check; internal/storage,
internal/telemetry, internal/jira, internal/workapi/..., issueops and the root
layering pins; the embedded `bd list`/`bd children`/max-rows CLI suites,
TestProxiedServerList under BEADS_TEST_PROXIED_SERVER=1 (58 subtests including
tree_parent, the three format modes, ready pagination and the three max-rows
refusals), TestProxiedLookup*, and the protocol corpus package.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
`bd create --file plan.md` had two implementations of one bulk create. The
direct route built types.Issue values in cmd/bd/markdown.go and handed them to
store.CreateIssues; the proxied route parsed the same templates again, opened a
unit of work, read a create context, checked the types itself and looped the
domain use case. Both now build ONE issueops.CreateBatchRequest from one shared
projection, and the difference between the two routes is which accessor answers.
THE ROLE. A batch's REQUEST is its transaction boundary, which is the same
reason BatchCloser exists and cannot be a loop over Lifecycle.Close: N creates
one call at a time are N transactions and N history entries, and the caller who
wants them to land together has no way to say so. It is its own role rather than
a Create overload because it is ALL OR NOTHING where the batch close keeps its
survivors, and one method cannot make both promises. The difference is what has
already happened: a close records work that is done, so a rollback destroys
information the batch was carrying; a create makes the work, so a refused item
leaves no survivors, and half a created plan cannot be re-run without
duplicating the half that landed.
It is born with Provenance, which CreateRequest does not have. Both --file
routes have always written `bd: create N issue(s) from <path>`, and a label
composed from the result cannot spell a file the result does not carry, so
without the field this commit would have caused the regression Q16 recorded
rather than inherited it.
USER-VISIBLE, and bigger than the bead described. The bead and the Q11 batch say
direct --file is non-atomic today - "a bad row can leave earlier rows created".
Reading the path does not support it: markdown.go built every issue first and
made ONE store.CreateIssues call, which both stores run in a single SQL
transaction. What was true is worse, and is recorded as Q25/Q26 in
AMBIGUITIES.md with A-bcr-2:
- a dependency naming an id that does not exist was SILENTLY DROPPED on the
direct route (the batch engine skips a dangling edge and nothing passed
OnSkippedDependency), while the proxied route already failed on it. Every
requested edge is now written or the batch refuses. An `external:` target
and an id belonging to another repository are still written, exactly as
`bd dep add` accepts them.
- --ephemeral, --no-history, --mol-type and --validate were accepted and
IGNORED on the direct route while the proxied route acted on all four, so
`--file --ephemeral` created durable issues locally and wisps on a team
server. All four now mean what they mean everywhere else, templates are
linted on both routes, and created_by/owner are set as the single-issue
create sets them.
- --file --json emits the stored post-create rows on both routes. Additive.
- proxied --file loses its config.yaml fallback for types.custom, the
convergence Q17 already recorded for single-issue create.
--graph is untouched, per Q10: an upsert over a declared shape is a different
contract and gets its own role when it gets one.
CONFORMANCE. backend/conformance/batch_creator_contract.go holds nine cases,
each citing the leaf doc by line, run at all three implementations with ZERO
parks: 27 subtests green. They are TWO independent bodies plus an engine check,
not three - dolt and embeddeddolt share issueops.ExecuteCreateBatch, which
prepares every item and hands the slice to one CreateIssuesInTxWithResult, while
the unit-of-work body creates item by item through the domain use case and keeps
"all or nothing" by returning early and letting the transaction roll back. That
is also why no case asks for a FORWARD reference inside a batch: the store body
could resolve one and the uow body provably cannot, so the role promises only an
edge onto an EARLIER item and the contract says so at the case site (A-bcr-4).
The store-backed body is an InTx function rather than an internal/workapi/store
package, the documented variant EdgeReader introduced: it must assign every id
before any row is written so an item's edge can name a sibling, which cannot be
expressed above storage.DoltStorage. It needs no depguard entry for the same
reason - the shared function takes a transaction, so no front door can call it.
HTTP. POST /v0/beads/issues:batchCreate is new canonical surface, spec written
first and the types generated from it. It is a collection-level custom method
spelled the way ready:count is, which leaves POST /v0/beads/issues free for the
single create that belongs there; it does not collide with the claim row's wide
POST wildcard, because that pattern requires the separating slash
(TestBatchCreateDoesNotShadowTheClaimRoute drives both). BatchCreateResponse
carries no allOf, so the oapi-codegen v2.6.0 pin-dropping trap does not apply,
and its Items are pinned to []types.Issue in pinning.go.
The wire publishes no `id` member, which is what keeps the role's
ErrAlreadyExists off a vocabulary that has no already_exists code (A-bcr-5): the
server assigns every id and `bd import` remains the upsert surface. The role's
ErrValidation is answered by the operation's own failure path rather than by
ClassifyError, because the dangling-edge refusal wraps BOTH ErrValidation and
ErrNotFound and the shared classifier reaches ErrNotFound first - a 404 for a
request that addressed no resource. Neither branch quotes the role's message: a
refused edge arrives as a driver error naming tables and constraints, and 4xx
details here reflect the caller's input.
httpapi.Config's roles source grows to eight roles. The half-set cases that
built a Config by hand now go through rolesConfig, so the next role does not
have to edit six literals that are not about the role set.
Verified: build, vet, gofmt clean; golangci-lint 0 issues; make api-check clean;
TestBatchCreatorContract green at dolt (9/9), embeddeddolt (9/9) and uow (9/9);
./internal/httpapi green including eleven new batch-create tests; TestCorpusGolden
green (the corpus has no --file capture); TestCreateFromMarkdownFile green; the
cmd/bd create suites green with BEADS_TEST_EMBEDDED_DOLT=1 and the proxied
integration create suites green with BEADS_TEST_PROXIED_SERVER=1;
TestProxiedLookup green.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
`bd purge` selected closed wisps in one transaction and deleted them in
another. A bead closed, unpinned or cited in the window between the two was
judged on one state and acted on in a different one — the TOCTOU the bead
names — and the proxied twin held a second copy of the whole flow: its own
candidate filter, its own glob match, its own closed_at recheck, its own
reference scan and 190 lines of output kept character-identical to the direct
route's by hand.
PURGE AND PRUNE ARE ONE CAPABILITY, which the design left open and the code
answers plainly: both routes already ran ONE function with a `purgeScope`
struct choosing the tier. So issueops.Sweeper has ONE method, reached through
store.Sweeper() and the provider's own accessor, and SweepRequest.Tier selects
the plane — `ephemeral` is purge, `durable` is prune, and the two are disjoint
by construction. What genuinely differed became request fields rather than a
second role: the require-a-filter refusal keys on Tier, and the citation
protection is ASKED FOR (ProtectReferenced) instead of being inferred from a
command name, which is what the shared body did (`scope.cmdName == "prune"`).
Q9 ANSWERED IN THE ROLE. The require-a-filter gate is
workapi.ValidateSweepRequest, below every front door: a durable sweep with
neither a cutoff nor an id pattern is ErrValidation. It is a safety invariant,
not presentation — without it a second front door is one handler away from an
unguarded mass delete, which is exactly what this commit's HTTP operation would
otherwise have been. The CLI keeps its friendly message, and says in place that
it is there for the WORDING while the guard is the role's; the contract case is
what proves the guard survives that branch being deleted.
THE DEFECT, AND ITS PRICE. The whole sweep is now one transaction, so the set
the result describes IS the set it deleted. That gives up the server-backed
store's batched wisp deletion (200 per transaction, added for Dolt's 10s write
timeout after bd-2ehd and ff-tqm): a sweep too large now fails WHOLE. That is
the better failure — the partial one it replaces reported a deleted count of
ZERO while having deleted rows — and the other two backends already worked this
way. It is written down as a promise WITH its cost, and recorded for sign-off.
TWO MORE DEFECTS the single call site removed. `--dry-run` passed force=false
to the delete where the real run passed force=true, so a preview could FAIL
over dependents the sweep would have orphaned — and the CLI answered that
failure with zeros. And `filepath.Match`'s error was discarded on both routes,
so `--pattern '['` printed "No closed beads to prune" and exited 0; it is now
ErrValidation quoting the pattern.
THE CONTRACT IS WHAT WAS DELETED, not what was reported.
backend/conformance/sweeper_contract.go holds ten cases, each citing the leaf
doc, run at all three backends with ZERO PARKS and zero divergences. Every case
that acts asserts row counts through QueryScalar rather than trusting the
result the sweep reported about itself, which on a destructive operation is the
assertion that matters; every case scopes itself with an id pattern, because a
sweep is asked of a whole TIER and an unscoped one would clear the next case's
seeds. They are TWO INDEPENDENT BODIES plus an engine check: dolt and
embeddeddolt share internal/storage/issueops.SweepInTx and differ only in how
they reach a transaction, and the unit-of-work provider reaches the same four
questions through the domain use cases.
THE HTTP OPERATION, spec first (per bd-jtp1h's A2 scope decision):
POST /v0/beads/issues:sweep, capability `issues.sweep` — the first DESTRUCTIVE
operation on a surface that was reads plus one claim. It is a collection-level
custom method with a body rather than DELETE with a query string, because a
dropped query parameter widens what is erased where an unknown body member is
refused by name. The handler decodes six members and calls the role; it does
not implement the safety gate, the tier vocabulary or the glob, all of which
are the role's ErrValidation reaching the wire as a 400 through failSweepErr.
No component carries allOf and none is x-go-type-pinned — there is no canonical
Go struct whose JSON encoding is this body, since the CLI publishes these
numbers under `purged_count`/`pruned_count` — so the projection is tested
instead. `bd serve --help` grew a DESTRUCTIVE OPERATIONS section and the
--allow-non-loopback warning now says peers can bulk-delete closed beads.
`bd gc` keeps the closed-candidate recheck by calling the SAME pure function
the role calls (workapi.FilterSweepCandidates), so the two cannot drift; the
reference matcher and its 10K-body budget moved to internal/workapi with the
scan. cmd/bd/purge.go and purge_proxied_server.go LEFT the forbidigo exception
list, which is how a role commit proves its front doors reached the role.
USER-VISIBLE, for the wave's changelog pass: the version-control label for a
sweep is now `bd: sweep <n> <tier> bead(s)` on both routes, where proxied wrote
`bd: prune <n> bead(s)` and direct wrote `bd: delete <n> issue(s)` — an HTTP
sweep is not `bd prune`, so the label names the operation and the tier from
every door; a malformed `--pattern` now exits non-zero; `--dry-run` no longer
refuses over dependents the real sweep orphans; and `bd serve` gains a
bulk-delete endpoint. Reasoning and the alternatives are in
/data/tmp/sd-server/AMBIGUITIES.md as A-swp-1..9.
Verified: build, vet, gofmt clean; golangci-lint 0 issues; make api-check
(regenerate-and-diff plus the httpapi suite) green; TestSweeperContract 10/10 at
dolt, embeddeddolt and uow; the internal/workapi, internal/storage and
internal/telemetry suites; TestEmbeddedPurge, TestEmbeddedPurgeConcurrent,
TestEmbeddedPrune, TestPrune_protectsBeadCitedByCustomStatusBead and
TestEmbeddedGC under BEADS_TEST_EMBEDDED_DOLT=1; TestProxiedServerPrune under
BEADS_TEST_PROXIED_SERVER=1; TestProxiedLookup*; and the root layering pins.
The protocol corpus has no purge/prune case to account for.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
`bd query "type=bug OR label=urgent"` has been answering with a prefix of its
answer and calling it complete. The expression language has OR, NOT and
parentheses, which no storage filter expresses, so both routes fetched a WINDOW
of candidate rows — max(3*limit, 100) — and applied the expression to those in
memory. A match past row 100 was absent from the page and unreported by
has-more. The same six lines of arithmetic were written twice, once per route,
and both copies were wrong in the same way.
THE ROLE. issueops.Querier, reached through store.Querier() and the provider's
own accessor. One method over a request whose predicate is a SENTENCE rather
than a set of fields, which is what makes it a role instead of a mode of
Reader: a ListRequest is a conjunction — every field narrows — and no
arrangement of its twelve callers' fields expresses a disjunction. It is
equally not a raw query passthrough; the language names no table, no join and
no column outside a closed vocabulary, which is why a contract can promise
anything about it at all.
THE FIX, which Q3 approved as user-visible. A predicate query's filter now
carries NO row limit: the predicate sees every candidate row, the page is the
first Limit MATCHES of the complete matching set, and has-more is exact. The
decision has one home, internal/workapi.BuildQueryPlan, which both bodies
execute. The cost is stated rather than hidden — a broad OR over a large
workspace now reads every row its base filters admit — and CHANGELOG.md says so
in the same words.
WHAT PINS THE FIX, at three levels, because the contract alone cannot see it.
TestBuildQueryPlanLeavesAPredicateQueryUNBOUNDED asserts the arithmetic in
microseconds. TestAPredicateQueryFindsAMatchBeyondTheOldWindow seeds 101 rows at
ONE backend and reads back the match at row 101 — verified to discriminate:
with the old window temporarily reinstated it returns zero rows. The portable
contract asserts the PROMISE the window broke (a page is a prefix, has-more is
exact) and, confirmed by the same experiment, does NOT discriminate the old
window at its small scale; the contract's header says so rather than implying
coverage it does not have.
THE CONTRACT. backend/conformance/querier_contract.go holds nine cases, each
citing the leaf doc by line, run at all three backends with ZERO parks. TWO
independent bodies plus an engine check: dolt and embeddeddolt share
internal/workapi/storequerier, and the unit-of-work provider is genuinely
separate — it is the only leg on which the Offset case takes its HONORED branch,
since that seam renders OFFSET where the store body refuses uniformly.
TWO SMALLER USER-VISIBLE CHANGES ride along, both filed in AMBIGUITIES.md
(Q22, Q23) for the owner's batch. `--offset` with an OR/NOT expression is no
longer refused: the offset skips MATCHES, which is only meaningful now that
every match is seen, so an error became an answer. `--limit -1` is now
ErrValidation instead of an undocumented second spelling of unlimited. The
`--offset` + `--sort` refusal survives and moved INWARD — the role makes it, for
every caller, because the order is applied to the rows the query bounded and
each page of an offset walk would be sorted for itself — so its wording changed
with its address, as did the wording of a malformed expression on both routes.
A DEFECT FOUND AND NOT FIXED, recorded as A-qry-1 rather than papered over: an
UNLIMITED request carrying an Offset renders SQL the Dolt engine answers with a
recovered panic (makeslice: cap out of range, out of topRowsIter). It predates
this role — `bd query --offset N --limit 0 --proxied-server` built the same
filter — and it is a storage-seam bug, so the contract case asks its question at
a bounded limit and says why at the case site.
THE HTTP OPERATION, spec first (per bd-jtp1h's A2 scope decision):
GET /v0/beads/issues:query, capability `issues.query`, answering a new QueryPage
{items, has_more}. It publishes no cursor and no `offset`: a predicate query's
matching set is assembled outside the database, so there is no keyset position
to encode, and an offset is honored by one database source and refused by the
other, which is not a difference to put on a wire. QueryPage carries no allOf
and its Items are pinned in pinning.go beside ReadyPage's and IssuesPage's — the
edit wave 2 missed once (bd-8ri3m). Adding a second sort enum made oapi-codegen
disambiguate the FIRST one, renaming the generated ListReadyWorkParamsSort
constants (Hybrid -> ListReadyWorkParamsSortHybrid); nothing outside the
generated file named them. httpapi.Config's roles source grows a required eighth
member, and a Config complete under the previous release is now refused at
Listen rather than nil-dereferencing on the first issues:query request.
WHAT ELSE CONVERGED. Both output modes read ONE query — the counted one --json
always used — so a predicate can no longer be applied to two different row sets
depending on the flag (A-qry-1's neighbour, Q24). The direct route prints the
truncation hint for the first time, not by new choice but because it finally has
an honest has-more to print.
Incidental: internal/storage/role_accessor_decorator_test.go's four
near-identical "the four read roles" paragraphs — one appended by each wave-2
slice — are collapsed into the one accurate paragraph the table needs. Same
defect as bd-8ri3m, comments only.
Verified: build, vet, gofmt clean; golangci-lint 0 issues; make api-check green;
TestQuerierContract 9/9 at dolt, embeddeddolt and uow;
TestAPredicateQueryFindsAMatchBeyondTheOldWindow; the internal/httpapi package
suite; internal/workapi, internal/storage, internal/telemetry, internal/query
and the root package; TestEmbeddedQuery under BEADS_TEST_EMBEDDED_DOLT=1 and
TestProxiedServerQuery under BEADS_TEST_PROXIED_SERVER=1; TestProxiedLookup*.
The protocol corpus drives no `bd query` invocation and is untouched.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
The version markers had two implementations of one rule. The direct route read
bd_version and bd_version_max out of the metadata plane in
cmd/bd/version_tracking.go, compared them with doctor.CompareVersions and wrote
them back; the proxied route opened a unit of work and called a ReconcileVersion
method on the config use case, which held its own copy of the same comparison,
the same two downgrade guards and the same high-water rule. The two agreed, but
nothing made them agree and no test compared them. Both now ask for a role, and
the difference between the routes is which accessor answers.
THE ROLE BELONGS TO NO COMMAND, and it is the only one in this programme that
does not. It fires from PersistentPreRun on EVERY startup, on both routes,
before the command the user typed has run — which is exactly why it went
unnoticed: `bd version` prints two strings, opens no store and reaches none of
this, so the state machinery was hiding behind a command that does not use it.
THAT ORIGIN IS A CONSTRAINT ON THE PROMISES, not a piece of history, and the
leaf doc says so where a reader will meet it. A role that runs before every
command pays for itself on every command, so it does two point reads on the path
that changes nothing, loads no configuration, takes no lock, repairs nothing —
and, the clause that matters most, it NEVER refuses the command in front of it.
A downgrade is an OUTCOME with a nil error, because an older binary is allowed
to use a workspace a newer one has opened; a genuine failure is an error the
CALLER logs and walks past, which both front doors do at debug level. A role
whose callers must ignore its errors has to say so where the promise is made
rather than leave each caller to decide.
TWO METHODS, ONE ROLE. RecordedVersion and ReconcileVersion are two shapes of
one question — the write's promise IS a statement about what a later read
returns — which is what the governing rule permits a role to be born with, and
WorkspaceConfig set the precedent. It is not padding: the direct front door
needs the READ alone. autoMigrateOnVersionBump probes a read-only store first so
an already-current workspace never pays for the writable open, and before this
commit that probe read the metadata key by hand — the "CLI knows the storage
key" shape this programme exists to remove, on the hottest path in the codebase.
WHY IT IS NOT WorkspaceConfig WITH TWO MORE KEYS. Two planes, two lifetimes. A
workspace setting is durable and travels with the database; these two markers
are dolt-ignored, do not survive a clone and are deliberately different per
machine. Publishing them through the settings plane would put a value that
cannot be shared behind an interface whose whole promise is that its values are.
ONE DECISION, THREE SUBSTRATES. workapi.PlanVersionReconcile is the pure planner
every implementation decides through; domain.ConfigUseCase LOSES ReconcileVersion
and gains SetLocalMetadata, the write half of the GetLocalMetadata it already
published, so the unit-of-work body can read, plan and write in ONE transaction.
Deleting the use-case method is what makes the rule single-sourced rather than
duplicated under a role.
CONFORMANCE. backend/conformance/version_reconciler_contract.go holds nine cases
run at all three implementations with ZERO parks and zero divergences. They
deliberately do NOT re-test the decision: the planner's whole table — upgrade,
no-op, both refusals, the catch-up to the mark, the dotted comparison in which
1.2.0 and 1.2.0-rc1 are equal — is pinned without a database in
internal/workapi/versionreconcile_test.go, and repeating it here would be
testing one pure function three times over three sql-servers. What only a real
backend can show is asserted instead: that a recorded marker is there for the
next caller (a new transaction on the unit-of-work backend), that a refusal and
a validation failure write NOTHING, that reconciliation adds no history entry at
all, and that a reconciliation which CANNOT COMPLETE reports an error and leaves
both markers standing. Two independent bodies plus an engine check, not three
votes: dolt and embeddeddolt share internal/workapi/storeversionreconciler.
The fixture carries one hook the frozen roleFixtureKit cannot supply, built at
each wiring site the way CycleDetectorFixture.Exec is: the two states that
matter most — a recorded version BELOW the high-water mark, and its catch-up —
are states the role can never produce, so they are seeded past it.
THIS IS THE FIRST COVERAGE THE DIRECT ROUTE'S RECONCILIATION HAS EVER HAD. Its
round-trip tests (MigratesVersion, AlreadyMigrated, RefusesDowngrade,
TracksMaxVersion) were deleted with the SQLite backend and never replaced; the
note recording that is still in cmd/bd/version_tracking_test.go. The seven
subtests of the deleted use-case method go with it, replaced by the exhaustive
planner table plus nine cases at three backends.
NO HTTP OPERATION, and that is a decision rather than an omission — recorded in
the leaf doc and as A-ver-2 for the owner. The markers are clone-local: they
describe the machine holding the database, so a remote client reading them
learns something it cannot compare against anything it holds. The one version
fact a client CAN act on, the serving binary's release, is already published as
ContextResponse.bd_version, which the document already names as the only field a
client may compare as a version. A write endpoint is worse: reconciliation is an
effect of a PROCESS STARTING, and a client asking a server to record the
client's version would be asking it to lie about which binary holds the
database. If the owner wants a read-only GET /v0/beads/version, the role, the
accessor and both bodies are already here.
NO USER-VISIBLE CHANGE. Every outcome is identical; only three debug lines
moved. One accidental behaviour became deliberate: a binary whose Version string
is empty used to be handled by the downgrade guard on a populated workspace and
by an equality short-circuit on an empty one, and is now an explicit
ErrValidation that writes nothing either way.
ENFORCEMENT. storeversionreconciler joins the cmd-bd-role-constructors deny
list. The version path never named types.IssueFilter, so there is no forbidigo
exception to remove. engdocs/ADDING_AN_ISSUEOPS_ROLE.md gains the two things
this role taught the checklist: a role may honestly have NO HTTP surface, and a
contract case may need a fixture hook for a state the role cannot produce.
Verified: build, vet, gofmt clean; golangci-lint 0 issues;
TestVersionReconcilerContract green at dolt (9/9), embeddeddolt (9/9) and uow
(9/9); the planner unit tests, both decorator enumerations, the root layering
pins, internal/jira and the internal/storage/domain/db config suite green;
internal/httpapi green and `make api-check` clean with no spec or generated
diff; TestReconcileVersionPersistsAcrossUOW green; TestProxiedLookup green;
`-run 'TestTrackBdVersion|TestAutoMigrateOnVersionBump|TestGetVersionsSince|TestMaybeShowUpgradeNotification|TestInitDoltMetadata'`
green under BEADS_TEST_EMBEDDED_DOLT and TestProxiedServerContext /
TestProxiedServerInfo green under BEADS_TEST_PROXIED_SERVER; TestCorpusGolden
green, so no command's JSON moved.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
`bd ready --limit 100` prints "showing 100 of 412", and the 412 came from
nowhere in particular. The direct route computed it inline: unwrap past the
storage decorators, type-assert to storage.ReadyWorkCounter, and fall back to
an unbounded ready query when the assertion missed — twice, once in the --json
branch and once in the text one, with two different fallbacks. The proxied
route could not compute it at all and published no `total` key, so the same
script read a number under one workspace topology and nothing under another.
THE ROLE. issueops.ReadyCounter, reached through store.ReadyCounter() and the
provider's own accessor. It answers a question neither neighbour can: Reader
answers with a PAGE and its verdict is has-more ("did the limit hide
anything"), where this is "how many" — strictly larger, and already published
output, so collapsing the two would change what a shipped surface says. Counter
answers a predicate over one table, and the ready predicate is blocker-aware:
it reads the dependency graph and the wisp tier, which no CountRequest can
describe. Counter's own doc already said the count of ready work would be its
own role for that reason.
It takes issueops.ReadyRequest VERBATIM, the precedent ClaimNextRequest set, so
a listing, a claim and a count ask ONE question of ONE set. Limit and Offset are
ErrValidation for the reason a claim refuses them: a cardinality has no page, so
a limit would answer "how many of the first N" and an offset would subtract the
rows it skipped from the size of a set that still holds them.
THE CONTRACT IS AN IDENTITY, not a resemblance:
CountReady(r).Total == len(Reader.Ready(r with Limit=0).Items)
at every implementation. backend/conformance/ready_counter_contract.go holds
seven cases, each citing the leaf doc by line, run at all three backends with
ZERO parks. They are TWO independent bodies plus an engine check: dolt and
embeddeddolt share internal/workapi/storereadycounter (one indexed COUNT(*) per
plane minus their overlap), and the unit-of-work provider is genuinely separate
code that runs the unbounded ready query and takes its length — which is why
the wisp-tier case is written the way it is, since that is where a COUNT and
the page it sizes are assembled by different arithmetic.
A DEFECT THIS FOUND, and it is not the count's. `bd ready`'s directory-label
default (GH#541) never reached the ReadyClaimer role. claimNextRequest re-ran
the gatherer's own emptiness test against in.filter — and the gatherer had
already written the default INTO that filter, so the test saw a non-empty label
set and skipped. The branch could never fire. In a directory with
`directory.labels` configured, `bd ready --claim` therefore claimed from the
WHOLE ready front while `bd ready` beside it listed only the configured scope:
exactly the "hand an agent work the listing never offered it" that
ReadyClaimer's contract exists to forbid. The gatherer now RECORDS its decision
(readyInput.dirLabels) and both roles read it, so there is one answer instead of
two derivations of it. Caught by writing the count's own test for the same
line, and pinned by cmd/bd/ready_role_request_test.go.
WHAT ELSE CONVERGED. Both routes and both output modes now ask one question
through one accessor: the direct route's two inline epilogues become one call,
and the proxied route's `pagination.total` exists for the first time. The
"showing X of N" text a human reads and the total a script parses are the same
number by construction. cmd/bd no longer names storage.ReadyWorkCounter at all
— the capability is required by the store body's PARAMETER TYPE, so a backend
that cannot size the ready set fails to compile instead of falling back to a
mega-query at runtime.
THE HTTP OPERATION, spec first (per bd-jtp1h's A2 scope decision):
GET /v0/beads/ready:count, capability `ready.count`, answering
`ReadyCount {total}`. It publishes no `limit` and no `sort`: a cardinality has
no page and no order, and the handler sends the listing's own sort default so
the request stays the listing's request rather than one that resembles it. The
filter vocabulary is decoded by ONE function shared with GET /v0/beads/ready
(readyFilters), so the two operations cannot admit different parameters — which
is what the identity rests on over the wire.
`TestCountReadyAndListReadyAdmitTheSameFilters` compares the two predicates
built from one query string. No component here carries allOf and none is
x-go-type-pinned: the pinned seven are canonical Go structs whose JSON encoding
IS the contract, and there is no canonical struct for this number — the CLI
publishes it inside its own stdout envelope, which is not a wire type — so
pinning would weld the body to a CLI presentation type rather than prevent a
drift. The generated output was read to confirm it (a struct with `Total
int64`, not an alias), which is the v2.6.0 trap this document warns about.
httpapi.Config's ROLES database source grows a REQUIRED third member. That is
the sharp edge for the next role commit and is now written down in
engdocs/ADDING_AN_ISSUEOPS_ROLE.md as step 13: a Config carrying the old pair
would bind and then nil-dereference on the first request that reached the new
handler, so Listen refuses it with the same message a half-set pair gets.
USER-VISIBLE, for the wave's changelog pass: proxied `bd ready --json --limit N`
now publishes `pagination.total`; `bd ready --claim` now honours the
directory-label scope on both routes.
Verified: build, vet, gofmt clean; golangci-lint 0 issues; make api-check
(regenerate-and-diff plus the httpapi suite) green; TestReadyCounterContract
7/7 at dolt, embeddeddolt and uow; the httpapi package suite; the direct-route
`bd ready` suites under BEADS_TEST_EMBEDDED_DOLT=1 and the proxied ones under
BEADS_TEST_PROXIED_SERVER=1, including the pagination envelope that now asserts
the total; TestProxiedLookup*; and the ready protocol-corpus tests, which are
byte-identical.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
`bd dep list a b c --direction=down` asks a different question from every
other dep read: it answers with RAW EDGE ROWS keyed by source, for many
anchors at once, and it has to say per anchor whether that anchor exists.
Both routes answered it off-role — the direct one out of
GetDependencyRecordsForIssues, the proxied one out of a unit of work — and
neither could tell "this issue has no dependencies" from "there is no such
issue".
THE ROLE. Relations is the near sibling and it cannot answer this. It is
SINGLE-ANCHOR, it answers with the ISSUES on the far end of an anchor's
edges, and an edge whose target this database has no row for — an
`external:` reference, an id in another repository — is silently not a
neighbor. A missing anchor is ErrNotFound there, which a batch cannot use
without discarding the anchors it did find. Different answer shape,
different miss policy, different arity: three, so a new role and a new
accessor rather than a second Relations method. Q12 confirmed the split
against merging it with BlockingAnnotator, which answers a derived
best-effort decoration rather than stored rows.
The direction is OUTGOING only and there is no parameter for it. The inbound
bulk read is a different read against a different key with its own
cross-table de-duplication, and no front door asks for it; a direction
nothing sets would be a promise nothing checks.
TWO DEFECTS THE ADOPTION FIXES, both of them the same shape — a silent
change of JSON document:
- the KNOWN DEFECT. The direct route's batched read fell through to the
hydrated neighbor listing on ANY error, so a transient failure turned
`bd dep list a b --json` from an array of dependency records into an
array of ISSUES, with no error and no warning.
- the same fall-through fired whenever routing split the anchors across
stores, so a cross-rig batch emitted that other document every time. The
role is reached per store now and the answers merge back into argument
order, so a routed batch and a local one have one shape.
Also fixed on both routes: `--type` used to test emptiness BEFORE filtering,
so an anchor whose every edge the filter rejected printed a header with no
rows under it. The role filters, so it prints "has no dependencies".
USER-VISIBLE, approved in the Q11 batch: PROXIED `bd dep list` NOW REPORTS
GHOST ANCHORS. It used to hand the raw arguments to the dependency use case,
which keys its answer by source and has no entry for an id that names
nothing, so a typo printed "<id> has no dependencies" and a script read a
clean graph. The role probes each anchor, so a typo now prints the warning
the direct route has always printed for an argument it could not resolve —
on stderr, in both modes, which is what leaves `--json` the flat array of
dependency records the command documents. The proxied route still resolves
nothing: ids go to the role exactly as the caller spelled them, because that
route has never done partial-id resolution.
One behaviour had no prior decision behind it and is recorded as Q15 rather
than chosen quietly: a repeated anchor now collapses onto its first mention,
where the old loop over a keyed map printed it twice.
CONFORMANCE. backend/conformance/edge_reader_contract.go holds fourteen
cases, each citing the leaf doc by line, run at all three implementations
with ZERO parks. They are TWO independent bodies plus an engine check, not
three: dolt and embeddeddolt both call storage/issueops.ExecuteEdgeRead
inside their own read transaction, and the unit-of-work provider is the
second body — it probes existence through two batched by-id use-case reads
where the stores run one batched EXISTS over both tables.
The store-backed body is an InTx function rather than an
internal/workapi/store<role> package, which is a documented deviation from
the twelve-step checklist and the reason is Relations': the anchor probe and
the edge read must share ONE transaction, or an anchor can be reported
missing by a probe that raced a create the edge read then saw. That cannot
be expressed above storage.DoltStorage. engdocs/ADDING_AN_ISSUEOPS_ROLE.md
now names that variant, including why it needs no depguard entry — the
shared function takes a transaction, so no front door can call it.
HTTP. GET /v0/beads/dependencies is new canonical surface, spec written
first and the types generated from it. `items` is an array of the already
x-go-type-pinned `Dependency`, so the CLI's `--json` and this body stay one
compatibility domain; the new `DependencyEdges` envelope carries no allOf,
so the oapi-codegen v2.6.0 pin-dropping trap does not apply, and the
generated `Dependency` is still an alias. A ghost anchor is on `missing`
rather than a 404, for the reason the role reports it per anchor. There is
no `limit` and no cursor: `bd dep list` has none either, so the QUESTION is
bounded instead — at most 100 `issue_id` values — which bounds the work
without truncating an answer a client could not then page.
httpapi.Config's roles source grows from two roles to three, and Listen
refuses a partially-set set for the reason it already refused a half-set
pair: the missing role is a nil dereference in a handler on a live server.
Verified: build, vet, gofmt clean; golangci-lint 0 issues; make api-check
clean; TestEdgeReaderContract green at dolt (14/14), embeddeddolt (14/14)
and uow (14/14); ./internal/httpapi green; TestCorpusGolden green, so the
committed `bd dep list --json` fixture is byte-identical; TestEmbeddedDep
and TestProxiedServerDep2 green with their gates set; TestProxiedLookup
green.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
`bd dep cycles` had two implementations of one sweep and the post-add cycle
warning had two more. The direct route walked store.DetectCycles; the proxied
route walked the same lossy slice off the use case; and dep.go and
dep_proxied_server.go each carried a copy of the arrow-path warning. The two
copies agreed, which is the only reason nobody noticed that the slice they
agreed about was map-ordered and silently shortened. All four now build one
issueops.DetectCyclesRequest and ask for the role.
THE ROLE. A cycle has no ANCHOR. Every Relations request names a source and
answers with that source's neighbours; this one is asked of the whole graph and
answers with paths, so a Relations request type would have carried an anchor
field a sweep must ignore. Its own role and its own accessor per the governing
rule.
TWO USER-VISIBLE CHANGES, both ruled on by the owner (Q4, Q5), both recorded in
CHANGELOG.md.
Q4 CANONICAL OUTPUT. Every source of nondeterminism is removed, not just the
order of the answer, because ordering the answer would not have been enough:
a depth-first enumeration records one cycle per BACK EDGE, and which edges are
back edges depends on the walk. The roots came off a Go map and the adjacency
lists out of an unordered SQL read, so two runs against an unchanged database
could disagree about which cycles EXIST, not merely about their order. The
walk is now sorted at both, each path is rotated to its lowest id, and the
paths are sorted against each other.
Q5 HONEST PARTIAL. A member the database cannot describe used to be dropped
from the path, so a 3-cycle rendered as a 2-cycle and looked complete, and a
wholly undescribable cycle vanished from the report and from the
`Found N dependency cycles` count. Every member is now carried with its id,
its DESCRIPTION is omitted rather than the member, and the cycle is marked
Partial. There is no separate total, because there is no cycle the slice
omits -- the reading of "still counted" is recorded in AMBIGUITIES.md
(A-cyc-1) along with what it would cost to add one.
`bd dep cycles --json` therefore emits a new shape: an array of
{members:[{id, issue?}], partial} where it emitted an array of arrays of
issues. The protocol corpus has no dep-cycles capture, so nothing was pinned
to the old bytes.
WHERE THE BODY LIVES, and why it is not a store<role> package. The work is a
graph read plus a hydration that must see one snapshot, and a transaction is
not reachable through storage.DoltStorage. So the sharing happens one level
down at issueops.DetectCycleReportInTx -- the function both stores' legacy
DetectCycles already call -- with a five-line accessor in each store package
and a new domain repository method for the unit of work. Two wrappers over one
function is still ONE vote. The parts that decide what the answer MEANS are
pure (CanonicalCyclePaths, BuildCycles) and pinned without a database.
CONFORMANCE. backend/conformance/cycle_detector_contract.go holds eight cases
citing the leaf doc by line, run at all three implementations with ZERO parks:
24 subtests green.
SEEDING ONE TAKES RAW SQL, which is a fact about the system rather than a
shortcut. No supported write can create a cycle -- the editor's per-edge probe,
its whole-graph gate and the storage seam all refuse -- so there is no verb that
produces the state this role reports. And foreign keys (dependencies.issue_id
-> issues, wisp_dependencies.issue_id -> wisps) mean an undescribable member is
reachable only with foreign_key_checks off. That is not academic: those are
exactly the paths a cycle arrives by. Recorded as AMBIGUITIES.md A-cyc-2 with
the alternative if the owner would rather the contract not write that way.
HTTP. GET /v0/beads/dependencies/cycles, spec first and the types generated
against it. Cycle and CycleMember are x-go-type-pinned to the ROLE package, so
the CLI's --json element and the HTTP item are one struct; the bijection test
grew a per-schema import path to cover them and immediately caught a missing
json tag on Partial. No allOf on either component (the v2.6.0 trap), verified
in the generated output: both emit `type X = issueops.X`. No limit and no
cursor -- truncating would shrink the count, which is the number an operator
acts on -- so has_more is documented as always false. httpapi.Config's roles
source now requires the third role beside Reader and Claimer, refused at Listen
for the reason a half-set pair is.
ONE DEFECT FIXED BESIDE THE TWO RULINGS: proxied `bd link` ran its cycle sweep
and its title lookups INSIDE the write transaction, so the warning described a
graph nobody else could see. It now runs them after the commit, through
depEdgeFeedback, which is where the dep routes already did it.
Verified: build, vet, gofmt clean; golangci-lint 0 issues; make api-check
green; TestCycleDetectorContract 8/8 at dolt, embeddeddolt and uow;
internal/httpapi 0 failures including the five new cycle-route cases;
TestProxiedLookup* green; TestEmbeddedDep* green;
BEADS_TEST_PROXIED_SERVER=1 TestProxiedServerDep* green; TestCorpusGolden
green.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
`bd status` (and its `bd stats` alias) had two implementations of the same
command. The direct route asked the store for statistics and, under
--assigned, built an assignee filter, ran a ready-work query and folded
five status counts itself; status_proxied_server.go did all four again
through a unit of work. Both now build an issueops request and ask for the
role, and the difference between the two routes is which accessor answers.
THE ROLE. Its numbers are DEPENDENCY-AWARE — the blocked count reads the
denormalized transitive is_blocked flag and readiness is derived from it —
so no predicate over the issues table describes them and this is its own
role rather than a sixth Counter dimension, which is what issueops/
counter.go already said it would be. Stats and AssigneeStats are born
together because they answer the same question of two sets; they are two
METHODS rather than one with an Assignee field because the assignee answer
fills four fields of the same struct by different definitions, and a
request whose optional string silently changed what a number meant is the
shape this programme exists to remove.
WHAT THE LEAF DOC NOW SAYS OUT LOUD, none of it written down anywhere
before: BlockedIssues counts the graph, not the "blocked" status;
ReadyIssues is arithmetic and NOT the cardinality of `bd ready`;
PinnedIssues overlaps every status bucket so the buckets do not sum to
Total; the workspace-wide answer excludes the wisp tier while the
assignee-scoped one merges it; --no-blocked is a HINT whose only report is
BlockedIssues being nil; and EpicsEligibleForClosure and AverageLeadTime
are structurally always zero, which is why `bd status`'s "Extended:"
branch has never once printed.
CONFORMANCE. backend/conformance/stats_reporter_contract.go holds thirteen
cases, each citing the leaf doc by line, run at all three implementations
with ZERO parks and zero divergences. Unusually for this suite they are
THREE genuine votes: the two stores share the role body (storestats) but
dolt/queries.go, embeddeddolt/statistics.go and domain/db/issue.go each
spell the blocked count and the ready subtraction themselves. Every
workspace-wide case asserts a before/after DELTA — a summary takes no
predicate, so there is no IDFilter to scope it with the way the Counter
contract scopes its cases.
HTTP. GET /v0/beads/stats is added to the Tier-1 document FIRST and the
types generated from it: a `Statistics` schema x-go-type-pinned to
types.Statistics (checked: the pin survives, and the schema is now in the
JSON-tag bijection test), a StatsResponse envelope mirroring the CLI's
--json shape minus `recent_activity`, which no shipped path populates. The
handler calls the same role both CLI routes call. `blocked_count_skipped`
is DERIVED from the answer, never echoed from the request, because the
hint is a hint. httpapi.Config's roles source grows a third field and
requires it with the other two: a source that answers some operations and
faults on others is not a source.
ENFORCEMENT. cmd/bd/status.go and status_proxied_server.go no longer name
types.IssueFilter or types.WorkFilter, so `status` LEAVES the forbidigo
exception list (63 -> 61 of 388 files). The role-constructor depguard list
gains storestats.
TWO USER-VISIBLE CHANGES, both improvements and both small: `bd status
--assigned` reports the underlying failure instead of the bare "failed to
get assigned statistics", identically on both routes; and the proxied
--no-blocked warning now fires from the ANSWER rather than from the route,
so a backend that gains a fast path stops printing it with no edit.
Verified: build, vet, gofmt clean; golangci-lint 0 issues; make api-check
clean (no codegen drift, whole httpapi package green);
TestStatsReporterContract 13/13 at dolt, embeddeddolt and uow;
TestEmbeddedStatus and TestProxiedServerStatus green with their gates set;
TestProxiedLookup green; TestCorpusGolden green.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
`bd config` had two implementations of the same four verbs. The direct route
called store.SetConfig/GetConfig/GetAllConfig/DeleteConfig in cmd/bd/config.go;
the proxied route opened its own unit of work and called the config use case in
config_proxied_server.go, then printed the same lines a hundred lines away. Both
now build an issueops request and ask for the role, and the difference between
the two routes is which accessor answers.
THE ROLE. issueops.WorkspaceConfig is the workspace's DURABLE SETTINGS PLANE:
the key-value rows the workspace database holds. It is born with four methods
because read, write, remove and enumerate over ONE keyed namespace are four
shapes of one question — the governing rule forbids appending to a role, not a
role being born whole — and because their promises are statements about each
other: SetSetting's promise is about what a later GetSetting returns, and
UnsetSetting's about what a later ListSettings omits.
The methods are GetSetting/ListSettings/SetSetting/UnsetSetting rather than
Get/List/Set/Unset, and that is not verbosity. Reader already has Get and List,
and the decorator conformance tests drive ONE sentinel that implements every
role at once; two roles with the same method name and different signatures make
that sentinel unwritable. The collision was the design telling us the short
names belong to issues.
ONLY THE KV SLICE IS A ROLE, and the rest is a deliberate no. `bd config show`,
`drift`, `apply` and `validate` are multi-source diagnostics over config.yaml,
environment variables, git config, this plane and server state at once. Three of
those five sources are files on the CLIENT's filesystem, which a server
answering for a remote workspace can never read, so a substrate role claiming to
answer them would be claiming to see something it cannot. `bd config set-many`
is off the role too, for a different reason: it exists to make N keys ONE Dolt
commit, the role writes and commits one setting per call, and
TestProxiedServerConfigSetMany pins the difference. A batched write is a
separate capability, exactly as `bd create --file` stays off Lifecycle.Create.
TWO LIVE DEFECTS FIXED.
1. THE PROJECTION, which is the Q11 user-visible change. Reads of the custom
status and type vocabularies are TABLE-first: they consult custom_statuses
and custom_types and fall back to the config string only when the table is
empty. The store backends have always rewritten the table in the same
transaction as the row; the unit-of-work backend wrote only the string. So
on a team server `bd config set types.custom "session"` reported success,
`bd config get` read it back, `bd doctor` re-verified against the string and
reported all-OK, and `bd create -t session` answered "invalid issue type"
for as long as the workspace lived. Fixed where dab71c5eb fixed it — in the
config repository, so the row and its projection commit together — and
verified by reverting the fix and watching ProjectsCustomStatuses and
ProjectsCustomTypes fail on uow alone.
2. `bd config set-many issue_prefix=x` re-prefixed the workspace. The
single-key verb refuses the prefix in both spellings and points at
`bd init --prefix`, `bd bootstrap` and `bd rename-prefix`; set-many
partitioned its pairs by source and wrote the database ones straight
through, so it never saw that guard. Beads created before the write and
after it disagreed about their own namespace with nothing to reconcile
them. The refusal is now in the role for every caller that goes through it,
and at set-many's front door because it does not.
THE BRIEF'S THIRD PREMISE IS FALSE, and it is worth saying so: "uow SetConfig
skips issue_prefix normalization" is not true at this base.
configSQLRepositoryImpl.SetConfig has trimmed the trailing hyphen since the file
was created (4fcbd5882, verified with git log -L). The normalization half needed
no fix; the custom-table half did, and dab71c5eb is NOT in this base.
WHAT ELSE CONVERGED. The status.custom parse lived in THREE places (both routes
of `bd config set` plus set-many) and is now one; the routing that stays at the
front door — which source owns a key, and whether writing it would leak a secret
into git — stays there, because those are questions about files on this machine.
CONFORMANCE. backend/conformance/workspaceconfig_contract.go holds fourteen
cases run at all three implementations with ZERO parks. Its shape is
deliberately not the issue contracts': there are no rows to seed, so it asserts
PRECEDENCE (which of two writes a later read sees, and whether a refusal leaves
the earlier value standing) and SIDE EFFECTS. Every projection case reads the
TABLE through QueryScalar rather than reading the setting back through the role,
because reading it back through the role is exactly the check that passed on the
backend where nothing took effect. Two independent bodies plus an engine check,
not three votes: dolt and embeddeddolt share
internal/workapi/storeworkspaceconfig.
TWO ASYMMETRIES ARE PINNED RATHER THAN FIXED, because all three backends agree
and closing either is a user-visible change this slice was not approved for.
UnsetSetting does not undo SetSetting's projection, so removing types.custom
leaves the custom types applying (bd-yby99.33); and `bd config unset
issue_prefix` is not refused where `bd config set` is (bd-yby99.34). Both are
stated in the leaf doc and asserted by a case, so neither can drift or be closed
on one backend while the owner decides.
HTTP. GET /v0/beads/config and GET /v0/beads/config/{key}, spec-first, taking
the v0 surface from six operations to eight. A setting whose KEY marks it as
credential-bearing — notion.token is database-backed — is published with
`redacted: true` and NO value: withheld values are omitted rather than masked,
which is the document's own "verbatim or absent" rule, and the CLI is unchanged
because its caller already holds the database while this surface has no
authentication. There is no HTTP WRITE, and that is the honest answer rather
than a hedge: `bd config set` routes most keys to config.yaml or git config
before the database is reached, so a server-side PUT of `export.auto` would
return 200 and land a row nothing reads. `Setting` is the one unpinned response
component, with the reason in the document beside it — the CLI marshals an
ad-hoc map, so there is no canonical struct to pin to, and minting one would
mean changing `bd config get --json` in order to satisfy a rule about not
changing it. All three are recorded in AMBIGUITIES.md as A-cfg-1..3.
ENFORCEMENT. storeworkspaceconfig joins the cmd-bd-role-constructors deny list.
`bd config` never named types.IssueFilter, so there is no forbidigo exception to
remove. engdocs/ADDING_AN_ISSUEOPS_ROLE.md gains what step 12 now costs since
the owner's scope decision: the spec operation, the route row, the Op constant
and operationCodes row, the capability token, and the Config field that a
store-shaped database source must now carry.
Verified: build, vet, gofmt clean; golangci-lint 0 issues;
TestWorkspaceConfigContract green at dolt (14/14), embeddeddolt (14/14) and uow
(14/14); the workapi validator unit tests, the two decorator enumerations, the
root layering pins and internal/jira green; internal/httpapi green and
`make api-check` clean; TestProxiedLookup green; `-run Config` green under
BEADS_TEST_EMBEDDED_DOLT and, under BEADS_TEST_PROXIED_SERVER, green except
TestConfigValidateReadOnlyIsHermetic, which fails identically on a pristine base
worktree under the same filter and passes standalone on both. TestCorpusGolden
green, so `bd config --json` is byte-identical to the committed corpus.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
`bd count` had two implementations of the same command. The direct route
built a types.IssueFilter in cmd/bd/count.go, loaded the workspace list
config and applied the --include-infra policy; the proxied route did all
four again in count_proxied_server.go and executed against the use case.
Both now build an issueops.CountRequest and ask for the role, and the
difference between the two routes is which accessor answers.
THE ROLE. Counts are NUMBERS; Reader answers PAGES OF ISSUES. Different
question, so its own role per the governing rule rather than a counted
variant on Reader: a count has no order, no page and no cursor, and a
request type carrying paging fields a count must ignore is the shape that
makes a caller believe --limit 10 bounded the answer. Count and
CountByGroup are two shapes of ONE question and cannot be separated in
practice - the grouped answer carries the scalar Total, because label
buckets overlap and the sum is wrong - so the role is born with both.
WHAT CONVERGED, beyond the duplication:
- the wisp-tier policy. BuildCountFilter is now the single definition of
what `bd count` means, beside BuildListFilter, and the GH#4387
cardinality-parity test moved from cmd/bd to internal/workapi where it
compares the two SHARED builders instead of a CLI helper against one
of them.
- the grouped Total. "use the scalar count, not the sum, because label
buckets overlap" lived in cmd/bd; an HTTP surface adding grouped
counts would have had to rediscover it.
- the config load. It happens inside the role, and only under
IncludeInfra, so a plain count still makes one query.
CONFORMANCE. backend/conformance/counter_contract.go holds twelve cases,
each citing the leaf doc by line, run at all three implementations with
ZERO parks. They are TWO independent votes plus an engine check, not
three: dolt and embeddeddolt both hand back internal/workapi/storecounter,
and the unit-of-work provider is the second body.
ENFORCEMENT. cmd/bd/count.go no longer names types.IssueFilter, so `count`
LEAVES the forbidigo exception list - the hole it needed is closed rather
than merely unused. The reader-constructor depguard rule becomes
cmd-bd-role-constructors and gains storecounter, so it is a list the next
role extends by one line instead of a rule per role.
NO HTTP HANDLER EXISTS for count. `bd serve` publishes /healthz,
/v0/beads/context, /v0/beads/ready, /v0/beads/issues, /v0/beads/issues/{id}
and POST /v0/beads/issues/{id}:claim, and the spec is Tier-1 ratified, so
none was invented.
THE PER-ROLE COST, which no design budgeted, is now written down in
engdocs/ADDING_AN_ISSUEOPS_ROLE.md: twelve steps derived from this commit,
naming the accessor line in internal/storage/storage.go, the hook and
telemetry wrappers, the two store accessors, the unit-of-work source, the
three conformance wirings, the five places each decorator enumeration
lists a role, and the two lint edits. Every later new-role commit follows
it.
Verified: build, vet, gofmt clean; golangci-lint 0 issues;
TestCounterContract green at dolt (12/12), embeddeddolt (12/12) and uow
(12/12); TestEmbeddedCount* and TestProxiedServerCount* green with their
gates set; TestCorpusGolden green, so `bd count --json` is byte-identical
to the committed protocol corpus.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
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>