* 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(list): bd list's remaining filters over http behind issues.list.filters
Over http every `bd list` filter beyond the created bounds and the title,
id and no-assignee scope refused (time bounds, priority range, text and external-ref
matches, spec, label pattern/regex, exclude-type, no-parent, no-labels,
empty-description, pinned/no-pinned, deferred, overdue, mol/wisp type).
The library entry already applied all of them: issueops.Reader.List via
workapi.BuildListFilter, shared by the CLI and the handler. This adds
only the wire.
- Server: GET /v0/beads/issues decodes 29 new optional parameters
(listFilterParams, decode only; countIssues' names where it already
spells the filter) into the existing ListRequest, behind one new
behavior token, issues.list.filters. mol_type/wisp_type are closed
enums refused by name (an empty value too). wire_revision stays 2;
apigen and the wireshape golden are regenerated (additive only).
- Every RFC 3339 bound the listing and count decode is normalized to UTC,
so an offset-bearing bound selects what its Z twin does on a zone-less
timestamp column.
- workapi.BuildListFilter refuses PinnedFlag with NoPinnedFlag
(ErrValidation, the CLI's own sentence) instead of letting PinnedFlag
win; over http that is a 400 on no_pinned.
- Client: the encoder sends the members (encode.ListFiltersMembers, one
list read by the encoder, the pre-dial gate and a spec-parity test).
Against a server not advertising the token, httpReader.List refuses
before dialing with ErrUnsupported naming issues.list.filters. The 29
E-ListRequest ledger refusal rows retire; the ledger doc is updated;
skew flag mappings added.
- Tests: handler decode/parity/enum/UTC/malformed/pinned-pair tests;
encode member/gate/spec parity and bound encoding; per-member
ride-behind-token and pre-dial skew refusal; two new Reader contract
cases on every leg (dolt, embedded, uow, served): the eight time
bounds at exact boundaries (strict, whole-second truncation, NULL never
matches, +02:00 equals UTC) and one in/out row per remaining family;
three served Reader cases unparked; TestE2E_ListFilterParityOverHTTP
(served == embedded, masked server refuses naming the token, no dial);
five corpus shapes marked pending until the reference server profile
advertises the token.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* feat(list): exclude_status on listIssues, the 30th issues.list.filters member
issueops.ListRequest gains ExcludeStatus: statuses to leave out of a
listing, appended to the default exclusions (never re-admitting what they
hide), comma-separated or repeated, and validated against the workspace's
statuses by the same rule CountRequest.ExcludeStatus uses (an unknown name
is ErrValidation). The rule moves into one shared function,
workapi.ParseExcludeStatus, called by both builders. With AllFlag it reads
the active set without enumerating every status, so an http-backed caller
can list O(active) rows instead of the whole history.
- Server: listIssues decodes a repeatable `exclude_status` under the same
issues.list.filters token (no new token); an unknown name is a 400 on
exclude_status. apigen and the wireshape golden are regenerated
(additive).
- Client: the encoder sends it and it joins encode.ListFiltersMembers, so
the pre-dial gate asks for the token.
- It is refused together with ReadyFlag, like the other members the ready
query cannot carry.
- No `bd list --exclude-status` flag yet (it would need the CLI docs
regenerated); the member is reachable through the library and the wire.
Tests: builder unit test (append, AllFlag, comma split, unknown name);
handler decode and 400; encoder, round-trip and gate; Reader contract
cases on every leg (active set under AllFlag, repeated and comma values,
adds to the defaults, narrows an explicit Status, unknown name refused).
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(list): label_regex compile errors are 400s; review polish for list filters
- An invalid `label_regex` on GET /v0/beads/issues, /v0/beads/ready and
/v0/beads/ready:count is now `400 invalid_argument` (`invalid_value` on
`label_regex`) instead of `500 internal`. The database still compiles
the pattern in its own dialect; a request that sent a regex and earned
the engine's "regular expression is invalid" refusal is attributed to
the parameter (failRegexReadErr). The same text on a request with no
regex stays a server fault.
- mol_type and wisp_type refuse each other's vocabulary (tests pin
`mol_type=heartbeat` and `wisp_type=swarm`), so the call-site
allowlist, not just the spec enum, is covered.
- exclude_status with a workspace custom status: leg tests on the
embedded store and over the served wire (accepted and applied; a name in
no vocabulary refused). ReaderFixture cannot configure custom statuses,
so these sit beside the count's twin rather than in the contract.
- The search e2e gains a positive arm: --desc-contains returns exactly the
row whose description carries the token.
- Docs: `all` plus `exclude_status` keeps every status not named (pinned,
hooked and custom done/frozen included unless named), not "the active
set"; label_regex documents its 400. A corpus source line is made
neutral; a test message says 30.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(list): compose issues.list.filters with the --title-contains fold
#7631, now on main, folds `bd list --title-contains` onto listIssues
`title` and refuses the TitleContains left over from a --title and
--title-contains pair that differs, because the listing then had one
title parameter. This branch publishes `title_contains` behind
issues.list.filters, so that leftover now rides it beside `title` and
the server applies both. Neither half is dropped, and against a server
without the token the pre-dial gate refuses, naming issues.list.filters.
- encode.FoldTitleContains still runs first; its doc now says where a
differing pair goes.
- Tests: the fold table expects `title` plus `title_contains` for a
differing pair, including the ſ/s pair strings.EqualFold would match;
the differing-pair refusal names issues.list.filters; the
list_filters_test sweep pairs its TitleContains probe with a differing
TitleSearch, since a lone one asks only for issues.list.title; the e2e
differing-pair refusal becomes a listFilterShapes row that answers
exactly child-a over http and embedded, and refuses before dialing
without the token.
- The gc-polecat-closed-after corpus shape's pending reason also names
issues.list.title. The CHANGELOG --title-contains entry no longer
lists the differing pair and --closed-after as refused.
Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* build(bazel): auto-sync BUILD files
Applied from the bazel-sync-patch artifact of https://github.com/gastownhall/beads/actions/runs/39013611268
(`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(list): serve --priority-max in search parity, refuse the parent pair
The proxied tier's search parity table still expected a remote
`bd search --priority-max 1` to refuse, because listIssues could not
carry it. This branch serves priority_max behind issues.list.filters,
so the remote route answered and the dolt-race shard went red in
TestProxiedServerSearchRoutesAgree. The row now expects the answer on
every route. It was the last wireCan=false row; the branch stays, with
a comment, for the next flag listIssues cannot carry.
- ParentID with NoParent: a served listing now carries no_parent beside
parent, and ANDing the two answered only the edge-less rows under the
parent's dotted id. BuildListFilter refuses the pair with
ErrValidation, in the sentence bd list and BuildCountFilter already
use, so issueops.Reader.List refuses it on every backend and the
listing answers 400 on no_parent. Pinned by a builder test, a reader
conformance case (dolt, embedded, uow, served http) and two httpapi
tests.
- POST /v0/beads/issues:claimNext shares the ready listing's
label_regex but answered a pattern the database cannot compile with
500. It now gives the listing's 400 invalid_value on label_regex,
through the helper the listing's mapping is split into.
- The descendant walk's ledger rows said listIssues publishes no
parameter for members it now serves behind issues.list.filters. They
now say the walk does not send them yet, and that --flat or --json
asks listIssues directly. The ExcludeStatus, Pinned and ExcludeTypes
rows, the parentwalk.go header, the walk table's doc and two walk test
comments are corrected the same way, and the ledger doc is
regenerated. parentWalkRefusals notes that a member moved off the list
must check issues.list.filters itself, because the walk dials past
the listing's pre-dial gate.
- Spec: the listing's no_parent documents the pair's 400, the count's
exclude_status no longer says it has no listing counterpart, and
claimNext's label_regex documents its 400. types.gen.go is
regenerated. Comment-only: countFilters, and readyScopeFields'
ExcludeStatus entry.
- CHANGELOG and README say the default `bd list --parent` tree view
does not carry the new filters yet; the label_regex entry names
claimNext, and a Changed entry records the parent-pair refusal.
Second review pass: docs and comments only, no behavior change.
- The prose copies of the issues.list.filters member set now match
ListFiltersMembers: CapIssuesListFilters and wire.CapListFilters name
the status exclusion, and the spec's capabilities text names
label-regex.
- Every time bound on the listing and the count goes through
q.timestamp, which normalizes it to UTC, and sqlbuild compares it
strictly at whole-second precision. listIssues' created_before and
created_after, and countIssues' created, updated and closed bounds,
now say so in the words the new listing bounds use. The count's
updated bounds also say what they filter, and its closed bounds say
that a NULL closed_at never matches. types.gen.go is regenerated.
- README and CHANGELOG: `--flat` or `--json` applies the filters to the
parent's direct children, not its whole subtree.
- The 29 listRefusal rows this branch serves stay deleted rather than
kept as retired rows, as #7550 deleted its TitleSearch, IDFilter and
NoAssignee rows when it served them. The CHANGELOG now says the rows
are removed, not retired.
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: Eddie the Engineer <338826946+gascity-eddie[bot]@users.noreply.github.com>
Co-authored-by: github-actions[bot] <41898282+github-actions[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(issueops): gate members on create and update, one bounds validator
The library half of serving gate await fields. Every local leg already
stores await_type, await_id, timeout and waiters on create, and await_id
on update; this adds the two missing pieces.
- IssuePatch.Waiters: a whole-value replacement of the waiter list (nil
or empty clears, stored as []), mapped by UpdateFields and by the
unit-of-work updateSpec, deep-copied by CloneUpdateRequest, and
classified as a non-coordination signal on the dolt leg. Duplicates are
stored as given; dedup stays the CLI's.
- ValidateGateFields / ValidateGatePatch with *issueops.GateFieldError
{Field, Detail} wrapping ErrValidation, mirroring ReclaimFieldError so a
front door can name the member. The rules are the columns' only:
await_type <= 32 characters, await_id <= 255 characters, the JSON
waiter list <= one TEXT column (65535 bytes), and timeout >= 0. No
await_type allowlist, no gate-type-only rule, no timer-needs-timeout
rule. Run from ValidatePublicCreateRequest (every create shape on every
backend) and ValidateUpdateRequest (await_id, waiters).
- Conformance: LifecycleCreate WritesTheGateMembers / BoundsTheGateMembers,
LifecycleUpdate PatchesTheGateMembers / BoundsTheGateMembers and
BatchApply CarriesTheGateMembers, each bound asserted from both sides,
wired on the dolt, embedded and uow legs and parked on the http leg on
the live refusal rows until the wire slices land.
- httpclient: IssuePatch.Waiters is refused before the dial on both patch
documents under a new W-IssuePatch.Waiters row (refuse-not-drop), until
the wire publishes it.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* feat(httpapi): publish the gate members on create and update
The wire half of serving gate await fields, over the library slice.
- createIssue and the issues:batchApply create item publish await_type,
await_id, timeout (nanoseconds, the encoding Issue.timeout reads back)
and waiters, behind the new behavior token issues.create.gates (one token
for both create shapes, the issues.create.defaultPriority precedent).
- updateIssue's patch and the batchApply update item's patch publish
await_id and waiters (whole-value replacement; [] clears), behind
issues.update.gates. await_type and timeout are not patch members: no
local update route changes them. Neither is nullable; null is refused
naming the member, as on title.
- The handlers only decode and project (createGateMembers,
patchGateMembers). The wire is no stricter than the library: every bound
is the role's *issueops.GateFieldError (await_type <= 32, await_id <=
255, the JSON waiter list <= one TEXT column, timeout >= 0), mapped to the
existing 400 invalid_argument with param naming the member at its level
(await_type, patch.waiters, items[i].create.timeout,
items[i].update.patch.await_id). The spec mirrors exactly that:
maxLength 32/255 and minimum 0, and no minLength/maxLength/maxItems on
waiters. Blank and duplicate waiters and any await_type reach the role
untouched.
- Spec: the four schemas, the capability prose, and the stale sentences
(createIssue's "await_* publishes on no operation, read or write" and the
patch's "spec_id and await_id publish nowhere yet"). apigen regenerated
(from the remote drift test's diff), wireshape golden regenerated:
additive entries and sides only, wire_revision stays 2.
- Client: the two tokens are mirrored in wire.behaviorCapabilities so the
vocabulary stays set-equal with the server's. The client still refuses
every gate member before the dial (the client slice flips that); the write-ledger
pending sets name the newly published members under their live refusal
rows, and the W-CreateRequest.Issue / W-IssuePatch.AwaitID /
W-IssuePatch.Waiters reasons, the served-leg park reasons and the S4b
waiver now say the server publishes them and this client does not send
them yet.
Tests: internal/httpapi/gate_fields_test.go pins member mapping on all four
bodies, clear-by-empty on both patches, null and unpublished-member refusal,
GateFieldError -> param at every nesting level, and both tokens advertised.
Mutating the handlers (dropping the mapping, the GateFieldError arms or the
tokens) turns them red.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* feat(httpclient): send the gate members behind their tokens
The client half of serving gate await fields, over the wire slice.
- Create: await_type, await_id, timeout (nanoseconds) and waiters join the
create vocabulary on createIssue and batchApply create items (now
twenty-four members), sent verbatim when populated. Patch: await_id (by
presence; "" clears) and waiters (whole-value; nil/empty travels as [])
are encoded on both updateIssue's and the batchApply update item's patch.
- Token gate before the dial: a create naming any gate member needs
issues.create.gates, a patch naming one needs issues.update.gates. Without
the token the request refuses with wire.NewCapabilityError naming it
(typed ErrUnsupported{Capability}), never a dropped member. batchApply
checks the whole plan once, so no partial plan is sent. A request naming
no gate member never reads either token. Store.requireCapabilityBeforeDial
is the shared helper; requirePersistenceMove now uses it.
- Bounds read back typed: the server's 400 invalid_argument/invalid_value
whose param names a gate member at any level (await_type, patch.waiters,
items[i].create.timeout, items[i].update.patch.await_id) is rebuilt as the
role's *issueops.GateFieldError, the problem kept in the chain (and a batch
refusal still becomes its *ItemError). Without this the served bounds
contracts could not pass.
- Ledger: W-IssuePatch.AwaitID RETIRED; the library slice's W-IssuePatch.Waiters row
deleted (it never shipped outside this branch); W-CreateRequest.Issue and
W-CreateItem.Issue no longer cover the gate members; new
W-CreateRequest.Gates (refuse, Capability issues.create.gates) records the
token-gated late refusal for both create shapes. engdocs ledger
regenerated from Ledger() (262 rows: 201 refuse, 34 degrade, 27 retired).
- Write-ledger table: the wire slice's pending sets are flipped into carried.
- Served leg: the five gate cases (LifecycleCreate Writes/Bounds,
LifecycleUpdate Patches/Bounds, BatchApply Carries) are un-parked and run;
the S4b waiver and served comments now say await_id is sent.
Tests: internal/httpclient/gate_fields_test.go (encode on all four bodies,
clears, old-server refusal per member naming the token with no dial, no
partial batchApply plan, plain requests unaffected on old and new servers,
GateFieldError rebuilt from the problem). Disabling the three pre-dial
checks turns the refusal tests red.
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/38841144413
(`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.
* docs(issueops): say the gate timeout rule is no column's
The gate validator's doc said its rules were the stored columns' and that
no command line can produce a negative timeout. The widths are the
columns' (VARCHAR(32), VARCHAR(255), TEXT), but timeout_ns is a BIGINT,
so a non-negative timeout is a rule no column enforces; the wire
publishes it as minimum 0. The raw store creates (CreateIssue,
CreateIssues) and import do not run the validator, so bd gate create
--timeout=-5m, a formula step's gate.timeout and a template clone still
store a negative timeout until they move onto the role.
Also say that GateFieldError.Detail is prose whose HTTP copy ends with
the server's own clause, so a caller dispatches on Field, and why a
create omits an empty waiter list while a patch sends [] to clear it.
Comments only; no behaviour change.
Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* test(corpus): gh:run await_id persist refuses by the missing gate token
#7604 (now on main) made bd gate check persist a gh:run gate's discovered
run ID through Lifecycle.Update. Its served test expected the HTTP
client's W-IssuePatch.AwaitID refusal, which persistGateCheckAwaitID
rewords to name await_id. This PR retires that row: the patch carries
await_id behind issues.update.gates. Through the reference proxy, whose
server advertises no gate token, the persist is now refused before the
dial by the capability error ("bd serve at ... does not advertise
capability "issues.update.gates", which updateIssue requires"), so the
merged tree failed the subtest's await_id and updateIssue assertions.
The subtest now expects that refusal: no writes, the error names the
gate, the missing token and the server, no role or store method leaks,
and await_id is untouched. persistGateCheckAwaitID already returns a
capability error as the role raised it (#7604 pins that), so no code
changes. Against a server that advertises the token the persist goes
through: a scratch probe against the in-process server recorded
await_id=4242 and closed the gate.
Also correct the gate.go comment and the CHANGELOG entry that still said
the HTTP client refuses every await_id patch.
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 <adopt-pr@gascity.com>
* feat(http): advertise issues.update.claim and route claims by it (S24a/b)
updateIssue has served `claim` (upstream #6890), resolved on both planes so
a wisp is claimable, with no capability token: a client could only find it
by eating the skew 400, and gc's wire_compat preflight (which lists
issues.update.claim as an optional token) never saw it, so gc claimed every
wisp through claimIssue, whose Claimer role excludes the wisp plane.
Server: CapIssuesUpdateClaim ("issues.update.claim") joins
behaviorCapabilities. The spec names it on UpdateIssueRequest.claim and in
the context capabilities prose (apigen regenerated, descriptions only). No
request or response member changes; wire_revision stays 2.
Client: Lifecycle.Update reads the token from the cached handshake before
the dial. With it, every claim is one updateIssue call and its answer is
final (no fallback on any error). Without it, a claim alone goes straight to
claimIssue (no doomed 400 first; a wisp still refuses by name,
W-ClaimRequest.Wisp, whose Why now names the token), and a claim beside a
patch, a guard or a force override is refused before the dial with
ErrUnsupported{Capability: issues.update.claim}. serverPredatesUpdateClaim
(the error-sniffing fallback) is gone.
Tests: the four capability lists (routes.go, wire/handshake.go,
server_test, wire vocabulary_test) move together; unit tests for both
routes (pre-dial refusal dials nothing; with the token nothing falls back);
served tests claim a wisp through updateIssue with the token (zero claimIssue
dials, post-claim revision stitched), refuse it by name without it (zero
updateIssue claims, one claimIssue), and refuse a claim beside a patch
without the token while the same request claims and patches the wisp with
it. Live-mutated: ignoring the token fails the unit test.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* test(http): count only ready --claim's requests in the claim-next check
TestE2E_AdvertisedExternalPolicyIsPassedThrough counted every request
since counter.reset(), so its "no by-id claim" check also saw the earlier
`update <other> --claim` step. The MC handshake mask does not advertise
issues.update.claim, so this PR routes that claim to claimIssue
(POST /v0/beads/issues/<id>:claim) by design, and the check failed in
Bazel / embedded Dolt tier (//backend/http:http_served_test shard 6 of
7), turning CI Gate / Required red.
Count from the snapshot length taken just before `ready --claim`, so the
check covers only the requests that command issues. The counter is not
reset: the close-policy check below scans the same history.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(http): refuse a token-less template claim on the client's pre-read
Against a server without issues.update.claim, Lifecycle.Update sends a
claim alone to claimIssue (claimWithoutUpdateClaim) and returns before
applyTemplateGuardForServer runs. claimIssue's role has no template check
(bd-jkp9v3), so `bd update <template> --claim` against every server
without the token claimed the template. The base refused it before any
write: on the client's pre-read against a server without
issues.update.allowTemplate, and in updateIssue's own guard against one
with it.
claimWithoutUpdateClaim now pre-reads the row and returns
AuthorizeTemplateUpdate's refusal before the claimIssue dial, whatever the
handshake says about allowTemplate: that token means updateIssue guards
templates, and this route never dials updateIssue. Any other row goes on
to claimIssue as before (a wisp to its refusal by name), and so does an id
the pre-read cannot find, so claimIssue's not-found stays the one reported.
TestUpdateClaimRefusesATemplateWithoutTheToken (stub wire) and
TestServedUpdateClaimRefusesATemplateWithoutTheToken (served tier) pin it
under an allowTemplate-only and a neither-token handshake. Both go red
without the pre-read; the allowTemplate-only legs also go red if the
existing guard is only moved above the claim branch.
TestUpdateClaimFailsClosedWhenThePreReadFails pins the pre-read's third
arm under the same two handshakes: a read that fails other than as
not-found returns that failure and never dials claimIssue, since the
row's template bit is unknown then. A best-effort pre-read (that failure
falling through to the claim) passed go test ./internal/httpclient/ and
its served Claim|Template tier before this test, and goes red on both
legs with it.
A claim beside AllowTemplate is refused before the dial with
ErrUnsupported naming the token, like a claim beside a patch, a guard or
a force override (isClaimOnlyUpdate already excluded it), but no prose
said so: claimWithoutUpdateClaim's doc, CapIssuesUpdateClaim's doc, the
test doc and the CHANGELOG entry now list it, and a
TestUpdateClaimAgainstAServerWithoutTheToken row pins it. Dropping
!req.AllowTemplate from isClaimOnlyUpdate passed the same unit and served
runs without that row and goes red with it.
The prose now follows the handshake rule too: the W-UpdateRequest.Claim
ledger row (and its re-rendered md) no longer calls claimIssue the
fallback for a server that 400s the member, Update's doc names
claimWithoutUpdateClaim instead of the nonexistent claimRouteForServer,
wire.UpdateFlags.Claim drops the "safe to read as skew" rationale no
caller relies on anymore, and the CHANGELOG entry says a template is still
refused on the token-less route.
Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Gas City Adopt-PR
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
* feat(http): serve IsBlockedBatch through the BlockingAnnotator role behind dependencies.blocking.isBlocked
gc's native ready cache needs bd's stored, transitive is_blocked column for
the active set (beads.BlockedQuerier.IsBlockedBatch). Over http the client
answered it with the generated stub, so every reconcile logged
`operation "IsBlockedBatch" not supported by the http backend`, the
projection stayed disabled and native Ready took ~5 s on the MC shadow.
No read a deployed (1.3.0) server serves can answer the column exactly:
the /v0 reads hydrate issues without is_blocked, the blocking decoration is
direct and two edge types only, and the flag also propagates down
parent-child edges and reads waits-for / conditional-blocks gates. So this
is an additive server behaviour plus a token, not a client-side
composition.
- issueops: BlockingRequest.IncludeIsBlocked asks for, and
IssueBlocking.IsBlocked carries, each answered id's stored flag (nil =
no row, never "free"). issueops.BlockedFlags is the one library entry
for the batched read over the role, chunked at BlockedFlagsChunk (100,
held equal to the served issue_id bound by an httpapi test).
- Bodies: storage/issueops.ExecuteBlockingAnnotation reads the flag with
IsBlockedBatchInTx in the same read transaction (dolt, embeddeddolt and
every sqlkit-style store that calls it); the unit-of-work body asks the
new DependencyUseCase/Repository IsBlockedBatch (same shared SQL body).
externaldeps keeps IsBlockedBatch's external-blocker invariant on the
local and remote annotators, and its Store.IsBlockedBatch no longer makes
the raw edge read over a role-served store.
- Wire: GET /v0/beads/dependencies/blocking accepts `is_blocked` behind the
new behaviour token dependencies.blocking.isBlocked (spec, apigen,
wire-shape golden). wire_revision stays 2.
- Client: httpBlockingAnnotator forwards IncludeIsBlocked and refuses it
BEFORE dialing with *ErrUnsupported{Capability:
dependencies.blocking.isBlocked} against a server that does not
advertise it; Store.IsBlockedBatch is issueops.BlockedFlags over that
annotator, so gc's errors.As latch still sees the typed refusal on an
old server, now naming the token that lifts it.
Tests: conformance case RunBlockingAnnotatorReportsTheTransitiveBlockedFlag
(child of a blocked parent is blocked, free is false, a ghost has no flag,
unasked carries none, BlockedFlags agrees) on the dolt, embedded, uow and
served legs; httpapi handler and chunk-bound tests; client tests for
chunking, the wire shape and the zero-dial refusal; vocabulary/capability
gates.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(externaldeps): keep the external blocker on the unit-of-work IsBlockedBatch
bd serve on a server or proxied-server workspace serves through the
unit-of-work arm (WrapUOWProvider) and advertises
policy.external_dependencies, so a client trusts the server's answers and
adds no external term of its own. That arm's dependency use case did not
override IsBlockedBatch, so the new dependencies.blocking.isBlocked flag
answered the stored is_blocked column, which has no external term. An issue
blocked only by an unsatisfied external: ref came back is_blocked=false,
with that ref listed in its own blocked_by, while GET /v0/beads/ready
excluded it.
dependencyUseCase.IsBlockedBatch now raises every id that has an
unsatisfied external blocker, deciding by the edges and resolver
GetReadyWork excludes by, read through the same unit of work. Unlike Ready
it resolves only the refs of the ids the column answered: a client asks in
chunks, and no chunk should reopen every foreign project the workspace
names. An id naming no row stays absent.
Also correct the store decorator's IsBlockedBatch doc (the served flag now
comes from the annotator role), add the CHANGELOG entry for the new
capability, and pin the flag against Ready on every arm: WrapUOWProvider,
directly and through its BlockingAnnotator (an absent id stays absent), the
local annotator, and the served test, which now asserts the flag and the
batched read. A counting opener pins that the unit-of-work read opens only
the foreign projects its asked rows name.
Checked against a real bd serve on a proxied-server workspace. At
97bcb57738 an issue blocked by external:remote:payments answered
is_blocked=false while /ready excluded it. With this change it answers
true, and once the capability ships /ready includes the issue and
is_blocked is false. Asked about a free issue alone, the server resolves
no external project; asked about the remote-blocked issue, it resolves
remote and leaves alone the unconfigured project another issue names.
Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* test(externaldeps): pin that a satisfied external blocker leaves the unit-of-work is_blocked false
Review of 192b73676 (bee-ghosttrack): the two new IsBlockedBatch tests only
had unsatisfied external refs, so a body that raised every answered id with
any external record (ignoring the resolver) stayed green.
TestWrapUOWProviderBlockedFlagResolvesOnlyTheAskedRefs's opener now
returns a foreign store whose labelled index carries a CLOSED provider of
provides:payments (the decorator_test.go shape). be-shipped blocks on
external:remote:payments (satisfied) and must read false; be-blocked moves
to external:remote:invoices (still unsatisfied) and reads true; both still
open /projects/remote once. With the reviewer's mutant applied
(`if _, ok := answered[id]; ok && len(state.refsByIssue) >= 0 {`) the test
fails on be-shipped in both new cases; restored, it passes
(bazel test //internal/storage/externaldeps:externaldeps_test).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* test(externaldeps): pin the store arm's satisfied external ref and the unasked is_blocked flag
The store arm decides an external blocker in two places: IsBlockedBatch's
local loop skips a ref the resolver reports satisfied, and the
BlockingAnnotator role folds IsBlocked's verdict, which applies the same
filter, into the served flag. Both annotators, store and remote, add that
flag only when the request asks for it. No test checked either store answer
for a ref whose project had shipped the capability, or that an unasked
annotation carries no flag, so dropping any of those checks left the
package green.
Pin them: IsBlockedBatch and the store annotator answer false for a row
whose only blocker is external:remote:payments once remote has closed its
provides:payments issue, and neither annotator flags a row unasked, even
one an external ref blocks. This is the store half of bd-yewju3; the
previous commit pinned the unit-of-work half.
Each mutant below survives the package at the previous commit and fails
exactly one test here (go test -tags=gms_pure_go
./internal/storage/externaldeps/; unmutated, bazel test
//internal/storage/externaldeps:externaldeps_test passes):
- decorator.go IsBlockedBatch: `&& !satisfied[dep.DependsOnID]` made
`&& len(satisfied) >= 0` fails TestIsBlockedBatchHonorsShippedExternalRef.
- decorator.go IsBlocked: `if !satisfied[ref.raw] {` made always true fails
TestBlockingAnnotatorLeavesShippedExternalRefUnblocked.
- role_accessors.go: `if req.IncludeIsBlocked {` made `if true {` fails
TestBlockingAnnotatorAddsNoFlagUnasked.
- remote_roles.go: dropping `req.IncludeIsBlocked &&` fails
TestRemoteBlockingAnnotatorMergesExternalBlockers.
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>
* fix(http): bd promote over http through issueops.Promote and issues.update.persistence (S21b)
`bd promote` refused over a connected HTTP workspace: it called the raw
PromoteFromEphemeral, which the http backend stubs, and updateIssue's patch
did not publish persistence. MC's PR-intake formula
(mol-normalized-issue-pr-v1) runs `gc bd promote <id> --reason ...`, so this
blocked the HTTP cutover.
- One library entry, issueops.Promote(ctx, PromoteRoles{Reader, Lifecycle,
Commenter}, PromoteRequest{Actor, IssueID, Reason, Provenance}): read the
row, refuse a non-wisp (*NotAWispError, the sentence bd promote always
printed), move it with ONE Lifecycle.Update whose patch is Persistence =
persistent (the role's atomic plane move: same id, labels, deps, events and
comments carried), then write the promotion comment (a comment failure is
reported, the promotion stands). A no-op move is a lost race and reports
NotAWispError without a second comment.
- cmd/bd: the direct route runs it over the store's own role accessors, so a
connected http workspace and a local one take the same entry. The history
label is "bd: promote <id>" where the store carries caller labels.
- bd serve: IssuePatchBody.persistence (persistent|ephemeral|no_history,
anything else a 400 naming patch.persistence) on PATCH
/v0/beads/issues/{id}, behind the new additive behavior token
issues.update.persistence. wire_revision unchanged. Spec, apigen and the
wire-shape golden regenerated; the handler only decodes and passes it to
the role.
- httpclient: Lifecycle.Update sends patch.persistence only to a server
advertising the token, and otherwise refuses BEFORE the dial with
*wire.CapabilityError naming it (unwraps to *storage.ErrUnsupported with
Capability set). The batchApply item still refuses it
(W-IssuePatch.Persistence now reads "ON issues:batchApply").
- Conformance: RunLifecycleUpdatePersistentPromotesAWisp on dolt, embedded,
uow and the served http leg; the served
PersistentPreservesUnversionedClass case is unparked.
- Served e2e TestE2E_PromoteOverHTTP: the mc-promote shape end to end
(label kept, comment written, one PATCH, re-promote refused), and under
the MC server mask a pre-dial refusal naming the token with no write.
- Corpus: mc-promote stays pending, relabelled SRV-1 with the reference
profile's exact refusal (the 1.3.0 server lacks issues.update.persistence).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(promote): run the proxied-server route through issueops.Promote (bd-4y73m9)
The adoption review found (major) that the proxied-server route still
promoted through the old engine, IssueUseCase.PromoteWisp in one
transaction with the comment, while the PR's docs said every route runs
issueops.Promote. Converge rather than reword: runPromoteProxiedServer
resolves the id, then runs issueops.Promote over the provider's own
notifying role accessors (proxiedIssueReader, proxiedIssueLifecycle,
proxiedCommenter), the entry the direct route runs. Both routes now share
promoteFailure (the error mapping) and reportPromotion (the comment
warning and the output), so neither contract can drift.
What a script sees change on the proxied-server route:
- the move is the persistence branch of Lifecycle.Update, so the child
counter moves with the row: a promoted parent's next
`bd create --parent` mints .3 after .1/.2 instead of failing with
"issue already exists";
- on_update fires twice, for the move and for the comment, as on the
direct route (it fired once, for the comment);
- a promotion is two Dolt commits, "bd: promote <id>" and
"bd: comment <id>" (it was one);
- a comment that cannot be written leaves the promotion standing behind
a warning, as on every other route, instead of rolling it back;
- a dual-plane id is refused rather than merged, the update role's
template guard applies, and a lost race reads "<id> is not a wisp
(already persistent)".
The PromoteWisp exemption in TestRecordingIssueUseCaseCoversItsSurface
stays, with its reason corrected: no route calls PromoteWisp now, and
its DoltStorage twin fires no hook either. The doc comments on the old
engine (PromoteFromEphemeral on DoltStore and the db layer, PromoteWisp)
no longer say bd promote uses it.
CHANGELOG: the promote entry now names what a script can see on the
direct and proxied-server routes: the hook firings, the comment row
`bd comments` lists, the child-counter carry, the two-commit shape, and
a comment failure that warns instead of rolling back.
Tests:
- TestEmbeddedPromoteMovesAWispParent promotes a wisp parent with .1/.2
children, a dependency and a comment under a counting on_update hook:
the hook fires twice, the dependency and the children's parent edge
survive, `bd comments` lists the old comment and the promotion reason,
and the next child is .3. At the pre-PR base it fails (the hook fired
0 times).
- The proxied journey pins the two commits, and new subtests pin the
child counter (the child_counters row, next child .3) and the two hook
firings. Against the contributor head each fails: one commit, no
counter row and a failing create, one firing.
Review iteration 2:
- TestEmbeddedPromoteMovesAWispParent gets its row in the embedded cmd
shard manifest (shard 64 of 100, from the generator's incremental
--write). Without it //scripts:go_test_sources_test fails both the
NotStale and the bare-write guard, and the generator's --check fails.
- notifying.go no longer lists the promotion comment as a divergence.
The direct route now writes that comment through st.Commenter(),
which HookFiringStore wraps, so an embedded promote fires on_update
for it (TestEmbeddedPromoteMovesAWispParent counts both firings). The
list counts four, and the empty-commit note becomes the fifth item.
- batchapplier.go no longer says persistence is absent from both patch
bodies: the update body publishes it behind issues.update.persistence,
and only batchApply refuses it (W-IssuePatch.Persistence).
- Three comments still tied promotion to the old engine: the
conformance fixture's PromoteWisp no longer claims to do what
`bd promote` does, the CLI differential's promote scenario names
issueops.Promote, and export_source's wisp-relations note names
issueops.MoveIssuePersistenceInTx.
- The Promote unit test compares the whole update patch with
reflect.DeepEqual. The helper it replaces checked 9 of the patch's 22
members, so a Promote that also set Description passed it.
Review iteration 3:
- A refused persistence move answered 500 `internal` over http and
emitted request_error, though the caller could fix the request. The
role now returns two refusals as ErrValidation, so bd serve answers
400 invalid_argument and the client maps that back to ErrValidation:
an unversioned row asked for ephemeral or no_history (the role wraps
types.ErrUnversionedWispMove, a new sentinel NormalizePersistenceMode
returns for that case alone, with its message unchanged), and a
demotion of a row with retained snapshots. A row that breaks its own
persistence invariants still answers 500.
- RunLifecycleUpdateWispModesRefuseAnUnversionedRow pins the refusal on
every leg (dolt, embedded dolt, the unit of work, served http): both
wisp modes match ErrValidation and leave the row durable, unversioned
and off the wisp plane. Without the wrap the dolt leg fails, and the
served leg fails on "answered 500 internal".
- TestMoveIssuePersistenceInTxRefusesDemotionWithRetainedSnapshots is
the first test of the snapshot refusal, and fails without its wrap.
The unversioned unit test now requires both sentinels. The types tests
pin the sentinel, its unchanged message, and that no row-invariant
error matches it: checking the unversioned class ahead of the
invariant checks fails them.
- CHANGELOG: the promote entry counts five script-visible changes, the
fifth being the lost-race refusal sentence, and says the two refusals
now answer 400 over bd serve and gain a `validation failed: ` prefix
locally.
- NotAWispError's doc comment records that a no-history wisp is refused
too: the gate reads the Ephemeral flag, as bd promote always has, and
`bd update --persistent` is the move for that row.
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(list): bd list --no-assignee, --title and --id over http behind per-parameter tokens (S15b)
Over http `bd list --no-assignee`, `--title` and `--id` refused: the list
encoder had no listIssues parameter for ListRequest.NoAssignee,
TitleSearch or IDFilter (B3 #11). All three are maintainer-city cutover
blockers: gc's default on_boot hook runs
`bd list --no-assignee --status=in_progress ...` on every agent boot, the
PR-intake formula lists by `--title "$SUBJECT"`, and the pr-review skill
by `--id <ids>`.
The library entry is unchanged: issueops.Reader.List, whose bodies
already apply all three through workapi.BuildListFilter, the same entry
the local route reads through.
- Server: GET /v0/beads/issues decodes `no_assignee`, `title` and `id`
into those ListRequest members (`id` handed over as written; the role
splits, trims and de-duplicates, as countIssues already does). Each is
behind its own new behavior token, issues.list.noAssignee,
issues.list.title and issues.list.id (additive, wire_revision stays 2):
each is a separate caller's dependency, and a refusal names exactly the
one it needed. The spec parameters cite their tokens; apigen and the
wire-shape golden are regenerated.
- Client: the encoder maps the three members to their parameters, and
httpReader.List refuses a request carrying one BEFORE dialing, with
ErrUnsupported{Capability: <token>}, unless the handshake advertises
that token (refuseUnservedSearch generalised to one table,
tokenedListFilters, with bd search's `q`). Never a round trip an older
server answers unknown_parameter, never a wider listing.
- ErrHTTPUnsupported's text names the capability when it has one, as the
portable sentinel does, so `bd list` says which token the server lacks.
- The three E-ListRequest ledger rows retire; the ledger is re-rendered.
The id scope unparks the served Reader contract: the sixteen cases parked
on E-ListRequest.IDFilter now run against the in-process server. Twelve
pass as written; four still park, each now on the member it actually
needs (Offset twice, PinnedFlag, ExcludeTypes). The served refusal sweep
asserts SpecPrefix where it asserted IDFilter.
Tests (failing first): handler test that each parameter reaches the
storage filter; client tests that each member rides its parameter behind
its token and refuses pre-dial, zero dials, naming its token, against a
server lacking it; round-trip and vocabulary gates; capability lists.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* test(backend/http): the four maintainer-city list shapes end to end; corpus marks relabelled SRV-1 (S15b)
TestE2E_ListScopeFiltersOverHTTP runs the corpus shapes gc-list-on-boot,
gc-list-on-boot-workflow, mc-list-title and mc-list-id through the real
bd against the in-process server (which advertises the three new tokens)
and requires each to answer an embedded workspace's rows and exactly the
rows it names: --no-assignee leaves out an assigned in-progress row on
the same lane, --title is case-insensitive, --id lists a closed id under
--all. Against the MC production server's handshake shape each shape
exits non-zero naming its token and never dials listIssues.
The corpus suite masks the served side to reference_server.json, the
deployed bd 1.3.0 surface, which advertises none of the tokens, so the
four shapes now get the named pre-dial refusal there. Their marks move
from S6c+S15b to SRV-1 with that reason, like mc-search. With a scratch
profile that adds the three tokens and parameters (not committed) exactly
these four shapes report "now passes; remove the pending mark" and
nothing else changes.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(list): adopt bd-enterprise's listIssues `id` contract: repeatable, issues.list.ids (S15b)
bd-enterprise already publishes listIssues `id` (E9-S2): a REPEATABLE
parameter, one id per value, behind `issues.list.ids`, with its client
sending IDFilter split into one value per member. The first cut of S15b
took ONE comma-separated `id` behind `issues.list.id`, so the same
parameter name had two incompatible meanings: an OSS client's "a,b" is a
400 on an enterprise server, and the enterprise rebase onto main would
collide. OSS now publishes enterprise's contract unchanged:
- Server: listIDFilter (ported verbatim) decodes the repeated `id` into
ListRequest.IDFilter's comma set; more than 200 values, an empty value,
a comma, leading or trailing whitespace, a control character or an
over-long id is a 400 `invalid_argument` on `id`. The spec parameter is
enterprise's (array, maxItems 200); apigen and the wireshape golden are
regenerated.
- Token: CapListIDs = "issues.list.ids", the enterprise spelling and name
on both sides.
- Client: the encoder splits the set the way the role does (splitIDSet)
and sends one `id` per member; the pre-dial gate fires only when the set
names an id.
- Tests: list_ids_test.go is enterprise's id cases (the exact set reaches
storage, the 200 bound is served, every refusal beside its control, the
spec bound matches the constant); the handler, client, round-trip and
e2e cases move to the repeated shape and the new token.
`no_assignee` and `title` are unchanged. Served tier, http e2e (including
TestE2E_ListScopeFiltersOverHTTP) and corpus_served_test pass; with a
scratch reference profile advertising the three tokens exactly the four
S15b shapes report "now passes".
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
* fix(show): --current through issueops.FindCurrentIssue over the Querier role; no swallowed refusal (S6e)
Over http `bd show --current` printed the WRONG issue, exit 0.
resolveCurrentIssueID asked the raw SearchIssues method for the actor's
in_progress and then hooked work; the http backend refuses that method, the
refusal was taken for "nothing found", and the command fell back to the
last-touched issue. The proxied route had its own copy of the lookup, read
inside its unit of work, with the same swallow.
One library entry now: issueops.FindCurrentIssue(ctx, Querier, actor). It
asks the Querier role (queryIssues over http, which every deployed server
publishes) for `status=<s> AND assignee="<actor>"`, limit 1 — exactly the
raw filter, answered in the store's default order, so the same row comes
first on every backend — in_progress, then hooked. A failed read is an
error; "" (two reads that answered and found nothing) is the only miss. The
actor is a quoted, escaped query value; the query language reads
`assignee=none`/`null` as "unassigned", so such an actor (or an empty one)
is not asked about.
Both CLI routes call it with their route's Querier (store.Querier() or the
proxied provider's) through one cmd/bd helper; what stays in the CLI is the
actor and the last-touched fallback (a workspace file). The proxied route
resolves --current before it opens its unit of work, and its duplicate
in-transaction lookup is deleted.
Tests: issueops unit tests (order, failure is an error on either read,
quoting, unaskable actors, each expression evaluates to exactly the raw
filter); cmd/bd fallback tests; served e2e TestE2E_ShowCurrentOverHTTP
(in-progress beats a later-touched issue, hooked when nothing is in
progress, last-touched only when neither). Against the old code the e2e
fails with exactly the reported bug.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(recompute-blocked): one library entry, storage.RecomputeBlocked; a no-op on a remote backend (S25)
`bd recompute-blocked` refused over http ("storage backend does not support
is_blocked recompute"), and gc's BdStore.RecomputeBlocked issues it.
is_blocked is server-derived. Every write a remote client makes is committed
by the server's own store, which keeps the flag under
issueops.BlockedStateInvariant's local-write clause (targeted, inside the
write's transaction; a Postgres-family server has no full recompute at all
and runs a no-op readiness strategy for the same reason). A client cannot
leave the flag stale and holds no copy of it. The invariant's merge clause
(a recompute skipped after a pull, bd-6dnrw.37; a migration that over-set
it, beads#7037) happens to the SERVER's database, and its repair is this
command in the server's workspace.
So the decision is in the library, not the CLI: storage.RecomputeBlocked
(internal/storage/blocked_recomputer.go) is the one entry every backend goes
through. A local store (storage.BlockedRecomputer) recomputes its column; a
store implementing storage.ServerMaintainedBlockedState — the http client,
whose BlockedStateMaintainedByServer answers true — recomputes nothing and
reports MaintainedBy "server". No wire operation: a whole-column rewrite any
bearer of a workspace credential could trigger, for state no client can have
caused, is not one to publish. The proxied route keeps its pinned-connection
plumbing around the same versioncontrolops body the stores run.
--json keeps rows_corrected (gc requires the member; wh-bridge-sync reads the
exit code) as 0 and adds maintained_by: "server"; the text says where the
repair runs.
Tests: storage unit tests (local repair runs, server-maintained wins even
over a local repair and runs none, neither refuses); served e2e
TestE2E_RecomputeBlockedOverHTTP (exit 0, JSON shape, text, ready set
unchanged). With the server-maintained branch disabled the e2e fails with
the old refusal.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* feat(search): every bd search route through Reader.List with issueops.SearchListRequest; listIssues `q` behind issues.list.search (S26)
`bd search` called the raw SearchIssues method with its text, which the http
backend refuses ("partial-id search is not available over HTTP"), and its
direct and proxied routes each mapped the flags onto a storage filter by
hand. No served operation could carry search's meaning (title OR id contains
the text, case-insensitively; an id-shaped text also matches exact id, id
prefix and external ref): TitleSearch is title-only and the query language
has no title-or-id predicate.
The library entry is issueops.Reader.List:
- issueops.ListRequest gains Query, SearchIssues' free-text argument as a
member. Both Reader bodies (workapi/storereader and the uow reader) pass it
to SearchIssuesWithCounts where they passed "". It narrows and lifts no
default exclusion; the ready arm refuses it (readyScopeFields).
- issueops.SearchListRequest(query) is search's scope as a request: Query,
every status (AllFlag), every kind of row (the four Include*), and the
store's default order (SortBy priority), so --limit keeps the rows a raw
read kept.
- CLI: ONE runSearch for the direct, proxied and remote routes. One builder
(searchListRequest) maps the flags onto SearchListRequest; the route only
picks the reader (store.IssueReader() or the proxied provider's).
--sort/--reverse reorder the page as before. search_proxied_server.go and
its hand-built filter are deleted, and search leaves the forbidigo
filter-writing exemption.
- Server: GET /v0/beads/issues decodes `q` into ListRequest.Query and calls
the same Reader role, behind the new issues.list.search behavior token
(spec parameter cites it; additive, no wire_revision bump; apigen and the
wire-shape digest regenerated).
- Client: the encoder maps Query to `q`; httpReader.List refuses a request
carrying Query BEFORE dialing, with ErrUnsupported{Capability:
issues.list.search}, unless the handshake advertises it — never a round
trip an old server would 400, never the unsearched listing passed off as
the search. CapListSearch mirrors the server token. Flags listIssues
publishes nothing for are put on the request so the encoder refuses them
rather than widening the search.
Tests: Reader contract case RunReaderListQueryMatchesTheTitleOrTheID (also
pins SearchListRequest's scope) on all four legs — dolt, embedded dolt, uow,
served http (label-scoped, so the served leg runs it as written); handler
test that `q` reaches the seam as the search text, not TitleSearch; client
tests for `q` and the pre-dial refusal (zero dials); round-trip and
vocabulary gates; TestSearchRoutesAgree runs the same twelve flag sets on
the direct, proxied and remote routes and requires identical answers
(remote is bd serve over the proxied database, so ids and order too); served
e2e TestE2E_SearchOverHTTP. The remote legs skip with the
SearchIssuesWithCounts refusal until S6c's externaldeps reader passthrough is
underneath (loud refusal, never an empty or wrong answer); with S6c
cherry-picked all three routes agree.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* build: resync BUILD srcs and the embedded storage shard manifest for S6e/S25/S26
gazelle picks up cmd/bd/show_current.go, cmd/bd/search_remote.go, the three
backend/http e2e files and internal/httpclient/list_search_test.go; the
embedded storage shard manifest gains
TestEmbeddedReaderListQueryMatchesTheTitleOrTheID
(scripts/ci/gen_embedded_storage_shard_manifest.py 15 --weights=duration
--write).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* style: gofmt list_show_filter_modes.go (trailing blank line)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* test(backend/http/corpus): drop the show --current and recompute-blocked marks S6e and S25 retire
With S26 folded in, `bd show --current` resolves through
issueops.FindCurrentIssue over the Querier role and `bd recompute-blocked`
goes through storage.RecomputeBlocked (a no-op on a remote backend), so
gc-show-current and gc-recompute-blocked lose their pending marks.
mc-search stays pending, relabelled S6c+SRV-1: bd search now asks listIssues
with q behind issues.list.search, which the reference server profile does
not advertise, so the client refuses before dialing.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* test(cmd/bd): split the bd search route agreement into the embedded and proxied lanes
TestSearchRoutesAgree skipped unless BEADS_TEST_EMBEDDED_DOLT=1, then ran
its proxied and remote legs only under BEADS_TEST_PROXIED_SERVER=1, and
its name matched neither lane's discovery (TestEmbedded* in
*_embedded_test.go, TestProxiedServer*/TestServerMode*). No CI lane ran
it, which main's #7468 guard (TestProxiedGatedTestsRunInTheProxiedLane)
now fails on.
Split it:
- TestEmbeddedSearchRoutesAgree (search_routes_embedded_test.go): the
direct route, embedded lane.
- TestProxiedServerSearchRoutesAgree (search_routes_proxied_test.go): the
proxied route and the remote route (bd serve over the proxied
workspace), gated only on BEADS_TEST_PROXIED_SERVER. The remote route
must still answer the proxied one row for row, ids and order included,
and refuse the flag listIssues cannot carry.
Neither lane can run the other's workspace, so the shared helper
(search_routes_parity_test.go: the seed, the twelve flag sets, and
checkSearchRoute) holds every route to one expected answer per flag set;
agreeing with it is agreeing with each other. The remote leg's "needs
S6c" skip is gone: S6c is on main, so a refusal now fails.
Both manifests regenerated incrementally (embedded 100-shard block, shard
71; proxied 34-shard block, shard 23). Bazel: bd_embedded_part2_test
(--config=embedded) and bd_proxied_test (--config=doltserver-proxied)
pass and run the new tests; //scripts:go_test_sources_test passes.
Swapping the title-sort expectation fails both routes of the proxied
test.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(search): keep an infra type's durable rows, expand --type aliases, fail the S26 e2e on refusal (bd-1ejjv6)
Review fixes for #7528, attempt 1: the three majors and three minors of
the synthesis.
`bd search --type <infra type>` dropped the type's durable rows (a
promoted wisp, an issue retyped after it was created), exit 0. The shared
listing (workapi.BuildListFilter) narrowed an infra --type to its
ephemeral rows unconditionally, so SearchListRequest's IncludeEphemeral
did not bring back what raw SearchIssues used to return. The narrowing
now applies only without IncludeEphemeral, in BuildListFilter and in the
count lockstep (applyCountIncludeInfra), and the http parent-walk
recognizer reads an infra type's Ephemeral back as the include_ephemeral
intent. This also fixes `bd list --type <infra type> --include-ephemeral`
and GET /v0/beads/issues, which shipped the narrowing in v1.3.1. Pinned by
workapi tests and by template, gate, wisp and promoted-message rows in the
Reader conformance Query case (new ReaderFixture.PromoteWisp) on the
dolt, embedded, uow and served backends; the issueops Reader/Counter docs
and the openapi descriptions say the same.
`bd search --type` handed the raw string to the Reader: an alias (feat,
mol, mr, ...) answered nothing and an unknown type an empty result. It is
now expanded with utils.NormalizeIssueType as `bd list` does, and an
unknown type exits 1. The help text and the CHANGELOG say so, and the
CHANGELOG also records the additive comments_omitted field in
`bd search --json` rows.
TestE2E_SearchOverHTTP skipped on the very SearchIssuesWithCounts refusal
it exists to catch; it now fails. The route agreement seeds "kinded"
template, gate, wisp and promoted-message rows and pins the alias, the
unknown-type refusal and the infra rows on the direct, proxied and remote
routes.
Minors: the CHANGELOG states the proxied `bd show --current` miss
fallback; the CommentsOmitted contract names `bd search --json`; the
storage.RecomputeBlocked and `bd recompute-blocked` comments name the
deliberate --proxied-server bypass.
Validation: go vet and gofmt on every changed package; make api-check;
workapi, issueops, httpclient/encode, types and storage unit tests; the
Reader conformance on dolt, embedded, uow and served; the embedded and
proxied route agreements (remote included), the embedded search tests,
TestProxiedServerSearch, TestProxiedServerRecomputeBlocked, the http e2e
search/show/recompute tests; docs flag, freshness and docsync checks; and
a hand-run bd search/list/count against a scratch workspace.
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>
* fix(create): let a remote backend mint the --parent child id
`bd create --parent` always called the raw GetNextChildID first, which the
http backend does not serve, so every child create on a remote workspace
refused before writing anything. The Lifecycle role already mints
<parent>.<n> for a create that carries a ParentID and no id of its own, on
every backend and inside the create's own transaction; conformance
RunIssueOperationsCreateUnderAParentMintsTheNextChildID pins it on every leg,
the served one included (and the bd-enterprise postgres leg the MC server
runs). So the create route needs no new capability token: on a registered
Remote backend the client skips the raw reservation and lets the server mint.
The local route keeps its reservation so its Dolt commit staging is
unchanged, and an explicit --id beside --parent is still refused up front.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(mol): molecule reads, auto-close and close --continue over issueops roles
Over the http backend three molecule paths failed, and two of them
silently:
- `bd mol current` / `bd mol progress` without an id answered "no molecules"
because the in_progress listing (a raw SearchIssues shape) and the parent
walk (raw GetDependencyRecordsForIssues) were refused and the refusal was
swallowed; with an id they refused on raw GetMoleculeProgress.
- The molecule auto-close after `bd close` never ran: findParentMolecules
swallowed the same refused edge read into "not part of a molecule".
- `bd close --continue` claimed the next step in a raw RunInTransaction.
The direct route now reads molecules through roleMolStore, which answers
through roles every backend serves: EdgeReader (batched at the wire's 100
anchors) for the parent walk, BatchGetter for the roots (Get per id where a
server does not publish issues.batchGet), Relations for the step rows (full
rows; the raw dependents read over http is getIssue's shallow projection,
which zeroed step assignees) and the progress counts, and Reader.List for the
in_progress/hooked listings. The auto-close closes the root through
Lifecycle.Close, and the --continue claim is one Lifecycle.Update guarded by
ExpectedStatus=open.
No refusal is swallowed any more: findParentMolecules, the molecule finders
and the hooked scan return their errors; `mol current/progress` report them;
the auto-close stays best effort but warns on stderr; AdvanceToNextStep only
moves on to the next ready step when the claim LOST a race (status mismatch,
not claimable, already claimed) and returns anything else. The one heuristic
still skipped is the id-pattern heal in loadDescendants, and only for an
ErrUnsupported backend that cannot express an id-prefix search; other
failures now surface. `mol current`/`mol progress` leave the
types.IssueFilter forbidigo hole, since they no longer build a filter.
gc does not depend on bd's molecule auto-close: it runs its own
(cmd/gc/molecule_autoclose.go, from the bd on_close hook and the
controller's bead-close events). Its worker prompts do run `bd mol current`.
Served e2e (TestE2E_MoleculesOverHTTP): create --parent mints <root>.1/.2,
mol current <id> is non-empty with the full in-progress step, mol progress
counts, close --continue auto-advances, closing the last step auto-closes
the root. `mol current` without an id now refuses out loud on this stack
(asserted: never an empty list); its non-empty assertion is skipped until
S6c (externaldeps reader passthrough) is underneath.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(mol): list molecule candidates with the four wire knobs, drop the S6c skip
On top of S6c the in_progress listing behind 'bd mol current' (no id)
reaches the v0 wire encoder, which refuses ListRequest.IncludeAllTypes.
Ask for templates, gates, infra and ephemeral rows explicitly, which the
wire publishes, and run the 'mol current without an id' served case.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* feat(issueops): one library entry each for molecule auto-close, advance and reads
The molecule rules lived only in cmd/bd, in copies that disagreed: two
auto-close implementations that closed the root through different
library entries outside the step close's transaction, a `close
--continue` claim that set no assignee and could take a step another
agent held on the direct and http routes, and three progress counts.
Every molecule rule now has one implementation in the public issueops
package, composed over three roles every backend serves (BatchGetter,
Relations, EdgeReader): MoleculeRoots, LoadMolecule, AnalyzeMolecule,
ViewMolecule, ReadMoleculeProgress, ActiveMoleculeIDs,
CompletedMolecule. Membership is the parent-child edge.
Auto-close: CloseRequest.AutoCloseMolecule and
CloseBatchRequest.AutoCloseMolecule (opt-in, so gc's own auto-close is
not doubled) close the molecule root a close completed IN THE SAME
TRANSACTION, unforced and guarded on the root revision read there:
storageissueops.CloseCompletedMoleculeInTx on the store backends (the
role bodies bound to the caller's tx, TxMoleculeReader) and
uow.CloseCompletedMoleculeInUOW on the unit of work. It replays on an
idempotent re-close, reports the root on CloseResult/CloseOutcome
.AutoClosedMolecule, and a root its own close policy refuses stays open
and is reported (MoleculeAutoCloseRefusal) without failing the step.
Advance: a new MoleculeStepper role (storage.DoltStorage accessor,
uow.MoleculeStepperSource) whose one implementation,
issueops.NewMoleculeStepper, claims the next ready step through the
Claimer (Lifecycle.Update's Claim for a wisp step): assignee set, a step
another actor holds skipped, never taken.
HTTP: closeIssue/batchCloseIssues carry auto_close_molecule behind the
issues.close.autoCloseMolecule behavior token, and POST
/v0/beads/issues/{id}:advanceMolecule (issues.advanceMolecule) serves
the stepper. Handlers only decode, call the role and encode. The client
sends the member and dials the operation only where advertised; against
an older server it DEGRADES rather than refuses — it runs the same
library rule over its own roles (issueops.CloseCompletedMolecule after
the close, NewMoleculeStepper for the advance), so the outcome is the
same in more round trips. The capability fallbacks that lived in
cmd/bd move into the client: BatchGetter answers one getIssue per id
without issues.batchGet, and EdgeReader splits past the operation's 100
anchors.
Conformance: RunMolecule* on dolt, embedded, uow and http (the http leg
twice: served, and against a server with the tokens struck out).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* refactor(cmd/bd): molecule commands and create --parent through the library entries
`bd close`, `bd close --continue`, `bd mol current`, `bd mol progress`,
`bd ready --mol` and `bd create --parent` now call the one library entry
for each rule on every route (direct, proxied server, remote):
- close (batch, --if-revision, proxied) sets CloseRequest/
CloseBatchRequest.AutoCloseMolecule and only reports what the library
closed in the step close's transaction. autoCloseCompletedMolecule,
autoCloseProxiedCompletedMolecule and closeCompletedMoleculeRoot are
gone, and so is the separate post-close write.
- --continue is the route's MoleculeStepper role: a real claim (the
assignee is set) that skips a step another actor holds. Before, the
direct and http routes flipped the status only and could take it.
AdvanceToNextStep, ClaimStepIfOpen and its two implementations are
gone.
- mol current / mol progress / ready --mol read through
issueops.ViewMolecule, ReadMoleculeProgress, ActiveMoleculeIDs and
LoadMolecule/AnalyzeMolecule over the route's roles. Over http this
fixes the missing step assignee on `ready --mol` (corpus mark
mc-ready-mol). The proxied route's SearchIssues fallback, the role
store, the third progress count and the cmd/bd copy of the readiness
analysis are deleted; only presentation stays here.
- create --parent asks the create role to mint the child id on every
route (the local CLI reservation is gone) and to inherit the parent's
labels (InheritLabelsFromParent) inside the create. The dry-run
preview still shows the labels, and a failed label read there is
reported, not swallowed.
TestProxiedServerMoleculeLifecycleAgreesOnEveryRoute runs one molecule
lifecycle through the real binary on the direct, proxied and remote
(`bd connect` to `bd serve`) routes and requires the same rows and the
same JSON on all three. The served e2e now also pins the held-step skip,
the claimed step's assignee and the full rows of `ready --mol`.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(httpclient): refuse molecule auto-close and advance before dialing an older server
The client used to DEGRADE against a server without
issues.close.autoCloseMolecule / issues.advanceMolecule: it closed the step
without the member and ran a second, client-side copy of the auto-close
(issueops.CloseCompletedMolecule) in its own transactions, and composed the
stepper over its own roles. That kept two executions of each rule alive.
Now the rule runs in ONE place, the server's library: a close or batch close
that sets AutoCloseMolecule, and an Advance, refuse before anything is dialed
with the typed capability error (storage.ErrUnsupported, Capability naming the
token). The composed single-item batch leg now carries the member too.
- issueops.CloseCompletedMolecule (the role-composed form) is gone.
MoleculeRootClose is the one root close request (unforced, the auto-close
reason, the session, guarded on the root revision read), and both
in-transaction bodies (storage issueops CloseCompletedMoleculeInTx, uow
CloseCompletedMoleculeInUOW) build from it.
- MoleculeView.Ready is `bd ready --mol`'s list (every analysis-ready node,
hydrated), so ready --mol and mol current derive from ViewMolecule alone.
Tests: unit pre-dial refusal and member pins (httpclient molecule_test.go),
TestServedMoleculeRefusesAgainstAnOlderServer (step stays open, nothing
claimed) replacing the degraded contract arm.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(cmd/bd): ask for the molecule auto-close only where the route serves it
The refuse-before-dialing client made every `bd close` over http fail
against a server that does not advertise issues.close.autoCloseMolecule
(an older bd serve, or the MC server shape, whose orchestrator owns the
molecule lifecycle): the CLI always set AutoCloseMolecule.
storage.ServesMoleculeAutoClose answers, through every decorator, whether a
store's closes may carry the flag (MoleculeAutoCloseProber, implemented by
httpclient.Store from its handshake; every local backend serves it). The
direct batch close and the --if-revision close set the flag from it; the
proxied route always serves it. Against a silent server the close goes out
without the member and the server's side owns the auto-close.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* test(backend/http): scope the advertised-policy check to reads before the close
The close policy check is the client-side policy's last chance: it runs
before the close request, so only the reads up to that request count. A
read after the close (the old-server molecule notice reads the closed
step's edges) is not the external-dependency policy.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* test(backend/http/corpus): drop the six marks S16 and S19 retire
With the molecule library entries underneath, mol current (with and
without an id, json and text), mol progress and ready --mol read through
issueops.LoadMolecule over the roles, and create --parent lets the server
mint the child id. Those six shapes pass on the reference profile.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(cmd/bd): never silent against a server without the molecule tokens
Against a server that advertises neither issues.close.autoCloseMolecule
nor issues.advanceMolecule (an older bd serve, or one whose orchestrator
owns the molecule lifecycle):
- `bd close --continue` closed the step and only then found the advance
refused, leaving the step closed and the next step unclaimed. It now
asks storage.ServesMoleculeAdvance (a MoleculeAdvanceProber the http
store answers from its handshake; local backends always serve it)
BEFORE the close and refuses up front, saying nothing was closed.
- `bd close` went out without auto_close_molecule and said nothing. When
the closed step belongs to a molecule (issueops.MoleculeRoot), a notice
on stderr now names the molecule and the missing token: its auto-close
is the server's to run. The batch and --if-revision closes both say it.
The served e2e masks both tokens out of the handshake and checks the
up-front refusal (the step stays open) and the notice; the httpclient
unit test pins ServesMoleculeAdvance to the handshake.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* refactor(cmd/bd): mol show through issueops.LoadMolecule on every route
`bd mol show` still loaded the molecule through cmd/bd's
loadTemplateSubgraph (raw GetIssue, GetDependentsWithMetadata and
GetDependencyRecords, plus an id-pattern child probe), while mol current,
mol progress and ready --mol read through the library. It now loads
through issueops.LoadMolecule over the route's molecule roles (the direct
store's, or the proxied provider's), so membership is the parent-child
edge everywhere and the http route reads through roles the server serves.
The served e2e checks mol show's root and step count.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* docs: the molecule auto-close fails the step's close on a non-policy error; stale comments
CloseRequest.AutoCloseMolecule and CloseCompletedMoleculeInTx now say what
changed when the auto-close moved into the close's transaction: a root
close the close policy refuses still leaves the root open and is reported,
but any other failure (a storage error, a lost race on the root's revision)
fails the step's close with it, where the CLI used to close the root
afterwards and only warn.
Stale: the advanceMolecule vocabulary entry said the client composes the
stepper over its own roles when unserved (it refuses before dialing), and
the graph-create collision probe called itself best-effort by transport
(the http GetIssue miss is storage.ErrNotFound like every other store's).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* docs(changelog): the molecule tokens and the S16/S19 behaviours
Entries for issues.close.autoCloseMolecule and issues.advanceMolecule, the
issueops molecule entries, the auto-close inside the step's close (and a
non-policy failure of it failing the close), the real claim behind
close --continue, the molecule reads on every route, the notice and the
up-front --continue refusal against a server without the tokens, and
create --parent / mol reads over http.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(httpclient): regenerate unsupported_gen.go for MoleculeStepper
The PR adds MoleculeStepper() to storage.DoltStorage (200 -> 201
methods). httpclient implements it by hand, but the generated shell's
trailer still counted 200, so
//internal/storage/unsupportedgen:unsupportedgen_test
(TestGeneratedShellIsFresh) failed in Bazel / test and
Bazel / integration, turning CI Gate / Required red.
Regenerated with `go generate ./internal/httpclient`; the only change
is the trailer count (143 of 201 methods generated; 58 left).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(molecule): auto-close refusals, write skew, close --json, docs
Review fixes for #7513, numbered as in each iteration's review
synthesis.
Iteration 1:
F1: a close guard's refusal of the root (TemplateReadOnlyError,
PinnedError, CloseNotAssigneeError) is an auto-close refusal, like the
close policy's: the root stays open and is reported, and the step's
close stands. Pinned by the new conformance case
RunMoleculeGuardedRootKeepsTheStepClose on dolt, embedded, uow and the
served http client.
F2: two closes that finish a molecule's last two steps in concurrent
transactions each read the other's step as open, so neither closed the
root and both committed. Every auto-close now rewrites the root's
coordination cell before it decides the root (local_metadata
molecule-coordination/v1/<shard>, the dependency coordination idiom and
sharding with a FreshRowLock value), in both twins
(CloseCompletedMoleculesInTx and CloseCompletedMoleculesInUOW). Two
deciders of one root now conflict at commit (1213), and the retry reads
the winner's close and closes the root. This is the synthesis's option
(c), applied through a coordination cell instead of the root row; it
needs no post-commit second transaction and no engine lock. The
deterministic two-transaction regression fails without the touch and
passes with it on dolt and uow; the concurrent-close tests end with the
root closed in every round, reported by exactly one close.
F3: the auto-close checks the root's eligibility before walking any
step, MoleculeStepsClosed stops at the first open step, and a batch
decides each root once and reports it on the first item under it.
F4: ErrVersionMismatch on the root is not a refusal; it fails the
step's close with it. The classifier unit test pins this. A conformance
case cannot stage that race deterministically through the public roles.
F5: storage.ServesMoleculeAdvance answers (bool, error), and bd close
--continue refuses before closing anything when the handshake cannot be
read.
F6: the CHANGELOG and the stepper and batch-closer doc comments say
what the code does.
F7: the unserved-auto-close notice fires only when the close left an
auto-closing molecule with every step closed and its root open
(issueops.CompletedMolecule): again on a re-close, once per root in a
batch, never for a step under an ordinary epic or an unfinished
molecule. Proxied mol show, mol current and mol progress again report a
read unit of work that cannot be opened as itself, not as a molecule
that was not found.
F8: the write-ledger comment says the close is refused before dialing.
The dead FirstClosed/LastClosed guards in mol progress pre-exist on main
and are left as they are.
Iteration 2:
F1: on the proxied route, bd ready --mol reported a read unit
of work it could not open twice: once as itself, then as "molecule
'<id>' not found", which under --json is a second error document on
stdout. It now returns moleculeNotResolved, as mol show, mol current and
mol progress do. TestProxiedReadyMolReportsAnUnopenableReadOnce drives
runMoleculeReady with a provider whose NewUOW fails and wants one Error:
line, or one JSON document; both subtests fail with the old return.
F2: the coordination cell serializes every concurrent close of a step
under an open auto-closing root, not only the closes that finish the
molecule. That is the price of deciding the root in the step's
transaction, so it is documented (TouchMoleculeCoordinationInTx, the
UOW twin, CloseRequest.AutoCloseMolecule, the CHANGELOG) and pinned on
dolt and uow: two sibling closes with a third step still open conflict
(both commit when the touch is removed, on either twin), and a six-step
fan-out closes every step through the store's retry, with the root
closed and reported by exactly one close. The synthesis's alternative,
a post-commit recheck by any close that read a step open, is not taken:
it is a second, best-effort transaction after the step's commit, the
shape this PR exists to remove.
F3: MoleculeRootClose's doc no longer promises that a step reopened
between the completion read and the root close fails the step's close.
The guard is the root's RowVersion, which a step reopen never writes;
the doc now says what the guard covers and that this race goes
undetected (it is inherited from the CLI's old post-commit auto-close).
F4: the user docs describe the auto-close. docs/workflows/molecules.md
replaces "Closing the last child does not close the molecule root"
with which roots close and which stay open, the refusal warning, the
unserved-server note and the --json members, and documents the claiming
--continue and parent-child step membership;
docs/reference/json-schema.md gains a bd close --json section. These
are main-only behaviors on pages pinned to v1.2.2 (docs/cli-docs.pin):
a maintainer call against §1 of
engdocs/decisions/2026-07-17-docs-release-pin.md, as in #6508, #5855,
#5997 and #5092. The auto-close itself shipped in v1.2.2
(cmd/bd/close.go autoCloseCompletedMolecule), so the old sentence was
already wrong at the pin. docs/cli-reference/ is generated from the
pinned release and is not hand-edited; the bd close and bd mol show
help texts carry the same facts and reach it at the next pin bump.
F5: bd close --json reports the auto-close. The entry of a close that
completed a molecule gains auto_closed_molecule (the root it closed) or
molecule_auto_close_refusal (why the root stayed open), the HTTP API's
names, on the direct, proxied and --if-revision routes. The members sit
beside the issue's own rather than wrapping the output in an object the
way --suggest-next does: an object would change the output's shape
exactly when a close completes a molecule and break every consumer that
reads an array, while members leave each entry decoding as the closed
issue, compose with `closed` under the flag objects, and leave a plain
close's bytes unchanged. Pinned on the embedded and proxied tiers
(TestEmbeddedCloseJSONReportsMoleculeAutoClose, TestProxiedServerClose2B
json_reports_*, and both --if-revision replay tests), all red without
the change.
F6: cmd/bd's BeadsTemplateLabel is issueops.MoleculeTemplateLabel, so
the template commands and molecule membership cannot drift apart.
F7: the UOW twin's revision probe says that it writes nothing,
and the BatchCloseRequest.auto_close_molecule spec description has its
verb back (apigen regenerated, no drift).
Iteration 3:
F1: on the unit-of-work route (bd serve, the proxied CLI), a refused
root's molecule_auto_close_refusal and warning carried the use case's
and repository's wrapping ("close <id>: db:
IssueSQLRepository.CloseChecked <id>: ...") around the refusal, where
the tx twin and the docs give the refusal alone. Both twins now report
it through RefusedMoleculeAutoClose, which answers the refusing guard's
or policy's own sentence. RunMoleculeRefusedRootKeepsTheStepClose,
RunMoleculeGuardedRootKeepsTheStepClose and the embedded and proxied
close --json tests want that exact sentence; the uow conformance leg
and the proxied test fail without the unwrap.
F2: the docs no longer promise ErrVersionMismatch for a write to the
root that races its auto-close. The root's read and its revision check
share one transaction snapshot, so that write conflicts with the root
close at commit and the retry decides the root again; the close fails
only if it still conflicts when its retry budget runs out
(MoleculeRootClose, IsMoleculeAutoCloseRefusal,
CloseRequest.AutoCloseMolecule, the tx twin's comment, the CHANGELOG
and the OpenAPI description, apigen regenerated).
F3: TestEmbeddedCloseJSONReportsMoleculeAutoClose moves above
TestEmbeddedCloseConcurrent's doc comment, which documents its own test
again.
F4: bd mol progress counting direct steps while the auto-close counts
every descendant predates this PR; it is left for a follow-up.
F5: cmd/bd's molReader drops GetMoleculeProgress, which nothing called
once mol progress read through issueops.ReadMoleculeProgress.
Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Gas City Adopt-PR
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
* fix(memory): preserve presence for empty values (#5963)
Recall and Forget now distinguish an existing empty memory row from an absent key across direct, embedded, and UOW storage paths.
Agent-Signature: codex-unknown-model-unknown-reasoning on behalf of sjarmak
* fix(memory): make bd recall report presence from row existence
printRecallResult (and the recallCmd caller) derived "found" from
value != "", so a memory stored as the empty string still printed
"No memory with key" and exited 1 even though the role's
RecallResult.Found was true and bd forget would delete the row.
Thread result.Found through instead: an empty-valued memory now
recalls cleanly (exit 0, empty value; JSON reports found: true), and
only an absent key is a miss.
Addresses maintainer review on #5964 (fixes#5963).
* test(httpapi): pin GET /v0/beads/memories/{key} as 200 for an empty value
TestGetMemoryAnswersAMissWithA404 pinned a RecallResult{Value: ""}
case (Found defaulting to its zero value, false) as a 404, a shape no
backend can produce since Found now comes from row existence rather
than value truthiness. Move that case into its own
TestGetMemoryAnswersAnEmptyValueWith200, which recalls Found: true
and asserts a 200 with an empty value. Also updates the handler's
doc comment, which still described the retired 404-on-empty
behavior.
Addresses maintainer review on #5964 (fixes#5963).
* docs(httpapi): fix openapi spec to say memory presence is row existence
The published spec still said an empty-valued memory is a 404 on
GET /v0/beads/memories/{key} and DELETE /v0/beads/memories/{key},
contradicting the role's RecallResult.Found (row existence). Rewrite
the operation descriptions, both 404 response bodies, Memory.value
and RememberedMemory.replaced to say presence is row existence
everywhere: an empty-string memory is a 200 (or is removed by
forget) with an empty value, matching what GET /v0/beads/memories
already enumerated. Regenerate types.gen.go via `make api-gen` so
the generated doc comments match.
Addresses maintainer review on #5964 (fixes#5963).
* docs(changelog): note the empty-valued memory presence fix
Add an Unreleased/Fixed entry for #5964 (fixes#5963): bd recall,
bd forget and GET /v0/beads/memories/{key} now treat an empty-valued
memory as present everywhere, instead of only on GET
/v0/beads/memories.
* fix(memory): make bd remember <bare-key> recall an empty-valued memory
rememberBareKeyPath decided presence from existing != "", so a bare slug
naming a memory stored as the empty string was refused as "no memory
named" instead of recalled. It now takes the role's Found, matching
printRecallResult, bd forget and the HTTP door.
* test(memory): pin empty-value presence through the real commands
TestPrintRecallResult and TestRememberBareKeyPath call the helpers directly,
so a RunE that went back to deciding presence from value != "" would leave
them green. TestEmbeddedMemory/empty_valued_memory_is_present empties a
memory row beneath bd and runs bd recall, bd remember <bare-key> and
bd forget against it, checking first that bd no longer sees the placeholder.
Two comments in problem.go and one in memories_test.go still said an
empty-valued memory is a 404. The CHANGELOG line now says a key with no row
is a miss, since a forgotten key was once stored.
* build(bazel): add the memoryops dep to the bd_test go_test (make bazel-sync)
memory_embedded_test.go now imports internal/storage/memoryops directly
(storagememoryops.StorageKey, to overwrite a memory row out of band), so
gazelle emits //internal/storage/memoryops on bd_test. cmd/bd/BUILD.bazel
landed on main after this PR branched, so the PR could not carry the dep;
without it, bazel.yml's "BUILD files in sync" step fails in the required
bazel-test lane. Generated by `make bazel-sync`.
Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Gas City Adopt-PR
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* test(memory): maintainer fixup — adoption review nits
Maintainer fixup for the adopt-pr iteration-1 review of #5964. Both review
lanes approved and the quality scorecard approved at 981; these are its four
non-gating nits, each confined to lines this PR already adds.
- internal/httpapi: TestForgetMemoryOfAnEmptyValuedKeyIs200 pins the DELETE
door's empty-value 200 the way TestGetMemoryAnswersAnEmptyValueWith200
pins the read. Guarding the handler's 404 on Value == "" reddens exactly
this test and nothing else.
- CHANGELOG: the bullet names DELETE /v0/beads/memories/{key} beside GET,
whose answer changed the same way (404 with the row left standing -> 200
with the row removed).
- uow: the two new GetAllConfig presence probes in Recall and Forget say why
they read the whole table, by pointing at Remember's rationale.
- conformance: RunMemoriesEmptyRowIsPresentUntilForgotten runs its
no-history-on-retry leg last and SKIPs it with a reason when a fixture has
no CountHistory, as the MemoriesFixture doc promises, instead of passing
quietly. All three in-tree fixtures wire the hook, so every in-tree run
is unchanged (19/19 on dolt, embeddeddolt and uow, 0 SKIP).
Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Gas City Adopt-PR
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(httpclient): report an empty-valued memory as present (base-refresh repair)
Maintainer repair from refreshing #5964 onto main b630f96f5b. Main's #7247
added the HTTP client store (internal/httpclient) after this PR branched,
and its memory role and served conformance leg still treated a memory
stored as the empty string as absent:
- Recall set Found from Value != "".
- The RecallMemory doc said an empty-valued row was a 404.
- TestServedMemoriesRecallConflatesStoredEmptyWithAbsent called
conformance.RunMemoriesRecallConflatesStoredEmptyWithAbsent, which this
PR deletes.
The rebase applied cleanly, but the merged tree did not compile.
- internal/httpclient/memories.go: Recall reports Found true on any 200.
With this PR the wire returns a 404 only for a key with no row; an
empty-valued row comes back as a 200 with an empty value. Setting Found
from Value would hide that row again on the HTTP backend. Forget already
reported Found true on a 200.
- internal/httpclient/wire/writes.go: the RecallMemory doc now says the
same.
- internal/httpclient/served_memories_deps_test.go: the hm10 served case
now runs RunMemoriesEmptyRowIsPresentUntilForgotten, the contract case
this PR adds in place of the one it deletes.
With BEADS_TEST_EMBEDDED_DOLT=1 the served memory tests pass with 0 SKIP.
Reverting the Recall line makes hm10 fail with
`Recall("hm10-stored-empty") = value "" found false, want value "" found
true`.
Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Gas City Adopt-PR
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: sjarmak <t@t.co>
Co-authored-by: Eddie the Engineer <adopt-pr@gascity.local>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
* feat(http): serve list/show counts/dep tree/ping, close+reopen under a session, one-lookup not-found (S6b/S6c/S6d)
S6c. The external-dependency decorator rebuilt its role views from the
legacy DoltStorage seam (storereader over itself, IsBlocked,
GetDependencyTree, ClaimReadyIssue), which a remote store only partly
serves: `bd list`/`bd children` refused on the SearchIssuesWithCounts stub,
`bd show --json` printed zero counts, the default `bd dep tree` refused,
`bd ready --claim` and `bd close` of an externally blocked issue reached
unsupported paths. For a storage.RemoteBackendStore each view now passes the
inner role through and lays the policy over it in role terms
(externaldeps/remote_roles.go): ready reads and the ready claim exclude the
workspace-wide blocked set over a widened window; per-issue checks (claim,
close, batch close, list annotations, tree leaves) read only the named
issues' edges through EdgeReader instead of every edge in the workspace. A
server advertising policy.external_dependencies (MC's does) gets a plain
passthrough. `bd ping` uses a new storage.Pinger, which the http store
answers with its authenticated context read.
S6d. A store reporting storage.CallerAttributionLimitedStore (http) cannot
carry a Provenance label or a patch's closed_by_session. The library still
refuses both; the CLI omits them where nothing is lost: `bd reopen`'s fixed
"bd: reopen <id>" label (the server labels the same entry), and the
closed_by_session of `bd update -s closed` (attribution only, usually the
ambient CLAUDE_SESSION_ID; an explicit --session prints a notice; `bd close`
still records it). See cmd/bd/remote_backend.go.
S6b. utils.ExactIDLookupStore: the resolver stops at exact lookups for a
store with no substring search, so a missing prefixed id is a not-found
(beadserrors.ErrNotFound, "no issue found matching") after one getIssue.
The general resolver no longer repeats an identical normalized probe. The
http SearchIssueIDs answers D11's partial-id refusal, which now unwraps to
ErrNotFound. Contributor auto-routing for a remote workspace reads local
config only, so the not-found fallback pays no settings round trip.
`bd update <absent> --claim` (gc's hook claim) answers a gc-classifiable
not-found in at most two requests.
Served e2e (backend/http/e2e_remote_roles_test.go): every gc list shape and
`bd children` against embedded, `show --json` count parity, default dep
tree parity, external blocking still enforced, close/reopen under
CLAUDE_SESSION_ID, missing-id request counts, absent-id claim against the
current server and the MC handshake mask, policy passthrough under the MC
mask, ping.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* test(externaldeps): role-level remote reader and claimer cases
bd ready and bd update --claim reach the policy through the legacy seam and
the lifecycle guard, so the remote Reader.Ready exclusion and the remote
Claimer guard (what bd serve and library callers reach) are pinned at the
role level with a fake remote store.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* feat(http): bd serve advertises policy.external_dependencies; clients pass through
bd serve composes every ready, claim, claim-next, close, blocking and tree
role through the external-dependency policy, but never said so. Every
client therefore ran the policy a second time, with the CLIENT machine's
external-project config, and claim-next became a non-atomic read-then-claim
loop on the client.
The server now advertises the token exactly when the roles it serves were
composed through the policy: httpapi.Config.ExternalDependencyPolicy, which
bd serve derives from its actual chain (externaldeps.Applied for the store
arm, externaldeps.AppliedToProvider for the provider arm). A server handed
raw roles still withholds it, so the token stays truthful.
Against a server that advertises it, every remote role view hands the
request to the server's own role untouched: no client validation, no edge
reads, claim-next is the server's one atomic call, and the ready count is
the server's countReadyWork (new remoteReadyCounter). The client-side
policy remains only for servers that do not advertise the token.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(create): default created_by to the request's actor in the create role
created_by was stamped in two front doors and never in the library: the
CLI (creationActorStamp, with a remote-workspace special case) and the
three httpapi create handlers. A library caller of Lifecycle.Create or
BatchCreator with an empty CreatedBy stored "" locally and the actor over
http.
PreparePublicCreateRequest, which every create shape prepares through
(Lifecycle.Create, BatchCreator items, batch-apply create items), now
defaults an empty CreatedBy to request.Actor; an explicit value is kept.
The handlers no longer stamp, `bd create` and the state event create pass
only the actor, and creationActorStamp/isRemoteBackendWorkspace are gone.
The CLI sites that still create through the raw CreateIssue seam (swarm,
todo, gate, the create form) keep stamping currentActor(): that seam is
shared with import, where defaulting would re-attribute imported rows, and
the http store refuses it anyway, so the remote special case was never
reachable there.
Conformance: the lifecycle-create, batch-creator and batch-apply contracts
now pin created_by == actor for an item that names none, on every leg.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(httpclient): GetIssue answers a miss with storage.ErrNotFound, like the local stores
The http store's raw GetIssue answered a missing id with (nil, nil), where
DoltStore and the embedded store return a wrapped storage.ErrNotFound. A
caller written against the backend contract read the http miss as a hit:
`bd create --graph` refused every explicit-id plan over http (patched in
cmd/bd on feat/http-mc-corpus; that workaround is reverted there).
GetIssue now returns the miss (and the empty id) as storage.ErrNotFound,
spelled as issueops.GetIssueInTx spells it. GetLabels, which reads through
GetIssue, keeps the local read's "no labels" answer for a missing id; the
`bd list --parent` walk reads the typed miss as "parent issue not found".
The served bridge test now holds the local reference store and the http
store to the same miss: ErrNotFound with the same text.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* test(createbatchequiv): re-record the apply golden for the created_by default
c2866ea7fe made the create role default an empty CreatedBy to the
request's actor, so every create item of the apply scenario's batch
(actor "apply-writer") now stores created_by "apply-writer" instead of "".
TestCreateBatchFastPathsMatchPerRow_*/apply compared the stored rows to a
digest recorded before that change and failed on exactly the three tables
the column reaches: issues and wisps (the row) and events (the update
event's old-value snapshot). Fast and per-row bodies still agree; the
batch-apply conformance contract pins the same value.
Bisected with bazel: passes at be92efe40f's integ twin 696f7acc8e, fails
from the created_by commit on. Only apply.json's three digests move.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* style: gofmt ledger.go and the externaldeps remote-roles test
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(cmd/bd): bd create reads routing settings local-only on a remote backend too
determineAutoRoutedRepoPath skipped a remote backend's settings document
(routing targets are local paths that one shared document cannot name for
every client), but getRoutingConfigValue, which `bd create` and
migrate-personal read routing.* and contributor.* through, still asked it.
The same workspace could route a create one way and a lookup another, and
every create paid a settings round trip per key.
Both now go through routingSettingsStore: nil for a remote backend, so
routing comes from config.yaml / the environment only there, and a local
store is still consulted. A unit test holds both reads to the rule with a
store that counts settings reads.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(cmd/bd): say so when update -s closed drops an ambient CLAUDE_SESSION_ID
Over http `bd update -s closed` cannot carry closed_by_session, so the CLI
drops it rather than refusing the close. An explicit --session printed a
notice; the ambient CLAUDE_SESSION_ID every agent under Claude Code exports
was dropped without a word, a silent data difference from a local backend
(the served corpus's mc-update-meta-status-closed). The drop is now named
on stderr in both cases, once per command, pointing at `bd close`, whose
wire operation records the session. The served e2e asserts the notice.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* test(backend/http): hold bd list --limit 2 to each side's own unlimited order
TestE2E_ListWithGCFiltersMatchesEmbedded compared the --limit 2 rows of
the served and embedded workspaces as sets. The seed has four P2 rows, so
the limit cuts a priority tie whose created_at order differs between two
workspaces seeded seconds apart: a test-only flake, the order itself being
total. Each side's two rows must now be, in order, the first two of that
same side's --limit 0 listing; the unlimited listings are still compared
across sides by the shape loop.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* test: unit-tier pins for the created_by default, the policy token and the GetIssue miss
Three review mutations were caught only by a heavier tier (the uow
conformance legs, the served httpclient tier) or by one package's test
alone. Each now has a unit test where its rule lives:
- issueops: PreparePublicCreateRequest defaults an empty CreatedBy to the
actor and keeps an explicit one, without mutating the caller's request.
- externaldeps: the policy layer AppliedToProvider finds becomes the
handshake's policy.external_dependencies through httpapi.Listen, the
composition bd serve performs, and a raw provider's handshake lacks it.
- httpclient (no embedded engine): GetIssue over the real wire client
against a stub server answers a 404 not_found, and the empty id without
dialing, as storage.ErrNotFound spelled like the local stores.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* docs(changelog): S6b/c/d entries match the code
The S6 entry still said `bd create` suppresses created_by on a remote
workspace and that the external-dependency policy runs client-side. Since
S6b/c/d, created_by defaults to the actor in the library on every backend,
and every bd serve composed through the policy advertises
policy.external_dependencies, so clients pass those operations through;
the client-side policy (now in role terms) runs only against a server that
does not advertise it.
New entries: the advertised policy token, bd ping over http, the created_by
library default, closed_by_session dropped by an http `bd update -s closed`
(with a notice, typed or ambient), reopen without a Provenance label over
http, local-only routing.* / contributor.* on a remote backend, GetIssue's
miss as storage.ErrNotFound, and list/children/show counts/dep tree over
http.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(externaldeps): keep S6's list --ready, --claim-next refusal and lost-race error on the S6c composition
The re-adopted S6 head (#7288) carries the review fixup's remote role
composition; S6c replaces it with its own (rolesAreRemote, the widened
ready window, the policy passthrough). Two behaviours S6 shipped and its
reviews pinned would otherwise go:
- bd close --claim-next against a server that does not apply the policy
is refused whole, before anything is read or closed, with "the served
batch close cannot carry a next claim, so nothing was closed; close
without --claim-next, then run `bd ready --claim`". S6c passed the batch
to the http closer, whose W-CloseBatchRequest.ClaimNext refusal drops the
remedy, so TestE2E_BDOverHTTP's two refuseClaimNext steps went red. A
request invalid on every backend is still ErrValidation first, and a
server that applies the policy still gets the request untouched.
- remoteReadyClaimer.ClaimNext reports a page on which every candidate was
lost to another actor as "claim ready: lost N races ...", not as the
empty answer that means there is no work.
- `bd list --ready` (List with ReadyFlag) is answered by the policy
store's own reader over the served ready reads, as S6 does. S6c passed
it to the served listing, which cannot carry ReadyFlag (httpclient
ledger row E-ListRequest.ReadyFlag), so it exited 1 over http with or
without external refs; TestE2E_BDOverHTTP and
TestServedRolesKeepTheExternalDependencyPolicy were red on it.
TestRemoteReaderAnswersAReadyListingWithoutTheWireFlag pins it, with the
fake's served List refusing ReadyFlag as the wire does.
S6's composition tests now run against S6c as remote_roles_composition_test.go.
Their fake serves Ready the way a server does (the S6 composition read
ready work through the legacy policy reader instead), and two call logs
gain that Ready. TestRemoteBatchCloserRefusesANextClaim,
TestRemoteBatchCloserValidatesANextClaimFirst and
TestRemoteReadyClaimerReportsLostRaces were red on S6c before this change.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(externaldeps): unassigned claim-next and fail-closed close reads
Review fixes for the S6c composition against a server that does not
advertise policy.external_dependencies: the two majors of review
attempt 1, plus the minors on the same code.
- ReadyClaimer: the composed claim-next reads only open, unassigned
ready rows (Unassigned=true, Assignee cleared), the candidates the
local ClaimReadyIssueInTx selects. A row another actor holds, or one
already assigned to the caller, is no longer taken or counted as a
lost race. Each pass reads 25 candidates past the blocked rows, as
httpclient's composed claim does, and a full window lost end to end
is read once more: claimed rows leave the unassigned set. Only a
claim that tried candidates and won none is an error.
- BatchCloser: an externally blocked item travels to the server only
when its status read finds it closed or not found (liveRefusal). Any
other read error is that item's outcome, so a transient or auth
failure no longer forwards a refused close to a server that will not
refuse it.
- TreeWalker: a failed capability probe renders the external leaves
over the walked tree instead of failing a walk the server already
answered. appendTreeExternalReferences skips an id the tree holds,
so an enforcing server's own leaves are not doubled.
- remoteEdges names each anchor once and skips an empty one, which the
http EdgeReader refuses with ErrValidation.
The composition fakes now honor Unassigned/Assignee as
workapi.BuildReadyFilter does, model a rival claim landing first and a
failing GetIssue, and refuse an empty edge anchor as httpclient does.
New: TestRemoteReadyClaimerTakesOnlyUnassignedWork,
TestRemoteReadyClaimerWalksAContendedFront,
TestRemoteBatchCloserAnswersAFailedReadWithIt,
TestRemoteEdgesNamesEachAnchorOnce, and the probe-failure cases of
TestRemoteTreeWalkerAddsExternalLeaves. Each is red with its fix
reverted.
From review attempt 2, three nearby cleanups:
- TestServedRolesKeepTheExternalDependencyPolicy seeds open rows held
by another actor and by the claimant ahead of the free work, then
claims with and without an assignee filter. The unassigned-only claim
is now pinned over a real served server, not only through the fakes:
red with the pre-fixup remote_roles.go, with filter.Unassigned
dropped, and (the filtered claim) with an explicit assignee honored.
- The capabilities description in openapi.v0.yaml (and the regenerated
types.gen.go comment) no longer calls the whole list build-level:
policy.external_dependencies depends on how the server composed its
roles, as the paragraph above it says.
- createbatchequiv's golden note names
issueops.PreparePublicCreateRequest instead of a commit id that is
not on this branch.
Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* test(backend/http): count a not_found read as reaching the remote in #7469's credential doors
main's #7469 added TestExplicitCredentialIgnoresTheEnvPlaintextGrant. Its
OpenWith and Open doors read bd-1 from plaintextRemote, which answers
every issue read not_found, and the granted leg needs that read to return
a nil error. That held while the http client answered a miss with
(nil, nil). This branch's "fix(httpclient): GetIssue answers a miss with
storage.ErrNotFound, like the local stores" makes the same read return
storage.ErrNotFound. So on main plus this branch both doors fail at
per_open_credential_test.go:392 ("with Target.AllowInsecureCredential:
not found: issue bd-1") under plain go test. The merge is textually
clean, so only a build of the merge shows it.
The two store doors now count storage.ErrNotFound as success, since that
answer came off the wire. The assertions are unchanged. The refused leg
still needs the "refusing to send a credential" error and no request on
the transport. The granted leg still needs exactly one request carrying
"Bearer explicit-token": a granted read that never reaches the wire still
fails at :408.
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>
* fix(issueops): one create priority default; HTTP absent priority is P2
The CLI defaulted `bd create` to P2, but issues:create, issues:batchCreate
and batch:apply create items left Issue.Priority at 0 when `priority` was
absent, so a gc/curl create stored P0 (critical) against the spec's "absent
means the default".
The default now lives in one place, the shared create preparation
(PreparePublicCreateRequest), behind a presence flag because Issue.Priority's
zero value is P0:
- issueops.CreateRequest.DefaultPriority, BatchCreateItem.DefaultPriority and
CreateItem.DefaultPriority ask for issueops.DefaultCreatePriority (2);
setting it with a non-zero priority is ErrValidation
(ValidateCreatePriority, shared with the HTTP client);
- every Lifecycle.Create, BatchCreator and BatchApplier leg (dolt, embedded,
uow) reaches it; CloneCreateBatchRequest now keeps scalar item members;
- the three handlers set the flag for an absent member and never make up 0;
the HTTP client omits `priority` for it (wirePriority) only when the
server advertises the new additive issues.create.defaultPriority token,
read from the cached handshake before the dial; an older server reads an
absent priority as P0, so the client sends DefaultCreatePriority (2)
explicitly to it (pinCreateDefaultPriority). An explicit 0 is still sent;
- `bd create` without --priority, `bd create --graph` nodes without priority
and `bd create --file` templates without ### Priority rely on the flag; the
flag's displayed default and the dry-run previews read the library
constant. CLI output is byte-identical (checked against origin/main).
Spec: the three priority descriptions now say the create default is P2 on
a server advertising issues.create.defaultPriority (apigen regenerated); the
wireshape golden already had priority optional, so no wire-shape change.
Conformance: RunLifecycleCreateAppliesTheDefaultPriority,
RunBatchCreatorAppliesTheDefaultPriority and
RunBatchApplyAppliesTheDefaultPriority on dolt, embedded, uow and http, plus
handler and client encoding tests, and
TestCreateSendsTheDefaultPriorityToAServerThatPredatesIt (new client,
handshake without the token: all three create roles send 2).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(issueops): apply review fixups for the default create priority (bd-kb61wg)
Apply the minor and nit findings from the review of #7426:
- CHANGELOG: tell out-of-tree storage backends they must honor
DefaultPriority (store issueops.DefaultCreatePriority, refuse it with a
non-zero priority as ErrValidation) and which conformance cases check
it; scope "CLI output is unchanged" to the in-tree backends.
- bd create --file: pin the default-priority path. The e2e test asserts
the printed priorities, and a buildMarkdownBatchRequest unit test pins
the flag and priority for an absent, a 0 and a 1 `### Priority`.
Deleting `DefaultPriority: !template.PrioritySet` now fails both.
- bd create --file: warn on stderr about a `### Priority` that does not
parse, as the `### Type` case already does, instead of dropping it
silently.
- httpclient: document pinCreateDefaultPriority's same-build assumption
(the handshake is cached per Store, so a stale one is silent here), and
test its no-context and failed-handshake branches on all three roles.
- Formula steps, `bd q` and `bd todo add` spell
issueops.DefaultCreatePriority instead of the literal 2.
- Conformance: the batch-creator and batch-apply default-priority cases
also pin DefaultPriority with a non-zero priority as ErrValidation with
nothing written.
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(issueops): mark the out-of-tree DefaultPriority change BREAKING (bd-0tcn1o)
Apply the minor findings from the relaunch review of #7426:
- CHANGELOG: move the obligation on out-of-tree storage backends out of
the `### Fixed` entry into its own `### Changed` entry, led by
"BREAKING (out-of-tree storage backends)" as the close-guard change
and the earlier out-of-tree contract changes are; RELEASING.md asks
breaking changes to carry their migration. The entry says what such a
backend used to receive from `bd create`, `--graph` and `--file`
(priority 2), what it receives now (priority 0 with DefaultPriority
set), the migration, and the conformance cases that check it. The
`### Fixed` entry keeps the HTTP P2 fix, points at the new entry, and
names the stale-handshake residual that only a code comment named: a
create that lands on an older build behind the same URL still stores
P0.
- bd cook: the proto root, the gate issue and the cooked formula root
spell issueops.DefaultCreatePriority instead of the literal 2, as the
formula steps in the same file already do. No behavior change.
Not taken:
- The literal 2s in create_form.go, gate.go and linear.go, and the
"default 2" in todo.go's --priority help: explicit P2s outside the
migrated paths (the help string also feeds the generated CLI
reference). Left for a follow-up sweep.
- Reusing in.priorityDefault in the direct bd create route: that route
builds no createInput (gatherCreateInput runs only on the proxied and
--file routes, and each returns), so there is nothing to reuse.
- A member-level range check in the single-create HTTP decode, as the
batch shapes have: the asymmetry predates this PR, and the role still
refuses an out-of-range priority on all three shapes.
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>
* fix(issueops): enforce the dotted-child dependency rule on every leg
The refusal of an explicit edge from a dotted-id child to its own ancestor
(bd-abc.1 -> bd-abc; only the parent-child edge to the immediate dotted
parent is allowed) lived only in cmd/bd (isDisallowedHierarchicalDependency).
HTTP dependencies:add, batch:apply dep_add items and `bd create --graph`'s own
edges skipped it.
It is now one library rule, issueops.CheckDottedChildDependency, returning
*issueops.DottedChildDependencyError (unwraps to ErrValidation, same message
the CLI printed):
- ValidateAddDependenciesRequest applies it, so DependencyEditor refuses on
dolt, embedded, uow and the server behind httpapi (400 invalid_argument);
- both BatchApplier bodies (issueops and uow) apply it to each dep_add item on
the resolved ids, so a key bound to a minted dotted child is refused too;
- the HTTP client checks it before the dial, as it does self-dependency, so
the typed error survives the wire.
cmd/bd keeps no copy: single-edge dep add / dep --blocks rely on the role;
bd link (still on the store verb) and the --file bulk reporter call the
library rule. CLI output is byte-identical (checked against origin/main).
Conformance: RunDependencyEditorRefusesADottedChildGatedOnItsOwnParent and
RunBatchApplyRefusesADottedChildGatedOnItsOwnParent wired on dolt, embedded,
uow and http, plus a raw-wire served test past the client check and handler
mapping cases.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(batch): refuse a dotted child gated on its own ancestor in bd batch
Review fixup for PR #7424 (iterations 1 and 2).
Major: a bd batch script line `dep add bd-abc.1 bd-abc` still wrote the
edge this PR refuses everywhere else, on both backends. Neither batch
dispatch writes through the DependencyEditor role that enforces the
dotted-child rule: the classic arm calls storage.Transaction.AddDependency
and the proxied arm the unit of work's AddDependencies verb. Both arms now
build the edge with one helper, batchDepAddEdge, which keeps the default
type and the arity and type errors, and asks
publicops.CheckDottedChildDependency the way bd link does. A refused line
rolls the whole batch back.
Tests: TestBatchDepAddEdge (default and explicit types, arity and type
errors, three refusals typed *DottedChildDependencyError matching
ErrValidation, and the immediate parent-child edge allowed), and
TestProxiedServerBatchDepAddRefusesADottedChildGatedOnItsParent (classic
and proxied: the refusal names line 2, rolls back an earlier update line
and writes no edge, and `dep add C P parent-child` still lands exactly
one), registered in the proxied shard manifest. A mutant that drops the
rule from the shared helper fails both; one that bypasses the helper in
the proxied arm alone fails the proxied leg.
Minors:
- For a child whose parent-child edge is already stored (a
`bd create --parent` child) the rule answers ahead of the hierarchy and
type conflicts, so an HTTP caller now gets 400 invalid_argument where it
got 409 dependency_cycle (blocking types) or dependency_exists (any
other type). Documented in the DependencyEditor role doc, the CHANGELOG
entry and the httpapi batch-apply test comment, and pinned by a
stored-hierarchy phase in the DependencyEditor and BatchApplier
dotted-child conformance contracts on every leg; a mutant that drops the
rule gets the hierarchy conflict instead (409 dependency_cycle on the
wire).
- The bd create --graph dry-run note now says the live create may also
refuse an edge that gates a dotted-id child on its own ancestor.
- The DottedChildDependencyError comment says the message is kept verbatim
and says "deadlock" whatever the type.
Not changed: bd relate (relates-to does not schedule) and the edges a
create writes with its issue (bd create --deps/--waits-for, and over
HTTP an explicit dotted id with a non-immediate ParentID) still write
through paths that skip the rule. The scheduling shapes need an explicit
dotted id or a grandparent target. Follow-up bd-25s1wh tracks moving the
rule down to the domain/store add verbs, with a structural bypass for
reparent and template edges.
Iteration 2 (minor): the CheckDottedChildDependency doc no longer implies
bd link and bd batch are the only writers outside the roles. It names
bd relate and the create edges as not applying the rule yet and cites
bd-25s1wh.
Complexity (cyclomatic/cognitive): runBatchOp 23/35 -> 21/31,
runBatchOpUOW 28/48 -> 26/44, batchDepAddEdge 5/4. Touching them brings
both pre-existing dispatch switches into the measured set; splitting them
is out of scope here.
Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Gas City Adopt-PR
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* docs(issueops,httpapi): document the dotted-child 400 and widen its gap list
Review fixup for PR #7424 (relaunch, iteration 1, minors).
- The OpenAPI spec now describes the wire change this PR makes. The
dependencies:add and issues:batchApply 400 vocabularies name an edge
from a dotted-id child to its own ancestor (anything but the
parent-child edge to its immediate parent; param `edges` and `items`).
dependencies:add says why that is request-intrinsic, and both 409s say
it is never dependency_cycle or dependency_exists, even for a child
whose parent-child edge is stored. Response descriptions only: the
generated types and the wireshape digest are unchanged (make api-check).
- The CheckDottedChildDependency doc no longer reads as a complete list of
the writers that skip the rule. Besides bd relate and the create edges
it names bd duplicate, bd supersede, bd duplicates --auto-merge (its
related link and its reparenting) and the tracker engine's
createDependencies, and says the molecule, template and swarm writers
are unaudited. bd-25s1wh's notes carry the widened scope, including
`bd duplicate bd-a.1 --of bd-a`.
Declined (nit): unifying the root issueops import alias across the PR's
cmd/bd files. batch.go is the one file that imports both issueops
packages, so one of them needs an alias there; it uses publicops, the
repo's usual alias for the root package, and aliasing the other side
instead would rewrite base-owned lines.
Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Gas City Adopt-PR
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
* fix(issueops): enforce the close guards on every close leg
The template read-only guard, the pin guard and the assignee authority
fence (be-035) lived only in cmd/bd (validateIssueClosable), so a close
through bd serve, issues:batchClose, a batch:apply close item or a library
caller of Lifecycle.Close / BatchCloser / BatchApplier closed what bd close
refused.
They now run inside the close's own transaction in CloseIssueCheckedInTx
(enforceCloseGuardsInTx), the body every checked close shares (dolt,
embedded, uow, and the server behind httpapi), for a target that is not
already closed:
- a template refuses with *issueops.TemplateReadOnlyError (no bypass);
- unless Force (CloseRequest, CloseBatchRequest, CloseItem) is set, a pinned
issue refuses with *issueops.PinnedError and another actor's bead with
*issueops.CloseNotAssigneeError (matches ErrNotOwner).
Wire: 409 template_read_only, issue_pinned and not_assignee (holder in
`assignee`, also on a batch-close outcome); the client rebuilds the typed
errors. The decision is one exported pure rule over the pre-image,
issueops.CheckClosable (internal/storage/issueops), which the in-tx guard
calls; bd close's direct and proxied preflights call it too, ahead of gate
satisfaction under the same already-closed skip, so bd close output, refusal
order and exit codes are unchanged (validateIssueClosable is gone). bd close
--if-revision now applies the guards too.
Conformance: RunLifecycleCloseEnforcesTheCloseGuards,
RunBatchCloserItemsAnswerToTheCloseGuards and
RunBatchApplyCloseItemsAnswerToTheCloseGuards on dolt, embedded, uow and
http, plus handler mapping tests, a CheckClosable table test, and a cmd/bd
test pinning that the guards outrank gate satisfaction.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(httpclient): send force on the raw close; scope the close guards
Review fixes for #7425 (adopt-pr bd-0h0ao4, iterations 1 and 2).
The raw close keeps parity over http. httpclient.Store.CloseIssue maps the
off-role raw close onto the role's closeIssue op and sent force=false.
With the guards in the role, a pinned or claimed target then refused (409
issue_pinned / not_assignee) on http only: dolt, embedded and proxied run
the raw close as issueops.CloseIssueInTx, which applies neither the guards
nor close policy. The molecule auto-close, `bd gate resolve`,
`bd todo done` and `bd human dismiss` all make that call, and its
signature carries no force a caller could pass. It now sends force. Over
http that also stops applying close policy to the raw close, which it did
at base and no other backend does; parity is the point, so that goes too.
The template guard has no bypass on the wire, so a template still refuses
the raw close over http where the other backends close it; no raw caller
is known to close one. TestServedRawCloseKeepsParityWithTheOtherBackends
closes both pin spellings, a held bead and a parent with an open child
through Store.CloseIssue and requires the template refusal; with force
back to false it fails on 409 issue_pinned.
The close guards stay on the close verbs. A status update that crosses
into the done category (`bd update -s closed`, PATCH, a batchApply update
item) still answers to close policy only, so it closes a pinned issue or
another actor's bead on every backend, as it did before this PR. Guarding
it changes what the update legs admit and needs its own refusal mapping on
PATCH and batchApply, so it is left for a follow-up; the update.go and
domain/db comments now say the exclusion is deliberate.
CHANGELOG: the entry moves from Fixed to Changed as BREAKING, is scoped to
the close operations, names the two paths the guards do not cover, and
adds a Migration line (send force or reclaim; templates are never
closable). Docs: the OpBatchCloseIssues item codes, the CloseIssueChecked
and CloseIssueOptions.Force docs (storage, dolt, embeddeddolt), the
oracle-a scenario strings that named the retired validateIssueClosable,
and the TestCloseCheckOne_CloseGuardsOutrankGateSatisfaction doc, which
claimed a proxied route it does not drive.
Iteration 2: the wire contract says what force waives. The OpenAPI
`force` members of CloseIssueRequest, BatchCloseRequest and ApplyCloseItem
said force bypasses close policy "and nothing else"; it also waives the
pin and the assignee guard, and never the template guard. The batchClose
"only two answers" paragraph now says the same, and types.gen.go is
regenerated (`make api-gen`). "Close guards" names the close operations
instead of "every route to a close" and adds that a status update into
the done category is not one, and the PATCH done-crossing paragraph says
a patch is never refused `issue_pinned` or `not_assignee`. The conformance
comments that quoted the old Force sentence (batch_apply_contract.go,
batch_closer_contract.go, lifecycle_close_reopen_contract.go) quote the
current docs, and the batch_apply failure message no longer says Force
does nothing else. CHANGELOG: a `close` line of `bd batch` is named among
the raw closes, and "a template is never closable" becomes "the close
operations never close a template, forced or not". The storage interface
CloseIssue gains a doc that states its HTTP exception.
TestCloseGuardRefusalsPrintTheGuardSentenceOnEveryRoute pins the sentence
`bd close` prints for each guard (template, pin, assignee) through each
printer (closeDirectRefusal, closeDirectTypedRefusal, closeProxiedRefusal,
closeProxiedTypedRefusal), with the refusal bare, wrapped by the use case
and the SQL repository, or inside a served problem envelope. One pinned
refusal also goes through closeProxiedOutcomes and closeProxiedFailures,
where the stderr line and the `--json` error field must both be the
sentence. Six overlay mutants fail it: closeGuardRefusal recognizing no
guard, or not the pin, and each of the four printers skipping its call to
closeGuardRefusal.
Not done here: a CLI test that `--if-revision` exits 1 on a guard refusal,
not ExitGuardMismatch. External PR #7372 carries per-id fence tests for
that route (6 of 7 pass at this head); they are better absorbed with
credit than rewritten.
Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Gas City Adopt-PR
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
* fix(issueops): enforce the template read-only update guard on every leg
The refusal of an update to a template (validateIssueUpdatable) lived only
in cmd/bd as a pre-read, so PATCH /v0/beads/issues/{id}, batch:apply update
items and library callers of Lifecycle.Update / BatchApplier edited
templates that `bd update` refused.
It is now one role rule, storage issueops.AuthorizeTemplateUpdate, returning
*issueops.TemplateReadOnlyError (matches ErrTemplateReadOnly; the message is
the sentence bd always printed). It runs in the update's own transaction,
after the compare-and-set preconditions (a stale guard still reports the
mismatch), and no force flag waives it:
- ExecuteUpdate (dolt, embedded) and the uow Update and batch update legs;
- the batch apply metadata splice that finishes a create item stays
unguarded on both bodies (a template the request creates is not modified);
- httpapi maps it to 409 template_read_only on updateIssue and applyBatch
(spec x-bd-codes and descriptions updated, apigen regenerated) and the
client rebuilds the typed error.
UpdateRequest.AllowTemplate stands the guard down for one request: the
caller edits a template deliberately. bd label (add, remove, remove-prefix)
and bd set-state set it, so they keep editing templates on every route, as
on origin/main. Over HTTP it is the optional `allow_template` member of the
PATCH body, advertised by the issues.update.allowTemplate behavior token,
which also says the server enforces the guard. httpclient Lifecycle.Update
decides from the cached handshake before the dial: against a server without
the token (no guard, no member) it runs the same rule
(AuthorizeTemplateUpdate) on a pre-read and never sends allow_template, so a
new bd against an older bd serve still refuses template updates.
cmd/bd: bd update, bd assign and the proxied assign/tag drop their pre-read
and print the role's refusal with the same line and exit code.
Conformance: RunLifecycleUpdateRefusesATemplate,
RunLifecycleUpdateAllowTemplateEditsATemplate,
RunBatchApplyUpdateItemsRefuseATemplate and
RunBatchApplySplicesTheMetadataOfATemplateItCreates on dolt, embedded, uow
and http (the http splice case is parked: the v0 create item has no
is_template member), plus handler and CLI rendering tests, and
TestUpdateTemplateGuardAgainstAServerThatPredatesIt (new client, handshake
without the token: refused before the dial, allow_template not sent).
Skew note (CHANGELOG): an older bd label / bd set-state against a new server
cannot send allow_template and now gets 409 template_read_only on a template.
bd comment, note, priority and tag keep their CLI-only pre-read guard.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(issueops): scope template read-only docs to updates, test label stand-down
Review fixups for PR 7427 (adopt-pr review loop, iteration 1):
- Contract: the role guard covers updates, not every mutation. The
CHANGELOG headline, ErrTemplateReadOnly and CodeTemplateReadOnly now
say so, and "Not yet moved" names claim, reopen, :casMetadata and the
served addComment, which have no template check yet (a PATCH with
claim: true refuses a template that POST :claim still claims). Close
is #7425's. Follow-up: bd-jkp9v3.
- Skew: the CapIssuesUpdateAllowTemplate client fallback covers
updateIssue only. A batch update item gets no client-side check, so
through an older bd serve it still edits a template; the CHANGELOG
and both capability docs say so.
- Tests: a template row now goes through the CLI on both tiers
(TestEmbeddedLabelEditReports, TestProxiedServerLabelC). bd label add,
bd label remove --prefix and bd set-state edit it (AllowTemplate);
bd update --title and bd assign exit 1 with the template sentence and
leave it unchanged. Mutants: dropping AllowTemplate from label.go and
state.go reds the three edits on both tiers; disabling
AuthorizeTemplateUpdate reds update and assign on both tiers.
- Stale comments: runTagProxiedServer, applyUpdateProxiedOne,
proxiedUpdateTarget, UpdateFlags (five booleans, not four) and the
ItemUpdate notes in applyLabelEdit and bd label propagate's proxied
route (UpdateItem has no AllowTemplate).
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): 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>
* ci(bazel): split //scripts:scripts_test by what it reads; partition //:repo_files
//scripts:scripts_test declared //:repo_files (the whole checkout), so every
PR re-ran it, and it took ~181s on rbe-west. Most of that (60-79s) was
TestBazelGatedLanesNeverRetryFlakyTests line-regexping the --run_under
wrapper's pinned dolt binary (tools/bazel/hermetic_bin/dolt, in every
test's runfiles); it now skips binary files, as git grep -I does.
tools/bazel/go_srcs.py's per-package repo_files block now partitions each
package's files into repo_go_srcs, repo_go_test_srcs, repo_doc_files and
repo_other_files, aggregated at the root; //:repo_files is their union
(same 4679 files). The //scripts tests are split into go_test targets by
what they read (traced per test with strace over a runfiles-shaped tree):
scripts_test CI/Bazel policy: //:repo_other_files (+1 Go file)
shell_scripts_test script fixtures: //scripts files, a few root files
go_test_sources_test _test.go scans: //:repo_go_test_srcs + shard files
go_sources_test check-testing-short.sh: every .go file
tracked_files_test every tracked file: //:repo_files
Shared helpers move to helpers-only files; TestScriptsTestTargetsPartition-
TheTests fails on a test file in no target or in two. //test/docsync and
the //scripts/repochecks slices declare partitions or single files instead
of //:repo_files where they can.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* ci(bazel): skip only the non-checkout hermetic_bin dir in the flaky-retry walk
Skipping every binary file also stopped scanning tracked binaries (images,
.binpb fixtures). Skip just tools/bazel/hermetic_bin, the --run_under
wrapper's runfiles directory, which is not in the checkout, so the walk's
coverage of tracked files is unchanged.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* feat(httpclient): carry DepAddItem.HasSpawner/ThreadID over the wire
The http leg's batchApply wire shape dropped a dep_add item's HasSpawner
and ThreadID fields -- an edit the caller believed landed. Extend the
wire body (ApplyDepAddItem.has_spawner/thread_id), gate sending either
field on a new additive behavior capability
(issues.batchApply.depAddLineage / CapBatchApplyDepAddLineage) so a
client refuses locally before dialing an older server instead of
silently dropping graph lineage, and wire the storage-layer spawner-id
stamping (StampWaitsForSpawnerID) through both the dolt and uow legs
that already had the fields but never stamped them. wire_revision and
min_client are unchanged; the golden digest and openapi spec are
regenerated.
Also fixes three generic bijection/vocabulary gates this change was
missing: write_ledger_test.go's applyBatch/item/dep_add carriage table,
and the literal behaviorCapabilities lists in
internal/httpapi/server_test.go and
internal/httpclient/wire/vocabulary_test.go.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* test(httpclient/wire): pin the item-count gate at 356 items
Add TestApplyBatchAt356ItemsWithoutTheCapabilityRefusesBeforeDialing,
exercising internal/storage/batchfixtures.Shape356's exact item count
-- the design's primary measured large-batch-apply shape -- rather than
only the floor+1/ceiling+1 boundaries the existing cases pin. The gate
is content-agnostic (it never looks past len(body.Items)), so a
synthetic plan here is behaviorally identical to a real Shape356 plan
for this one check; realistic-content coverage follows in the next
commit.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* test(httpclient): prove a 356-item Shape356 plan commits atomically or leaves zero rows
Add two tests against the real served stack using
batchfixtures.Shape356's realistic, heterogeneous content (102 creates,
136 blocks edges, 102 tracks-to-root edges, 16 assign updates):
- TestServedBatchApplyShape356CommitsAtomically applies the full plan
once and verifies every create landed with a bound key, matching the
issues table row-for-row.
- TestServedBatchApplyShape356PlusAStaleGuardLeavesZeroRows appends a
357th item guarding the pre-existing root issue with a deliberately
stale ExpectedVersion. Because the root is untouched by the other 356
items, this exercises the real server-side precondition_failed round
trip (rather than the static same-request-row ErrValidation rule),
asserting errors.Is(err, issueops.ErrVersionMismatch) and that none of
the 356 creates landed -- the "never chunk" ceiling: an all-or-nothing
request that fails on its last item must leave nothing behind.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* test(httpclient): close S5 review HIGH findings (lineage gate, thread_id, gc mappings)
2026-10 Opus review on the S5 batch-apply slice found the wire change
correct but coverage missing:
- HIGH-1: refuseUnservedDepAddLineage (batchapplier.go) had no coverage
at all -- deleting it passed every existing test. Add a test pinning
that HasSpawner or ThreadID on a server without
issues.batchApply.depAddLineage refuses *storage.ErrUnsupported
before dialing, and that a plan touching neither field still dials.
- HIGH-2: thread_id was never asserted end to end. Add
RunBatchApplyCarriesThreadIDOntoTheStoredEdge to the shared
conformance package, wire it onto the dolt, embeddeddolt and uow
legs, and add the http leg's own case
(TestServedBatchApplyCarriesThreadIDOntoTheStoredEdge), which is the
one case that proves the field survives both the client's encode and
the server's decode at once.
- HIGH-3: DESIGN Sec 3.8 ("Guarded writes: no new roles") documents two
gc mappings onto BatchApplier that had no coverage: an update carrying
a metadata patch plus ExpectedVersion followed by a close in one
request (CloseWithMetadataIfMatch, atomic -- a stale version leaves
zero changes), and a keyed create/MetadataRefs/dep_add
(parent-child included)/trailing-update plan (ApplyGraphPlan). Document
both compositions on the BatchApplier interface and add http-leg tests
for each.
Mutation-verified: removing the lineage gate call, dropping thread_id on
the client's encode, and dropping it on the server's decode each now
fail a test that previously passed unconditionally.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* fix(httpclient): nil-guard snapshot consumers, fix spec wording, sync Bazel
2026-10 Opus review MED/LOW findings on the S5 batch-apply slice:
- LOW-6: Store.snapshot returns (nil, nil) when a Store has neither a
wire nor a cached handshake. Store.Counter() does not call roleWire
first (unlike Sweeper/BatchApplier), so this is reachable through the
ordinary public accessor and a scoped count would panic on
snap.Capabilities. Nil-guard every snapshot() consumer
(batchapplier.go, counter.go, sweeper.go) so a nil snapshot is treated
as "nothing advertised" and falls through to the capability refusal.
Add TestCounterRefusesScopeGracefullyWithNoTransportAndNoSnapshot,
mutation-verified to panic without the guard.
- LOW-7: the ApplyDepAddItem spec comment said an old server would
"silently ignore" has_spawner/thread_id; it answers its own 400 for
an unknown member. Fix the wording and regenerate apigen/types.gen.go.
- MED-4: internal/httpclient/BUILD.bazel was missing
served_batch_apply_large_test.go, expected_revision_contract_test.go,
served_dualwrite_history_test.go and the
//internal/storage/batchfixtures dep. Sync with gazelle (confirmed
idempotent) and go_srcs.py --check.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* fix(storage): carry thread_id on a same-type dep re-add; bound batch thread_id
A same-type re-add of an existing dependency compared and rewrote only
metadata, so on both write legs (issueops.addDependencyInTx and the uow
dependency repository) a re-add naming a new ThreadID was read as
change-free and the thread was dropped, and a metadata-plus-thread re-add
stored the metadata without the thread. Both arms now read the stored
thread_id through one shared rule, issueops.ReAddedDependencyThread: a
named thread the row does not carry is a change (UPDATE, replacement-edge
journal entry, exactly one version, #5898 leg 2), and a re-add naming no
thread keeps the stored one, so callers that never carry a thread cannot
erase it. The journal's EventDep has no thread member, so a thread-only
re-add journals the same payload as the original add; the source's version
snapshot is what records the new thread, and the comments on both arms now
say so instead of promising a complete replacement edge.
planApplyBatchDepAdd bounds DepAddItem.ThreadID with CheckFieldLen, so an
over-long thread id is ErrValidation before any database work on every
leg, as the http leg's decode already refuses it, instead of an opaque
mid-transaction "string too long" on the local legs. Only the length bound
is shared: the http leg's control-character refusal stays http-only.
The HasSpawner/ThreadID docs now name the producer that actually sets
HasSpawner (an embedder lowering a graph plan, e.g. gc's ApplyGraphPlan
mapping) instead of bd create --graph, and drop the CHANGELOG reference
that had no entry behind it.
New conformance cases, wired on dolt, embeddeddolt, uow and served:
RunBatchApplyCarriesThreadIDOntoAnExistingEdge,
RunBatchApplyRefusesAThreadIDLongerThanItsColumn and
RunDependencyEditorSameTypeReAddWithChangedThreadMintsOneVersion.
Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Gas City Adopt-PR
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* ci(shards): add the re-add thread test to the embedded storage shard manifest
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* ci: trigger the first PR CI run now that the base is main
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(httpclient): gate has_spawner to waits-for edges; refuse empty thread_id
Review iteration 1 fix-up for #7265 (synthesis F1, F2, F4, F5, F6, F7).
F2: the client's CapBatchApplyDepAddLineage gate refused HasSpawner on
every edge type, but the role reads the flag on a waits-for edge only
(StampWaitsForSpawnerID is a no-op off one). An embedder plan setting it
on, say, a blocks edge works against every existing server, yet this
client refused it during a mixed-version rollout. depAddNamesSpawner now
holds the role's own rule: the flag is gated and encoded on a waits-for
edge only, and dropped elsewhere, which loses nothing the role would
store. ThreadID stays gated on every edge type, since a thread is stored
on all of them. The "spawner flag on any other edge type" subtest is
restored to an unadvertising server and now also asserts the flag is
dropped from the body, and
TestApplyBatchRefusesUnservedDepAddLineageBeforeDialing gains a
ThreadID-on-blocks case. The W-DepAddItem.HasSpawner ledger row and the
regenerated engdocs/design/http-divergence-ledger.md say the same.
F5: the document gives thread_id minLength: 1, but the decoder read an
empty string as no thread. applyDepAddItem now refuses a present, empty
thread_id with 400 invalid_value naming items[i].dep_add.thread_id, as
it does an empty type; an absent one still names no thread. New
TestApplyBatchRefusesAnEmptyThreadID; the documented-body test now
forwards has_spawner and thread_id as well.
F1: bd create --graph does set HasSpawner (buildGraphApplyBatchRequest,
on the embedded and proxied legs, since #7209), so the DepAddItem doc
names both producers again and the conformance doc's CHANGELOG pointer
is restored; the [Unreleased] entry behind it is on the base.
F4: the CapBatchApplyDepAddLineage comment said an older server would
silently drop the members; it answers either one with
400 invalid_argument/unknown_parameter.
F6: the create-edge ledger comment said no operation publishes a thread
member; batch apply's dep_add item now does.
F7: TestServedBatchApplyGcApplyGraphPlan adds a waits-for item carrying
HasSpawner and ThreadID and reads the stored row back, pinning
metadata.spawner_id to the resolved spawner and the thread on the
served leg.
F3 (the journal's EventDep carries no thread member) is not addressed
here.
Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Gas City Adopt-PR
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
Co-authored-by: Eddie the Engineer <adopt-pr@gascity.com>
* feat(httpclient): wire the S4 Sweeper extension (wisps-plane, live-dependent protection, limit)
Publish SweepRequest.ProtectLiveDependents and .Limit (plus a
wisps-plane tier and SweepResult.Remaining/.LiveDependent) on the v0
wire behind three new behavior-capability tokens
(issues.sweep.wispsPlane, issues.sweep.liveDependents,
issues.sweep.limit), and wire the client to send them once the
handshake advertises the tokens (refuseUnservedSweep otherwise).
Retire the two W-SweepRequest ledger rows that previously refused
these fields for lack of a wire member.
CurrentWireRevision stays at 2. A new wisps-plane SweepRequest.Tier
value is a request-only enum widening: it cannot cause an older
client to misdecode a response, and it is already gated by its own
capability token, so it is additive rather than a wire break. Teach
wireshape's drift gate that distinction directly: a Digest.Sides side
channel records whether each schema member is request-only,
response-only or both, and widensAdditively now treats a request-only
enum's new value as additive while still treating any response-side
widening as breaking, with tests pinning both directions and a
regenerated golden.json. min_client_wire_revision stays 0.
internal/httpapi/apigen/types.gen.go and openapi.v0.yaml's comments are
regenerated/updated to match (make api-gen).
Six served Sweeper contracts that were parked now run for real against
the in-process HTTP server; TestSweepSendsTheS4MembersOnceTheServerAdvertisesThem
pins the capability-gated encode.
Re-review fix: walk()'s side classification short-circuited on a
name-only visited set, so a node already walked from one side never
had its CHILDREN walked again when a later path promoted the parent
to "both" — children stayed classified under whichever side reached
them first, order-dependent on Go's map iteration. Side recursion is
now guarded per (schema, side) pair (sideWalked, keyed on
name+"\x00"+side) instead of per schema name alone, so a child
reachable from both sides is always walked, and therefore recorded,
from both. Added TestSidePropagatesToNestedChildren (a named grandchild
and an inline nested child both reachable from a request body and,
via a wrapper, a response, assert "both" on every level and that
widening either enum breaks instead of being classed additive),
TestEnumWideningOnSharedNestedChildIsNotAdditive, and
TestComputeFromSideAssignmentIsDeterministic (200 runs, asserts
identical Sides/Entries every time). golden.json is confirmed
unchanged by the fix (regenerated and diffed byte-for-byte). Also
removes a bd-enterprise mention introduced in this slice's own
write_ledger_test.go comment (not a provenance header) in favor of
neutral wording.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* fix(storage): ratchet the http leg's role-contract ceiling to zero
Classify all 42 previously-ceilinged http-leg entrypoints and clear
the ceiling:
- ExpectedRevision + Refusal (10): wire a Phase-0 all-nil fixture,
matching every other backend's current (unbuilt-CAS-feature) state.
Said honestly: these ten entrypoints are counted here, the hook is
unbuilt on every leg (not just this one), and every case runs zero
assertions until a CompareAndSetVersion wire operation exists for
this client to bind.
- Lifecycle ExpectedVersion concurrency (4): wire the two races that
land on Priority/Notes and on Close for real over the served HTTP
harness (precondition_failed decodes to storage.ErrVersionMismatch
via errors.Is, same as the local legs). The other two, which race
IssuePatch.SpecID/.AwaitID/.Owner edits against updateIssue, stay
waived, but PENDING rather than permanent: IssuePatchBody refuses
those three fields outright (W-IssuePatch.SpecID/.AwaitID/.Owner,
D8 refuse-not-drop) rather than ever sending them, so the race never
reaches the wire today. Closing the gap means publishing those
fields on the wire, tracked as a follow-up slice, S4b: publish
owner/spec_id/await_id on the wire.
- DualWrite (6): wired for real instead of waived. Mutate and
MutateAsNoOp drive the client's Lifecycle role (Create/Update)
against an in-process served harness with its own reference store,
so VersionedHistoryConfigurer can be toggled per fixture;
CurrentRevision, VersionRowCount and LatestVersionAttribution read
the reference store's raw columns the same way every other served
fixture's postcondition hooks do. All six FR-1/FR-2/FR-3/FR-5/FR-7
cases (one version row per accepted mutation, no-op skip, atomic
attribution, current_revision parity, and flag-off producing no
rows) now run and pass.
- VersionReconciler + InitVerifier (13), and the raw
IssueOperationsUpdate seam (3): waived — unservable over a typed
HTTP role boundary, not a wiring gap.
adoptionCeiling: 42 -> 0 for the http leg; the "adopting" field is
removed (a zero ceiling with a reason is a registry error) since every
remaining gap is now a named waiver, PENDING or permanent as stated
above, instead of a budgeted unnamed one. Also deletes the scratch
zzz_dump_missing_test.go used to enumerate the ceiling during triage.
Re-review fix: the shared conformance attribution case only asserts
change_actor is non-empty (it runs across every leg, each with a
different literal Mutate actor). The http fixture's own Mutate always
sends Actor: "writer", so this leg's AttributionIsRecordedWithTheMutation
subtest now also mutates a second, independent issue and asserts the
recorded actor equals exactly "writer", in addition to the shared
non-empty check.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* fix(types): make ParseRevisionToken the exact inverse of FormatInt
ParseRevisionToken's doc comment already promised it accepts exactly
what RevisionToken emits, but strconv.ParseInt alone is looser than
that: besides a leading "+" that FormatInt never produces, it also
accepts a leading zero on a digit string longer than one character
("007") and the literal "-0" — none of which FormatInt ever emits
(FormatInt(0, 10) is always "0", never "-0", and it never pads a
digit run). A caller is only ever supposed to echo a token a response
carried, so any of these is a client that invented a value rather
than a server this client should follow; reject them explicitly
instead of accepting them silently.
Pins the string<->int64 boundary with
TestParseRevisionTokenRejectsMalformedTokens, covering empty strings,
fractional/exponent spellings, leading "+", surrounding whitespace,
non-decimal bases, one-past-int64-boundary values, non-ASCII digits,
and now "007", "-007" and "-0".
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* fixup(wireshape): guard widensAdditively against "no enum before"
bee-ghosttrack / CHANGES_REQUESTED on #7251: widensAdditively required
len(new.Enum) > len(old.Enum), which holds vacuously when the old side
has no enum at all (a free `type: string`). That let a request-only
member go from unconstrained to a fixed enum at the same wire_revision
-- the opposite of widening, since the server now 400s a value an old
client could send yesterday.
Add the guard `len(old.Enum) == 0 || len(new.Enum) <= len(old.Enum) ->
false` so the no-enum-before case falls through to the ordinary
non-additive Changed path, same as a strict narrowing. Add a pinning
case to TestEnumWideningAdditivity and extend the doc comment.
Also reword the ExpectedRevision contract file comment from "runs ZERO
assertions" to "SKIPS", per the reviewer's note that the Run* helpers
t.Skip when CompareAndSetVersion is nil -- it's a skip, not an
assertion-free run.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* docs(httpclient): regenerate the divergence ledger after rebasing onto #7247's review fixes
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* test(httpclient): Sweep Limit now refuses on the missing issues.sweep.limit capability
#7247's review round pinned Sweep{Limit} as an encoder refusal. With S4 the
wire carries limit behind issues.sweep.limit, so against a server without
the token the refusal is a pre-dial capability refusal: still
*storage.ErrUnsupported for this backend, now naming the capability.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(httpapi,httpclient): name the invalid_value refusal; add tests to Bazel
Maintainer fixup for the review of #7251 (iteration 1). There are no blocker or
major findings. This applies the three optional findings that both reviewers
reported.
- Eight comment and description sites added by this PR say that an older
server refuses an unpublished `tier` (or S4) member with `unknown_value`.
No such reason exists. The server refuses with ReasonInvalidValue =
"invalid_value" (internal/httpapi/problem.go), and sweep.go uses it for a
bad tier. The sites are in openapi.v0.yaml, apigen/types.gen.go (regenerated
by `make api-gen`), routes.go, sweeper.go and wire/handshake.go. The base has
none of them, so this only corrects the PR's own text. A client author now
matches the token the server actually sends.
- wire/handshake.go said the tier member carries no ledger row because it
"narrows" an existing enum. Adding a value widens the accepted set, so the
word is now "widens".
- internal/httpclient/BUILD.bazel: add expected_revision_contract_test.go and
served_dualwrite_history_test.go to the httpclient_test srcs. Both files are
new in this PR. Without the entries, `go test` runs them but no Bazel lane
compiles them. The srcs list now matches the package's files, and the
existing deps already cover their imports.
Provenance: this is the residue of the stranded fixup cad1cf02a2 from the
previous adoption of this PR, replayed onto the current head. Its patch-id
(b62e7d6d5562) is identical to that reviewed residue. That fixup's
widensAdditively guard and SKIP-message nit are not repeated here. The author
already landed both in b3f1516e55 (d41f317e0a after the rebase).
Validation: git diff --check; make api-gen (no-op) and make api-check;
go build, go vet and gofmt on internal/httpapi/... and internal/httpclient/...;
go test for internal/httpclient/wire, internal/httpclient/encode and
test/docsync; the httpclient Sweep* and TestExpectedRevisionContract tests; the
served dual-write tests with BEADS_TEST_EMBEDDED_DOLT=1; and
tools/bazel/go_srcs.py --check.
Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* docs(httpclient): regenerate the divergence ledger on main after #7247 merged
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(httpclient): give encode_test the httpclient tests its pin check reads
Maintainer fixup for the pre-review CI of #7251. Bazel / test and
Bazel / integration (PR run 37781419956) each fail one target,
//internal/httpclient/encode:encode_test, which also fails CI Gate / Required.
TestLedgerRowsAreWellFormed reports that rows W-SweepRequest.ProtectLiveDependents
and W-SweepRequest.Limit are pinned by
TestSweepSendsTheS4MembersOnceTheServerAdvertisesThem, which is "neither a test
in this package nor a TODO(<bead>)".
The pin is right. The test lives in internal/httpclient/bulk_roles_test.go.
testFunctionsInThisPackage collects test names from ".", ".." and
../../../cmd/bd, but the data of encode_test declares only its own sources,
//cmd/bd:go_srcs, the ledger doc and the OpenAPI spec. Under Bazel, ".."
exists in the runfiles but holds no _test.go files, so the walk silently finds
nothing there. go test reads the real directory and passes. This PR changes
neither the walk nor the BUILD file. Every pin on main resolves from this
package or cmd/bd, which is why main is green. These two rows are the only ones
pinned to a test that exists only in internal/httpclient. The red stayed hidden
until now because the PR sat on a stacked base. PR CI, including the Bazel
lanes, runs only for PRs against main, release/** and hotfix/**.
Declare //internal/httpclient:go_srcs as data, so Bazel sees the files that
go test reads. The filegroup already exists with //:__subpackages__ visibility.
The pins stay on the test that actually covers the S4 members.
Validation: bazel test //internal/httpclient/encode:encode_test --config=ci
--nocache_test_results, run two ways. In the local processwrapper sandbox
(--remote_executor= --strategy=TestRunner=processwrapper-sandbox) the same
command fails both rows without this change and passes with it. It also passes
on the remote executor. Plus tools/bazel/go_srcs.py --check, gazelle
-mode=diff on the package (no change), git diff --check, and
go test ./internal/httpclient/encode/.
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(httpapi): pin the S4 sweep members at the wire edge, gate golden sides
The `sides` map this change adds to golden.json predates schemas main gained
since (#7248's BatchGetIssue*, BatchGetIssuesRequest* and
BatchGetIssuesResult*, plus IssueDetails.gated_by[]), so the rebase left it 9
schemas short of what gendigest writes, and goldenDrift never compared Sides,
so nothing noticed. Regenerated (+9 sides lines, no entry changes), and
goldenDrift now fails with the regenerate instruction when the golden's sides
disagree with a fresh digest; TestGoldenDrift drives that arm three ways.
The SweepSkips description still called the first two buckets protections
and the last four defenses, which filed the new live_dependent protection
under the defenses. It now names pinned, referenced and live_dependent as the
protections (apigen regenerated: the two comment copies only), and
handleSweep's comment counts eight members.
internal/httpapi's sweep pins stopped at the original six members: nothing
there sent protect_live_dependents or limit, refused a mistyped one, or read
live_dependent or remaining back. The forward, refuse and publish tests now
cover all four, and TestSweepResponseCarriesEveryRoleField, named by
sweepResponse's comment but never written, counts both projection levels and
requires every wire field populated from a fully set role result.
The httpclient Sweep defer comment described ProtectLiveDependents/Limit
refusal paths this change replaced with capability gates; it now says why
the pass-through defer stays.
Validation: go test ./internal/httpapi/... ./internal/httpclient/... (CGO,
gms_pure_go), the served sweeper tier with BEADS_TEST_EMBEDDED_DOLT=1 (19/19
pass, none skipped), make api-check, go vet, git diff --check, and bazel test
--config=ci on httpapi_test, wireshape/..., httpclient_test, encode_test and
types_gen_drift_test. Mutants, each restored: disabling the sides arm reds
three TestGoldenDrift arms; the pre-fix golden reds TestWireShapeDigest
naming the 9 schemas; dropping the live_dependent or remaining projection,
the protect_live_dependents decode, or the limit assignment each reds its
new pin.
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>
* wy-j2upyy: render the derived GATED decoration on bd show and bd list
A bead an open gate blocks is excluded from `bd ready` but rendered
`[P2 · OPEN]` by `bd show` and with a plain ○ by `bd list`, so the human
surfaces disagreed with the readiness query.
The decoration is DERIVED, never stored: no status write, no --status
filter change, no existing JSON field reshaped.
- internal/types/gated.go: IsActiveGate, the ONE predicate — a gate-typed
dependency reached over a blocking edge (blocks / conditional-blocks /
waits-for) whose status is neither closed nor pinned. That is the
is_blocked recompute's blocking leg restricted to gates, so a rendered
GATED and a `bd ready` exclusion cannot disagree. GateDescription /
GateReason own the reason's round trip with `bd gate create`.
- bd show: `[P2 · OPEN · GATED]` plus one `Gated by: <id> (<type>[:
<reason>][, awaiting <await-id>])` line per gate, beside Deferred:. The
dependency read the DEPENDS ON section already made is hoisted, so the
decoration costs no extra query.
- bd list: ⊘ in the glyph column (circle family, distinct from ○ and ❄),
and a legend entry when the page carries one. Batched by id set —
at most two extra queries per listing, one in the tree view where the
edge map is already loaded.
- --json: additive `gated_by: [{id,type,reason}]` on the detail view,
omitted when empty; documented in the OpenAPI IssueDetails schema.
Tests (red first): cmd/bd/gated_render_embedded_test.go drives real
bd show/list/--json over an embedded rig — gated, resolved, deferred+gated,
JSON additivity — plus pure unit tests for the predicate and formatters.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* wy-j2upyy: document the additive gated_by field in the JSON schema reference
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* wy-j2upyy: cover the flat list route's own batched gate read
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* wy-j2upyy: make GATED the readiness rule's gate clause, both halves
The adversarial review found the "one predicate shared with bd ready" claim
false on two axes, and both were reproducible by hand:
BLOCKER 1 — waits-for is not the status rule. The is_blocked recompute applies
"target not closed and not pinned" only to its blocks / conditional-blocks
legs; the waits-for leg goes through waitsForGateBlockedSQL, a fanout over the
target's open parent-child children (or an also_blocks spawner). A plain
`bd dep add X G -t waits-for` onto an open childless gate therefore leaves X
in `bd ready` while every new surface called it GATED. Mirroring that leg in
Go would be a second implementation of a rule the database owns, so the edge
clause now names the two legs it really mirrors (types.IsGateEdge) and the
test that pinned the wrong direction is flipped.
BLOCKER 2 — the subject half was missing and spelled three different ways.
unmarkAllBlockedSQL forces is_blocked=0 for a closed or pinned subject
whatever its edges say, so `bd ready` never withholds one on a gate's account;
show and workapi filtered nothing, cmd/bd/gated.go filtered closed only, and
list_format.go filtered closed at two more sites. A force-closed bead rendered
[CLOSED · GATED] with gated_by on show while list showed a plain row — show
and list disagreeing about one bead, which is the drift this was meant to
prevent. The clause is now types.SubjectCanBeGated, asked once in
types.GatesHolding (which replaces ActiveGates and takes the subject) and once
in the listing helper that has no hydrated deps; the formatters re-ask the SAME
exported predicate rather than inventing a fourth spelling.
SHOULD 3 — agent mode computed the gate reads and threw them away, in every
CLAUDE_CODE seat, i.e. the population that filed the bug. Decorating it is the
real fix, so gatesByIssueID now returns the gate IDS and formatAgentIssue
carries "gated by: <id>" in the parenthetical it already prints. A gate is
also a blocker, so its id appears under both "blocked by" and "gated by": the
first says what to wait on, the second says which of those nobody can clear by
doing more work. --long and --format render no gate and no longer pay for the
reads.
NOTE 5 — a pinned+gated row kept ⊘ instead of 📌; with the subject clause a
pinned bead is not gated at all, so the pin survives by construction.
NOTE 6 — the cost comments claimed "two queries" / "exactly ONE"; the id-set
readers are a few round trips each. The bound that is real (per page, never
per row) is what the comments now say.
Tests, red-first: the flipped waits-for case; TestGatesHoldingSubjectStatus and
TestSubjectCanBeGated (open/in_progress/deferred yes, closed/pinned/nil no);
TestFormatIssueCompactGated and TestFormatAgentIssueGated; and four embedded
arms — a waits-for edge that bd ready lists and no surface decorates, a
force-closed subject and a pinned subject that render nothing and publish no
gated_by, and the agent line naming its gate. Each was watched to fail against
the pre-fix predicate before it passed.
Ran: go test ./internal/types/ -run 'TestGateIsHolding|TestGatesHolding|
TestSubjectCanBeGated|TestGateDescriptionRoundTrip|TestGateRefsProjection';
go test ./cmd/bd/ -run 'TestFormat*Gated|TestFormatIssueCompact*|
TestFormatDependencyInfoWithParent|TestListRoles*|TestDisplayPrettyList*';
BEADS_TEST_EMBEDDED_DOLT=1 go test ./cmd/bd/ -run TestEmbeddedGatedRendering
(11/11 subtests); gofmt -l (empty), go vet and golangci-lint on cmd/bd,
internal/types, internal/ui, internal/workapi; scripts/ci/pr-policy.sh.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* wy-j2upyy: render GATED on the proxied `bd show` text route
SHOULD 4 of the review, and required for this rig: the constellation runs
proxied-server, where `bd show --json` already carried gated_by (uow
issue_reader -> workapi.BuildIssueDetails) while the TEXT renderer called the
plain formatters. The same bead read two ways from the same server disagreed.
proxiedRenderIssue now hoists the outgoing-edge read it already did for the
DEPENDS ON section above the header — the gates are the gate-typed subset of
that very set, so the decoration costs no extra query — and passes them to
formatIssueHeaderWithGates / formatIssueMetadataWithGates. The proxied LIST
routes were wired in the previous commit.
TestProxiedServerGatedRendering covers all five text surfaces plus the JSON
one beside them (header + Gated by line, pretty glyph, compact glyph + "gated
by", agent line, and a closed subject that renders nothing). Watched red first
with the proxied decoration stubbed out: four of six subtests failed, and the
--json arm passed, which is exactly the asymmetry the review reported.
Ran: BEADS_TEST_PROXIED_SERVER=1 go test ./cmd/bd/
-run TestProxiedServerGatedRendering -count=1 (6/6, 37.8s).
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* wy-j2upyy: put cmd/bd/state.go on the shared "Reason:" marker
NOTE 7 of the review: types' gateReasonMarker was not gate-private —
cmd/bd/state.go wrote the same "\n\nReason: " into state-change EVENT
descriptions from its own literal. No live collision (events are not
gate-typed), but the constant's doc claimed GateReason returns "" for every
gate not made by `bd gate create`, and that is false for any description
carrying the marker.
The previous commit exported the constant as types.ReasonMarker, reworded
GateReason to say what the pair really guarantees (a round trip, not a
provenance check) and pinned the honest behavior in
TestGateDescriptionRoundTrip. This commit is the second writer: state.go now
builds its event description from the same constant, so the two cannot drift
apart by accident.
Ran: go build ./...; go test ./internal/types/ -run TestGateDescriptionRoundTrip
-count=1; gofmt -l cmd/bd/state.go (empty); go vet ./cmd/bd/.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* wy-j2upyy: alias types.GateRef in package backend
gated_by on IssueDetails makes GateRef reachable from the public backend
contract; TestPublicSurfaceComplete requires every such type to carry an
alias here.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
* wy-j2upyy: build(bazel): register gated.go and its tests in cmd/bd and internal/types
The rebase onto e766da5ed carried the new source files but not their
BUILD.bazel entries, so every Bazel lane failed to compile internal/types
(undefined: GateRef). This is CI's own bazel-sync patch for 9ad7eb96c3,
applied unchanged.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
* wy-j2upyy: compute gated_by AFTER the dependencies read in BuildIssueDetails
The be-lpi merge (#6352) moved src.Dependencies() below the cardinality
counts so the unresolvable-edge delta reads count-first. That hunk merged
cleanly, which left details.GatedBy computed on the still-nil slice, and
both CI shards' show_json…carries_gated_by subtests went red (PR Risk
Embedded Dolt Cmd 20/20, Proxied Dolt Cmd 4/15 at d21237f3dc).
Move the GatedBy line to directly after details.Dependencies = deps, still
before the BriefDeps trim that rewrites the slice, and pin the ordering with
a workapi unit test over both DetailSource seams and BriefDeps on/off (red
on the pre-fix code, green after).
Ran: go test ./internal/workapi; go vet ./internal/workapi;
BEADS_TEST_EMBEDDED_DOLT=1 go test ./cmd/bd -run TestEmbeddedGatedRendering;
BEADS_TEST_PROXIED_SERVER=1 go test ./cmd/bd -run TestProxiedServerGatedRendering.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
* ci: register #6606's gated-rendering tests and gated_by wire shape with main's generated gates
Maintainer fixup for adopt-pr #6606. The adopted head merges the PR head
(c43eb567d2) into main (800d43eb8d). The PR's merge-base (02f05340f6)
predates three generated artifacts on main that every PR adding a cmd/bd
tier test or a wire member has to keep current, so the merged tree is red
on them even though the PR's own CI cannot see them:
- .github/scripts/embedded-cmd-test-shards.txt: the Bazel-only 50-shard
block must name every TestEmbedded* test exactly once, or
TestCmdEmbeddedShardManifestGeneratorNotStale fails `go test ./scripts/`.
`gen_embedded_cmd_shard_manifest.py 50 --weights=duration --write`
(incremental) placed TestEmbeddedGatedRendering on shard 16 and moved
no existing assignment; the frozen 20-shard block is untouched.
- .github/scripts/proxied-cmd-test-shards.txt: likewise for the 30-shard
block and TestProxiedServerGatedRendering (shard 2), via
`gen_proxied_shard_manifest.py 30 --weights=duration --write`, so
TestProxiedShardManifestGeneratorNotStale passes.
- internal/httpapi/wireshape/testdata/golden.json: TestWireShapeDigest
(#7182) pins every response member. `go run
./internal/httpapi/wireshape/cmd/gendigest` recorded the PR's new
IssueDetails.gated_by array and its id/type/reason members as four pure
additions (+25/-0), so no wire_revision bump is owed.
The PR's own files are unchanged.
Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Gas City Adopt-PR
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* docs(gated): state gated_by one way, mark --watch as undecorated, fix stale refs
Review follow-ups for #6606. Comment and doc text only; no behavior change.
- gated_by is now documented in one direction. internal/types/types.go,
internal/types/gated.go and docs/reference/json-schema.md said the list
is nonempty EXACTLY when `bd ready` withholds the issue on a gate's
account. Only one direction holds: the is_blocked recompute also blocks
a child whose parent is blocked (its parent-child legs), so a child of a
gated parent leaves `bd ready` with an empty gated_by. All three now say
"nonempty means withheld", as the OpenAPI text already did, and name the
parent-child case.
- bd list --watch passes a nil gated map on both routes
(runListProxiedWatch, displayWatchedIssueList), so a bead the one-shot
listing marks with the gated glyph keeps its plain status glyph while
watched. Watch is out of this PR's scope; the three call sites now say
so instead of reading as a forgotten argument.
- show_format.go named types.ActiveGates, which does not exist; the
predicate is types.GatesHolding.
- gated.go's best-effort note compared the gate read with `bd list`'s
blocking annotation, which only the direct route swallows. It now scopes
that comparison to the direct route and names the proxied route's
failing read (A-blk-1).
- proxiedGatedIssueIDsOwnUOW now notes that its unit of work is a second
snapshot, so one render can name a just-resolved gate under "blocked by:"
but not "gated by:".
Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Gas City Adopt-PR
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(list): hydrate proxied gate candidates from both planes (bd-p8k7dm)
The proxied list resolved gate candidates through the use case's
GetIssuesByIDs, which reads the issues table only, while the edges it
resolved came from GetForIssueIDs, which reads both dependency tables.
A wisp gate (`bd mol wisp` clones a formula's gates as wisps, held to a
wisp step by a blocks edge) therefore hydrated to nothing. Its step
listed undecorated in pretty, --flat and agent output while `bd show`,
`--json` and `bd ready` called it gated.
Read the wisps beside the issues, the two-plane idiom
ready_proxied_server.go and uowMolReader already use. A failed wisps
read keeps the durable candidates. Correct the cost-bound comment that
claimed the id-set readers partition the planes on both routes.
Tests: a wisp-step + wisp-gate case in TestProxiedServerGatedRendering
and TestEmbeddedGatedRendering asserts the pretty, --flat and
CLAUDE_CODE=1 rows of `bd list --include-ephemeral`, and
TestProxiedGatedIssueIDsHydratesBothPlanes pins both planes plus the
failed-wisps-read fallback.
Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Gas City Adopt-PR
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-authored-by: Eddie the Engineer <adopt-pr@gascity.com>
* fix(storage): parent-child cascade propagates only exogenous blockedness (wy-3eb07b, #6506)
A parent-child edge used to cascade the parent's is_blocked bit to its
children WHATEVER set it. So the "close gate on the epic" idiom — P carries
blocks edges onto its own children C1 and C2 so P cannot close before them —
darkened the very children P was waiting for. Neither child could reach
bd ready, so neither could be worked, so neither could close: a permanent
lock, and the one direction cmd/bd/dep.go does not refuse.
The contract (#6506): a parent-child edge propagates only EXOGENOUS
blockedness. P counts as blocked FOR CHILD C iff P has a blocking reason —
an open blocks/conditional-blocks target, or a live waits-for gate — whose
target is NOT one of P's own parent-child children, or P's own parent is
(recursively) exogenously blocked. P's OWN is_blocked is unchanged: it really
does depend on open children. Only the propagation narrows.
DESIGN: a second-pass predicate on the parent row, not WITH RECURSIVE.
Both parent-child legs of shouldBeBlockedIDsUnionScopedSQL keep their
p.is_blocked = 1 conjunct and gain parentCascadesBlockedSQL, which says "p's
blockedness is not solely explained by p's own children":
EXISTS (blocking reason of p whose target is not p's child)
OR NOT EXISTS (blocking reason of p whose target IS p's child)
The second disjunct carries the contract's recursive clause through the
EXISTING fixpoint instead of through SQL recursion: a parent that is blocked
with no child-targeted reason of its own is dark either exogenously or
because ITS parent is, and either way its children inherit — one level per
pass, exactly as the cascade always converged.
A recursive CTE was the other candidate and is rejected on cost, not on
engine support. Its seed set is the direct-exogenous set, which includes the
waits-for gate, and the seed cannot be confined by the batch scope (%[3]s)
because a batch's ancestors are by definition outside the batch. That would
put an UNSCOPED whole-table gate evaluation into every batched mark/unmark —
the statement shape #6288 removed, now on every write instead of only on the
full repair. The predicate here is correlated to a parent that is already
known blocked, so it probes idx_dependencies_issue for a handful of rows.
The scope splice, the DISTINCT waits-for barrier and the doctor-count
lockstep are all untouched.
One gap this form does not express: a parent that is BOTH blocked by its own
open child AND darkened by an exogenously blocked ancestor is not
distinguishable from one blocked only by its children, so its children stay
bright. That is an under-propagation in a corner the contract would darken;
it needs a second stored bit (or the CTE above) to see, and it cannot
recreate the lock this commit removes.
Also: AffectedByDepChange{,ForWisp}InTx now seeds the parent's other children
on a parent-child edge change (appendSiblingsUnderParentInTx). Writing that
edge reclassifies the parent's blocking reason on the new child from
exogenous to child-derived, which flips the answer for the SIBLINGS — the
close-gate epic is built one child at a time, and the second edge is what
un-darkens the first. Without it the incremental write path and the full
repair disagree, which the new tests catch as a nonzero doctor count.
Tests (internal/storage/dolt/blocked_consistency_test.go), all four seeded
through the real write path and each verified RED against the pre-fix SQL
except the control:
- ParentBlockedOnlyByItsOwnChildren: the repro, plus a GetReadyWork
assertion that the children are workable again.
- ExogenousParentStillCascades: the control — the fix narrows the cascade,
it does not remove it. Green before and after.
- ThreeLevelChainBothWays: GP exogenous darkens P and C; GP blocked only by
its child P darkens neither. Repaired from an inverted plane too, since
the chain is the case that needs more than one pass.
- WaitsForGateOverOwnChildren: a gate whose spawner is the parent's own
child does not darken; one on an outside spawner does.
TestRecomputeAllIsBlocked_CascadesThroughParentChild is unchanged and green,
including its single-pass lower-bound count — which is why the legs keep the
p.is_blocked = 1 conjunct rather than deriving the cascade from the graph
alone.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* feat(dep): warn when a parent blocks on its own child (wy-3eb07b, #6506)
`bd dep add P C` where C is already P's parent-child child is the "close gate
on the epic" idiom: P carries a blocks edge onto its own child so P cannot
close before it. dep.go refuses the OTHER direction (a child blocking on its
dotted-ID parent, "would create a deadlock") and says nothing about this one,
which is the direction that used to deadlock for real — the cascade darkened
the child, so it could never reach bd ready, be worked, or close.
Since the cascade fix the edge is harmless, so this is an advisory, not a
refusal: it names what the edge now means (the parent stays blocked; the
child and its siblings are NOT hidden from bd ready) so an operator does not
have to rediscover the contract from a query.
It fires only for blocks/conditional-blocks, only after the edge has actually
landed and committed, and stays silent on any read error — an advisory must
not turn a successful write into an error, and must not precede a refusal for
an edge that was never written (the hierarchy and cycle guards reject this
pair whenever both edges already exist, in either order, which is why the
shape usually arrives one edge at a time or through import).
Unlike the D1 implicit-blocks warning it is NOT gated on an interactive
stderr: that one fires on the documented-default majority path, where
training callers to ignore stderr is the risk; this one fires on a rare
deliberate shape, and an agent wiring a close gate is exactly the caller who
should read what it does.
Wired into both direct paths (`bd dep add` and `bd dep --blocks`); the
proxied-server paths return earlier and are untouched.
Tests beside the existing dep-add warning tests: the predicate table
(including the two controls — right id with a blocks edge is not a child, and
the parent's other children do not match), the message content, and the type
gate proving it returns before touching the store.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* feat(doctor): report parent-blocks-on-own-child edges (wy-3eb07b, #6506)
A new "Parent Close Gates" check lists every blocking edge from a parent onto
one of its own parent-child children — the close-gate idiom, where P blocks
on C1 and C2 so P cannot close before them.
INFORMATIONAL, with no --fix and no effect on the overall result. Before the
cascade fix these edges were a trap: the parent's blocked bit propagated to
its children whatever set it, so the gate hid the very children it was
waiting for and nothing under it could become ready. The cascade now
propagates only exogenous blockedness, so the edges are legal and usually
deliberate. What an operator wants from doctor is therefore the inventory —
which beads in this store use the idiom, and where a pre-6506 store's
mysteriously invisible children came from — not a repair, and certainly not a
warning that would train people to remove a working gate.
It is the mirror of the existing "Child-Parent Dependencies" check, which
finds a CHILD blocking on its PARENT (still a deadlock, still fixable). The
two differ in how they match: that one reads dotted-ID ancestry, this one
matches real parent-child edges, because the close gate is wired between
unrelated ids.
Tests beside the child-parent ones: the empty inventory (with an ordinary
hierarchy present, which must not be mistaken for a gate), and the reported
case with two controls in the same fixture — an exogenous blocker on the
parent and an ordinary blocker on the child, neither of which may appear.
Gate note: these live in package cmd/bd/doctor, which the brief's cmd/bd
selector does not reach; `go test ./cmd/bd/doctor/` was run in full.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* revert(dep): drop the unreachable parent-blocks-own-child warning (wy-3eb07b, #6506)
This reverts 34b7f5b42. The warning it added could never print.
Its precondition is "a blocks edge from P onto C succeeded AND C is already
P's parent-child child", and the store refuses exactly that edge.
CheckBlockingHierarchyInTx (internal/storage/issueops/dependencies.go) rejects
a blocker that is the source's own descendant, and it sits OUTSIDE the
SkipCycleCheck gate, so no caller opts out of it; batch_apply.go:533 applies it
again on the DependencyEditor path `bd dep add` actually uses. Written in the
other order, the parent-child edge that closes the pair is refused as a cycle.
So the reverted code paid a GetDependentsWithMetadata read on EVERY
blocks/conditional-blocks `bd dep add` to emit something no operator could
ever see, and its 102-line test pinned a predicate instead of a behaviour.
What an operator DOES hit is the refusal — and the cascade fix left its stated
reason false. It read "blocked status cascades to descendants, so <blocker>
would inherit the block and never close". Since #6506 a parent-child edge
propagates only the parent's exogenous blockedness, so the descendant does not
inherit and nothing deadlocks. The refusal still stands, because a blocks edge
is not how the hierarchy says "I close after my children" — so the reason now
names the form that is: a waits-for gate over the children, `bd gate`.
The same false sentence was the OpenAPI description of
Problem.blocker_is_ancestor, so it is corrected there too, with types.gen.go
regenerated by `go generate ./internal/httpapi/apigen/` to keep `make
api-check` green.
The doctor "Parent Close Gates" check from 4c5f2f77b is KEPT. A warning on a
write path that refuses the write is noise; an inventory of the edges a store
already carries — from import, from merge, from the pre-refusal past — is what
an operator can act on.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* fix(storage): the parent-child exogeneity test is over the whole SUBTREE (wy-3eb07b, #6506)
B1 of the adversarial review: 648ab0af6 tested "is this blocking reason's
target one of my own children" as a DIRECT parent-child child, but #6506's
contract is about blockedness originating outside the parent's own SUBTREE.
At depth 1 the fix worked; at depth 2 it left the permanent lock alive.
P --blocks--> G, pc C -> P, pc C2 -> P, pc G -> C
G is not P's child, so P read exogenous, so P darkened C, so C darkened G —
and G is the only row whose close can free P. Exactly the shape-1 mutual lock
the issue says no contract intends, one level down. Pinned as
TestParentChildCascade_ParentBlocksItsOwnGrandchild, verified RED at
4c5f2f77b: p/c/c2/g all blocked, all three children missing from ready work,
and the full repair changing nothing.
The test is now a real ancestor walk (subtreeWalkDepth levels of indexed
LEFT JOINs up from the reason's target), so a reason anywhere under the
blocker counts as its own.
Also B2 — the cost regression, which is the same edit, because the shape that
makes the test correct and the shape that makes it affordable are one
decision. The union's parent-child legs no longer carry a per-row correlated
EXISTS. They subtract an uncorrelated set instead:
AND p.id NOT IN (parents explained by their own subtree)
and the UNBATCHED statements (full repair, doctor count) do not even spell
that set as a subquery: it is read ONCE per fixpoint pass and bound as ids.
A repair pass is four statements and each would otherwise derive the same set
twice; reading it once is the whole difference. The batched mark/unmark keep
the spliced subquery, where it is confined to the batch's own parents by the
existing scope splice and costs a few rows.
MEASURED, gastownhall/beads#6506 bar: full repair and doctor count <= 1.5x
origin/main, write path <= 1.2x. Committed benchmark
(internal/storage/dolt/blocked_scale_bench_test.go, -short-skipped), 1000
issues / 2870 deps / 333 blocked rows, embedded dolt 2.2.0, run INTERLEAVED
main/head to cancel machine drift, four pairs, medians:
origin/main 71c4cd08b this branch ratio
full repair 48 71 43 46 -> 47 ms 66 56 54 55 -> 55 ms 1.18x
doctor count 55 62 44 53 -> 54 ms 67 61 57 57 -> 57 ms 1.06x
write path, per CloseIssue 37 30 21 22 -> 26 ms 30 23 16 24 -> 23 ms 0.91x
All three inside the bar; the worst single PAIR is 1.38x on the repair and
1.30x on the count. The two sides disagree on blocked rows by construction
(604 on main, 333 here) — that IS the fix.
NOT inside a bar, and disclosed rather than hidden: the benchmark's fourth
timing, a 200-id RecomputeIsBlockedForIDsInTx (the bulk/import batched path,
which no metric in the review covered), is 53-63 ms on main against 400-556 ms
here — 6.9x at the medians. The cause is structural and measured: a batched
pass runs many small statements, each deriving the set twice, and the set
costs a few ms however it is written. The per-pass read that fixes the
unbatched statements makes the SMALL-batch case worse, not better (one
whole-store read costs more than the subqueries a two-id batch pays), so the
fix is a per-batch-scoped read threaded through expandBatchTemplate's
placeholder plumbing — a separate change, and the reason this timing is
committed rather than left in a scratch file.
Three shapes were built and measured before this one, all at the same scale:
- the review's own: per-row correlated EXISTS with two more inside,
3.3-3.7x full repair, 5.2x doctor count;
- the set as a DISTINCT derived table LEFT JOINed on p.id, which is what B2
recommended: ~30x. dolt plans a join operand as the inner side of a nested
loop and rebuilds it per outer row — the correlated shape in a derived
table's clothes. This is the one finding that contradicts the review, and
it is why the set is subtracted with NOT IN instead;
- WITH RECURSIVE for the ancestor walk: blew the driver read timeout on the
full repair. A recursive CTE pays a query's overhead per ITERATION; the
seeded walk cost 45 ms per evaluation against 6 ms for four levels of
joins, which is why the walk has a horizon (subtreeWalkDepth = 4, epic ->
sub-epic -> leg -> task). Past it a reason reads as exogenous, which
propagates MORE and hides nothing the old code showed.
Seeding: AffectedByDepChange{,ForWisp}InTx now walks UP from a parent-child
edge's target, not just to it. Hanging G under C changes nothing about C and
everything about any ANCESTOR of C that blocks on G, so each such ancestor's
sibling set is reseeded — otherwise the incremental write path and the full
repair disagree, which the new test catches as a nonzero doctor count. The
walk is filtered to ancestors that carry a blocking reason at all: without
that filter a 70-deep chain reseeds every ancestor's subtree on every edge
written into it, which timed out TestGetReadyWork_ParentFilterReturnsDeepDescendants.
CHANGELOG now names the limitation the review ruled acceptable but undocumented
(a sub-epic blocked both by its own children and by an exogenously blocked
ancestor keeps its children visible), marked tracked upstream; bee files the
follow-up issue at PR time.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* fix(doctor): rune-safe Detail truncation, Category on the N/A returns (wy-3eb07b, #6506)
The "Parent Close Gates" check joins its inventory with U+2192, three bytes
wide, and then cut the joined string at byte 200. Two of every three offsets
land mid-rune, so `bd doctor --json` could carry invalid UTF-8 in Detail — a
display nuisance in the terminal, but a value a JSON consumer has to decode.
truncateDetail walks back to a rune boundary first; the test drives every
entry count from 1 to 120 so the cut lands at all three offsets within the
arrow and asserts utf8.ValidString on each.
The same byte cut appears twice more in this file (:101, :561) on ASCII-only
details. Left alone here: they are not this bead's, and changing them would
put a behaviour change in two checks a reviewer of #6506 has no reason to be
reading.
The check's two "N/A" early returns also omitted Category, unlike its three
real returns, which drops them out of the categorised report. Both now carry
CategoryMetadata.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* perf(storage): read the batched exogeneity set once per batch, not per statement (wy-3eb07b, #6506)
D1, the PR blocker from the round-1 review. The batched mark/unmark templates
spliced parentsExplainedBySubtreeSQL — the "which blocked parents are explained
only by their own subtree" query — into both of their parent-child legs,
batch-scoped. The scope made it look cheap. It was not: dolt pays for a
`p.id NOT IN (subquery)` once per leg per STATEMENT, and a batched pass is a
mark and an unmark, so one 200-id RecomputeIsBlockedForIDsInTx derived the set
four times and measured 6.9x origin/main (53-63 ms -> 400-556 ms). That is the
bulk/import path and the cost shape #6288 removed.
The set is now READ once per batch and BOUND into both statements as ids —
the same trade the unbatched full repair already makes per pass — which is why
markBlockedTemplate/unmarkBlockedTemplate are built per batch now: the number
of bound ids is a property of the batch. In front of the read sits a cheap
indexed guard, batchParentKindsInTx: a parent KIND with no parent-child row in
the batch has an empty candidate set, hence an empty exogeneity set, so its
read is pure overhead, and the read is a ten-join walk under two CTEs that
dolt spends ~8 ms planning whether it returns rows or not. Most batches name
no wisp parent at all; a batch of roots names neither. Without the guard the
2-id case measured 1.9x, with it 0.94x.
expandBatchTemplate now WALKS the template instead of counting "%s": the batch
scope and the bound exogeneity ids alternate inside the union (leg 3's scope,
leg 3's NOT IN, leg 4's scope, leg 4's NOT IN), so only text order says where
each group goes. It returns an error on a ?/bound mismatch rather than handing
the engine an opaque argument-count failure. The %s budget is back to 6 from
8, re-pinned, with two new pins beside it: the ? group is exactly the bound
exogeneity ids (none for an empty set), and the mismatch is refused.
KEPT, on round-1's measurements: the NOT IN subtraction (the derived-table
JOIN measured ~30x in dolt) and the 4-level LEFT JOIN ancestor walk (WITH
RECURSIVE blew the driver read timeout).
MEASURED. n=1000 issues / 2870 deps / 333-604 blocked, embedded dolt 2.2.0,
TestBlockedStateScaleTiming, SIX interleaved origin/main(71c4cd08b)/head pairs,
medians, worst single pair in brackets. The bench now times three batch sizes
instead of one, because the per-statement and per-id costs pull opposite ways:
metric main head ratio bar
full repair 49 ms 57 ms 1.16x [1.32x] <= 1.5x MET
doctor count (consistent) 48 ms 57 ms 1.18x [1.32x] <= 1.5x MET
write path, per CloseIssue 25 ms 26 ms 1.03x [2.59x] <= 1.2x MET
batched recompute, 200 id 54 ms 69 ms 1.28x [1.57x] <= 1.5x MET
batched recompute, 20 id 17 ms 22 ms 1.29x [1.50x] (measured)
batched recompute, 2 id 22 ms 21 ms 0.94x [1.03x] (measured)
All four stated bars are met on medians. The worst-pair column is at or inside
this box's own noise: over the same six runs origin/main's OWN spread is 2.07x
on the full repair, 2.33x on the write path, 1.92x on the 2-id batch and 1.19x
on the 200-id batch, so a single pair's ratio is not evidence at this
resolution and the medians are what the bars are read off.
DISCLOSED, not a stated bar and not fixed here: the bench FIXTURE BUILD —
2870 AddDependency calls plus 240 CloseIssue through the store — is 75 s ->
102 s, 1.36x [1.61x]. That is the dependency-ADD write path, and the cost is
round 1's incremental seeding (AffectedByDepChangeInTx now walks up to every
reason-carrying ancestor and reseeds its whole sibling set), which is what
buys the incremental/full-repair agreement pinned by the lockstep test in the
next commit. Per-edge it is sub-millisecond; it shows up here because the
fixture writes the hierarchy of a 1000-issue store edge by edge.
GATE: go build ./... ; go vet ./internal/storage/issueops/ ; go test
./internal/storage/issueops/ (ok, includes the rewritten template and sqlmock
pins) ; BEADS_TEST_EMBEDDED_DOLT=1 go test ./internal/storage/dolt/ -run
'ParentChildCascade|RecomputeAllIsBlocked' (ok) ; gofmt -l clean. The full
enumerated gate is on the bead.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* test(storage): pin both sides of the subtree-walk horizon, and the incremental/full-repair lockstep (wy-3eb07b, #6506)
D2 and D3 from the round-1 supervisor ruling.
D2 — THE HORIZON IS NOW PINNED, not commented. "Inside my own subtree" is
decided by a fixed 4-level ancestor walk (subtreeWalkDepth), because a
recursive walk cost 7.5x per evaluation and blew the driver read timeout. Two
tests that differ by ONE EDGE straddle it:
_ReasonAtTheWalkHorizon P blocks a descendant exactly 4 pc levels down.
The walk reaches P, so the reason is
subtree-derived and the chain comes bright.
RED on origin/main (4 rows dark that the fix
brightens) — so it is not vacuous.
_ReasonPastTheWalkHorizon one level further. The reason reads as EXOGENOUS,
so the whole chain stays dark, which is
origin/main's own answer — and that test PASSES
UNCHANGED ON origin/main (verified in a temp
worktree at 71c4cd08b, since removed). It also
asserts no row of the shape appears in
GetReadyWork: no new dark rows AND no new visible
rows past the horizon, checkable rather than
argued. Raising the constant makes it fail and
name the row that changed.
Both also repair from a fully inverted plane, which is the leg that needs the
fixpoint rather than the write path's seeding. The CHANGELOG now names the
4-level horizon beside the existing limitation sentence, and the constant's own
doc names the two pins.
CAN THE HORIZON BE RAISED? Measured, and the answer is "not on this evidence".
Same bench, same box, full repair / doctor count / 20-id batch / 200-id batch:
depth 4 57 ms / 58 ms / 21 ms / 69 ms (shipping)
depth 6 126 ms / 118 ms / 52 ms / 101 ms 2.2x, TWICE reproduced
depth 8 59 ms / 74 ms / 24 ms / 68 ms ~= depth 4, TWICE reproduced
The curve is NON-MONOTONIC: 6 falls off a cliff and 8 comes back. That is a
dolt planner artifact, not a cost model, and raising a semantics-bearing
constant on the strength of a number nobody can explain is the wrong trade —
depth 8 also makes every past-horizon shape newly bright, which is a behavior
change and not this round's business. Left at 4, with the numbers recorded for
whoever picks the knob up.
D3 — THE LOCKSTEP. _IncrementalMatchesFullRepairAcrossEdits walks one graph
through the mutations that reclassify a blocking reason WITHOUT touching the
row that carries it, and after every one asserts both the exact flags and
assertConvergedAndStable: detection counts 0 AND a full repair changes 0 rows.
An under-seeded incremental path (the AffectedByDepChange{,ForWisp}InTx
ancestor walk round 1 added) fails here as a nonzero repair over a graph the
write path just finished maintaining. The mutations: re-parent the reason's
target INTO the blocker's subtree (which is how the shape arrives — the store
refuses a blocks edge straight onto an existing own descendant, and that
refusal's reason text is what 3a5203979 corrected), close the descendant,
reopen it, re-parent it back OUT, remove the blocks edge. The
into/out-of-subtree steps are the ones that flip rows the edge does not name
(the parent's other children), which is exactly what
appendSiblingsUnderAncestorsInTx exists to seed. RED on origin/main for the
semantic values; origin/main's own incremental/full-repair agreement holds
there, so what this pins is the agreement, not the numbers.
GATE: BEADS_TEST_EMBEDDED_DOLT=1 go test ./internal/storage/dolt/ -run
'ParentChildCascade' -count=1 — 8/8 ok; gofmt -l clean; go vet clean.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* fix(doctor): the close-gate inventory walks the same four parent-child levels as the cascade (wy-3eb07b, #6506)
The "Parent Close Gates" check listed only DIRECT parent->child gates, so the
fix's own headline shape (a parent that blocks on its grandchild) never
appeared in the inventory. The check now joins a descendant-pairs set built
to the same four parent-child levels the cascade uses for "inside my own
subtree" (issueops subtreeWalkDepth), as plain joins over the dependency
union rather than a correlated subquery, which dolt declined to plan once
rows were present. Messages say "own-descendant"; the tests add a grandchild
gate (2 listed, the exogenous edge still not) and assert Category.
CHANGELOG cites the nested-gap follow-up, gastownhall/beads#6601.
Tests run: go build ./... 0; go vet ./cmd/bd/doctor/ 0; gofmt -l clean;
env -u BEADS_ACTOR go test ./cmd/bd/doctor/ -run 'ParentBlocksOwnChild|TruncateDetail' -count=1 PASS (3/3).
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
* ci: allowlist TestBlockedStateScaleTiming's -short skip (wy-3eb07b, #6506)
scripts/check-testing-short.sh reserves testing.Short() for runtime, stress
and large-fixture skips and keys them by file::func. The scale-timing test
added in this PR builds a 1000-issue / ~2000-edge dolt fixture and times the
blocked-state paths over it: a large-fixture skip, and PR Core runs with
-short, so it needs the entry. One line, the same shape as the
TestUOW_ConcurrentMergeOps_NoLostUpdate row from #4732.
Local: ./scripts/ci/pr-policy.sh rc 0 (check testing.Short boundaries
succeeded; the other nine legs unchanged).
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
* wy-3eb07b: build(bazel): register blocked_scale_bench_test.go in internal/storage/dolt
The rebase carried the bench test but not its BUILD.bazel entry, so the
Bazel test lane's gazelle sync and Go test equivalence steps failed while
every Go lane was green. This is CI's own bazel-sync patch for 043f9c47b9,
applied unchanged.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
* fix(blocked): resolve explained parents through their ancestry; walk ancestors on hinted per-table members
Maintainer fixup for #6602 (adopt-pr review iteration 1, quality scorecard
760/1000, request_changes; amended at iteration 2, 906/1000, approve). It
fixes the review's two major findings, the doctor check's message and its
swallowed query failure, the stale core-builder doc, and the stale
test-comment names. At iteration 2 it also takes both nits and corrects a
CHANGELOG sentence this fixup had made false.
- Mixed-arm leak (major). The explained-parent read decides from a
parent's own reason rows, and the fixpoint carries the recursive clause
only for a parent with no reason row of its own. With Q blocked on an
outside X, P a child of Q, and P blocking on its own child C, P read as
explained and C came bright under an epic still gated by X, on the
write path and in full repair alike. pruneExplainedByAncestryInTx now
shrinks every read to the greatest set whose members' blocked parents
are all members. A full-repair read is complete, so a blocked parent it
did not return is unexplained. A batch-scoped read climbs instead,
reading the blocked parents above the batch by id (explainedAmongInTx).
The suggested one-level NOT EXISTS is not enough: put a second close
gate between them (R blocked on X, pc Q -> R, Q blocks on P, pc P -> Q,
P blocks on C) and P's blocked parent Q is in the set, so R's gate
never reaches C.
- ancestorChainInTx (major) walked the derived UNION of both dependency
tables that #7224 removed from isAncestorInTx, on every parent-child
write and merge replay. It now walks reachabilityMembers, the hinted
per-table recursive members split out of reachabilityQuery, with the
reason filter kept in the outer SELECT. TestGraphWalkPlansHonorJoinHints
(embedded) gains an ancestor-chain subtest that pins the lookup plan;
the old walk fails it.
- New dolt tests: TestParentChildCascade_OwnGateUnderExogenousParent
(write path, full repair, and X closed and reopened),
_NestedGatesBothWays (the two-gate chain both ways, then a close of the
children's own blocker, which re-evaluates them through a batch whose
read covers nothing above their parents), and
_WispGateUnderExogenousParent (a wisp gate under an issue epic, an
issue gate under a wisp epic, then an explained wisp gate the walk must
read by id above such a batch). Five mutants of the prune were each
killed: no prune (the PR head), a one-level check, an over-prune, a
scoped read treated as complete, and a scoped read that trusts every
parent above it. The eight existing cascade tests pass under all five.
Iteration 2 killed two more, each by its own section of the wisp test
alone: dropping the lookup of a wisp parent from blockedParentEdgesInTx,
and dropping explainedAmongInTx's wisp leg, which had survived all
eleven cascade tests.
- The doctor check no longer says the children "stay in bd ready", and
a failed or timed-out inventory query is now a warning carrying the
error, as in validation.go's other checks, instead of an OK that reads
as "no gates". TestCheckParentBlocksOwnChildDB_QueryFailureWarns pins
it with a closed handle, and it fails with the old status. A warning
does not touch doctor's overall result, and it can be suppressed.
- The core builder's doc no longer describes the spliced design, and
three test comments name builders that exist.
- explainedAmongInTx says why it does not tolerate a missing table, as
the file's wisp reads do: the prune runs only on a non-empty read,
which came from the same core query over all four tables.
- The CHANGELOG entry no longer calls #6601's shape (a sub-epic gated on
its own children under an exogenously blocked epic) a known limitation
that keeps the children visible. The prune darkens them, as
TestParentChildCascade_OwnGateUnderExogenousParent pins.
Left as-is, all non-gating: the refusal hint's "(bd gate)", an API string
pinned by the golden corpus; a parent-child add/remove timing in the
scale bench, whose 1000 issues cannot show the 50k shape (the plan pin
guards it); and hints for the explained-parent subtree walk and the
doctor query. The measured complexity major is runDiagnostics (50/66),
the same at base; the PR adds two lines to it.
Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* test(storage): re-pin the classic batch-apply statement count for the parent-child cascade
The B0 statement-count pins predate this PR's parent-child cascade. The
first full run of the storage tiers on the adopted head measured the
40 (classic) shape at 835 statements on both backends, against the
pinned 786 +/- 2.
All 49 extra statements are reads, seven for each of the shape's seven
distinct parent-child dep adds (its eighth repeats a pair and is a
no-op):
- appendSiblingsUnderAncestorsInTx reseeds the parent's other children:
one ancestorChainInTx walk and four child probes, +5.
- The batched mark/unmark reads its exogeneity set first
(batchExogeneity): the parent-kind probe and the issue-parent read, +2.
Measured by logging every statement of the classic apply on the CI base
233d151b37 (786) and on b2b93515bf (835), then diffing the two logs by
statement shape. Those seven shapes are the whole difference, each
exactly +7, and no write changed. The 356 and 712 shapes are unchanged
on both backends.
This is the deliberate re-measure and re-pin the pins' doc comment asks
for. The per-change breakdown is in pinnedEmbeddedStatementCounts.
Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-authored-by: Eddie the Engineer <adopt-pr@gascity.com>
fast-checks, PR Policy, and the Linux leg of check-doc-freshness-platforms
ran repository guards on GitHub runners. They now run as Bazel tests in
bazel.yml's `test` lane (remote, cached), each over only the files it reads:
- tools/bazel/repo_subset.bzl picks a narrow, path-selected slice of
//:repo_files at analysis time. scripts/repochecks/run_check.sh copies that
slice into a throwaway git checkout and runs the unchanged guard there.
- //scripts/repochecks: build_tags, workflow_tags, go_install_guidance,
winget_portable_alias, migration_hygiene (checks A and B),
fmt (registered SDK gofmt), doc_freshness, workapi_frontend_boundary,
types_gen_drift (`make api-check` drift, oapi-codegen from go.mod).
- //scripts:doc_freshness_required_test (integration lane, -required-suite)
and //scripts/gitattributespolicy:gitattributespolicy_required_host_test
cover the Linux doc-freshness leg.
- check-versions stays covered by //internal/versioncheck:versioncheck_test.
check-testing-short stays covered by //scripts:scripts_test.
pr-policy-wrapper is deleted. fast-checks keeps only the two checks that
need the PR base: migration hygiene's delta half (MIGRATION_HYGIENE_SCOPE=
delta) and the .beads diff. check-doc-flags stays, because it builds bd from
the pinned release tag. The example Go modules leave .bazelignore so gofmt
and the grep guards see them. check_testcases.py now accepts --not-go
//pkg:all.
Refs: ga-96smfk.20
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
//scripts:scripts_test and //scripts/check-versions:check-versions_test
drop their host-tools/no-remote-exec/no-remote-cache tags and run on the
rbe-west workers like every other target (the worker image ships bash, git,
python3, jq, yq, curl, openssl, unzip and coreutils; a missing tool fails the
test under Bazel rather than skipping it). Go comes in hermetically as the
registered SDK; check-versions.sh's `go build` is stood in for by the
Bazel-built checker.
The tests that walked the source checkout now get it as data:
tools/bazel/go_srcs.py keeps a managed `repo_files` filegroup in every
package and aggregates them into //:repo_files (exactly the tracked files
Bazel can see; make bazel-sync-check fails on a package without one).
scripts_test and docsync_test take it instead of hand-listed filegroups,
and every TEST_SRCDIR/IsBazel skip and go-test-only block in them is gone.
The release formula under .bazelignore'd .beads/ comes in through a
@beads_formulas local repository; npm-package/ and .claude/ are visible to
Bazel again (only their node_modules/worktrees stay ignored), so the npm
manifest release check and the AGENTS.md skill links run under Bazel too.
TestZZStdioNotLeaked falls back to TestMain's pre-run streams instead of
skipping in a shard without its baseline.
tools/bazel/equivalence_allowlist.txt shrinks from 20 skip entries to the
two cmd/bd tests of plain go test's own bd build fallback, which Bazel never
takes; pr-preflight-platforms now runs them on Linux, macOS and Windows. The
scripts-go-checks scripts-test and allowlisted legs, their scripts
(scripts-go-test.sh, allowlisted-go-tests.sh, run_allowlisted_go_tests.py)
and main.yml's --compile-only warm for them are removed. The vet leg stays
(ga-96smfk.18).
Refs: ga-96smfk.16
Co-authored-by: Claude Opus 5.5 (1M context) <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>
* feat(httpapi): wire-shape signal — wire_revision, floor header, golden digest, param tokens
S0 of the HTTP role-parity program: give a client a single place to learn
whether this build's wire shape has moved under it, and give CI a gate that
catches an undocumented move.
- GET /v0/beads/context reports wire_revision (bumps only on a non-additive
response-shape change) and min_client_wire_revision. An optional
Bd-Wire-Revision request header lets a client declare the revision it was
built for; checkWireRevision refuses a declared revision below the floor
with 400 invalid_argument/reason=wire_revision_unsupported and a
min_wire_revision field, on every route but /healthz (wireRevisionExempt) —
including the identity handshake, where catching the mismatch is cheapest.
Absent header is today's behavior; malformed value is invalid_value, never
wire_revision_unsupported. The floor lives in Server.minClientWireRevision
(defaulting to the MinClientWireRevision constant) so a test can raise it.
- internal/httpapi/wireshape: a golden digest over every response's every
content-type schema (including application/problem+json) across the whole
spec, keyed by schema+member. TestWireShapeDigest fails closed when a
member's JSON name or type changes without wire_revision bumping to match;
regenerate with `go run ./internal/httpapi/wireshape/cmd/gendigest`.
- GET /v0/beads/issues' `sort` parameter now carries the issues.listSort
capability token, the same convention `capabilities` entries use.
TestNewParameterOnExistingOperationHasABehaviorToken requires every new
parameter on an existing operation to carry one, checked against a
write-once grandfather baseline (testdata/pretoken_parameters.json) of
parameters that predate the rule; TestUntokenedParameterRuleFires proves
the checker itself against a synthetic fixture.
- Docs: engdocs/design/bd-serve-v0.md gets a "The wire-shape signal" section;
CHANGELOG.md gets an Added entry.
Live-mutated and reverted three RED demonstrations during development:
retyping api_version in the spec failed TestWireShapeDigest; short-circuiting
checkWireRevision's floor comparison failed
TestWireRevisionBelowFloorRefusesEveryEnforcedRoute; adding an untokened
query parameter to listIssues failed
TestNewParameterOnExistingOperationHasABehaviorToken. All three now pass
against the unmutated tree.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* fix(httpapi): rename issues.listSort to issues.list.sort, harden token rule
Opus review of 12c5144ca (HIGH-1, MEDIUM-5):
- Rename the capability token issues.listSort -> issues.list.sort to match
bd-enterprise's client (httpstore/wire/handshake.go:121, DESIGN.txt S4e),
and widen capabilityToken to accept an optional third segment.
- untokenedParameters() now requires the extracted token to be one
Capabilities() actually serves, not just backtick-shaped text. This
catches real false positives that existed in the spec already
(workapi.DefaultReadyLimit, status.custom) which only shape-matched the
old regex; they're added to the pretoken baseline as genuinely
pre-existing untokened parameters.
- Extend the rule to request body members (new
testdata/pretoken_request_body_members.json baseline) and exempt
brand-new operations via a frozen testdata/pretoken_operations.json
snapshot.
- Add TestPretokenBaselinesNeverGrow pinning all three baseline sizes so
a future change can't hand-add an exemption instead of a token.
- Update spec prose for the widened rule scope.
go test ./internal/httpapi/... and the reviewer's pmut.py all pass as
expected: plain/bogus modes go RED, reuse (real-but-unrelated token) stays
green, matching the review's literal ask ("a token must be one advertised
by Capabilities()").
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* fix(wireshape): close four digest-coverage gaps, add gendigest write guard
Opus review of 12c5144ca (HIGH-2, MEDIUM-4). The digest only tracked
Type/Format/Enum/Required on direct properties, missing:
- nullable: true (never read at all)
- array item shape (Issue.labels items string->integer was invisible;
only object-shaped items got recursed into)
- additionalProperties value shape (IssueCount.groups)
- request bodies entirely (Compute() only walked responses, so
DeleteIssuesRequest.expected_version string->integer, the other half
of #6053, was invisible)
Also added defensive oneOf flattening alongside the existing allOf merge
(dormant today -- grep confirms this spec uses oneOf nowhere -- but no
longer silently invisible if that changes).
Extracted the golden-vs-computed comparison into wireshape.Compare(),
shared by TestWireShapeDigest and the new wireshape.SafeToWrite(), which
gendigest now calls before writing: it refuses to overwrite golden.json
with changed/removed entries unless the candidate's wire_revision is
strictly greater than the existing golden's. Pure additions always write.
TestSafeToWrite exercises both guard directions.
golden.json is regenerated. This single regen is a one-time exception to
the new guard, done by writing the digest directly rather than through
gendigest: confirmed via a throwaway diff (not checked in) that every one
of the 57 "changed" entries differs only in the NEW fields the wider walk
now populates (ItemType/ItemFormat/Nullable/AdditionalProps*) -- every
pre-existing Type/Format/Required/Enum value is byte-identical. Nothing on
the wire changed; the measurement got more precise. Bumping
CurrentWireRevision for this would have written a false "the protocol
changed here" entry into the revision history table. Going forward, any
REAL change the guard now reports uses the normal bump-then-regenerate
path, same as before.
Verified against the reviewer's mut.py: nested_type, nullable,
nullable_issue, array_items, addlprops, request_body and format all go RED
on TestWireShapeDigest, each reverted after confirming.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* fix(httpapi): make bd_version wire_revision inference advisory
Opus review of 12c5144ca (HIGH-3). The spec told a client inferring
wire_revision from bd_version to use the release cutoff >= 1.3.0, and said
nothing about what happens when that inference is wrong -- which it
demonstrably is for real builds already in the field:
- main builds up to commit b3ef65c85 report bd_version 1.2.2 (below any
1.3.0 cutoff) while already sending the string-typed revision/
expected_version shape (#6053).
- 1.3.0-rc.N pre-release builds sort BELOW the release cutoff 1.3.0 under
plain string comparison despite already carrying the string shape.
- The bd-enterprise compatibility line at d3ab32773462 reports bd_version
1.1.0 while also sending strings.
Moved the cutoff to >= 1.3.0-rc.1 (compared as semver-with-prerelease,
which at least captures the rc builds), documented both named exceptions
inline, and made the whole inference explicitly ADVISORY: a client must
accept revision/expected_version as either a string or a number whenever
wire_revision is absent (or probe directly) rather than let the inferred
value choose a decoder, and must never refuse solely because the inferred
revision is 0. Mirrored into engdocs/design/bd-serve-v0.md.
This is spec/doc prose only -- there is no server-side inference code to
change, since this server always sends wire_revision directly; the
inference is guidance for clients reading a pre-signal server's response
(this server, past builds, or an unrelated implementation).
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* fix(httpapi): LOW-7/8/9/10 review follow-ups for wire-revision signal
LOW-7: WireRevisionUnsupported now also sets Problem.wire_revision (this
server's CurrentWireRevision) and Problem.bd_version on the
wire_revision_unsupported refusal, alongside the existing
min_wire_revision, so a client logging the refusal has this server's
full self-description without a second /v0/beads/context call.
LOW-8: gazelle + make bazel-sync add the BUILD.bazel entries the prior
commits were missing: wire_revision.go/wire_revision_test.go in
internal/httpapi's srcs, new BUILD.bazel files for wireshape and
wireshape/cmd/gendigest, and a testdata glob on httpapi's go_test so
the pretoken_*.json baselines are visible under `bazel test`. Verified
with `bazel build //internal/httpapi/...` and
`bazel test //internal/httpapi/... --test_env=BEADS_TEST_SKIP=dolt`
(both green) and `python3 tools/bazel/go_srcs.py --check` (clean).
LOW-9: narrowed CHANGELOG.md and engdocs/design/bd-serve-v0.md to
describe the digest's actual final coverage (format/enum/required/
nullable, array items, additionalProperties, request bodies, $ref/
allOf/oneOf recursion, the SafeToWrite revision-bump guard) and the
token rule's actual final shape (three pinned baselines, request-body
members, Capabilities()-membership validation, new-operation
exemption) instead of the original, narrower claims.
LOW-10: Bd-Wire-Revision now parses via a strict decimal-only
parseStrictNonNegativeInt (no leading '+', no leading zero except a
bare "0") instead of strconv.Atoi alone, so two different header
bytes can no longer name the same revision. New malformed-header test
cases: "+1", "01", "007".
Regenerated apigen/types.gen.go (make api-gen) for the new Problem
fields and wireshape/testdata/golden.json (go run
.../wireshape/cmd/gendigest) for the two new additive Problem members;
the latter wrote cleanly through SafeToWrite itself, since both are
pure additions.
go test ./... and bazel test //internal/httpapi/... both green.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* fix(httpapi): re-review LOW follow-ups — retirement test, gendigest -init, docs
1. TestRetiredRevisionsStayBelowTheFloor pins the PRESENCE guarantee the
wire_revision property doc relies on: CurrentWireRevision >= 2 (so 0
and 1 stay permanently retired) and MinClientWireRevision <=
CurrentWireRevision (so this build's own floor never refuses every
request against itself).
2. gendigest now refuses to create a golden.json that does not exist yet
unless run with -init. Previously a missing file (moved testdata,
wrong path, accidental delete) was indistinguishable from a real first
run and silently wrote a fresh golden with no revision history checked
against anything. writeGolden() is extracted out of main() so this is
covered directly: TestWriteGoldenRequiresInitWhenMissing,
TestWriteGoldenInitCreatesWhenMissing,
TestWriteGoldenIgnoresInitWhenGoldenExists (the existing-golden path is
still governed only by SafeToWrite, -init or not).
3. Narrowed the two remaining stale claims that still described the
digest's original, narrower coverage: the wire_revision property's
prose in openapi.v0.yaml (regenerated into apigen/types.gen.go via
make api-gen) and wireshape/doc.go now both list nullable, array item
shape, additionalProperties value shape, request bodies, and
$ref/allOf/oneOf recursion, plus the new -init guard.
go test ./internal/httpapi/... and make api-check both green;
bazel test //internal/httpapi/... (httpapi, wireshape, and the new
gendigest test target) green; python3 tools/bazel/go_srcs.py --check
clean.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* feat(wireshape): cover operation parameters in the wire-shape digest
The digest previously walked only response and request-body schemas, so a
type, enum, required, or removal change on one of the spec's 138 operation
parameters (123 query, 14 path, 1 header) passed the gate silently — the
open item from PR review on #7182.
Each parameter is now recorded as its own Entry, keyed by
"param:"+operationId / location+":"+name (operation-scoped, not
schema-scoped, since two operations' same-named parameter are independent
wire contracts), capturing type, array item shape, enum, required, style,
explode and default. Adding a parameter stays additive; removing,
retyping, narrowing its enum, or changing required/style/explode/default
now trips SafeToWrite exactly like a response or request-body change.
Verified against the live spec: retyping listIssues' `limit` query
parameter from integer to string now fails TestWireShapeDigest (confirmed
red, then reverted — not part of this commit). golden.json regenerated via
gendigest; the new parameter entries are a pure addition, no wire_revision
bump needed. Added TestParameterMutationsAreCaught (remove/retype/narrow-
enum against real golden entries) and updated wireshape's doc.go, the
`wire_revision` spec prose, and the CHANGELOG to describe the new
coverage.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* fix(wireshape): review fixes — stale-golden and lowered-revision arms, effective param serialization, digest boundary
Maintainer fixup from the adopt-pr review loop (iterations 1 and 2), on
top of e17ba924f.
- goldenDrift (A, I): TestWireShapeDigest's comparison moves into a
goldenDrift helper. An addition alongside a moved wire_revision no
longer passes with a stale golden: it asks for a regenerate, as a
changed or removed entry after a bump already did. Every message now
names response/request-body members AND parameters, and TestGoldenDrift
pins each arm. This takes only the test half of the stranded fixup
(adopt-pr/bd-47kdge/stranded-fixup-528cd6095); its doc half, which says
parameters are outside the digest, is false since e17ba924f and is not
replayed (J).
- Lowered wire_revision (D): a CurrentWireRevision LOWER than the
golden's is a wrong constant, not a stale golden, so goldenDrift says to
restore it instead of regenerating, and SafeToWrite (so gendigest)
refuses any write at a lower revision, whatever the entries.
- Effective style/explode (B): walkParam records style and explode with
OpenAPI 3.0's defaults filled in (form for query/cookie, simple for
path/header; explode defaults to style == form). Adding `explode: false`
to a query array that relied on form's implicit explode is now a
changed entry, while spelling out a default changes nothing.
testdata/golden.json is regenerated with -init: 111 parameter entries
change only in style/explode (96 to form/true, 15 to simple), 828
entries before and after, wire_revision stays 2. The golden is new in
this PR and unreleased, so this needs no bump.
- TestWalkParam (H): a package-internal table test
(wireshape_internal_test.go) pins every field walkParam extracts,
through a computeFrom(document, revision) seam that Compute now wraps:
per-location defaults, $ref'd parameters and items, format, nullable and
default, content parameters, and the nil returns.
TestEffectiveSerializationIsCompared pins B end to end through Compare
and SafeToWrite. BUILD.bazel embeds the library in the go_test, which is
gazelle's own output.
- Required inputs and the digest boundary (C, E, F; docs only): all five
prose surfaces (openapi.v0.yaml's wire_revision description and the
regenerated apigen/types.gen.go, wireshape/doc.go, CHANGELOG.md,
engdocs/design/bd-serve-v0.md) now say that a new REQUIRED request
input is recorded as an ordinary addition and needs its own review,
that value constraints and member-level composition are outside the
digest, and that object and content parameters are recorded only as
their container. bd-serve-v0.md also gains the parameter coverage it
was missing.
- G: a brand-new operation is permanently exempt from the
capability-token rule; its own review decides its capability story.
- Iteration 2 (nit): walkParam's comment now says that the location
default it records as a `content` parameter's style and explode is a
placeholder, since OpenAPI 3.0 applies style and explode only to a
parameter described by `schema`. All 138 operation parameters in the
spec use `schema`, so the golden does not change.
Validated: go test ./internal/httpapi/... (gms_pure_go), make api-check,
go vet for linux/windows/darwin, gofmt, git diff --check, gazelle on the
package (no drift), make bazel-sync-check, and bazel test
//internal/httpapi/wireshape/... in the local processwrapper sandbox
(2 of 2 pass). Overlay mutation probes: dropping the added-after-bump
arm, the lowered-revision arm, SafeToWrite's lowered check, or the
effective-default fill each turns the new tests red.
Iteration 2 changes only that comment; go test
./internal/httpapi/wireshape/... (gms_pure_go), go vet, gofmt and git
diff --check pass again.
Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Gas City Adopt-PR
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* feat(httpclient): lift the HTTP client wire/encode layers from bd-enterprise (MIT contribution)
Contributed by gascity from bd-enterprise (github.com/gascity/bd-enterprise,
internal/enterprise/httpstore @ 49d1df2f6) to OSS beads under the MIT
license, with the owner's explicit approval. Every lifted file carries a
provenance header naming its source path.
Lifted into internal/httpclient:
- wire/ the HTTP transport, lazy handshake, project-identity stamping,
problem-code decoding, retry behaviour and the capability vocabulary
- encode/ request/response encoders for the role operations
- credential*.go, ca*.go, target*.go the bearer credential ladder,
host-scoped CA trust and the http_target.json sidecar
Not lifted (stays enterprise-only): the hosted gateway (httpgw/gwauth),
box-login, storage profiles and gasworks.
Deferred to later slices (kept aside, not in this tree): the store transport
seam (WireClient/WireDialer/process-wide dialer, which goes to S3 with
dial.go), the enterprise-only BatchCloseRequest.claim_next encoder
(ClaimNextBody; the OSS server has no claim_next on batch close), and the
tests that need the store/dial layer.
This commit is the mechanical lift: import paths rewritten, package renamed,
two compile gaps removed. The production code builds. Known follow-up in the
next commit: reconcile the client's vocabularies and encoder tables with the
OSS spec (e.g. the OSS problem code notes_overwrite_refused, policy/sort
differences), restore the test helpers the lifted tests need, and wire in the
S0 wire_revision handling and S1 OpenOptions credentials.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(httpclient): compile the lifted client and reconcile with the OSS wire
The lift in ab11cb1f8 carried relative test paths and vocabulary tables
from bd-enterprise's internal/enterprise/httpstore (4 directories below
repo root) into internal/httpclient (3 below), and several tables
described enterprise-only server behavior OSS does not serve. Reconcile:
- Add testTarget test helper (written fresh) so internal/httpclient
compiles and its tests pass.
- Fix four relative paths off by one "../" from the package relocation
(skew_test.go, ledger_render_test.go, bijection_test.go x2).
- skew_test.go: importsHTTPClient now matches internal/httpclient instead
of the retired internal/enterprise/httpstore path; the cmd/bd sweep no
longer hard-fails when it legitimately finds zero matching files (cmd/bd
does not import this client yet - that's S3's wiring).
- encode/table.go, encode/ledger_fields.go: removed a Reserved "reverse"
entry and a refused ExcludeIDs field claimed for listIssues/ReadyRequest;
OSS's listIssues never accepts "reverse" (confirmed against
internal/httpapi/reads.go and routes.go's CapIssuesListSort, which gates
`sort` only) and issueops.ReadyRequest carries no ExcludeIDs member in
OSS. Each removal is documented in place.
- encode/table.go, encode/encode.go, encode/roundtrip_test.go: countIssues
publishes has_metadata_key and include_ephemeral that CountRequest
carries and the table/encoder/round-trip corpus all silently dropped;
mapped and wired through.
- encode/ledger.go: ~70 ledger rows cited enterprise store-conformance and
cmd/bd subprocess-parity tests (dual-run reader, claim races, flag-mode
refusals) that don't exist in this package and belong to S3's store/dial
seam and cmd/bd wiring. Re-pinned to a documented TODO(S3) sentinel
(pinnedByS3Conformance) rather than deleted, per the ledger's own
well-formedness discipline.
- wire/handshake.go, wire/vocabulary_test.go: added CapBatchApplyLarge
(issues.batchApplyLarge) alongside the server's behaviorCapabilities.
- wire/problem.go: mapped the notes_overwrite_refused problem code to
issueops.ErrNotesOverwrite.
internal/httpclient/... is fully green.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* feat(httpclient): wire-revision handshake gate and batch cap from capability
S0 integration (task #2): Client.Handshake now reads ContextResponse's
wire_revision/min_client_wire_revision and refuses with a typed
*WireRevisionSkewError before any post-handshake call when the server's wire
shape falls outside [ClientMinWireRevision, ClientWireRevision] -- mirroring
DESIGN.txt sec 4's "Client rule". A decoded 0 is treated as "the server
omitted the member" per the permanently-retired-values rule, never as a value
needing refusal. The client now also stamps Bd-Wire-Revision on every request
(client.go's stampRequest), and problem.go gained the per-request mirror:
*WireRevisionUnsupportedError, decoded from the reason:"wire_revision_unsupported"
extension members, for the case where the SERVER refuses this client's
declared revision as too old. Both error types are deliberately distinct --
one is this client declining after reading a 200, the other is the server
refusing a request outright -- and neither branches on bd_version (only
assigns it into error text), so TestNoFeatureBranchesOnBdVersionOrSchemaVersion
stays green.
Also added legacyRevisionFields/decodeRevisionToken to problem.go: a
precondition_failed refusal's expected_version/actual_version, typed *string
on the generated Problem, now tolerates a pre-#6053 server sending either as a
bare JSON integer rather than the decimal string every server since has used,
recovering the field the primary decode silently drops rather than losing it.
Batch cap (task #3): ApplyBatch reads the handshake snapshot on every call and
enforces 100 items unless the server advertises issues.batchApplyLarge, in
which case the ceiling is issueops.MaxApplyBatchItems (1000) -- never a bare
compiled constant. A plan over the applicable cap refuses before the dial: via
the existing *CapabilityError machinery when advertising the capability would
help (D7 case 2), or via a new *BatchTooLargeError (unwraps to
issueops.ErrValidation) when it would not. BatchTooLargeError lives in
handshake.go rather than beside ApplyBatch because every exported method in
writes.go is swept by TestEveryOperationMethodRoutesThroughTheSharedDispatch as
an operation-dispatch method.
All three internal/httpclient/... packages build and `go test` passes with
TMPDIR=/data/projects/.scratch/s2t BEADS_TEST_SKIP=dolt.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* feat(httpclient): REQUIRE-mode credential resolution bridge to backends.Credential
Task #4: adds the knob internal/storage/backends/backends.go's OpenOptions.Credential
doc explicitly deferred ("S1 does not add a RequireCredential knob to enforce
the multi-tenant rule mechanically -- that is deferred to S2").
ProvidedCredential wraps an embedder-supplied wire.CredentialProvider (via its
httpclient alias) as a backends.Credential, so a multi-tenant embedder (for
example gc, Gas City: one process serving many workspaces) can carry a
per-workspace credential through backends.OpenOptions without the backends
package needing to know this package's CredentialProvider shape.
ResolveCredential(opts, base, require) is the bridge itself:
- nil Credential, require=false: NewBearerProvider(base), the existing
single-tenant ambient bearer ladder (unchanged).
- nil Credential, require=true: ErrCredentialRequired -- the multi-tenant
fail-closed case backends.go's doc names: a missing per-workspace
credential must be a loud refusal, not a silent fall-through to
process-global ambient env that cannot tell one tenant's workspace from
another's.
- a ProvidedCredential with a non-nil Provider: returned directly,
regardless of require.
- a ProvidedCredential with a nil Provider, or any other
backends.Credential this package does not recognise: refused -- the
former as ErrCredentialRequired (a present-but-empty wrapper must not
look like "a credential was supplied"), the latter wrapping
backends.ErrUnsupportedCredential per the OpenWith contract
internal/storage/backends/open_with_test.go already pins
(TestBackendOpenWithRefusesUnsupportedCredentialType).
No bd-enterprise source was copied for this file; it is new code written
against the OSS backends.go contract and the existing BearerProvider/
CredentialProvider types already lifted into this package. Live-mutated all
three guards (the require branch, the ProvidedCredential type assertion, and
the nil-Provider check) and confirmed each produces a RED test before
reverting.
go build/vet/gofmt clean; `go test ./internal/httpclient/...` passes with
TMPDIR=/data/projects/.scratch/s2t BEADS_TEST_SKIP=dolt.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* test(httpclient): S2 task #6 wire-revision/legacy-decode coverage, fix legacyRevisionFields bug
Add httptest coverage for the two wire-revision mechanisms task #2 added
(commit 7ff68b29d8):
- handshake_wire_revision_test.go: the client-initiated skew gate
(checkWireRevision/WireRevisionSkewError) and the per-request
Bd-Wire-Revision header stamp. Live-mutated both switch arms in
checkWireRevision and the stamped header value; confirmed RED, reverted.
- problem_wire_revision_test.go: the server-initiated
wire_revision_unsupported refusal (reason-before-code dispatch priority)
and the legacy-integer revision-token fallback.
Writing the legacy-decode tests surfaced a real bug in legacyRevisionFields:
its presence guard treated any non-nil *string field as "already decoded,"
but encoding/json's indirect() pre-allocates a pointer to "" for a *string
field before discovering a type mismatch (e.g. a bare JSON integer). A
type-mismatched expected_version/actual_version therefore arrived as a
non-nil pointer to the empty string, not nil -- exactly the one case the
fallback exists to recover, and exactly the case the old guard skipped.
Fixed by adding revisionNeedsFallback(p) (nil-or-empty), used in place of
the bare nil checks. No legitimate server response uses a literal
empty-string revision token, so this changes no other behavior.
Live-mutated the fixed guard back to the old nil-only checks; confirmed RED
on both recovery tests, reverted.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* test(httpclient): S2 task #6 ApplyBatch item-cap coverage
Add writes_batch_cap_test.go: httptest coverage for ApplyBatch's
capability-gated item ceiling (task #3), separate from the generic
two-speed "is issues.batchApply routed at all" gate writes_twospeed_test.go
already covers.
Cases: at-or-under the 100-item floor succeeds without the capability;
over the floor without issues.batchApplyLarge refuses with a
*CapabilityError before any dial past the handshake; the capability raises
the ceiling to issueops.MaxApplyBatchItems (1000), both at the new ceiling
and strictly between the old floor and it; over the absolute ceiling
refuses with *BatchTooLargeError regardless of the capability, also
without dialing the batch-apply endpoint.
Live-mutated all three guards in ApplyBatch (the limit computation, the
n > limit check, and the capability-vs-absolute-ceiling branch); confirmed
each produces a distinct RED, reverted.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* test(httpclient): S2 task #6 live TLS coverage for wrong-CA refusal
Add ca_wrong_ca_test.go: an end-to-end httptest TLS dial proving
TransportFor's configured CA pool is actually enforced at the wire, not
just recorded on the transport struct. ca_test.go already proves the
latter (TestTransportForReplacesRootPoolNotExtends, via
x509.CertPool.Equal) and proves the RIGHT CA dials successfully
(TestTransportForFileRotationClosesSupersededIdleConnections's live GETs);
neither exercises a server whose leaf a DIFFERENT CA signed.
TestTransportForWrongCARefusesTheTLSHandshake dials a server through a
transport built from an unrelated CA file and asserts the handshake fails
with x509.UnknownAuthorityError. TestTransportForRightCASucceedsOverTLS is
the positive control, using the same (newly-exercised) ca.startServer
helper that was defined but had no caller before this test -- without it,
a mutation that drops RootCAs entirely (falling back to the system pool)
would still pass the wrong-CA test for the wrong reason; the positive
control catches that case. Live-mutated transportForFile to drop RootCAs;
confirmed the positive control goes RED, reverted.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* build(bazel): gazelle BUILD files for the lifted httpclient package tree
Task #7: bazel run //:gazelle, now that internal/httpclient and its
encode/wire subpackages exist in the OSS tree (ab11cb1f8) and have gained
this S2 slice's new files. No existing BUILD.bazel files changed; these
three packages previously had none.
Note for S3: bazel test //internal/httpclient/... fails on tests that read
sibling source trees by relative path at runtime
(TestLedgerRowsAreWellFormed, TestEveryEncoderTableParameterIsPublished,
TestDivergenceLedgerDocMatchesLedger in encode, and
TestNoFeatureBranchesOnBdVersionOrSchemaVersion,
TestEveryOperationMethodRoutesThroughTheSharedDispatch,
TestEveryOperationMethodIsCoveredByTheTwoSpeedTable in wire) -- paths like
../../../cmd/bd and ../../httpapi/spec/openapi.v0.yaml resolve under `go
test`'s working directory but not Bazel's sandbox, which gazelle cannot
infer `data` attributes for. Pre-existing in code from task #1/#2, not
introduced by this commit; `go test ./internal/httpclient/...`,
`go vet ./...`, `gofmt -l .`, `golangci-lint run ./internal/httpclient/...`,
and `make api-check` are all clean.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* fix(httpclient/wire): tolerate bare-integer revision on success-path responses
Review HIGH #2: against a fake pre-#6053 server (one whose ContextResponse
omits wire_revision), CloseIssue and its revision-bearing siblings
(ApplyBatch, ReleaseIssue, ReopenIssue, UpdateIssue) failed with an untyped
`json: cannot unmarshal number ... revision of type string`. S0's
string-or-number tolerance (problem.go's legacyRevisionFields) only covered
the problem+json error path, never the success path.
Adds revision_tolerance.go: a pre-unmarshal rewrite that walks a response
body and turns a bare JSON number at a "revision" key into its exact decimal
string, scoped to the five apigen response types that carry the member and
gated on the handshake having seen no wire_revision at all. Left
apigen/types.gen.go and the OpenAPI spec untouched (both are
regenerate-and-diff gated by `make api-check`), rather than introducing a
custom Revision JSON type through codegen, to keep the fix's blast radius to
the wire package's own reader.
Updates ClientMinWireRevision's doc comment (handshake.go) to describe
tolerance on both halves of the wire instead of overclaiming the error-path
fix alone covered it. Adds revision_tolerance_test.go: a read (ListReadyWork)
and a guarded write (CloseIssue with ExpectedVersion) against a fake
pre-#6053 server, plus a modern-server control proving the rewrite never
fires when wire_revision is present. Mutation-tested: disabling the rewrite
reproduces the exact untyped UnmarshalTypeError the review reported.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* build(bazel): sandbox internal/httpclient's source-reading tests (Bazel gate green)
Review HIGH #1: the Bazel lane was red because three tests under
internal/httpclient read sibling/cross-package files by relative OS path at
runtime, which bazel test's sandbox does not materialize without an explicit
`data` dependency.
- internal/httpclient/encode/BUILD.bazel: encode_test gets
data = ["//cmd/bd:go_srcs", "//internal/httpapi/spec:openapi.v0.yaml",
"//:engdocs/design/http-divergence-ledger.md"] + glob(["*.go"]), covering
bijection_test.go's cmd/bd scan and ledger_render_test.go's golden-doc read.
- internal/httpclient/wire/BUILD.bazel: wire_test gets
data = ["//cmd/bd:go_srcs", "//internal/httpclient:go_srcs"] + glob(["*.go"]),
covering skew_test.go's AST sweep of both trees.
- internal/httpclient/BUILD.bazel gains a go_srcs filegroup via `make
bazel-sync` (tools/bazel/go_srcs.py): added "internal/httpclient" to the
script's managed PACKAGES list rather than hand-writing the block.
- internal/httpapi/spec/BUILD.bazel and the root BUILD.bazel gain
exports_files for openapi.v0.yaml and engdocs/design/http-divergence-ledger.md,
scoped to //internal/httpclient/encode:__pkg__.
- bijection_test.go's loadPublishedParameters now reads the wire contract
through spec.OpenAPIV0() (the package's existing go:embed) instead of a
relative os.ReadFile path, per review suggestion -- the embed makes the
parameter set reachable without a `data` dependency on the YAML at all; the
openapi.v0.yaml data entry above stays as defense in depth for any other
reader the package gains.
Ran via `bazel run //:gazelle` then `python3 tools/bazel/go_srcs.py`
(bazel-sync-check passes). `bazel test //internal/httpclient/...` is fully
green: 3/3 test targets pass.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* docs(httpclient): scrub private/enterprise infra references from code and docs
Review MEDIUM #3. Provenance headers ("Contributed by gascity from
bd-enterprise...") stay by design -- this removes references to private
infrastructure and unported internals from comment bodies and generated docs:
- wire/doc.go: dropped the internal/enterprise/hostedbeads and
internal/enterprise/storageprofile build-tag comparison (neither exists in
this OSS tree) and the dangling citation of the never-written
engdocs/design/http-client-backend.md, replacing both with an accurate
description of this package's own build-tag-free status and a pointer to
the divergence ledger that does exist.
- credential.go: CredentialProvider's doc no longer names gwauth/DPoP/gateway
auto-detection by their private spelling; describes the interface generically.
- ca.go: dropped "cherry-to-AWS RTT" (generalized to "a typical cross-region
RTT") and the cmd/bd/enterprise_connect.go file reference (generalized to
"a `bd connect --ca-file X`-style command").
- ca_permissions_unix.go / ca_permissions_unix_test.go: ~/.config/gascity and
/etc/gascity example paths replaced with ~/.config/bd and /etc/bd.
- encode/skew_test.go: beads.corp replaced with bd.example.invalid.
- encode/ledger_render.go + ledger_render_test.go: the generated-doc preamble
and regenerate-hint strings now name internal/httpclient/encode (this
package) instead of internal/enterprise/httpstore/encode; regenerated
engdocs/design/http-divergence-ledger.md via `go test
./internal/httpclient/encode -run TestDivergenceLedgerDocMatchesLedger
-update-ledger-doc` rather than hand-editing it.
Final grep for enterprise/cherry/gascity/corp/gwauth under internal/httpclient
and engdocs turns up only: provenance headers (kept deliberately), this
session's own "no bd-enterprise source copied" disclaimers, and a handful of
generic "enterprise-tagged"/"enterprise server" references describing a
build-tag or commercial-tier server concept in the abstract -- none name a
private host, path, or credential.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* test(httpclient): review LOW items -- S3 TODO, env-driven CA test, lockstep doc
Review LOW #4-#6:
- wire/skew_test.go: TODO(S3) on the branch where the cmd/bd AST sweep is
vacuous (no store/dial wiring yet), naming the slice that closes it.
- ca_wrong_ca_test.go: TestTransportForWrongCAViaEnvRefusesTheTLSHandshake,
the BEADS_HTTP_CA_FILE env-driven sibling of the existing direct-CAFile
wrong-CA test -- same live-TLS refusal, resolved through resolveCAFile's
host-scoped env syntax instead of Target.CAFile.
- vocabulary_test.go: expanded the ClientWireRevision/CurrentWireRevision
comment to explain why this repo holds them in strict lockstep (client and
server ship from the same commit) rather than merely <=, distinguishing it
from the real cross-version compatibility ClientMinWireRevision exists for.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* fix(httpclient/wire): re-review HIGH-a/b -- cover IssueDetails, stop recursing into metadata
HIGH-a: the legacy-revision set was missing apigen.IssueDetails (GET
/v0/beads/issues/{id}'s body, an alias for types.IssueDetails that a grep for
"type ... struct" never sees). getIssue is a baseline op that can dispatch
with no cached handshake at all, so serverPredatesRevisionStrings now treats
"no snapshot" the same as "WireRevision == 0" instead of only the latter.
revisionBearingResponse's set is now pinned exhaustively against
internal/httpapi/wireshape/testdata/golden.json -- the same committed digest
TestWireShapeDigest guards -- by a new test
(TestRevisionBearingResponseCoversEveryWireShapeSchemaWithARevisionMember), so
a future schema gaining a `revision` member can't silently miss coverage
again. New coverage: both "with" and "without" a prior handshake for getIssue,
and an explicit items[].revision test for ApplyBatchResponse.
HIGH-b: the previous fix recursed into every nested object looking for a
bare-number "revision" key, which reached caller-owned blobs like
CloseIssueResponse.issue.metadata -- real user data shaped like
{"revision":3} came back silently coerced to a string, on every server the
broadened gate above now also covers. tolerateLegacyRevisionNumbers no longer
recurses at all: it rewrites only the body's own top-level "revision", and,
for *apigen.ApplyBatchResponse specifically, each item's top-level
"revision" in the top-level "items" array. New
TestCloseIssueLegacyRewriteNeverTouchesIssueMetadata proves a metadata
document with "revision" keys at three nesting depths round-trips
byte-for-byte unchanged.
Mutation-tested both guards by hand (not committed): dropping the
IssueDetails case turns TestRevisionBearingResponseCoversEveryWireShapeSchemaWithARevisionMember
and both getIssue tests red with the exact missing-coverage/decode-failure
messages; reinstating a fully recursive rewrite turns
TestCloseIssueLegacyRewriteNeverTouchesIssueMetadata red, showing the
metadata's revision keys silently rewritten at all three depths. Both
reverted clean before this commit.
internal/httpapi/wireshape/BUILD.bazel and internal/httpclient/wire/BUILD.bazel
export/declare testdata/golden.json as data for wire_test's new exhaustiveness
test.
Verified: go test ./internal/httpclient/... (ok, one pre-existing unrelated
flake in ca_wrong_ca_test.go confirmed not reproducible across 8 reruns),
golangci-lint run ./internal/httpclient/... (0 issues), make api-check (no
apigen drift), bazel test //internal/httpclient/... //internal/httpapi/wireshape/...
(5/5 PASSED).
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* fix(httpclient): stop the wrong-CA TLS tests racing Happy Eyeballs
Root cause: startServer rewrites its httptest TLS server's URL to the
hostname "localhost" so SNI is actually sent, but the server itself only
binds 127.0.0.1. net/http's default dialer does RFC 6555 Happy Eyeballs
for a hostname with more than one address family, racing a tcp6 dial to
::1:<port> against the real tcp4 dial. On this host, many unrelated
processes (JVM tooling) are bound to high ::1 ports, so the tcp6 race
occasionally "won" against a listener that had nothing to do with the
test, and the client spoke TLS to it instead -- surfacing as "tls: first
record does not look like a TLS handshake" rather than the expected
x509.UnknownAuthorityError. Confirmed via ss -tlnp captured at the moment
of failure (a java process holding the exact port raced) and via an
immediate manual redial to 127.0.0.1 on that port succeeding against the
real, still-live test server.
Fix: forceIPv4Loopback (new shared helper in ca_test.go) rewrites the
returned *http.Transport's DialContext to dial tcp4 only. SNI and the
request Host are unaffected, since crypto/tls and net/http derive both
from the URL, never from which address family carried the bytes. Wired
into every TLS fixture test in the package (ca_wrong_ca_test.go's three
tests, and ca_test.go's rotation test) -- grepped the rest of the repo
for the same "rewrite to localhost for SNI" pattern and found no other
occurrences.
Also fixed a latent bug this surfaced: TestTransportForWrongCAViaEnvRefusesTheTLSHandshake
called TransportFor(Target{}) with a nil BaseURL, so caHostMatches always
returned false and the CAFileEnv path was never actually exercised --
the nil RoundTripper was silently masked by http.Client's fallback to
http.DefaultTransport, which also failed to verify (via system roots)
for an unrelated reason. Now passes Target{BaseURL: u} so the test
exercises the host-scoped env-resolution path it documents.
go test -race -count=50 -run WrongCA: 8/8 clean. Whole package
go test -race -count=20: clean, twice. bazel test, golangci-lint,
make api-check: all green.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* fix(httpclient): repair CI-red tests and apply review fixes (adopt-pr #7210)
Three defects on the contributor head, none of them present on the base:
- test/docsync's TestEngdocsAndRootMarkdownLinks fails: the generated
divergence-ledger doc links http-client-backend.md, an architecture
spec this repository does not carry. Name it in a code span instead,
in ledgerDocPreamble, and regenerate the doc (-update-ledger-doc).
- TestCAFileHygieneRefusesGroupWritableFile fails under umask 022:
os.WriteFile's 0o660 passes through the umask, so the file lands 0640,
is never group-writable, and TransportForFile accepts it. Chmod it
explicitly. Its acceptance twin had the same gap on its file (only the
explicitly chmodded directory reached the user-private-group
exception), so chmod that file too: a mutant that drops the exception
for files alone passed the old test under umask 022 and fails the new
one.
- That acceptance twin calls the unix-only isUserPrivateGroup from
ca_test.go, which carries no build constraint, so the package's tests
do not compile for GOOS=windows. Move it, otherwise verbatim, into
ca_permissions_unix_test.go beside the other isUserPrivateGroup tests.
Review fixes (iteration 1):
- Encode dispatched through nine case arms of op/shape conjunctions
(cyclomatic 24). Switch on an (op, shape) struct key instead, and move
the getIssue and search-bridge arms into encodeGetIssue and
encodeSearch. The arms are disjoint, so dispatch and every error string
are unchanged. Cyclomatic 24 -> 10.
- EventStream.Next kept four accumulators and the per-field switch in
one loop (cognitive 27). Gather the accumulators into sseEvent and
fold each field line, per-event cap included, in applyField. Next
cognitive 27 -> 12; applyField is 11/11.
- The CA hygiene walk joined a relative symlink target onto the textual
containing directory, so with a/link -> ../b/c and b/c/x -> ../y it
resolved a/y where the kernel opens b/y: a valid CA was refused, or a
hygienic file at a/y was checked and read instead. readLinkTarget joins
onto the directory's EvalSymlinks path, taken after that directory's
own ancestors passed the hop-by-hop check. The regression test plants
a decoy at a/y; a lexical-join mutant reads it and fails.
- SaveTarget wrote a relative CAFile that every later LoadTarget
refuses. Both now go through checkCAFileAbsolute, so SaveTarget refuses
first, with LoadTarget's own message, and writes nothing.
- Document the cached transport TransportFor and TransportForFile return
as shared and read-only.
Review fixes (iteration 2):
- The walk still dropped a ".." inside a symlink target textually:
filepath.Join cleans a relative target, and an absolute target's
ancestors come from filepath.Dir, while the kernel takes that ".."
from wherever the component before it really leads. Both reviews
rated the relative leaf as a wrong-file read, and it is one: with
x/d -> ../e/s, x/L -> d/../y read a decoy at x/y where the kernel
opens e/y. The other three shapes are hygiene bypasses: an absolute
leaf target x/d/../y, and an ancestor link to d/../dir or x/d/../dir
with the CA at x/L/y, each read a file in a world-writable e that the
walk never checked. readLinkTarget now refuses a target with a ".."
after any other component, relative or absolute; a leading run of
".." is still taken from the directory's physical path. The test pins
all four shapes behind a control that refuses e/y named directly, and
a table pins hasInteriorDotDot's boundary. Mutants that drop the
refusal, limit it to relative targets, refuse every "..", or count
"." as a component each fail.
Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Gas City Adopt-PR
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
Co-authored-by: Eddie the Engineer <adopt-pr@gascity.com>
* feat(httpapi): wire-shape signal — wire_revision, floor header, golden digest, param tokens
S0 of the HTTP role-parity program: give a client a single place to learn
whether this build's wire shape has moved under it, and give CI a gate that
catches an undocumented move.
- GET /v0/beads/context reports wire_revision (bumps only on a non-additive
response-shape change) and min_client_wire_revision. An optional
Bd-Wire-Revision request header lets a client declare the revision it was
built for; checkWireRevision refuses a declared revision below the floor
with 400 invalid_argument/reason=wire_revision_unsupported and a
min_wire_revision field, on every route but /healthz (wireRevisionExempt) —
including the identity handshake, where catching the mismatch is cheapest.
Absent header is today's behavior; malformed value is invalid_value, never
wire_revision_unsupported. The floor lives in Server.minClientWireRevision
(defaulting to the MinClientWireRevision constant) so a test can raise it.
- internal/httpapi/wireshape: a golden digest over every response's every
content-type schema (including application/problem+json) across the whole
spec, keyed by schema+member. TestWireShapeDigest fails closed when a
member's JSON name or type changes without wire_revision bumping to match;
regenerate with `go run ./internal/httpapi/wireshape/cmd/gendigest`.
- GET /v0/beads/issues' `sort` parameter now carries the issues.listSort
capability token, the same convention `capabilities` entries use.
TestNewParameterOnExistingOperationHasABehaviorToken requires every new
parameter on an existing operation to carry one, checked against a
write-once grandfather baseline (testdata/pretoken_parameters.json) of
parameters that predate the rule; TestUntokenedParameterRuleFires proves
the checker itself against a synthetic fixture.
- Docs: engdocs/design/bd-serve-v0.md gets a "The wire-shape signal" section;
CHANGELOG.md gets an Added entry.
Live-mutated and reverted three RED demonstrations during development:
retyping api_version in the spec failed TestWireShapeDigest; short-circuiting
checkWireRevision's floor comparison failed
TestWireRevisionBelowFloorRefusesEveryEnforcedRoute; adding an untokened
query parameter to listIssues failed
TestNewParameterOnExistingOperationHasABehaviorToken. All three now pass
against the unmutated tree.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* fix(httpapi): rename issues.listSort to issues.list.sort, harden token rule
Opus review of 12c5144ca (HIGH-1, MEDIUM-5):
- Rename the capability token issues.listSort -> issues.list.sort to match
bd-enterprise's client (httpstore/wire/handshake.go:121, DESIGN.txt S4e),
and widen capabilityToken to accept an optional third segment.
- untokenedParameters() now requires the extracted token to be one
Capabilities() actually serves, not just backtick-shaped text. This
catches real false positives that existed in the spec already
(workapi.DefaultReadyLimit, status.custom) which only shape-matched the
old regex; they're added to the pretoken baseline as genuinely
pre-existing untokened parameters.
- Extend the rule to request body members (new
testdata/pretoken_request_body_members.json baseline) and exempt
brand-new operations via a frozen testdata/pretoken_operations.json
snapshot.
- Add TestPretokenBaselinesNeverGrow pinning all three baseline sizes so
a future change can't hand-add an exemption instead of a token.
- Update spec prose for the widened rule scope.
go test ./internal/httpapi/... and the reviewer's pmut.py all pass as
expected: plain/bogus modes go RED, reuse (real-but-unrelated token) stays
green, matching the review's literal ask ("a token must be one advertised
by Capabilities()").
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* fix(wireshape): close four digest-coverage gaps, add gendigest write guard
Opus review of 12c5144ca (HIGH-2, MEDIUM-4). The digest only tracked
Type/Format/Enum/Required on direct properties, missing:
- nullable: true (never read at all)
- array item shape (Issue.labels items string->integer was invisible;
only object-shaped items got recursed into)
- additionalProperties value shape (IssueCount.groups)
- request bodies entirely (Compute() only walked responses, so
DeleteIssuesRequest.expected_version string->integer, the other half
of #6053, was invisible)
Also added defensive oneOf flattening alongside the existing allOf merge
(dormant today -- grep confirms this spec uses oneOf nowhere -- but no
longer silently invisible if that changes).
Extracted the golden-vs-computed comparison into wireshape.Compare(),
shared by TestWireShapeDigest and the new wireshape.SafeToWrite(), which
gendigest now calls before writing: it refuses to overwrite golden.json
with changed/removed entries unless the candidate's wire_revision is
strictly greater than the existing golden's. Pure additions always write.
TestSafeToWrite exercises both guard directions.
golden.json is regenerated. This single regen is a one-time exception to
the new guard, done by writing the digest directly rather than through
gendigest: confirmed via a throwaway diff (not checked in) that every one
of the 57 "changed" entries differs only in the NEW fields the wider walk
now populates (ItemType/ItemFormat/Nullable/AdditionalProps*) -- every
pre-existing Type/Format/Required/Enum value is byte-identical. Nothing on
the wire changed; the measurement got more precise. Bumping
CurrentWireRevision for this would have written a false "the protocol
changed here" entry into the revision history table. Going forward, any
REAL change the guard now reports uses the normal bump-then-regenerate
path, same as before.
Verified against the reviewer's mut.py: nested_type, nullable,
nullable_issue, array_items, addlprops, request_body and format all go RED
on TestWireShapeDigest, each reverted after confirming.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* fix(httpapi): make bd_version wire_revision inference advisory
Opus review of 12c5144ca (HIGH-3). The spec told a client inferring
wire_revision from bd_version to use the release cutoff >= 1.3.0, and said
nothing about what happens when that inference is wrong -- which it
demonstrably is for real builds already in the field:
- main builds up to commit b3ef65c85 report bd_version 1.2.2 (below any
1.3.0 cutoff) while already sending the string-typed revision/
expected_version shape (#6053).
- 1.3.0-rc.N pre-release builds sort BELOW the release cutoff 1.3.0 under
plain string comparison despite already carrying the string shape.
- The bd-enterprise compatibility line at d3ab32773462 reports bd_version
1.1.0 while also sending strings.
Moved the cutoff to >= 1.3.0-rc.1 (compared as semver-with-prerelease,
which at least captures the rc builds), documented both named exceptions
inline, and made the whole inference explicitly ADVISORY: a client must
accept revision/expected_version as either a string or a number whenever
wire_revision is absent (or probe directly) rather than let the inferred
value choose a decoder, and must never refuse solely because the inferred
revision is 0. Mirrored into engdocs/design/bd-serve-v0.md.
This is spec/doc prose only -- there is no server-side inference code to
change, since this server always sends wire_revision directly; the
inference is guidance for clients reading a pre-signal server's response
(this server, past builds, or an unrelated implementation).
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* fix(httpapi): LOW-7/8/9/10 review follow-ups for wire-revision signal
LOW-7: WireRevisionUnsupported now also sets Problem.wire_revision (this
server's CurrentWireRevision) and Problem.bd_version on the
wire_revision_unsupported refusal, alongside the existing
min_wire_revision, so a client logging the refusal has this server's
full self-description without a second /v0/beads/context call.
LOW-8: gazelle + make bazel-sync add the BUILD.bazel entries the prior
commits were missing: wire_revision.go/wire_revision_test.go in
internal/httpapi's srcs, new BUILD.bazel files for wireshape and
wireshape/cmd/gendigest, and a testdata glob on httpapi's go_test so
the pretoken_*.json baselines are visible under `bazel test`. Verified
with `bazel build //internal/httpapi/...` and
`bazel test //internal/httpapi/... --test_env=BEADS_TEST_SKIP=dolt`
(both green) and `python3 tools/bazel/go_srcs.py --check` (clean).
LOW-9: narrowed CHANGELOG.md and engdocs/design/bd-serve-v0.md to
describe the digest's actual final coverage (format/enum/required/
nullable, array items, additionalProperties, request bodies, $ref/
allOf/oneOf recursion, the SafeToWrite revision-bump guard) and the
token rule's actual final shape (three pinned baselines, request-body
members, Capabilities()-membership validation, new-operation
exemption) instead of the original, narrower claims.
LOW-10: Bd-Wire-Revision now parses via a strict decimal-only
parseStrictNonNegativeInt (no leading '+', no leading zero except a
bare "0") instead of strconv.Atoi alone, so two different header
bytes can no longer name the same revision. New malformed-header test
cases: "+1", "01", "007".
Regenerated apigen/types.gen.go (make api-gen) for the new Problem
fields and wireshape/testdata/golden.json (go run
.../wireshape/cmd/gendigest) for the two new additive Problem members;
the latter wrote cleanly through SafeToWrite itself, since both are
pure additions.
go test ./... and bazel test //internal/httpapi/... both green.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* fix(httpapi): re-review LOW follow-ups — retirement test, gendigest -init, docs
1. TestRetiredRevisionsStayBelowTheFloor pins the PRESENCE guarantee the
wire_revision property doc relies on: CurrentWireRevision >= 2 (so 0
and 1 stay permanently retired) and MinClientWireRevision <=
CurrentWireRevision (so this build's own floor never refuses every
request against itself).
2. gendigest now refuses to create a golden.json that does not exist yet
unless run with -init. Previously a missing file (moved testdata,
wrong path, accidental delete) was indistinguishable from a real first
run and silently wrote a fresh golden with no revision history checked
against anything. writeGolden() is extracted out of main() so this is
covered directly: TestWriteGoldenRequiresInitWhenMissing,
TestWriteGoldenInitCreatesWhenMissing,
TestWriteGoldenIgnoresInitWhenGoldenExists (the existing-golden path is
still governed only by SafeToWrite, -init or not).
3. Narrowed the two remaining stale claims that still described the
digest's original, narrower coverage: the wire_revision property's
prose in openapi.v0.yaml (regenerated into apigen/types.gen.go via
make api-gen) and wireshape/doc.go now both list nullable, array item
shape, additionalProperties value shape, request bodies, and
$ref/allOf/oneOf recursion, plus the new -init guard.
go test ./internal/httpapi/... and make api-check both green;
bazel test //internal/httpapi/... (httpapi, wireshape, and the new
gendigest test target) green; python3 tools/bazel/go_srcs.py --check
clean.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* feat(wireshape): cover operation parameters in the wire-shape digest
The digest previously walked only response and request-body schemas, so a
type, enum, required, or removal change on one of the spec's 138 operation
parameters (123 query, 14 path, 1 header) passed the gate silently — the
open item from PR review on #7182.
Each parameter is now recorded as its own Entry, keyed by
"param:"+operationId / location+":"+name (operation-scoped, not
schema-scoped, since two operations' same-named parameter are independent
wire contracts), capturing type, array item shape, enum, required, style,
explode and default. Adding a parameter stays additive; removing,
retyping, narrowing its enum, or changing required/style/explode/default
now trips SafeToWrite exactly like a response or request-body change.
Verified against the live spec: retyping listIssues' `limit` query
parameter from integer to string now fails TestWireShapeDigest (confirmed
red, then reverted — not part of this commit). golden.json regenerated via
gendigest; the new parameter entries are a pure addition, no wire_revision
bump needed. Added TestParameterMutationsAreCaught (remove/retype/narrow-
enum against real golden entries) and updated wireshape's doc.go, the
`wire_revision` spec prose, and the CHANGELOG to describe the new
coverage.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* fix(wireshape): review fixes — stale-golden and lowered-revision arms, effective param serialization, digest boundary
Maintainer fixup from the adopt-pr review loop (iterations 1 and 2), on
top of e17ba924f.
- goldenDrift (A, I): TestWireShapeDigest's comparison moves into a
goldenDrift helper. An addition alongside a moved wire_revision no
longer passes with a stale golden: it asks for a regenerate, as a
changed or removed entry after a bump already did. Every message now
names response/request-body members AND parameters, and TestGoldenDrift
pins each arm. This takes only the test half of the stranded fixup
(adopt-pr/bd-47kdge/stranded-fixup-528cd6095); its doc half, which says
parameters are outside the digest, is false since e17ba924f and is not
replayed (J).
- Lowered wire_revision (D): a CurrentWireRevision LOWER than the
golden's is a wrong constant, not a stale golden, so goldenDrift says to
restore it instead of regenerating, and SafeToWrite (so gendigest)
refuses any write at a lower revision, whatever the entries.
- Effective style/explode (B): walkParam records style and explode with
OpenAPI 3.0's defaults filled in (form for query/cookie, simple for
path/header; explode defaults to style == form). Adding `explode: false`
to a query array that relied on form's implicit explode is now a
changed entry, while spelling out a default changes nothing.
testdata/golden.json is regenerated with -init: 111 parameter entries
change only in style/explode (96 to form/true, 15 to simple), 828
entries before and after, wire_revision stays 2. The golden is new in
this PR and unreleased, so this needs no bump.
- TestWalkParam (H): a package-internal table test
(wireshape_internal_test.go) pins every field walkParam extracts,
through a computeFrom(document, revision) seam that Compute now wraps:
per-location defaults, $ref'd parameters and items, format, nullable and
default, content parameters, and the nil returns.
TestEffectiveSerializationIsCompared pins B end to end through Compare
and SafeToWrite. BUILD.bazel embeds the library in the go_test, which is
gazelle's own output.
- Required inputs and the digest boundary (C, E, F; docs only): all five
prose surfaces (openapi.v0.yaml's wire_revision description and the
regenerated apigen/types.gen.go, wireshape/doc.go, CHANGELOG.md,
engdocs/design/bd-serve-v0.md) now say that a new REQUIRED request
input is recorded as an ordinary addition and needs its own review,
that value constraints and member-level composition are outside the
digest, and that object and content parameters are recorded only as
their container. bd-serve-v0.md also gains the parameter coverage it
was missing.
- G: a brand-new operation is permanently exempt from the
capability-token rule; its own review decides its capability story.
- Iteration 2 (nit): walkParam's comment now says that the location
default it records as a `content` parameter's style and explode is a
placeholder, since OpenAPI 3.0 applies style and explode only to a
parameter described by `schema`. All 138 operation parameters in the
spec use `schema`, so the golden does not change.
Validated: go test ./internal/httpapi/... (gms_pure_go), make api-check,
go vet for linux/windows/darwin, gofmt, git diff --check, gazelle on the
package (no drift), make bazel-sync-check, and bazel test
//internal/httpapi/wireshape/... in the local processwrapper sandbox
(2 of 2 pass). Overlay mutation probes: dropping the added-after-bump
arm, the lowered-revision arm, SafeToWrite's lowered check, or the
effective-default fill each turns the new tests red.
Iteration 2 changes only that comment; go test
./internal/httpapi/wireshape/... (gms_pure_go), go vet, gofmt and git
diff --check pass again.
Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Gas City Adopt-PR
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* feat(count): add Counter scope fields (S8) — ParentID, NoParent, ExcludeTypes, ExcludeStatus
Extends issueops.CountRequest with ParentID, NoParent, ExcludeTypes and
ExcludeStatus, closing the gap where bd count could not express the
filters bd list already has, forcing downstream consumers like gc to
fall back to listing everything just to get a count.
- issueops.Counter: four new CountRequest fields, documented against the
List equivalents they mirror (ParentID/ExcludeTypes) or newly define
(NoParent, ExcludeStatus has no List counterpart). Status "all" is
pinned as equivalent to unset, matching BuildListFilter's own "all" and
preserving count/list cardinality parity (the role's reason to exist).
- internal/workapi.BuildCountFilter: maps the four fields onto the one
types.IssueFilter builder all three storage legs (dolt, embeddeddolt,
uow) already share via internal/storage/issueops and sqlbuild, so no
per-leg storage code was needed.
- cmd/bd: --parent, --no-parent, --exclude-type, --exclude-status flags.
- HTTP: adds parent/no_parent/exclude_type/exclude_status to GET
/v0/beads/issues:count, behind the new issues.count.scope behavior
token (routes.go), wired in reads.go's countFilters, documented in
openapi.v0.yaml with per-parameter tokens and an extended capabilities
description. gendigest confirms a byte-identical golden.json: query
parameters are outside the wire-shape digest's scope, so this is a
zero-diff, no-revision-bump change as expected.
- backend/conformance: four new Counter contract cases (ParentID scoping,
NoParent's edge-only semantics vs ParentID's edge-or-dotted-id match,
ExcludeTypes composing with include_infra's own exclusions, and
ExcludeStatus), run identically against all three storage legs via a
new CounterFixture.AddDependency hook shared with ReaderFixture.
Verified: go build ./...; go test ./internal/httpapi/... ./internal/workapi/...
./issueops/... and the Counter contract on all three legs (dolt via
testcontainers, embeddeddolt, uow via local dolt binary); make api-gen
(additive-only apigen diff) and make api-check; go vet and golangci-lint
clean; gofmt clean; gazelle diff empty (no new files/imports). Mutation
testing: dropping issues.count.scope from behaviorCapabilities turns
TestCapabilitiesAdvertiseEveryImplementedOperation,
TestSpecCapabilityVocabularyMatchesTheRouteTable and
TestNewParameterOnExistingOperationHasABehaviorToken red; no-op'ing
ExcludeStatus in BuildCountFilter turns
TestBuildCountFilterExcludeStatusTakesNamesAsWritten and the
embeddeddolt ExcludeStatusNarrowsThePredicate conformance case red. Both
reverted and reconfirmed green.
Deviation: DESIGN.txt's literal text would make count --status all an
ErrValidation; shipped behind a test and a doc comment instead, since
"all" already means "every status" on both count and list and rejecting
it would break the count/list parity this role exists to guarantee.
S3/S4 note: no OSS HTTP client exists yet to enforce capability-token
skew. A doc comment on CapIssuesCountScope in routes.go specifies the
required behavior once one lands: check issues.count.scope against the
cached handshake capabilities and refuse locally with a typed
ErrUnsupported{Capability} before sending any of the four new params to
an older server.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* fix(count): S8 review follow-ups — refusal parity, exclude-status validation, doc fixes, parity tests
Addresses the Opus review's six required changes for S8 (bd count scope
fields):
1. BuildCountFilter now refuses ParentID+NoParent together as ErrValidation,
matching bd list's CLI refusal wording; wired through the role, the CLI,
and invalid_argument classification in internal/httpapi/reads.go.
2. Status:"all" is documented in DESIGN.txt as every status, matching List's
no-filter reading (count/list cardinality parity) — a coordinator decision
recorded in beads-design/DESIGN.txt, outside this worktree.
3. ExcludeStatus names are now validated against the workspace vocabulary
(built-in statuses plus workspace-custom ones); an unknown name is
ErrValidation instead of a silent no-op, since a typo here would overcount.
4. Fixed openapi.v0.yaml and issueops/reader.go doc claims about bd list
--parent's default tree-walk vs. the one-level role answer that bd count
--parent agrees with (confirmed by tracing list_show_filter_modes.go); fixed
an Oxford-comma nit in routes.go and the spec.
5. Added storage-level count == len(List) parity tests for ParentID, NoParent
and ExcludeTypes (List has no ExcludeStatus counterpart), plus wisp-child
and closed-child contract cases, across all three backends (dolt,
embeddeddolt, uow). CounterFixture gained a List hook for this.
6. Extended the routes.go skew note: gc's ErrCountUnsupported fallback to List
is now named explicitly, with a note that S3/S4 must add a skew test that
masks the token and asserts the fallback fires.
Also fixed RunCounterExcludeStatusNarrowsThePredicate's now-stale "unrecognized
status excludes nothing" assertion to expect ErrValidation instead.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* fix(count): PR #7199 review follow-ups — exclude-status config load, ParentID doc swap
Addresses bee's REQUEST-CHANGES on gastownhall/beads#7199 (S8):
1. BLOCKER: storecounter.filter and uow.countFilter only loaded the
workspace list config when IncludeInfra was set, so BuildCountFilter's
ExcludeStatus validation refused a workspace's own custom status unless
the caller also passed the unrelated IncludeInfra flag. Both legs now
load the config when IncludeInfra OR len(ExcludeStatus) > 0, with
comments corrected to say so. Added leg-level regression tests (the
conformance fixture cannot drive a workspace-configured custom status)
on embeddeddolt and uow, reproducing the reviewer's CLI repro directly,
plus an HTTP-level probe in cmd/bd's real-Dolt proxied count test.
2. issueops.ReadyRequest.ParentID's comment had been overwritten with the
one-level direct-children wording that belongs to ListRequest.ParentID;
Ready actually walks all descendants via GetDescendantIDsInTx (GH#3396).
Restored the descendants comment on ReadyRequest.ParentID and moved the
one-level explanation to ListRequest.ParentID, which had none.
Verified: make api-check; dolt-server, embeddeddolt and uow Counter
contract legs (BEADS_TEST_DOLT_SERVER=local with a pinned dolt binary for
uow; Docker for the dolt-server leg); the new proxied HTTP exclude_status
probe (BEADS_TEST_PROXIED_SERVER=1).
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* chore(wireshape): add the countIssues scope parameters to the wire-shape golden
#7182 now digests operation parameters. The four new issues:count parameters
(parent, no_parent, exclude_type, exclude_status) are additive entries, so no
wire_revision bump is needed; regenerated with gendigest.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* test(conformance): register the S8 count-scope cases with RunRoleContracts (adopt-pr #7199)
The PR adds nine RunCounter* contract cases to counter_contract.go and wires
them into the three in-tree TestCounterContract legs, but not into the
Counter row of roleContractCases. TestRoleContractCasesCoverEveryContractCase
derives the expected set from source, so it fails on the PR head, and an
external backend running RunRoleContracts would never see the new cases.
Register them in source-declaration order (after
RunCounterAnUnknownStatusMatchesNothing), which the same guard enforces.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* docs(count): correct the S8 scope docs the review found wrong (adopt-pr #7199)
Comment and spec-description fixes only; no behavior change. Review-loop
iterations 1 and 2 of the #7199 relaunch.
- ListRequest.ParentID (issueops/reader.go) said "DIRECT children only
... the same one-level clause". The sqlbuild clause has two arms and
neither walks: the parent-child edge arm stops at one level, but the
dotted-prefix arm (`id LIKE CONCAT(?, '.%')` for rows with no
parent-child edge) reaches every edge-less dotted id at any depth, which
RunReaderListParentReachesEveryDescendantAndOnlyItsOwn pins with an
edge-less X.1.1. State both arms, and say the CLI tree view re-runs the
clause against the store once per level (findAllDescendants calls
SearchIssues, not the role). Document ListRequest.NoParent, which had no
doc. The contributor's ReadyRequest.ParentID text is kept; only its
cross-reference to this field changes from "one-level" to "non-walking".
- CountRequest.NoParent (issueops/counter.go) and the count flag comment
(cmd/bd/count.go) said NoParent counts rows with "neither" an edge nor a
dotted prefix. Its SQL checks only the edge table, so an edge-less X.1
is counted by both --parent X and --no-parent, as bd list lists it.
- RunCounterExcludeStatusNarrowsThePredicate's header said an
unrecognized name "excludes nothing rather than failing" while its body
asserts ErrValidation. The header now matches the body.
- The OpCountIssues entry in problem.go's operationCodes said the role has
"exactly one reachable refusal". It has three: an invalid metadata key,
an unrecognized exclude_status name, and parent with no_parent (named
no_parent), all classified by invalidFilterParam. The code set is
unchanged.
- BuildCountFilter's header said cfg is "only read under IncludeInfra".
It is also read to validate ExcludeStatus against the workspace's
custom statuses, which is why both callers load it when ExcludeStatus is
non-empty.
- The countIssues `parent` description in openapi.v0.yaml carried the
same one-level claim as ListRequest.ParentID; it now states both arms.
types.gen.go is regenerated (make api-gen); make api-check passes.
Review fixes (iteration 2), still comment and spec text only:
- The iteration-1 problem.go rewrite called all three count refusals
ErrValidation. Only the exclude_status and parent-with-no_parent
refusals wrap issueops.ErrValidation (internal/workapi/count.go). The
metadata-key refusal is ValidateMetadataFilters' plain fmt.Errorf
chain, so errors.Is(err, ErrValidation) is false for it; it reaches the
wire as a 400 only because invalidFilterParam matches message prefixes.
The comment now says that, so a later move to typed errors cannot trust
it and demote the metadata-key refusal to a 500. The sentinel itself is
not added here: ValidateMetadataFilters is shared with the list and
ready builders.
- invalidFilterParam's comment on the count rows pointed at the
metadata-key rows as "above"; they come after it in the switch.
- The countIssues `parent` description said the CLI tree mode walks
"every edge-linked descendant". findAllDescendants re-runs the full
two-arm predicate per level, so it also descends through edge-less
dotted ids; it now says "every descendant reachable through either
arm". types.gen.go is regenerated; make api-check passes.
Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Gas City Adopt-PR
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* chore(wireshape): re-record the count scope params under the base's param digest (adopt-pr #7199)
The base branch (feat/wire-revision-signal, #7182be1f0bad72) now digests
the effective style/explode of scalar query parameters. This PR's golden
entries for countIssues query:parent and query:no_parent were written by
the old algorithm, so after the base refresh TestWireShapeDigest reported
them as "changed without a wire_revision bump".
No bump is owed: all four count-scope entries (parent, no_parent,
exclude_type, exclude_status) are additions this PR introduces and are
absent from the base golden. golden.json was reset to the base copy and
regenerated with `go run ./internal/httpapi/wireshape/cmd/gendigest`. The
result is four pure additions against the base (+35/-0); parent and
no_parent gain "style": "form" and "explode": true, and wire_revision
stays 2.
Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Gas City Adopt-PR
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* ci: place the PR's new embedded counter test in the shard manifest
TestCounterExcludeStatusAcceptsAWorkspaceCustomStatusWithoutIncludeInfra,
added to internal/storage/embeddeddolt in f23bf5ddbf, is a new top-level
embedded storage test. The 15-shard block of
.github/scripts/embedded-storage-test-shards.txt must list every
discovered test exactly once. Without the entry,
TestStorageEmbeddedShardManifestGeneratorNotStale (scripts/) fails, both
on the reviewed head 89a387de6c and on the merge. CI never ran the check
on this PR: pr.yml runs only for PRs based on main, release/** or
hotfix/**, and this PR was based on feat/wire-revision-signal until the
retarget.
Generated with
`python3 scripts/ci/gen_embedded_storage_shard_manifest.py 15 --weights=duration --write`.
The incremental write adds this one line, in shard 4, and moves no other
test.
Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Gas City Adopt-PR
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
Co-authored-by: Eddie the Engineer <adopt-pr@gascity.com>
Co-authored-by: Eddie the Engineer <adopt-pr@gascity.local>
* feat(httpapi): wire-shape signal — wire_revision, floor header, golden digest, param tokens
S0 of the HTTP role-parity program: give a client a single place to learn
whether this build's wire shape has moved under it, and give CI a gate that
catches an undocumented move.
- GET /v0/beads/context reports wire_revision (bumps only on a non-additive
response-shape change) and min_client_wire_revision. An optional
Bd-Wire-Revision request header lets a client declare the revision it was
built for; checkWireRevision refuses a declared revision below the floor
with 400 invalid_argument/reason=wire_revision_unsupported and a
min_wire_revision field, on every route but /healthz (wireRevisionExempt) —
including the identity handshake, where catching the mismatch is cheapest.
Absent header is today's behavior; malformed value is invalid_value, never
wire_revision_unsupported. The floor lives in Server.minClientWireRevision
(defaulting to the MinClientWireRevision constant) so a test can raise it.
- internal/httpapi/wireshape: a golden digest over every response's every
content-type schema (including application/problem+json) across the whole
spec, keyed by schema+member. TestWireShapeDigest fails closed when a
member's JSON name or type changes without wire_revision bumping to match;
regenerate with `go run ./internal/httpapi/wireshape/cmd/gendigest`.
- GET /v0/beads/issues' `sort` parameter now carries the issues.listSort
capability token, the same convention `capabilities` entries use.
TestNewParameterOnExistingOperationHasABehaviorToken requires every new
parameter on an existing operation to carry one, checked against a
write-once grandfather baseline (testdata/pretoken_parameters.json) of
parameters that predate the rule; TestUntokenedParameterRuleFires proves
the checker itself against a synthetic fixture.
- Docs: engdocs/design/bd-serve-v0.md gets a "The wire-shape signal" section;
CHANGELOG.md gets an Added entry.
Live-mutated and reverted three RED demonstrations during development:
retyping api_version in the spec failed TestWireShapeDigest; short-circuiting
checkWireRevision's floor comparison failed
TestWireRevisionBelowFloorRefusesEveryEnforcedRoute; adding an untokened
query parameter to listIssues failed
TestNewParameterOnExistingOperationHasABehaviorToken. All three now pass
against the unmutated tree.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* fix(httpapi): rename issues.listSort to issues.list.sort, harden token rule
Opus review of 12c5144ca (HIGH-1, MEDIUM-5):
- Rename the capability token issues.listSort -> issues.list.sort to match
bd-enterprise's client (httpstore/wire/handshake.go:121, DESIGN.txt S4e),
and widen capabilityToken to accept an optional third segment.
- untokenedParameters() now requires the extracted token to be one
Capabilities() actually serves, not just backtick-shaped text. This
catches real false positives that existed in the spec already
(workapi.DefaultReadyLimit, status.custom) which only shape-matched the
old regex; they're added to the pretoken baseline as genuinely
pre-existing untokened parameters.
- Extend the rule to request body members (new
testdata/pretoken_request_body_members.json baseline) and exempt
brand-new operations via a frozen testdata/pretoken_operations.json
snapshot.
- Add TestPretokenBaselinesNeverGrow pinning all three baseline sizes so
a future change can't hand-add an exemption instead of a token.
- Update spec prose for the widened rule scope.
go test ./internal/httpapi/... and the reviewer's pmut.py all pass as
expected: plain/bogus modes go RED, reuse (real-but-unrelated token) stays
green, matching the review's literal ask ("a token must be one advertised
by Capabilities()").
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* fix(wireshape): close four digest-coverage gaps, add gendigest write guard
Opus review of 12c5144ca (HIGH-2, MEDIUM-4). The digest only tracked
Type/Format/Enum/Required on direct properties, missing:
- nullable: true (never read at all)
- array item shape (Issue.labels items string->integer was invisible;
only object-shaped items got recursed into)
- additionalProperties value shape (IssueCount.groups)
- request bodies entirely (Compute() only walked responses, so
DeleteIssuesRequest.expected_version string->integer, the other half
of #6053, was invisible)
Also added defensive oneOf flattening alongside the existing allOf merge
(dormant today -- grep confirms this spec uses oneOf nowhere -- but no
longer silently invisible if that changes).
Extracted the golden-vs-computed comparison into wireshape.Compare(),
shared by TestWireShapeDigest and the new wireshape.SafeToWrite(), which
gendigest now calls before writing: it refuses to overwrite golden.json
with changed/removed entries unless the candidate's wire_revision is
strictly greater than the existing golden's. Pure additions always write.
TestSafeToWrite exercises both guard directions.
golden.json is regenerated. This single regen is a one-time exception to
the new guard, done by writing the digest directly rather than through
gendigest: confirmed via a throwaway diff (not checked in) that every one
of the 57 "changed" entries differs only in the NEW fields the wider walk
now populates (ItemType/ItemFormat/Nullable/AdditionalProps*) -- every
pre-existing Type/Format/Required/Enum value is byte-identical. Nothing on
the wire changed; the measurement got more precise. Bumping
CurrentWireRevision for this would have written a false "the protocol
changed here" entry into the revision history table. Going forward, any
REAL change the guard now reports uses the normal bump-then-regenerate
path, same as before.
Verified against the reviewer's mut.py: nested_type, nullable,
nullable_issue, array_items, addlprops, request_body and format all go RED
on TestWireShapeDigest, each reverted after confirming.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* fix(httpapi): make bd_version wire_revision inference advisory
Opus review of 12c5144ca (HIGH-3). The spec told a client inferring
wire_revision from bd_version to use the release cutoff >= 1.3.0, and said
nothing about what happens when that inference is wrong -- which it
demonstrably is for real builds already in the field:
- main builds up to commit b3ef65c85 report bd_version 1.2.2 (below any
1.3.0 cutoff) while already sending the string-typed revision/
expected_version shape (#6053).
- 1.3.0-rc.N pre-release builds sort BELOW the release cutoff 1.3.0 under
plain string comparison despite already carrying the string shape.
- The bd-enterprise compatibility line at d3ab32773462 reports bd_version
1.1.0 while also sending strings.
Moved the cutoff to >= 1.3.0-rc.1 (compared as semver-with-prerelease,
which at least captures the rc builds), documented both named exceptions
inline, and made the whole inference explicitly ADVISORY: a client must
accept revision/expected_version as either a string or a number whenever
wire_revision is absent (or probe directly) rather than let the inferred
value choose a decoder, and must never refuse solely because the inferred
revision is 0. Mirrored into engdocs/design/bd-serve-v0.md.
This is spec/doc prose only -- there is no server-side inference code to
change, since this server always sends wire_revision directly; the
inference is guidance for clients reading a pre-signal server's response
(this server, past builds, or an unrelated implementation).
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* fix(httpapi): LOW-7/8/9/10 review follow-ups for wire-revision signal
LOW-7: WireRevisionUnsupported now also sets Problem.wire_revision (this
server's CurrentWireRevision) and Problem.bd_version on the
wire_revision_unsupported refusal, alongside the existing
min_wire_revision, so a client logging the refusal has this server's
full self-description without a second /v0/beads/context call.
LOW-8: gazelle + make bazel-sync add the BUILD.bazel entries the prior
commits were missing: wire_revision.go/wire_revision_test.go in
internal/httpapi's srcs, new BUILD.bazel files for wireshape and
wireshape/cmd/gendigest, and a testdata glob on httpapi's go_test so
the pretoken_*.json baselines are visible under `bazel test`. Verified
with `bazel build //internal/httpapi/...` and
`bazel test //internal/httpapi/... --test_env=BEADS_TEST_SKIP=dolt`
(both green) and `python3 tools/bazel/go_srcs.py --check` (clean).
LOW-9: narrowed CHANGELOG.md and engdocs/design/bd-serve-v0.md to
describe the digest's actual final coverage (format/enum/required/
nullable, array items, additionalProperties, request bodies, $ref/
allOf/oneOf recursion, the SafeToWrite revision-bump guard) and the
token rule's actual final shape (three pinned baselines, request-body
members, Capabilities()-membership validation, new-operation
exemption) instead of the original, narrower claims.
LOW-10: Bd-Wire-Revision now parses via a strict decimal-only
parseStrictNonNegativeInt (no leading '+', no leading zero except a
bare "0") instead of strconv.Atoi alone, so two different header
bytes can no longer name the same revision. New malformed-header test
cases: "+1", "01", "007".
Regenerated apigen/types.gen.go (make api-gen) for the new Problem
fields and wireshape/testdata/golden.json (go run
.../wireshape/cmd/gendigest) for the two new additive Problem members;
the latter wrote cleanly through SafeToWrite itself, since both are
pure additions.
go test ./... and bazel test //internal/httpapi/... both green.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* fix(httpapi): re-review LOW follow-ups — retirement test, gendigest -init, docs
1. TestRetiredRevisionsStayBelowTheFloor pins the PRESENCE guarantee the
wire_revision property doc relies on: CurrentWireRevision >= 2 (so 0
and 1 stay permanently retired) and MinClientWireRevision <=
CurrentWireRevision (so this build's own floor never refuses every
request against itself).
2. gendigest now refuses to create a golden.json that does not exist yet
unless run with -init. Previously a missing file (moved testdata,
wrong path, accidental delete) was indistinguishable from a real first
run and silently wrote a fresh golden with no revision history checked
against anything. writeGolden() is extracted out of main() so this is
covered directly: TestWriteGoldenRequiresInitWhenMissing,
TestWriteGoldenInitCreatesWhenMissing,
TestWriteGoldenIgnoresInitWhenGoldenExists (the existing-golden path is
still governed only by SafeToWrite, -init or not).
3. Narrowed the two remaining stale claims that still described the
digest's original, narrower coverage: the wire_revision property's
prose in openapi.v0.yaml (regenerated into apigen/types.gen.go via
make api-gen) and wireshape/doc.go now both list nullable, array item
shape, additionalProperties value shape, request bodies, and
$ref/allOf/oneOf recursion, plus the new -init guard.
go test ./internal/httpapi/... and make api-check both green;
bazel test //internal/httpapi/... (httpapi, wireshape, and the new
gendigest test target) green; python3 tools/bazel/go_srcs.py --check
clean.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* feat(wireshape): cover operation parameters in the wire-shape digest
The digest previously walked only response and request-body schemas, so a
type, enum, required, or removal change on one of the spec's 138 operation
parameters (123 query, 14 path, 1 header) passed the gate silently — the
open item from PR review on #7182.
Each parameter is now recorded as its own Entry, keyed by
"param:"+operationId / location+":"+name (operation-scoped, not
schema-scoped, since two operations' same-named parameter are independent
wire contracts), capturing type, array item shape, enum, required, style,
explode and default. Adding a parameter stays additive; removing,
retyping, narrowing its enum, or changing required/style/explode/default
now trips SafeToWrite exactly like a response or request-body change.
Verified against the live spec: retyping listIssues' `limit` query
parameter from integer to string now fails TestWireShapeDigest (confirmed
red, then reverted — not part of this commit). golden.json regenerated via
gendigest; the new parameter entries are a pure addition, no wire_revision
bump needed. Added TestParameterMutationsAreCaught (remove/retype/narrow-
enum against real golden entries) and updated wireshape's doc.go, the
`wire_revision` spec prose, and the CHANGELOG to describe the new
coverage.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* fix(wireshape): review fixes — stale-golden and lowered-revision arms, effective param serialization, digest boundary
Maintainer fixup from the adopt-pr review loop (iterations 1 and 2), on
top of e17ba924f.
- goldenDrift (A, I): TestWireShapeDigest's comparison moves into a
goldenDrift helper. An addition alongside a moved wire_revision no
longer passes with a stale golden: it asks for a regenerate, as a
changed or removed entry after a bump already did. Every message now
names response/request-body members AND parameters, and TestGoldenDrift
pins each arm. This takes only the test half of the stranded fixup
(adopt-pr/bd-47kdge/stranded-fixup-528cd6095); its doc half, which says
parameters are outside the digest, is false since e17ba924f and is not
replayed (J).
- Lowered wire_revision (D): a CurrentWireRevision LOWER than the
golden's is a wrong constant, not a stale golden, so goldenDrift says to
restore it instead of regenerating, and SafeToWrite (so gendigest)
refuses any write at a lower revision, whatever the entries.
- Effective style/explode (B): walkParam records style and explode with
OpenAPI 3.0's defaults filled in (form for query/cookie, simple for
path/header; explode defaults to style == form). Adding `explode: false`
to a query array that relied on form's implicit explode is now a
changed entry, while spelling out a default changes nothing.
testdata/golden.json is regenerated with -init: 111 parameter entries
change only in style/explode (96 to form/true, 15 to simple), 828
entries before and after, wire_revision stays 2. The golden is new in
this PR and unreleased, so this needs no bump.
- TestWalkParam (H): a package-internal table test
(wireshape_internal_test.go) pins every field walkParam extracts,
through a computeFrom(document, revision) seam that Compute now wraps:
per-location defaults, $ref'd parameters and items, format, nullable and
default, content parameters, and the nil returns.
TestEffectiveSerializationIsCompared pins B end to end through Compare
and SafeToWrite. BUILD.bazel embeds the library in the go_test, which is
gazelle's own output.
- Required inputs and the digest boundary (C, E, F; docs only): all five
prose surfaces (openapi.v0.yaml's wire_revision description and the
regenerated apigen/types.gen.go, wireshape/doc.go, CHANGELOG.md,
engdocs/design/bd-serve-v0.md) now say that a new REQUIRED request
input is recorded as an ordinary addition and needs its own review,
that value constraints and member-level composition are outside the
digest, and that object and content parameters are recorded only as
their container. bd-serve-v0.md also gains the parameter coverage it
was missing.
- G: a brand-new operation is permanently exempt from the
capability-token rule; its own review decides its capability story.
- Iteration 2 (nit): walkParam's comment now says that the location
default it records as a `content` parameter's style and explode is a
placeholder, since OpenAPI 3.0 applies style and explode only to a
parameter described by `schema`. All 138 operation parameters in the
spec use `schema`, so the golden does not change.
Validated: go test ./internal/httpapi/... (gms_pure_go), make api-check,
go vet for linux/windows/darwin, gofmt, git diff --check, gazelle on the
package (no drift), make bazel-sync-check, and bazel test
//internal/httpapi/wireshape/... in the local processwrapper sandbox
(2 of 2 pass). Overlay mutation probes: dropping the added-after-bump
arm, the lowered-revision arm, SafeToWrite's lowered check, or the
effective-default fill each turns the new tests red.
Iteration 2 changes only that comment; go test
./internal/httpapi/wireshape/... (gms_pure_go), go vet, gofmt and git
diff --check pass again.
Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Gas City Adopt-PR
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
* test(storage): measure ApplyBatchInTx SQL statement counts (B0)
Adds a driver.Connector-level counting/latency-injecting wrapper
(internal/storage/sqlcount) plus shared plan-request fixtures
(internal/storage/batchfixtures: mol-normalized 356/712-item shapes and a
40-item classic shape) and backend-specific pinning tests + benchmarks
(internal/storage/embeddeddolt, internal/storage/dolt) that measure the
ACTUAL number of SQL statements issueops.ApplyBatchInTx issues for each
shape, on both the embedded and Dolt (TCP) backends.
Measured totals (Prepare+Exec+Query+StmtExec+StmtQuery inside one
transaction): 356 items ~7008-7009, 712 items 14014-14015, 40 items 846,
identical on both backends (expected: statement issuance is driven by Go
application logic, not backend-specific SQL planning). Pinned with a small
(+/-2) tolerance to absorb an observed, host-contention-driven +/-1 Query
drift (Exec is deterministic on every run). This is the regression baseline
slice B2 (a later, lighter fast path) must demonstrably lower.
batchfixtures.UncappedPlan bypasses issueops.MaxApplyBatchItems so this
measurement does not depend on slice B1's cap raise.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* feat(httpapi,issueops): raise batchApply envelope to 1000 items with bounded large-apply handling
POST /v0/beads/issues:batchApply now accepts up to 1000 items (up from 100);
issueops.MaxApplyBatchItems moves accordingly and the request body cap rises
to 16 MiB. The whole plan still applies in exactly ONE transaction. A request
over 100 items runs under a separate, flat, operator-configured whole-run
budget (`bd serve --large-apply-ceiling`, 5 minutes by default) instead of
the ordinary 60s request deadline; a request at or under 100 items is
unaffected and keeps exactly the 60s deadline and 15s commit-retry ceiling it
always had.
Concurrency and shutdown are bounded, not just documented:
- Oversized requests serialize through a dedicated one-wide semaphore, and at
most one caller may wait for that semaphore at a time (a CAS-guarded single
waiter) — a burst of oversized requests is shed with 503 rather than
queuing and starving ordinary traffic behind the general semaphore.
- The run deadline is stamped only once the slot is actually acquired, not
at the time the request arrived.
- Graceful shutdown closes new admissions before computing its drain budget,
then waits out an in-flight large apply up to its own remaining deadline
(plus a few seconds' grace for the response to write); any large apply
still queued for the semaphore when shutdown begins is refused rather than
extending the drain further. A queued caller that disconnects gets a clean
503, never a misclassified context error. `bd serve`'s orchestrator stop
grace must be at least `--large-apply-ceiling` — see
engdocs/SERVE_RUNBOOK.md.
- ApplyBatch's commit-retry budget only extends past the ordinary 15s ceiling
on this explicit large-apply path (via a context marker), with headroom
reserved so the final retry attempt can't be killed mid-commit by the
context's own expiry.
A new `issues.batchApplyLarge` capability token on `GET /v0/beads/context`
lets a client learn whether a given server accepts the raised envelope.
Wall-clock measurement (embedded Dolt, whole-transaction build+commit) backs
the 5-minute ceiling default: 356 items ~12.6s (23.8x headroom), 1000 items
~57.5s (5.2x headroom).
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* fix(httpapi,serve): wire the large-apply retry budget; repair stale pins
Review fixes for the large batchApply envelope, on top of the test
repairs the PR needed against main.
The extended commit-retry budget was never switched on.
internal/storage/uow's retryTxBudget lets a large apply keep retrying a
commit-time conflict past the ordinary 15s ceiling only when its context
carries issueops.WithExtendedRetryBudget's marker, and the docs on both
sides say admitLargeApply sets it, but nothing did: the marker's only
callers were the uow tests, which mark their contexts by hand. A
1000-item apply that hit a conflict still gave up after 15s with most of
its 5-minute ceiling unused. admitLargeApply now marks the run context
it builds, and TestApplyBatchMarksOnlyALargeApplyForTheExtendedRetryBudget
pins the seam over HTTP: marked at 101 and 1000 items, unmarked at 100.
Removing the mark fails the 101 and 1000 cases; marking every request in
handleApplyBatch fails the 100 case.
Smaller fixes from the same review:
- `bd serve --large-apply-ceiling` repeated the 5m default as a literal
of its own, and since bd serve always passes a positive ceiling, that
literal, not httpapi's, was the default every deployment ran. Export
httpapi.DefaultLargeApplyCeiling, default the flag to it, and pin the
flag's 5m0s default in TestServeFlags.
- admitLargeApply's release cancels the run context before clearing
s.largeApplyDeadline, the order acquireLargeApply's doc states; it
cleared the deadline first.
- Drop the batchfixtures test's dead t.Skipf, which waited for the cap
to reach 1000, and correct a graph-counter comment that still cited
the 100-item cap and the TestServeFlags doc line that called the
no-argument server unchanged.
The PR raises issueops.MaxApplyBatchItems from 100 to 1000 and adds
`bd serve --large-apply-ceiling`, but two base-owned tests still pinned
the old surface and went red on every lane that runs them (Bazel / test,
Test (macos-latest)):
- TestServeFlags pins the exact `bd serve` flag list; add
large-apply-ceiling.
- TestPlanApplyBatchRefusesAnUnusableRequest/too_many_items built 101
items and expected "at most 100 items", a request the 1000 cap now
plans successfully. Size the over-cap request and its message from
issueops.MaxApplyBatchItems, as TestPlanApplyBatchAcceptsTheBoundary
already does for the other side of the cap; the cap's value stays
pinned by TestCapBatchApplyLargeTiesAllThreeLimits.
The PR's own TestLargeApplyBurstNeverStarvesSmallRequestsForSemTimeout
also went red in PR Core (-race, -p 4 on a 4-vCPU runner): all eight
small requests took 160-165ms against a 100ms bound. The stall it
guards against lasts semTimeout (5s), while a small request can still
queue briefly behind the refused large requests, each holding a general
sem slot while its body decodes. Bound it at a second, the "want well
under a second" its sibling TestLargeApplyQueueDoesNotStarveOrdinaryRequests
already uses. Pinned to four cores beside 24 busy loops, small requests
measured 183ms mean and 338ms max, and the 1s bound passed 80/80 runs;
with the one-waiter gate in acquireLargeApply disabled the test still
fails 3/3, on its 2s never-completed check.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(uow): stop a doomed large-apply retry before ctx cuts it off
retryTxBudget sizes maxElapsed once at ApplyBatch entry, but says nothing
about how long an individual attempt takes. A slow first attempt (e.g.
157s of a large apply's commit) left little of the budget for a retry,
which then got killed mid-transaction by ctx's own deadline instead of
finishing and reporting its own outcome -- surfacing as
context.DeadlineExceeded (isUnavailable excludes it -> a generic 500)
instead of the exhausted-write-conflict result this loop already reports
correctly (-> 503 + Retry-After).
RunTxResultWithin now tracks the previous attempt's duration and, before
starting a new one, stops early with the last real serialization error
when time left on ctx is less than that duration plus a fixed headroom --
but only when publicops.HasExtendedRetryBudget(ctx) is set (the same
marker retryTxBudget itself checks). Applying the look-ahead
unconditionally regressed TestApplyBatchHonorsAnExtendedRetryBudgetFromContext's
unmarked case: ordinary requests have cheap attempts and are meant to run
until their own ctx deadline ends the loop, and the large-apply-sized 5s
headroom was tripping that for any short-ctx caller with a near-instant
failing attempt.
Adds TestRunTxResultWithin_SlowAttemptStopsBeforeADoomedRetry (a 1.2s
commit against a 2s marked ctx must stop after one attempt with its own
serialization error, never DeadlineExceeded, and never touch a second
unit of work) and its control, TestRunTxResultWithin_ShortAttemptStillRetries
(a 50ms attempt against the same shape must still retry and succeed).
Both mutation-checked against the look-ahead condition and its gate.
Also updates the stale "items accepts at most 100 entries" prose on the
applyBatch endpoint description (openapi.v0.yaml) to the large-envelope
wording already used elsewhere in the spec: 1000-item cap behind the
issues.batchApplyLarge capability, large-apply-ceiling deadline extension,
<=100 unaffected. dependencies:count's own "at most 100" lines are
unrelated and untouched.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
* fix(ci,serve): fit the 1000-item cap's tests in the storage shard budget
Review fixes for the relaunched #7051, iteration 1.
Raising issueops.MaxApplyBatchItems from 100 to 1000 made the base-owned
TestBatchApplyContract take 604s under -race, against 97s at the old cap
(main run 35862663577). It hashed onto the legacy test-embedded-storage
shard 2/5, beside ~5m of other tests, and that shard hit its 15m budget
twice (PR Risk run 36807191489). PR Risk no longer runs the legacy tier
on same-repo PRs (#7071), but Main's push run and fork PRs still do, so
the merge would have carried the timeout to Main.
Raising the jobs' timeout-minutes alone would not fix it: the shard
script passes the binary its own -test.timeout=15m. So:
- embedded-storage-test-shard.sh passes -test.timeout=20m (and its go
test fallback -timeout 20m), as embedded-test-shard.sh does for
cmd/bd.
- test-embedded-storage in main.yml and pr-risk.yml: timeout-minutes 15
-> 25, the script's 20m plus setup.
- embeddeddolt_embedded_test appends -test.timeout=19m, as
bd_embedded_test does, so Go's timeout, which dumps every goroutine,
fires before rbe-west's 1200s action kill, which does not.
TestBazelEmbeddedJobMirrorsEmbeddedTier now checks the override on
both sharded targets instead of only cmd/bd's, and the PR Risk
coverage test pins the storage target's new args.
- embedded-storage-test-shards.txt places TestBatchApplyContract on
shard 4, which has ~3m of other tests, and the PR's two large-batch
tests, TestLargeBatchApplyStatementCounts_Embedded (247s) and
TestLargeBatchApplyWallClock_Embedded (261s), on shards 2 and 5. From
the PR run's per-test times, the heaviest shard projects to ~13m, down
from shard 2's 15m-plus.
Also correct the stop-grace guidance. For an in-flight large apply,
Serve's drain waits out the apply's remaining deadline plus drainGrace
(5s), so the orchestrator's stop grace must be at least
--large-apply-ceiling plus 5s, as Serve's own doc says. The runbook, the
flag help, the LargeApplyCeiling field doc and the CHANGELOG entry asked
for the ceiling alone.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
* fix(update): fence unforced --notes overwrites behind --force across all surfaces
bd update --notes silently replaced existing notes, destroying handoff
history. The contract now refuses an unforced overwrite of non-empty
notes with ErrNotesOverwrite (409 notes_overwrite_refused over HTTP,
force_notes_overwrite to override), enforced inside the mutation
transaction on both the dolt and uow backends, for single updates and
batch apply alike. CAS guards keep precedence: a stale
--if-assignee/--if-status still surfaces as the exit-13 mismatch, on
both backends, before the fence speaks.
CLI: --force and --if-assignee are no longer mutually exclusive (that
exclusion made overwriting under a guard impossible); both update
routes translate the fence's sentinel into the same actionable advice
(--force to overwrite, --append-notes to preserve history), and the
post---force warning is worded as an audit statement. The shipped
plugin skill docs and bd note help now prescribe --append-notes for
handoffs instead of the newly fenced bare --notes.
The fence is the single enforcement point: no client-side pre-read
copies of the rule. Conformance contracts, unit tests for
AuthorizeNotesOverwrite, and embedded/proxied/httpapi regression
coverage included.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MAFpn9pUw8WKMfymteZHbh
* fix(update): exempt explicit clears from the notes fence; share its predicate
CI surfaced three gaps in the fence's reach:
- Clearing notes (--notes "" / patch.notes: "") was refused, diverging
from every sibling text field's clear and from the backend behavior
contracts. The fence now targets only its actual footgun — replacing
non-empty notes with different non-empty content — via a single shared
predicate, issueops.NotesReplacement, used by both the contract's
AuthorizeNotesOverwrite and the CLI's warning path, so the two can no
longer drift. Prose updated to match everywhere the rule is stated
(ErrNotesOverwrite, ForceNotesOverwrite, OpenAPI spec + regenerated
types).
- The revision-CAS integration tests' incidental concurrent writes now
patch design instead of notes, so they no longer depend on notes-fence
semantics at all.
- The historical-upgrade harness deliberately replaces fixture notes and
asserts the new value; its two bd update --notes calls now pass
--force.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MAFpn9pUw8WKMfymteZHbh
* fix(update): address review — changelog BREAKING entry, problem.go doc block, close-policy-under-guard test
Review follow-ups on #5946 (bee-ghosttrack, MERGE-AFTER-FIXES):
- CHANGELOG: BREAKING entry under [Unreleased] ### Changed for the notes
fence on both wires (CLI exit 1, HTTP 409 notes_overwrite_refused), with
the --force / --append-notes migration line. It also names the two
deliberate edges: the explicit-clear exemption, and --force widening to
the close-policy half under --if-assignee now that the flag pair is legal.
- problem.go: CodeNotesOverwrite's comment had landed inside
CodeDependencyCycle's doc block; each const now sits under its own docs.
- assign_fence_embedded_test.go: pin the previously untested close-policy
half of --force under --if-assignee (refused unforced, authorized forced).
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JyuQ6Tjv3D7tpNqeb2WDED
* test(update): align TestWarnNotesReplacement with the post-fence warning copy
The test landed on main after this branch was cut and pins the pre-fence
wording, where the warning fired on any unforced overwrite. Since the fence,
an unforced overwrite is refused outright and warnNotesReplacement fires only
after a forced one — the audit trail for a habitual --force — so the copy it
pins is now '--force replaced existing notes'.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JyuQ6Tjv3D7tpNqeb2WDED
* docs(import): record bd import's notes-fence exemption as by-design (GH#6190)
Import consults none of the per-field live-state fences — notes overwrite,
live-claim reassign, close policy — and that is the intended shape, not an
omission: its contract is wholesale row replacement, guarded by its own
staleness check (only strictly-newer rows rewrite local state, --allow-stale
is the single deliberate-overwrite opt-in) and reported field-by-field in
updated_issues. Named in AuthorizeNotesOverwrite's enforcement-boundary
comment and in bd import's help; the published CLI docs pick the help text
up at the next release pin bump.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JyuQ6Tjv3D7tpNqeb2WDED
* fix(update): refuse --notes "" and add --clear-notes; stop --notes help reading as additive
GH#6021: an empty --notes wiped the whole notes field at exit 0 behind the
same ✓ Updated receipt as a successful write — and the empty string is
exactly what a dead command substitution collapses to. The empty value is
now refused on both CLI routes (the accident and the deliberate clear are
the same bytes at the flag layer), and the deliberate clear gets its own
verb, --clear-notes, mutually exclusive with --notes/--append-notes. A verb
rather than the proposed --allow-empty-notes opt-in: what needs authorizing
is an intent, not an input path — --allow-empty-description unblocks
stdin/file plumbing, which notes does not have — and an opt-in passed
habitually would silently disarm the guard while a habitual --clear-notes
fails loudly. --force does not bypass the refusal; the fence's clear
exemption stands, so the verb alone authorizes the erase. The HTTP API is
unchanged: patch.notes "" still clears.
GH#6272: bd update --help called --notes "Additional notes" and the prime
text said "Add supplementary notes" — both read as appending, so agents
following the injected guidance faithfully clobbered prior context. The
update help now names the operation with the --append-notes contrast at the
point of use, the shared/create help is field-named like --description and
--design, and the prime line points at bd update --append-notes.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JyuQ6Tjv3D7tpNqeb2WDED
* fix(bazel): enumerate the PR-new files in cmd/bd and issueops srcs
The base added cmd/bd/BUILD.bazel and internal/storage/issueops/BUILD.bazel
with EXPLICIT srcs lists after this branch was cut, so the three files this
PR adds were never enumerated:
cmd/bd/update_notes_guard.go (go_library bd_lib)
cmd/bd/update_notes_guard_test.go (go_test bd_test)
internal/storage/issueops/aggregate_authorize_notes_test.go (go_test)
The go_library omission is a hard build break, not a silent skip:
update.go:215,220 and update_input.go:106,111 are enumerated and call
validateNotesUpdate / clearNotesRequested, so //cmd/bd:bd_lib compiles the
callers without the callee. bazel.yml arms unconditionally for fork PRs
(head.repo.fork == true) and builds //cmd/bd:bd + //cmd/bd:bd_test, so this
reds the lane. make bazel-sync-check cannot see it -- go_srcs.py only
validates the glob-based go_srcs filegroup, never the rule srcs lists.
Generated by make bazel-sync (gazelle), not hand-edited, so the workflow's
own BUILD-files-in-sync drift step agrees byte-for-byte.
* fix(notes): name --clear-notes in bd note's rm guidance, correct the fence boundary comment, pin both request-shape rules
Takes all three non-gating minors from the review. No behavior change: two
prose fixes and two test cases.
1. cmd/bd/note.go's rm|remove|delete branch advised
`bd update <id> --notes "text" --force` under "To change or clear notes",
but clearing through --notes is exactly what this PR made impossible --
validateNotesUpdate refuses an empty value unconditionally and --force does
not reach it. The branch now names both verbs separately: --notes --force to
replace, --clear-notes to clear. The edit and update branches speak only of
replacing and were already correct, so they are untouched.
2. aggregate.go's enforcement-boundary comment claimed the UpdateIssueInTx
funnel's "one notes-replacing caller is bd edit". Under this PR's own
NotesReplacement predicate there are at least four more (bd note's
read-combine-write, bd defer --reason, bd rename and delete-tombstoning's
mechanical ID rewrites, bd compact's clears). The exemption is still sound --
every funnel writer derives its new value from the current notes -- so the
comment now names those CLASSES instead of a single caller, which is the
claim that is actually true and that a future fence auditor can check.
3. Both branches this PR adds to ValidateUpdateRequest were uncovered: the
batch apply leg reaches them here and nowhere else, while the single-issue
HTTP handler's own pre-check returns before storage. Added a sibling table
(the existing one varies only the patch; these two rules are properties of
the REQUEST) with a case each. Mutation-checked, disjoint: neutralizing the
force-without-notes branch reds only the first case, neutralizing the
notes+append branch reds only the second, and the pre-existing
canonical-fields table stays green under both.
Not an amend of 5ffcc9c16c: that commit's message states it was generated by
make bazel-sync and not hand-edited, so folding hand-written Go into it would
falsify the claim its own BUILD-files-in-sync argument rests on. No new files,
so the srcs lists it repaired stay correct.
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
* fix(show): disclose dependency edges the listing cannot represent (be-lpi)
`bd show --json` emitted a self-contradicting payload on any issue with a
cross-repo or `external:` dependency:
{"id":"hq-cv-ftcra","dependency_count":1,"dependencies":null}
and `bd show` in text mode rendered no dependency section at all, so
`bd dep add x liveop-y` reported success and the `bd show x` a caller ran
straight after was indistinguishable from the edge never having been written.
THE COUNT IS CORRECT. THE ENUMERATION IS THE DEFECT.
`GetDependenciesWithMetadataInTx` reads the edge rows, resolves each far end,
then does a bare `continue` past any id with no local row. An `external:` or
cross-repo target HAS no local row by construction: `IsExternalDepTarget`
routes exactly the ids this database cannot hold into `depends_on_external`,
the one target column with no foreign key into issues. The count queries have
no such join. So the count keeps the edge and every listing drops it, and the
difference is precisely the set of edges that are real, stored, and
unrenderable from here.
Reported as a phantom count on convoy beads. It is neither phantom nor
convoy-specific: `hq-cv-ftcra` carries a real `tracks` edge to
`external:liveop:liveop-kmf`, and convoys are simply the only producer of
external targets in that store (77 external edges, all `tracks`). The
`bd list --json` zero the report also cites is correct by design and unrelated
— that count is blocks-only per `SearchCountsSQL`, and the edge is `tracks`.
Publish the difference instead of leaving the caller to infer it, following
the `comments_omitted` precedent (ga-clgh):
- `IssueDetails` gains `unresolvable_dependencies` / `unresolvable_dependents`
- `BuildIssueDetails` sets them, so every frontend — CLI `--json` and the
HTTP detail view — gets it at once
- text mode says the same thing on stderr, never stdout, so the rendered
issue is byte-identical for the common fully-local case; that is the
choice `warnDroppedDepEdges` already made in dep.go for this same gap
- the notice helper is shared with the watch-mode render so the two cannot
drift apart in what they disclose
Set ONLY when the row list was actually read and came back short: the
dependency read's error is now kept rather than discarded, because a FAILED
read and a SHORT read both leave the slice empty and must not collapse into
one signal. `unresolvable_dependents` only under `IncludeDependents`, where
the rows exist — without them the slice is nil by design and a delta would
report every dependent an issue has as unresolvable.
Deliberately NOT done: making the count match the listing. The count is right
and the edge is real, so zeroing it would delete the only signal these edges
exist. Nor does `GetDependenciesWithMetadata` synthesise placeholder issues
for external targets — it has 14 non-test call sites including the Linear,
GitLab, Jira and ADO sync paths, which would then map a fabricated issue onto
a remote tracker.
`bd dep list` needed no change: bd-mtla already warns there and points at
`bd dep list <id> <id>`, which prints the raw edge record. The installed
v1.2.2 predates that fix, which is why the bead's measurements saw a bare `[]`.
Tests. `internal/workapi/detail_unresolvable_test.go` pins the arithmetic
against a source whose counts and rows are set independently, with negative
controls for a fully local store, a failed row read, a failed count read, and
count-only mode. `cmd/bd/show_unresolvable_deps_embedded_test.go` drives the
production path — init, create, `dep add`, `show` — for both target shapes
plus a fully local control, and asserts the notice reaches stderr and not
stdout. Verified the scratch fixture's stored columns are identical to the
production row rather than merely similar. Sabotage control run on both tiers:
removing the guard turns each red, and the negative controls stay green.
`docs/reference/json-schema.md` is intentionally untouched — it is
hand-written and documents the pinned release (`docs/cli-docs.pin` is v1.2.2),
not main. Follow-up filed as be-soj.
Agent-Signature: claude-code-claude-opus-5[1m]-unknown-reasoning on behalf of Marc Cressall
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017B2Z4eQi2a9Cgfumj2RRnR
Executed-By: beadsrig/polecats/toast
* fix(show): do not read a failed dependency listing as unresolvable edges (be-lpi)
Codex review of the previous commit, and it is right.
`bd show` renders dependencies best effort and discarded the listing error:
depsWithMeta, _ := issueStore.GetDependenciesWithMetadata(ctx, issue.ID)
so when that read FAILED while the count query succeeded, the new notice
reported every counted edge as cross-repo/external. A transient backend error
was rendered as a claim about the data, which is the more expensive of the two
mistakes — the user goes looking for edges that are simply unread.
This is the distinction `BuildIssueDetails` already draws with `depsErr` on
the JSON side, and it is the reason that error is kept there. The text path
did not draw it at all, so the two planes disagreed under failure: `--json`
stayed silent and the human render accused the data.
Carry each direction's rows and error together in a `depListing` and require
BOTH reads to have succeeded before reporting a difference. Rendering stays
best effort; only the diagnosis is gated. A failure in one direction no longer
suppresses the other, which is a case the single-error shape could not express.
`cmd/bd/show_unresolvable_deps_unit_test.go` pins it: 10 cases including the
two the review found, a fully local negative control, a failed count read, and
one direction failing while the other stays reportable. Sabotage control —
relaxing the guard back to `countErr != nil` alone fails exactly the two
listing-read-failed cases and nothing else.
Reuses the existing race-safe `captureStderr` from test_helpers_pure_test.go
rather than a second copy.
Agent-Signature: claude-code-claude-opus-5[1m]-unknown-reasoning on behalf of Marc Cressall
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017B2Z4eQi2a9Cgfumj2RRnR
Executed-By: beadsrig/polecats/toast
* fix(show): read the dependency counts before the row listings (be-lpi)
Second codex finding on this change, and it is real on the path `bd show`
actually uses.
The unresolvable-edge difference is computed from two reads. Where the source
is not snapshot-consistent, a write landing between them skews it — and with
the listing read first the skew was the expensive direction: a freshly added,
perfectly ordinary local edge came back as `unresolvable_dependencies: 1` and
as a stderr notice accusing the data.
Only the store-backed source is exposed. `uow.issueReader.Get` wraps the whole
build in `RunTxRead`, so the UOW path shares one snapshot; `storereader` — what
`EmbeddedDoltStore.IssueReader` returns, and therefore what `bd show` runs on —
issues a connection per call.
Read the counts FIRST. An edge added in the window then leaves the count
stale-LOW, the difference goes negative, and nothing is reported. The text path
gets the same order structurally: the helper is split into `readDepCounts`,
called before the listings, and `warnUnresolvableDepEdges`, called after, so
the ordering is visible at both call sites rather than buried.
THIS IS AN ORDERING MITIGATION, NOT A FIX, and the code says so. A concurrent
DELETE still leaves the count stale-HIGH and produces a spurious notice. Closing
that needs a shared snapshot across the two reads, or a store method that counts
edges whose target has no row directly — either is a new seam across both
backends and the domain path, out of proportion to an advisory field. Filed
separately. Deletion of a dependency edge is also far rarer than addition, which
is why this ordering is strictly better rather than merely different.
The first version of the JSON-side test DID NOT PIN THE ORDER. It used a source
returning fixed values, so reversing the two reads still passed — a test
pinning arithmetic while claiming to pin an order, and the sabotage run is what
caught it. Replaced with `mutatingSource`, where whichever read runs first sees
one edge and the second sees two; swapping the reads in `BuildIssueDetails` now
fails with exactly the false report the review described. The text-side case is
relabelled to say it covers the subtraction only, since the call-site order is
not in its scope.
Agent-Signature: claude-code-claude-opus-5[1m]-unknown-reasoning on behalf of Marc Cressall
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017B2Z4eQi2a9Cgfumj2RRnR
Executed-By: beadsrig/polecats/toast
* fix(show): disclose unrenderable dep edges in proxied render (be-lpi)
`bd show` has three text renders and be-lpi closed two of them.
usesProxiedServer() returns at show.go:45 before any of the fixed code,
and runShowProxiedDefault binds the shared issueops.Reader -- hence
BuildIssueDetails, hence unresolvable_dependencies -- only when
`jsonOutput && !in.shortMode`, so plain text falls through to
proxiedRenderIssue, which rendered both dependency sections from
proxiedListDeps with discarded errors and said nothing. On a
server-backed repo the change`s own symptom survived: a cross-repo or
`external:` dependency still rendered as no dependency at all.
Call warnUnresolvableDepEdges from that route too, counts before the
listings, taking the counts through workapi.NewUOWDetailSource. The
domain use cases behind a proxied UOW are per-table, so proxiedDepCounter
carries the isWisp flag the DetailSource counts take. That flag is
arithmetically inert on this path, and the earlier claim here that the
store seam "resolves" it was the wrong mechanism: the repository read
seam discards it outright -- CountByID forwards only Direction and Types
to CountDependencyEdgesInTx, and ListWithIssueMetadata forwards only the
source id to Get{Dependencies,Dependents}WithMetadataInTx
(dependency.go:888-917) -- so both sides span `dependencies` and
`wisp_dependencies` alike and only the mutating paths pick a table.
The conclusion is unchanged and is what the notice depends on: the
arithmetic is the same on both routes, because
CountDependencyEdgesInTx counts `dependencies` plus `wisp_dependencies`
with no join to `issues`, and proxiedListDeps runs the very
GetDependenciesWithMetadataInTx the direct route runs, so the difference
means here what it means there. --refs and --children stay out of scope:
an alternate query with no count beside it to contradict. The precedent
this design cites, warnDroppedDepEdges, covers both of its own routes
(dep.go:1148, dep_proxied_server.go:457), which is the in-repo standard
applied here.
Pinned by TestProxiedServerShow2/show_discloses_unresolvable_dep_edges
with a fully-local negative control. Measured, not assumed: deleting the
new call reds the first and leaves the control green.
Also from the same review, all non-gating:
- The recovery pointer is outbound-only now. `bd dep list <id> <id>`
reaches raw edge records through the duplicate-id form, which
dep.go:1101 selects on `batchMode && direction == "down"`, and
dep.go:1144 says in the repo`s own words that "up" has the same gap
with no inbound EdgeReader role to close it. An issue short only on
dependent edges was handed a command that cannot show them, and now
gets a line saying so instead.
- The ordering comment no longer advertises a guarantee nothing holds.
Splitting readDepCounts from warnUnresolvableDepEdges makes the
counts-first order readable at the call sites; it does not pin it.
Measured: reversing it at all three sites leaves this package green,
including the embedded production-path test, because the unit test
drives warnUnresolvableDepEdges directly and no CLI test can land a
write inside the window. The only automated pin is one tier down, on
TestBuildIssueDetails_ConcurrentAddIsNotReportedAsUnresolvable. A CLI
test that could fail on the order would have to own that window, which
is out of proportion for an advisory notice, so the comment now states
its scope rather than overstating it.
- The plane asymmetry is documented rather than changed: text mode reads
dependents unconditionally and always discloses the inbound direction,
while unresolvable_dependents needs include_dependents (--json only).
The per-field restriction is the correct half -- without the rows a
delta would call every dependent unresolvable -- so the godoc and the
spec description record the disagreement.
One correction to be-lpi`s own commit message, which cannot be amended
from here: enumerating the edges via issueStore.EdgeReader() is not "a
new seam across both backends and the domain path" on the CLI path.
EdgeReader() sits on the variable that path already holds
(storage.go:235, used at show.go:177). The concurrent-DELETE residual
still stands on the two-reads argument alone, which remains true of
ReadEdges plus a set difference.
Review iteration 2 adds the BUILD-file sync the required Bazel lane
needs, plus one comment correction:
- cmd/bd/BUILD.bazel and internal/workapi/BUILD.bazel now list the three
test files this change adds. The relevant failure is not a broken
build: bazel.yml`s "BUILD files in sync" step (:382-406) runs
`make bazel-sync` and exits 1 on a non-empty `git status --porcelain`,
and that step`s job is BAZEL_TEST, one of seven Bazel rows in
pr.yml`s CI_GATE_REQUIRED (:1496-1524, mapped at :1551), so the drift
reds a required lane rather than merely leaving the files invisible to
Bazel. The repo`s own fixture agrees: scripts/ci_workflow_test.go`s
bazelLaneGateIDs holds bazel-test, and bazelAdvisoryLanes retains only
bazel-integration.
The rows are gazelle output rather than hand-written. `make bazel-sync`
on this head proposes five; init_git_bootstrap_routing_test.go and
init_role_environment_test.go are base staleness that origin/main
already lists, and a run on the merge target proposes them not at all,
so only the three this change owns are committed.
Certificate, run on the merge target rather than argued: merge
origin/main into this head, resolve, `make bazel-sync`, then
`git status --porcelain --untracked-files=all` is empty -- which is
exactly the gate step`s own test, and it also confirms the resolution
is byte-identical to what gazelle emits. `bazel build //cmd/bd:bd_test
//internal/workapi:workapi_test` on that tree completes successfully,
so the widened srcs lists compile.
These rows do introduce a merge conflict this change did not have
before: origin/main added show_watch_loop_test.go into the same slot of
the same sorted srcs list in cmd/bd/BUILD.bazel. It is an add/add with
an empty base -- neither side edits shared text -- and the resolution
is the sorted union of all three rows, which is what gazelle emits and
what the certificate above was run against.
- The ordering comment`s measurement clause named show.go and
show_display.go while the claim was true of three call sites, the
third being the show_proxied_server.go site this fixup added. It now
names all three, re-measured at this head: reversing readDepCounts
below its listings at every site leaves the selector green -- 35
subtests across TestWarnUnresolvableDepEdges,
TestEmbeddedShowUnresolvableDeps and TestProxiedServerShow2.
Maintainer fixup for PR #6352, review iterations 1-2.
---------
Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
* test(count): pin include_ephemeral as the plane bit and nothing else
PR #6240 added `bd count --include-ephemeral` so a count can reach the
wisps table without IncludeInfra's other three changes: dropping
templates, dropping gates, and routing an infra type to the ephemeral
tier. Nothing asserted that second half. Routing IncludeEphemeral
through the builder's infra branch, or mapping `include_ephemeral` onto
IncludeInfra in the HTTP handler or the CLI, passed every existing test.
- workapi: TestCountIncludeEphemeralIsThePlaneBitAndNothingElse, the
count twin of the list pin. IncludeEphemeral (no type, a named type,
an infra type) leaves IsTemplate, ExcludeTypes and Ephemeral unset;
IncludeInfra still sets all four.
- httpapi: TestCountForwardsTheEphemeralPlaneParameter sends each plane
parameter alone and asserts the exact request the role receives.
- cmd/bd: TestCountIncludeEphemeralFlagShape pins the flag, its false
default, and that --include-ephemeral alone leaves IncludeInfra false.
Each new test fails against its mutant, and it is the only test that
does:
- builder: `if in.IncludeInfra || in.IncludeEphemeral`
- handler: `IncludeInfra: q.boolean("include_infra") || q.boolean("include_ephemeral")`
- CLI: `IncludeInfra: includeInfra || includeEphemeral`
Post-merge review follow-up for #6240.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* docs(count): name include_ephemeral where the plane prose said include_infra alone
#6240 added a second way to reach the wisps tier, but several statements
still said only include_infra could reach it:
- spec, countIssues "Planes": "DURABLE-PLANE ONLY unless include_infra
is set" now names both knobs and says what include_ephemeral changes.
- spec, include_infra: "Unset, the count is durable-plane only" now holds
only with include_ephemeral also unset (types.gen.go regenerated).
- issueops.CountRequest: the same "Unset" sentence on IncludeInfra and on
IncludeEphemeral, each now conditional on the other knob.
- workapi.applyCountIncludeInfra: "a count without IncludeInfra keeps its
durable-only semantics" now allows for IncludeEphemeral.
- httpapi countFilters: the "plane switch" comment named one knob;
IncludeEphemeral now has its own comment saying why it is never folded
into IncludeInfra.
- count_test.go: the default-plane comment names both zero values, and
the stale "25 filters" / "26th filter" literals are dropped (the
struct has 26 fields).
Comment and spec-prose only; `make api-check` is green.
Post-merge review follow-up for #6240.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Eddie the Engineer <adopt-pr@gascity.local>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
* feat(issueops): type the blocked-close refusal as BlockedError
Every close-policy blocker refusal was fmt.Errorf("%w: %s is blocked by
%v", ErrCloseBlocked, ...), so the blocker list existed only as prose. A
caller reporting the refusal elsewhere (the HTTP surface) had to parse it
or drop it.
issueops.BlockedError carries IssueID, the typed []Blocker (id plus the
blocking edge type when known) and the wrapped sentinel. Its message is
byte-identical to the historical sentence, so the direct and proxied CLI
lines and failed[].error do not move, and errors.Is(ErrCloseBlocked) still
matches. The sentinel is a field rather than fixed so other "X is blocked
by Y" refusals (e.g. a blocked claim) can reuse the type.
The in-transaction guard keeps the edges typed (isBlockedByInTx, with
IsBlockedInTx formatting through Blocker.String), and the external guard
builds the error from IsBlocked's []string via ParseBlocker, the inverse
of that spelling.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* feat(httpapi): name the blockers on a live-blocker not_closable
The served close refusal said only "issue is blocked", so an HTTP client
could not tell the user what held the close, while bd close on the direct
and proxied routes prints "cannot close blocked issue: X is blocked by
[Y]".
A live-blocker not_closable now carries a `blockers` extension member,
[{id, kind: local|external, type?}], read from *issueops.BlockedError's
typed list, and a detail that opens with the direct route's sentence
built from the same list. It covers issues/{id}:close, per-item
issues:batchClose outcomes, PATCH into a done status and
issues:batchApply. The code, status and open_children discriminator are
unchanged; an error that only mentions blockers in prose keeps the old
generic detail and no member.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(issueops): test the external: prefix before the type split in ParseBlocker
Maintainer review fixup for #6893.
ParseBlocker tried the " (" / ")" split before the external: prefix
branch, so it won for any external reference whose capability ends in
")". validateExternalRef (cmd/bd/dep.go) constrains a capability to
non-empty only, so `external:remote:pay (beta)` is a legal reference
created by the sanctioned `bd dep add` path -- and it parsed to a
truncated ID of "external:remote:pay" plus Type "beta", a value outside
the documented blocks|waits-for|conditional-blocks vocabulary that
falsifies the spec's own promise that an external blocker carries no
type.
Only the structured half was wrong: the mis-split round-trips through
String(), so the prose detail and the CLI sentence stayed byte-identical
and the failure was silent on exactly the new `blockers` member this
change exists to make trustworthy.
Hoisting the prefix test is loss-free -- Blocker.Type's doc comment
already states an external reference never carries a reported type.
Pin: the ParseBlocker/String table in
TestBlockedErrorKeepsTheHistoricalSentence gains the paren-suffixed
external row; every external case tabled there was paren-free, which is
why this got through. Restoring the old ordering reds the new row.
The DeepEqual failure now prints %#v, because Blocker implements
String() and the default verbs render got and want identically for
precisely this defect.
---------
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
* feat(stats): count the rows the default listing suppresses
bd status counts the issues table; bd list hides gates and templates on
account of what they are. The two therefore disagree, and nothing
reconciles them: a teardown driven by bd list leaves a gate behind and
status reports a total the operator cannot account for from any listing.
Break the suppressed rows out as their own counts. TotalIssues keeps
counting the database, which is what a command titled "Issue Database
Status" should report; these say how much of that total no default
listing will show. Every backend's statistics path funnels through
ScanIssueCountsInTx, so one query serves all of them.
Infra types need no counterpart here: they live on the wisp plane, which
this query does not read.
* fix(status): disclose the counted rows bd list will not show
bd status reported "Total Issues: 2" for a workspace whose every listing
showed one, because gates and templates are suppressed from a default
bd list. Nothing connected the two numbers, so the remainder read as a
phantom -- most visibly after a teardown driven by bd list, which leaves
its gates behind and then cannot see them.
Report the suppressed rows under the summary they qualify, naming the
flag that reveals each kind. The breakdown is printed rather than a
single hidden-total, since a template gate would otherwise be counted
twice. Nothing is printed when there is nothing suppressed.
Stacked on the statistics counts that make this reportable.
* docs(api): put gate_issues and template_issues on the Statistics schema
The Statistics schema is pinned to types.Statistics, so the two new
counts were on the wire the moment the struct grew them, and
TestWireTagBijection fails the openapi gate until the spec says so:
Go fields with no spec property: [gate_issues template_issues]
Document both as a breakdown of total_issues rather than an addition to
it — they count rows the default `bd list` suppresses, which
total_issues already includes — and warn against summing them, since a
row can be both a gate and a template.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* fix(status): give --assigned the same disclosure, and test the behavior
Three points from review.
1. `bd status --assigned` never printed the line. AssigneeStats does not
go through ScanIssueCountsInTx - it folds one actor's rows through
workapi.FoldStatsAssigneeSummary, which left both new fields zero. That
route's filter sets only Assignee, so IsTemplate stays nil and the
actor's gates and protos really ARE in those rows while
`bd list --assignee` suppresses both: the same reconciliation gap, one
scope down. The fold now counts them, and its doc says they are set
deliberately rather than borrowed from a workspace-wide answer.
2. The infra-type suppression is now explained rather than asserted away,
and the answer is that a durable infra row is NOT unreachable, so the
third breakdown is filed as GH#6439 rather than dismissed. Both the
plane routing and the listing's exclusions read the workspace-configured
types.infra set, and writing that key only invalidates a cache
(dolt/config.go) - it never moves rows already written. So durable rows
created while a type was not infra stay durable once it becomes one, and
a type evicted from the set creates durable rows outright, which the
create contract already pins ("evicted infra type",
issue_operations_contract.go). Counting them needs that configured set,
which ScanIssueCountsInTx - portable SQL with no config seam, called
from six backend sites - cannot reach; guessing with the built-in names
would be wrong in exactly the workspaces where it matters.
suppressedTypeSummary's doc now carries that reasoning.
3. The behavior itself had no test - both existing cases exercised a pure
string formatter, and would pass with the render call site deleted. Now:
- TestRenderStatusEmitsTheSuppressedRowsLine captures renderStatus's
stdout, asserts the line and both parts, and asserts it sits after the
totals it reconciles rather than in the extended block. It fails with
the call site removed ("renderStatus did not emit the disclosure
line"), plus a companion asserting the line is absent when there is
nothing to disclose.
- Three conformance cases in stats_reporter_contract.go, wired into all
three role wirings (dolt, embeddeddolt, uow), so the new SQL is
checked cross-backend rather than at one call site:
BreaksOutTheRowsTheDefaultListingSuppresses (with the negative rows a
loose predicate would also move), BreaksOutAGateThatIsAlsoATemplate
(the two suppressions are independent, so a proto's gate step counts
in both), and AssigneeStatsBreaksOutTheSuppressedRows for the fold.
statsReporterCounts and assertStatsReporterDelta carry the two fields.
All three are behavioral reds against zeroed counts, not compile
errors:
GateIssues moved by 0 (0 -> 0), want 1
TemplateIssues moved by 0 (0 -> 0), want 1
GateIssues = 0, want 1 - the actor's gate is in this answer but
not in `bd list --assignee`
4. Nit: pluralCount takes both spellings instead of appending "s", so a
caller with an irregular plural is not silently mis-served.
Also adds the CHANGELOG entry the behavior change was missing, including
the GH#6439 gap.
Reported-by: bee-ghosttrack
Agent-Signature: claude-code-opus-5-unknown-reasoning on behalf of Harry Miller
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* fix(conformance): declare the new stats cases in the order the table runs them
TestRoleContractCasesCoverEveryContractCase checks more than coverage: the
roleContractCases table has to list cases in the order their contract file
DECLARES them, because that is the order the unit-of-work leg's runners use
and the order its config-writing cases depend on.
I declared all three new cases together, then registered the assignee one
with the other assignee cases in the table, so the two orders disagreed:
roleContractCases is out of declaration order at position 449: table
has RunStatsReporterAStatusOutsideTheTalliesIsCountedOnlyInTotal,
source has RunStatsReporterAssigneeStatsBreaksOutTheSuppressedRows
Fixed by moving the declaration rather than the table entry, since the
assignee case belongs beside the other assignee-scoped ones anyway - the
grouping the table already had was the correct one. Caught by CI because I
ran go vet over backend/conformance but not its tests; both now pass.
Agent-Signature: claude-code-opus-5-unknown-reasoning on behalf of Harry Miller
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* docs(changelog): move this PR's entry under [Unreleased]
The 1.3.0 cut renamed the old [Unreleased] block, so the entry this branch
added there now merges cleanly into the released [1.3.0] section (#6643).
Agent-Signature: claude-code-opus-5-5-unknown-reasoning on behalf of Harry Miller
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(status): complete the disclosure's remedy and pin its population
Maintainer review fixes for PR #5763 (adopt-pr iteration 1). Four of the
five review findings taken; the nit is declined with its measurement.
Finding 2 (minor, gate impact minor) - the printed remedy was incomplete.
The two counters come from the same scan as TotalIssues and are status-blind
with it, but the flags they named lift only the TYPE exclusion, so a CLOSED
gate was counted while `bd list --include-gates` still would not show it.
Gates are closed as the work they guard completes, so that is the ordinary
case rather than an edge.
Took the "complete the hint" arm over the "scope the counters" arm. Every
other field ScanIssueCountsInTx fills is workspace-wide; the disclosure
exists to account for TotalIssues, a database number printed three lines
above it; and scoping these two to the listing's population would leave them
explaining nothing about the total they are broken out of. `--all` "replaces
the status exclusions only" and lifts no type exclusion of its own
(backend/conformance/reader_contract.go:487), so the two flags together are
exactly the remedy. Recorded the population in the types.go field comment,
the status.go doc, and the CHANGELOG, which printed the old example verbatim.
Finding 3 (minor) - the three new conformance cases seeded only open rows,
so a backend counting over every status and one counting only the listing's
population returned identical numbers on all of them. Added a closed gate and
a closed proto to the first case. Proved it now decides the question: scoping
both SQL SUMs with `AND status <> 'closed'` reds exactly that case
("GateIssues moved by 1 (0 -> 1), want 2") while the all-open sibling
BreaksOutAGateThatIsAlsoATemplate stays green.
Finding 4 (minor) - the normative role doc in issueops/statsreporter.go
enumerated only the six prior counts. Added the two to that scan's bullet and
corrected two statements this PR had falsified: the headline "six counts of
one set", and the AssigneeStats bullet's "the fold ... tallies the five
statuses and nothing else", which stopped being true when the fold gained the
two increments.
Finding 1 (minor, gate impact minor) - ran `make bazel-sync`. It proposed
exactly one line, `+ "status_suppressed_test.go"` in cmd/bd/BUILD.bazel, and
nothing else, confirmed by porcelain rather than by bazel-sync-check.
Generator-owned, not hand-edited.
Finding 5 (nit) - declined. The three helpers already in package main
(pluralIssue, pluralize, plural) all DERIVE the "s" and cannot render a
caller-chosen pair; the tree's one two-form helper, pluralWord, is unexported
in internal/storage/issueops, and exporting it so a CLI string could reach it
would add exported surface to a storage role for a cosmetic. Recorded that
trade in pluralCount's doc comment instead.
Validation: `go build ./...` and `go vet` (6 pkgs) clean, gofmt clean,
`git diff --check` clean; cmd/bd 4/4 named PASS, internal/httpapi
TestWireTagBijection|TestSpec* PASS, internal/workapi PASS,
internal/storage/uow TestStatsReporterContract 18/18 subtests PASS. Both new
pins are mutation-proved: reverting `--all` reds all four table cases, both
flag subtests and the render-path pin, while the absence assertion stays
green.
Not done here: the PR body carries the same stale example line
("1 gate (--include-gates)"). Review iterations do not touch the PR surface,
so that correction is stamped for finalize.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
The update operation had no way to express a claim, so an HTTP client of
`bd serve` had to refuse `bd update <id> --claim` outright. The request now
carries a `claim` boolean that passes straight through to
issueops.UpdateRequest.Claim on the same lifecycle role the direct route
uses, so the claim and the patch land in one transaction with the direct
route's semantics: same-actor re-claim is idempotent (changed: false), a
foreign holder is 409 already_claimed and an unclaimable status 409
not_claimable, both naming `claim` and carrying {id}:claim's extension
members (shared through claimRefusal), and a refused claim writes none of
the patch.
With claim: true the patch may be empty (the claim is the whole write).
claim beside expected_assignee, expected_status or force_assignee_transfer
is refused at the edge as a 400 naming `claim` rather than surfacing the
role's ErrValidation as the generic patch 400. No capability token: per the
document's version-skew rules, member presence is probed, and an older
server refuses `claim` as unknown_parameter before any database work.
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Co-authored-by: Eddie the Engineer <adopt-pr@gascity.local>
* feat(count): --include-ephemeral, the plane knob `bd count` never had
`bd count` can admit the wisps table only through `--include-infra`, which
makes four changes at once. This adds the flag that makes just the first one,
mirroring the `--include-ephemeral` that `bd list` gained in #6098.
## Why the plane is unreachable on its own
The write path routes on STORAGE CLASS, not type — dolt's `useWispsTable` is
`Ephemeral || NoHistory || WispType != "" || IsInfraType`. So a `no_history`
task lives in the wisps TABLE while remaining ordinary durable work, and a
default `bd count` never sees it.
Recovering it today means `--include-infra`, which this repo's own doc calls
"FOUR changes at once and not one": it admits the plane, drops the infra-type
exclusions, changes the template treatment, and reconciles cardinality with
`bd list --all`. Its template exclusion then silently drops template rows of
the named type — so a caller who wanted the plane trades one silent undercount
for another.
`ListRequest.IncludeEphemeral` has been the narrow answer on the listing side
since #5476, and #6098 gave it a CLI flag. `CountRequest` had no equivalent
field at all. This is the missing half of that pair.
## The change
- `issueops.CountRequest.IncludeEphemeral` — the plane knob alone: exactly the
first of `IncludeInfra`'s four changes, with none of the other three.
- `internal/workapi/count.go` — one line, `} else if !in.IncludeEphemeral {`.
- `cmd/bd/count.go` — flag registration, matching `bd list`'s wording.
- `internal/httpapi` — `include_ephemeral` on `countIssues`, in the spec; the
generated `types.gen.go` is `make api-gen` output, not hand-edited.
Unset, the count is durable-plane only: the historical answer, unchanged. Every
default is untouched.
It does NOT promise a count and a listing agree. They already differ on
TEMPLATES without this flag and still do with it — a count includes template
rows unless `IncludeInfra` excludes them, a listing excludes them unless
`IncludeTemplates` admits them. That predates this and is unchanged by it; only
`IncludeInfra` sets out to reconcile cardinality, and it pays with three
changes beyond the plane.
## Verification
ok github.com/steveyegge/beads/internal/workapi
ok github.com/steveyegge/beads/internal/httpapi
ok github.com/steveyegge/beads/issueops
--- PASS: TestEmbeddedCountIncludeEphemeral (39.71s)
--- PASS: TestCountIncludeInfraFlagShape
--- PASS: TestParseCountRequestCarriesEveryFilterFlag
`TestEmbeddedCountIncludeEphemeral` was run with `BEADS_TEST_EMBEDDED_DOLT=1`
and really executed — 39.71s, not a skip. The default fast tier would have
skipped it and reported `ok`.
`make api-gen` reproduces `types.gen.go` byte-for-byte from the spec hunk, so
the two cannot drift apart in review. `go build ./...`, `go vet` and `gofmt`
clean.
Claude-Session: https://claude.ai/code/session_01X1jMLQTSrCwtzFRS1xeUC6
* count: reframe the comments for this repo, not the fork they came from
Review on #6240 (bee-ghosttrack): five comment blocks were written from the
fork's point of view and become false once merged here — "belongs upstream",
"the half that still has to go upstream", "the fork's old wide default",
and "upstream's default" meaning the current default.
Find-and-replace, as asked: the reasoning is kept, only the frame of reference
changes. "upstream's default" -> "the default before this change"; the bd
list sibling "landed in #6098"; the infra-type divergence is "pinned, not
fixed, here" with the reason; the embedded test's fork-maintenance history is
replaced by what it actually pins. No code changes.
* build(bazel): list the two test files this PR adds in their go_test srcs
Maintainer review fixes for #6240, review iteration 1. The synthesis and the
quality scorecard both returned approve with no required changes; this commit
takes the one minor whose subject is the PR's own added files.
Taken:
- Change Impact / Blast Radius (minor, gate impact minor). The PR adds
cmd/bd/count_include_ephemeral_embedded_test.go and
internal/workapi/count_skipwisps_test.go, but neither was listed in its
package's explicit go_test srcs, so the PR's own assertions were invisible to
`bazel test`. Both rows are now listed.
Gazelle's verdict, not a hand-guess: `make bazel-sync` was run (bazel 9.2.0 is
available here) and it produced exactly these two entries. Its full output
also rewrote 12 other BUILD.bazel files -- pre-existing base drift from other
PRs' files, plus dep/select churn -- which is out of scope for this PR, so the
generated result was reverted and only the two rows this PR is responsible for
were re-applied, at the slots gazelle chose. Both srcs lists remain sorted
with no duplicates (cmd/bd bd_test 637 entries, internal/workapi workapi_test
24 entries).
The cgo build tag on count_include_ephemeral_embedded_test.go does not exempt
it: the repo lists tag-gated *_embedded_test.go files anyway (99 of the 101 in
cmd/bd are listed, and the sampled ones are simultaneously listed and tagged).
Declined:
- Test Evidence Quality (nit, gate impact none). The filing lane itself marked
it optional and explicitly said not to gate on it, and its own reasoning holds:
internal/storage/dolt/counts.go and internal/storage/embeddeddolt/counts.go
both delegate to the same issueops.CountIssuesInTx, differing only in
transaction acquisition.
Validation: go build ./... and CGO_ENABLED=1 go vet on cmd/bd, internal/workapi
and issueops all clean; go test ./internal/workapi/ ./issueops/ ok. No
production code changed -- the commit is two generated-list rows.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
---------
Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
bd list, bd ready and bd search all take --has-metadata-key. bd count did
not, so counting the rows that merely carry a key meant listing them and
measuring the page. This is the last metadata-filter parity gap between
count and the listings.
The storage layer already carries the filter: types.IssueFilter has
HasMetadataKey and sqlbuild.AppendMetadataClauses consumes it. What was
missing is the role field, the builder wiring, the CLI flag and the HTTP
contract, so this is one change rather than a stack.
Parsing matches list_input.go and ready_input.go, including the key
validation. BuildCountFilter now passes the key to ValidateMetadataFilters
instead of the empty string it passed before, which makes the role's
existing refusal reachable from the count surface; failReadErr already
classifies that error as a 400 on has_metadata_key.
apigen types are regenerated from the spec via go:generate, not hand
edited. The pinned CLI docs are untouched.
Fixes#6160
Co-authored-by: postoso <postoso@users.noreply.github.com>
Co-authored-by: Gas City Adopt-PR <noreply@example.com>
* build(bazel): add side-by-side Bazel scaffold (module + gazelle)
Add a Bzlmod Bazel build alongside the Go toolchain. `go build` and
`go test` are unchanged; nothing in CI invokes Bazel yet.
- MODULE.bazel: rules_go 0.63.0, gazelle 0.53.0, Go SDK 1.26.7 (matches
the go.mod toolchain directive), go_deps from go.mod.
- ICU policy (engdocs/ICU-POLICY.md): a go-mysql-server gazelle_override
selects the pure-Go regex backend and excludes regex_cgo.go, and
.bazelrc builds with --@rules_go//go/config:tags=gms_pure_go, so no
target depends on go-icu-regex or links libicu.
- third_party/patches: three module_override patches for dolt deps that
ship WORKSPACE-era BUILD files, adapted from the gascity project.
- .bazelrc: prcore/ci test configs (inert for now; they match pr-core's
test selection, not yet its environment isolation) and a generic
remote-exec config with a bounded remote timeout. Executor endpoints and
TLS credentials come only from a gitignored .bazelrc.local/user.bazelrc
or a CI rc outside the workspace.
- .bazelversion pins Bazel 9.2.0; .bazelignore skips separate modules,
non-Go trees, nested agent worktrees (.claude, .worktrees) and local
data/output dirs (.beads, .dolt, dist, .runtime, tmp), so a primary
checkout neither builds nor gazelle-rewrites nested worktree copies.
- Gazelle-generated BUILD.bazel files for every Go package.
- Makefile: `make bazel-sync` (gazelle + bazel mod tidy).
- .gitignore: bazel-* output symlinks and machine-local rc files.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* test(bazel): policy tests for the Bazel configuration
Add scripts/bazel_policy_test.go, plain Go tests that run under both
`go test ./scripts` and `bazel test //scripts:scripts_test`:
- MODULE.bazel go_sdk.download version equals the go.mod toolchain.
- ICU policy: .bazelrc sets gms_pure_go for build, the go-mysql-server
gazelle_override excludes regex_cgo.go, and the root BUILD.bazel
carries `# gazelle:build_tags gms_pure_go`.
- .bazelversion pins an exact Bazel release.
- .bazelrc.local and user.bazelrc are gitignored (parsed from .gitignore
and cross-checked with git check-ignore when in a checkout).
- No remote-execution endpoints or credentials in committed bazelrc-like
files, Markdown docs or .github/**: remote/BES/TLS flags
(--remote_executor, --remote_cache, --bes_backend, --remote_header,
--tls_client_certificate, ...) with a literal value, with or without a
URL scheme, and non-loopback gRPC URLs in rc/.github files. Placeholders,
$VARIABLES, and loopback are allowed; Markdown gRPC URLs (OTel exporter
docs) are not flagged. Skipped outside a git checkout, e.g. in the Bazel
sandbox.
Each check is a pure function also exercised against fixtures that break
the invariant. The files the tests read are declared as data via
//:bazel_policy_files so they resolve from runfiles under Bazel.
scripts/check-build-tags.sh now treats Bazel invocations as governed by
.bazelrc: the shell command segment that invokes Bazel (split on &&, ||,
;, |, $( and backticks) is exempt from the per-line `go` tag check, while
a bare `go` in another segment of the same line is still flagged. When
any scanned file invokes Bazel (or .bazelrc exists) .bazelrc must set
--@rules_go//go/config:tags=gms_pure_go for build.
scripts/check_build_tags_test.go covers both in a temp repository.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(scripts): split bazel lines in pure bash so check-build-tags works with BSD sed
BSD sed (macOS) does not expand \n in s/// replacements, so the segment
split never happened and the Bazel-exemption tests failed on macos-latest.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* test(scripts): skip check-build-tags tests when bash lacks mapfile
macOS runners use /bin/bash 3.2, which has no mapfile; check-build-tags.sh
has always required bash >= 4, so the new tests are skipped there.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(list): expose comment bodies and mark the omission in bd list --json (be-73x)
`bd list --json` reported comment_count and carried no comment text and no sign
that any was missing. The consequence is not a missing field: a content search
over a listing answers with a well-formed, NON-EMPTY result set whose matching
rows are absent, and nothing about that answer invites a second look. An empty
result invites suspicion; eight rows do not.
Two halves, and the second is the one that fixes what was actually reported:
1. --include-comments on `bd list` populates each row's comments with the
full bodies, the list twin of `bd show --include-comments`. Opt-in: it
costs one query per row that has comments.
2. Every row with a nonzero comment_count whose bodies were NOT hydrated now
carries comments_omitted=true, by default, with no flag. A flag nobody
knows to pass does not fix a silent hole; a marker on the row does.
The bodies ride on types.Issue.Comments, which already carried the `comments`
key for export/import and was simply never populated on this path, so the only
new field is the marker.
Hydration is one shared body (workapi.HydrateListComments) called from BOTH
issueops.Reader.List implementations, the store-backed and the unit-of-work
one. Those are separate bodies that have answered one contract method
differently before; it runs in the page epilogue beside FinishPageAt, after the
trim, so a page never pays for rows it is about to drop.
The source parameter is a CONSTRUCTOR rather than a source, and that is
load-bearing. Building the unit-of-work comment source eagerly made a
capability only the opt-in path uses into a requirement every caller had to
satisfy, and turned `GET /v0/beads/issues` into a 500 on a provider without a
comment use case — on requests that had asked for no comments. A count-only
listing now constructs nothing, pinned by a test that fails if the constructor
is called.
Tests pin each implementation separately rather than duplicating: unit tests
over a fake source, an embedded-dolt test over the real CLI on the direct
route, and a proxied-server test over the real CLI on the unit-of-work route.
Sabotage-controlled three ways — no-op the shared body and all three suites go
red; unwire either reader alone and only that reader's CLI test fails, which is
what proves neither integration test is redundant.
Not addressed, deliberately: gt-mfp5 (bd comment does not advance updated_at,
the orthogonal recency axis) and be-ozp (bd ready --json carries no marker; it
does not route through Reader.Ready).
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XK4B7N2CrgfKGEQvDTPM4D
Executed-By: beadsrig/polecats/dag
* fix(list): do not read a skipped comment count as proof of no comments (be-73x)
Codex review of the parent commit, correctly.
`IncludeComments: true` combined with `SkipCounts: true` returned a page with
no comment bodies at all — no error, no marker, nothing — while
`IncludeComments` documents a guarantee to populate them. The hydration loop
skipped any row whose CommentCount was zero as an optimisation, and SkipCounts
zeroes every count: `issueops.ListRequest.SkipCounts` says in its own doc that
a zero then means UNKNOWN rather than none.
That is this bead's own failure mode reintroduced one layer down by the fix for
it: a silent, well-formed, empty answer to a request that asked for content.
I had considered the interaction and resolved it wrongly, in a comment reading
"the count is authoritative here because the JSON route never sets SkipCounts".
True of today's CLI callers, and not a property of the contract — issueops
.ListRequest is a PUBLIC request type and permits both fields at once. A
comment saying "X cannot happen because of how callers behave today" on a
public type is a bug with a justification attached, and worse than no comment,
because it tells the next reader the case was checked.
countsKnown is now a parameter rather than an assumption; call sites pass
!req.SkipCounts.
countsKnown true a zero count proves a row has nothing; skip its query.
countsKnown false query every row, because nothing proves otherwise, and
mark no row omitted, because comments_omitted asserts a
nonzero count the page cannot support.
The second half is the mirror defect on the marker path — the same conflation,
the other direction — which the review did not name.
No behaviour change on any current CLI path: the JSON route never sets
SkipCounts, so it passes countsKnown true, and the text route asks for no
comments and marked nothing before either. Verified: `bd list --json` output
identical, and text output identical with and without the flag.
Regression tests HonorsIncludeWhenCountsAreSkipped and
MarksNothingWhenCountsAreSkipped. Sabotage-controlled: restoring the
count-authoritative skip fails the first with "issued 0 comment reads, want 2".
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XK4B7N2CrgfKGEQvDTPM4D
Executed-By: beadsrig/polecats/dag
* fix(list): resolve the comment plane by residence, not by the row's flags (be-73x)
Maintainer review fixup for #6473, iteration 1. Both review lanes reached the
same major independently and the synthesizer re-verified it against the tree.
The new list hydration derived the comment table from the row's own
Ephemeral/NoHistory flags - issueops.IsWisp's rule, which is right for routing a
record being WRITTEN and wrong on a read. `bd import` pins a `no_history` record
to the DURABLE table while preserving the flag on the row, because clearing it
would change the content hash and break export->import->export byte-identity,
and every clone materializes its database by importing JSONL. So a promoted
no-history bead that has been through a round-trip is a durable row whose flags
say wisp:
bd list --json --include-comments read wisp_comments, found nothing, and
returned comment_count=N beside an empty
`comments`, with no marker and no error
bd comment, bd show write and read that same row's comments on
the issues plane, by found-table
That is be-73x's own failure mode reintroduced under the flag whose contract is
"gets them or gets an error", and a cross-role divergence: `bd list` and
`bd show` disagreed about one row. The mirror case is real too - an import
record whose `wisp_plane` key pins it to the wisps table with neither flag set
reads back as durable - so no flag-based rule gets both directions right.
The plane now comes from the seam that knows it. HydrateListComments takes a
CommentPlanes lookup instead of inferring; the unit-of-work reader answers it
from the wisps TABLE (IssueUseCase.GetWispsByIDs, the call edgeReader.ReadEdges
already makes for the same question), once per page, inside the page's own read
transaction. The store-backed seam passes SourceRoutesCommentPlanes because its
source routes ids itself (DoltStore.GetIssueComments picks the table from
isActiveWisp) and would buy a lookup for an argument it ignores. isWispPlane is
deleted: nothing on this path infers a plane any more. A nil lookup is an error
rather than a silent "durable", so a third seam has to answer the question
rather than inherit the default this bug was.
A MISSING WISPS TABLE STAYS "NO WISPS" rather than a failed listing, classified
through the same two helpers the counts query that produced the page uses
(dberrors.MissingTableName + sqlbuild.OptionalWispTable). Any other failure of
the lookup fails the call: a guessed plane answers with the wrong table's
contents and nothing in the response shows it.
Tests. The unit table now asserts residence AGAINST the flags, with each row's
comments present only on the plane it lives on, so a wrong-table read shows up
as missing TEXT and not merely as a wrong flag in a recorded call. Restoring the
flag inference reds exactly the two rows where flags and table disagree
(durable-carrying-no_history, wisp-table-carrying-no-flags) and leaves the two
agreeing rows green. The old `override_wins_over_flags` case is gone:
WispPlaneOverride is `json:"-"` and set only by import, in memory, so no scanned
row can carry it and that branch was unreachable on this path - which is what
made the suite look sufficient (Codex's separate minor, folded in here as the
same root cause). New seam-level tests drive the real uow Reader.List over both
shapes, and pin that a listing without the flag resolves no planes at all, that
a missing wisps table is tolerated, and that any other lookup failure
propagates; emptying the residence answer reds the wisp-row leg.
Also from the review, non-gating:
- types.IssueWithCounts.CommentsOmitted and the OpenAPI property stated the
marker rule unconditionally on a type Reader.Ready and the claim response also
return, neither of which calls the epilogue. Both now scope the rule to the
List surfaces and cite be-ozp, which is where the parent commit deliberately
left the ready surfaces. (`bd ready --json` does not route through
Reader.Ready; GET /v0/beads/ready and ClaimNextResponse.claimed do.)
- GET /v0/beads/issues gained no `include_comments` parameter, so its
description now says so and points at the detail read, in the idiom the
`revision` paragraph above it already uses.
- One internal/httpapi list test for the new wire field: the marker present for
a commented row, absent for an uncommented one. It was asserted only by the
spec file; the detail twin has get_issue_test.go. Neutering
markCommentsOmitted reds it.
Validation: go build ./...; go vet over the changed packages and again with
CGO_ENABLED=0; make api-check clean, so the spec edits oblige no regeneration;
go test ./internal/workapi/... ./issueops/... ./internal/types/;
TestBothReaderImplementationsAgreeOnTheListEpilogue plus the new plane tests in
./internal/storage/uow/; BEADS_TEST_PROXIED_SERVER=1
TestProxiedServerListComments 3 PASS and BEADS_TEST_EMBEDDED_DOLT=1
TestEmbeddedListComments 4 PASS.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
---------
Co-authored-by: Julian Knutsen <julianknutsen@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Forward-ports the 38 commits that shipped on release/1.3.0 (tagged v1.3.0 at
f45b249ce) into main, as RELEASING.md mandates after a tag. None of them had
ever been forward-ported. Recorded as a merge so main becomes a superset of
the release branch and the lineage is in the history.
Migration ordinal collision (the reason this needed a human-shaped merge):
both branches independently claimed clone-local ignored slot 0026 under
different filenames, so git merged both in with no conflict and left the
series with two migrations at ordinal 26 — a single-integer cursor cannot
address that, and migrationSource.list() panics on it.
Main's ignored/0026_add_wisps_current_revision is renumbered to 0027.
Release's 0026_dep_rekey_dedup_marker is in the shipped v1.3.0 tag, so field
stores have already recorded it at 26 and it can never move; main's twin has
never shipped in any release, so it is the one that is free to move. 0027 was
unused in the ignored series (both sides topped out at 26).
This trips check-migration-hygiene.sh Check C (frozen migrations), which has
no exemption mechanism. That is expected and accepted: breaking the collision
requires a rename, and the ignored series' cursor table is itself dolt-ignored,
so its content hashes are clone-local and never participate in the cross-clone
ContentHashSkew comparison that Check C exists to protect. Main's 0067 body is
deliberately NOT edited for the same reason in reverse — it is main-plane and
its hash IS compared across clones.
Conflicts resolved:
CHANGELOG.md release's finalized [1.3.0] section kept
byte-identical; main's two unreleased
entries (#6023, #5859) moved up under
[Unreleased] where they belong
cmd/bd/init_safety.go union — release's added paragraph is
cmd/bd/init_safety_help.go accurate against the merged code (three
exit-12 sources, incl. init.go:3147)
internal/storage/uow/dolt_sql_provider.go
kept main's newProvider refactor AND
release's readOnly field/assertion;
newProvider gained readOnly: opts.readOnly
so release's read-through-refused-migration
behavior survives main's refactor
.github/workflows/main.yml single -timeout=30m per release's #6091
scripts/ci_workflow_test.go design (flag on the invocation, not in
matrix.test-flags); the shadowed 25m in
matrix.test-flags removed
scripts/migration-test/lib/versions.sh
union — main's darwin/arm64 corpus plus
release's v1.2.2 linux/amd64 entry
integrations/beads-mcp/uv.lock ruff 0.16.5 (release, newer); block is
internally consistent, uv lock --check ok
default.nix vendorHash left at main's value and is
KNOWN STALE — see below
Version stamp lands at 1.3.0 (main had been sitting at the previously-released
1.2.2, this project's between-releases pattern). check-versions.sh: 24/24.
Known follow-up: default.nix vendorHash. The merged go.mod/go.sum is a genuine
union (release's kin-openapi/oapi-codegen bumps + main's newer Dolt stack) and
matches neither side, so neither recorded hash is correct. It must be
regenerated with scripts/update-nix-vendorhash.sh. The repo's automatic fixer
(update-vendor-hash.yml) is dependabot-only and will not run on this PR.
* refactor(create): extract resolveCreateStorageClass from the direct RunE
The flag→class block (parse, per-type config fallback, ephemeral spelling →
wisp plane, --no-history exclusivity, plane reconciliation) becomes one helper
so the other CLI doors can call the same decision instead of reimplementing or
skipping it. Pure refactor: the direct route's behavior and error strings are
unchanged.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* fix(create): wire --storage-class through the proxied, markdown, and graph doors
createInput carries the resolved class, so the proxied single create persists
it, routes `--storage-class ephemeral` to the wisp plane, rejects a durable
class paired with --ephemeral/--no-history, and honors the per-type
storage-class.<type> config default — all four of which it silently dropped.
buildMarkdownBatchRequest resolves the class per template, which fixes `--file`
on BOTH transports at once (one shared projection), and --graph now refuses a
plan-wide --storage-class the way it already refuses --mol-type, pointing at
the per-node storage_class field that works.
The v0 HTTP wire is unchanged: storage_class stays off the create member list
and unknown members are still refused by name. The spec gains one sentence
saying the per-type config defaults are CLI-door policy, so the divergence is
documented rather than silent.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* test(create): pin the storage-class contract on every CLI door
The pure table covers resolveCreateStorageClass end to end (three classes,
config default, alias-normalized type key, both conflict arms) plus the two
links the proxied bug broke: gatherCreateInput populating createInput and
buildCreateIssueFromInput carrying it.
storage_class_proxied_integration_test.go is the proxied mirror of the embedded
suite, asserting the raw storage_class cell on the plane each request should
have landed on — the JSON alone would have agreed with itself. It reproduces
what the field report hit (unversioned dropped, an ephemeral request minting a
durable row, the wisp-plane conflict silently collapsed, the config default
skipped) as failing assertions.
The embedded suite grows --file subtests on all four class outcomes and the
--graph rejection.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
* fix(metadata): restore v1.2.2 scalar typing for --set-metadata values
8ebd53e88 moved the CLI's metadata-edit helpers into
internal/storage/metadata.go and, in the move, replaced v1.2.2's
toJSONValue inference with a MetadataEditValue that always json.Marshals
the value as a string. The intent was GH#4146 (a numeric-looking id or a
version like "1e3" came back as a JSON number, breaking map[string]string
Go consumers), but it silently changed the shipped CLI contract:
`bd update --set-metadata k=5` started storing "5" instead of 5. That
regression shipped only in the deprecated/superseded v1.2.1, never in
v1.2.2, and 1.3.0 would freeze it.
Restore v1.2.2's inference body-for-body inside MetadataEditValue, so the
parity claim stays checkable against `git show v1.2.2:cmd/bd/update.go`:
"null" is JSON null, "true"/"false" are booleans, a spelling that scans
as a float AND is valid JSON on its own is emitted as that literal
(5 -> 5, 1e3 -> 1e3, 0.50 -> 0.50, while 05, +5 and NaN stay strings),
and everything else is a string. Every --set-metadata caller funnels
through this one function: embedded (cmd/bd/update.go ->
storage.ApplyMetadataEdits), proxied (parseSetMetadataFlags) and the
update executor's []string path.
GH#4146's concern is served by the explicitly typed routes, which are
untouched: --metadata / --metadata-json on the CLI (MergeMetadataJSON)
and the typed set map on the HTTP/Go path (applyTypedMetadataEdits).
No data migration: a "5" written by an in-window build is
indistinguishable from a string a user set intentionally through the
typed paths, so normalizing stored metadata would corrupt intended data.
Re-running the same --set-metadata k=5 retypes any given key.
Tests: new table in internal/storage/metadata_edit_value_test.go pinning
the v1.2.2 matrix plus an ApplyMetadataEdits end-to-end; the tests that
pinned the string-always behavior are flipped (domain/db mergeops suite,
update_lifecycle patch mapping, cmd/bd toJSONValue table) and the
embedded + proxied CLI suites now assert a stored JSON number. The
contract corpus is regenerated: its update/list/ready goldens run
`--set-metadata phase=2`, so `"phase": "2"` becomes `"phase": 2` and
nothing else moves.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* fix(create): echo full-precision timestamps from bd create, not the DATETIME(0) re-read
b92442d1a routed `bd create` through issueops.Lifecycle, whose executors
build their result by re-reading the row they just wrote
(HydrateIssueOperationResult -> GetIssueInTx). created_at/updated_at are
DATETIME(0) columns, so that snapshot comes back at whole-second
precision and cmd/bd/create.go echoes it. v1.2.2 returned the caller's
own in-memory struct, which PrepareIssueForInsert stamps with
time.Now().UTC() including nanoseconds, so `bd create --json` used to
print e.g. 2026-08-28T12:34:56.789012345Z. Agents that create several
issues in a burst order them by exactly that fraction; rounded to the
second they all tie.
Restore the echo with OverlayCreateTimestamps: after hydration, put back
the created_at/updated_at (and closed_at, when the write set one) the
INSERT actually sent. Everything else on the snapshot stays DB-truth,
which is the facade's contract — only create, and only these fields.
Applied at every create body, not just the two the CLI reaches:
issueops.ExecuteCreate and ExecuteCreateBatch behind the dolt and
embedded-dolt stores, and the unit-of-work provider's own Create,
CreateBatch and batch-apply create item, which is what the proxied server
and POST /v0/beads/issues run on. Fixing only the shared executors would
have left the two bodies disagreeing about the same promise.
What is NOT changed, because it is not a regression: `bd show --json` and
`bd list --json` answered whole seconds in v1.2.2 too — they read the
column — and update/close/reopen re-read after writing there as well.
Widening the columns to DATETIME(6) would give reads sub-second times
too, but that is a schema migration on user Dolt DBs and touches paths
that deliberately compare at second precision; it is a 1.4 change.
The accepted skew, which predates this and stays: the engine ROUNDS to
the column rather than truncating, so a later read of the same row can
sit up to half a second either side of the create echo.
Tests: two new conformance cases, run on all three backends —
RunLifecycleCreateEchoesSubSecondTimestamps (a caller-supplied
nanosecond stamp must survive to the result exactly; the auto-stamped arm
stays a bounded smoke check, since requiring a non-zero fraction off the
clock is flaky by a billionth) and RunBatchCreatorEchoesSubSecondTimestamps
(per item, since both bodies build the result one snapshot at a time).
Plus a cmd/bd embedded test asserting `bd create --json` prints a
fractional part, and one httpapi assertion that the wire does not round
the role's snapshot on the way out. All four fail on the pre-fix tree.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* fix(httpapi,types)!: revision / expected_version tokens are opaque JSON strings
The optimistic-concurrency token is minted by freshRowLock over the FULL
int64 range (crypto-random, non-zero) and published on the wire as a JSON
number: `revision` on responses, `expected_version` on guarded requests.
A JSON number does not survive a consumer that decodes into an IEEE-754
double — JavaScript's JSON.parse, Go's `any`, Python's `float`, jq. Live
tokens run past 5e17, where a double's ulp is already 64, so such a
client reads back a value NEAR the token, echoes that as its guard, and
earns a 409 against a row nobody else touched. The spec already carried
"DECODE IT AS A 64-BIT INTEGER" paragraphs telling clients to work around
this; that is a workaround for a wire type that should not have been a
number.
Emit and accept the token as a decimal STRING instead. It is documented
as opaque and EQUALITY-ONLY — compare it, never order or interpret it —
and a string round-trips exactly in every JSON consumer. It also leaves a
future backend free to mint a token that is not an int64 at all.
Internals are untouched: freshRowLock, the row_lock BIGINT column, its
migration, types.Issue.RowVersion and the ExpectedVersion *int64 guards
on the issueops requests all stay int64. Only the wire projection moves,
through the one spelling of the encoding — types.RevisionToken and
types.ParseRevisionToken.
STRICT STRING ONLY, with no transitional number-or-string acceptance.
This API already refuses unknown members by name and keeps one spelling
of the guard, and a number is precisely the shape a double-based client
has already rounded before it left the client — accepting it would
preserve the defect. A numeric guard is a 400 naming the member.
Chosen over clamping freshRowLock to 53 bits: a clamp does not fix rows
already minted with full-range tokens by in-window builds, so a JS
consumer reading one still rounds past 2^53 — repairing that would need a
row_lock normalization sweep over issues and wisps, a migration days
before a tag.
Surface: types.IssueDetails.Revision (what `bd show --json` prints and
GET /v0/beads/issues/{id} returns), the five hand-assigned httpapi
response fields, applyVersionGuardMember (now the reader for the batch
update item too, ahead of its typed decode, so a mistyped token still
earns a 400 naming the member), Problem.expected_version, and 14 OpenAPI
members regenerated through `make api-gen`. actual_version goes with them
— it is documented as "the `revision` the row was found holding", so
leaving it an integer would make the expected/actual pair disagree about
its own type; it is declared but never populated, so nothing changes
behaviorally.
Nothing shipped in a tagged release ever carried this member: v1.2.2 has
no internal/httpapi at all and no `revision` anywhere on the wire, so the
whole surface is in-window and can still be changed compatibly. Legacy
migration-0054 rows read as the string "0" with the same CAS semantics.
Corpus goldens are UNCHANGED: the canonicalizer already replaced any
`revision` value with the string "<REVISION>" whatever its JSON type.
Tests: types-level pins that the marshaled member matches `"revision":
"-?\d+"` and that RevisionToken/ParseRevisionToken round-trip MinInt64,
MaxInt64 and 2^53+1, plus a JS-realistic decode of 2^53+1 with a float64
control proving the token really is one a number would corrupt; httpapi
refusal tests for a numeric guard on update, close, reopen, delete and
both batch item kinds; a 409 echo asserted as the string; and the proxied
serve integration tests now splice the response's own token back in
verbatim rather than re-rendering a parsed one.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
* feat(httpapi): serve `bd list`'s order with `sort` on listIssues
The issue listing served one order, `(created_at DESC, id ASC)`, because the
cursor is a keyset position in it. The spec stated the constraint in its own
words: "the sort order is welded to the cursor contract, and a new order needs
new surface." That welding put the cost on every client wanting `bd list`'s
ordering — the only way to get it was to page the whole result set and sort
locally, which is the one cost on this surface that grows with the project.
Measured against a real `bd serve` over 1400 rows at the 200-row page an HTTP
client actually uses: walk-and-sort is 7 requests plus a client-side
comparator, `?sort=priority` is 1. Both are checked against `bd list --json`
row for row, because the claim that matters is not "fewer requests" but "the
same order".
`sort` takes `created` and `priority` and nothing else. Each value is a keyset
contract — a position shape, a strictly-after predicate, an index — not a
display preference, and both keys are provably total (priority and created_at
are non-null, id is unique) so a page boundary inside a run of equal keys
resolves on id. The seven other orders `bd list --sort` takes have no such key:
`id` is natural-numeric and no database expresses it, `updated` moves on every
write, `closed` is nullable, and status/title/type/assignee are mutable and
unindexed. `priority` here is (priority ASC, created_at DESC, id ASC), which is
both `bd list`'s flagless order and what `--sort priority` produces — a stable
priority sort over the created order is the same sequence — so one served order
retires the walk for both.
Absent `sort` still means `created`, permanently: it is the compatibility
contract for every client written before the parameter existed.
THE CURSOR NOW CARRIES ITS ORDER. This is the half that makes the parameter
safe rather than merely useful, and the obvious implementation gets it wrong.
The token was base64 of `{t,i}` with no binding, so a created-order cursor
replayed under `sort=priority` decoded perfectly and was read as a position in
a different total order — a page that skips and duplicates rows, served with a
200, undetectable by the client. Tokens are now `v2` with an explicit order
member, and decode takes the wanted order as a parameter so a mismatch is
unrepresentable at the seam rather than merely detectable past it. Outstanding
`v1` tokens stay readable as the created-order positions they are, so no
traversal in flight has to restart. This does not contradict "the token carries
no filters": filters select the set, the order decides what the position means.
Storage grows one field. IssueFilter.AfterPriority extends the existing
position; the predicate nests the created one rather than restating it, because
the created/id comparison is only reachable at the cursor's own priority.
Flattening it the way the created predicate's leading-bound trick invites looks
equivalent and is not — it re-delivers rows at the cursor's priority created
after it, which the new conformance walk catches against real Dolt.
NO INDEX MIGRATION, by measurement rather than by omission. A composite
(priority, created_at, id) index was tried on Dolt 2.2.0 against the production
predicate, in both the plain ascending and the mixed-direction spelling Dolt's
DDL accepts: the plan is byte-identical in all three cases, keeping the
single-column priority seek and the TopN. It would have bought write
amplification on every insert and every priority update for no measured change.
The sargability guard pins what is achieved — an IndexedTableAccess range on
idx_issues_priority — and records the measurement to redo if Dolt learns to
stream the composite.
Agent-Signature: claude-opus-5
Co-authored-by: CI Bot <ci@beads.test>
* fix(changelog): drop leftover diff3 conflict marker in sort entry
The rebased adopt-PR head left a stray '|||||||' merge-base marker on the first line of the new `sort` CHANGELOG entry (CHANGELOG.md:381), which `git diff --check` flagged as a leftover conflict marker. Remove only the marker line; the resolved entry content is unchanged. Maintainer fixup for PR #5666 adoption review.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
---------
Co-authored-by: CI Bot <ci@beads.test>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
* feat(events-journal): record the mutating actor on every journal row (bd-mbrxm)
The bd_events_journal row recorded op/ts/issue_id/payloads but never WHO
performed the mutation, so downstream attribution (e.g. same-field,
different-actor conflict detection over the journal) had nothing to key on.
- Schema: `actor VARCHAR(255) NOT NULL DEFAULT ''` on bd_events_journal, on
both migration planes (0066 + ignored/0025) so the two-door shape converges.
- Record*InTx takes the actor explicitly (no ambient ctx) — every call site
already sits beside an audit-event emit that has the actor in hand; thread
that same value (incl. the UOW door's MovePersistence). Comment rows carry
the comment's author. Blank = unattributed (derived maintenance, deletes —
follow-up bd-zxt49 — and pre-column rows); never user attribution.
- `bd events tail/export` JSON gains an additive, omitempty `actor` field;
the wire vocabulary is otherwise untouched (openapi spec, reference doc,
CHANGELOG; golden regenerated deliberately).
- CLI bundle: direct-DDL override for 0066 in cliCompatibleMigrationSQL —
dolt 2.2.0 (CI's pin) no-ops the prepared ALTER (dolthub/dolt#11345), so
without it the parity oracle sees actor only on the runtime side. Measured:
AllMigrationsSQL() through 2.2.0 lands bd_events_journal WITHOUT actor and
2.3.1 WITH; with the override both land it. String assertions + a
requireDoltColumnShape guard pin it without a Dolt binary.
Verified (enumerated): go build ./...; gofmt; go vet; migration hygiene
(BASE_SHA=07c163df0); internal/storage/schema (string test + CLI-apply test
under dolt 2.3.1 AND 2.2.0); internal/storage/domain/...; eventsjournal;
journalops; httpapi (wire-tag bijection incl. actor); storage/dolt
-run 'Journal|EventsJournal|ActorAttribution' against real dolt;
cmd/bd -run Events (golden); storage/uow -p 1 (-timeout 90m): every test green except 3
timeout-shaped reds (ConcurrentInstantiation lock-acquire, EndToEnd 30s
init-schema, PreexistingDirty docker reaper) in a /private/tmp worktree
under box load 40-68; the same 3 at origin/main in that worktree also
red, and at THIS commit in the primary clone all 3 PASS (130s) — box
flake, not the diff.
* docs(events-journal): align seq:4 example with the actorless golden fixture
Maintainer review follow-up on PR #5908 (bd-mbrxm). Both reviewers flagged that
the reference JSONL example's seq:4 is_blocked derived-maintenance row carried
"actor":"worker-1", contradicting the record-contract field table (derived
is_blocked recomputes are actorless) and the golden fixture
cmd/bd/testdata/events_journal_records.jsonl, which emits that same seq:4/bd-100
row without an actor. Drop the actor member so the doc example mirrors the
fixture byte-for-byte and consumers do not misclassify a system recompute as a
user write.
The other, optional review nit (the "stray typographic quote" in the
insertEventRow doc comment) is intentionally left as-is: that glyph is gofmt's
canonical rendering of '' in a Go 1.19+ doc comment (TeX-style quoting turns two
ASCII apostrophes into U+201D), so the reviewers' literal '' suggestion is a
no-op the enforced pre-commit gofmt reverts on every commit. It is cosmetic and
non-gating; the DDL and INSERT are already correct.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
---------
Co-authored-by: Eddie the Engineer <julianknutsen@users.noreply.github.com>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
GET /v0/beads/context required both. They are the only two members of the
identity handshake that describe the SERVER's filesystem rather than the
workspace's logical identity, and an absolute host path is not something a
remote client can act on: it cannot open it, and project_id, database and
backend are what tell two servers apart.
The schema already called publishing them a cost "an operator accepts when
binding beyond loopback". While they were required, accepting it was the only
conforming option -- a deployment that did not want to disclose its filesystem
layout had no way to withhold them and still serve a body matching this
document. Making them optional restores that choice, in the only direction
that cannot break a client that was already reading the document.
No body changes. bd serve publishes both, always, exactly as before; the
optionality is a promise to clients that absence is legal and must be
tolerated, not a switch on the server. In Go the two generated members become
*string, and the handler takes the addresses of the same published values.
TestContextResponseRequiredSet pins the split from both sides -- the
document's required list and the generated struct's pointer-ness -- so
re-requiring a member re-imposes the disclosure only with a test edit, and
dropping one that belongs there fails the same way.
Co-authored-by: CI Bot <ci@beads.test>
* test(feat): red — canonicalActor collapses the --/__ axes: misses gascity slash identities and widens ActorMatches (bundled with be-vc51 authorize/verify split) (refs be-fh0g)
* feat: green — canonicalActor collapses the --/__ axes: misses gascity slash identities and widens ActorMatches (bundled with be-vc51 authorize/verify split) (refs be-fh0g)
* docs(identity): correct the five contract surfaces that still document the pre---- collapse rule
canonicalActor stopped collapsing an exact "--" run when it started decoding
that run to "/", but five places still tell a reader the old rule: a run of
".", "_" or "-" matches any other such run. That is now false for "--", and
two of the five are public contract surfaces rather than internal comments --
the OpenAPI description a client reads, and the conformance text a backend
implementor is expected to satisfy.
Corrected in place, all saying the same thing: an exact "--" run decodes to
"/" because that is gascity's session-name encoding of a rig-qualified
agent's slash, so "a--b" matches "a/b" and no longer matches "a__b" or "a-b";
longer and mixed runs, "__" included, still collapse.
issueops/releaser.go ExpectedAssignee's contract
issueops/issueops.go the update-side cross-reference
internal/httpapi/spec/openapi.v0.yaml wire contract (source of truth)
internal/httpapi/apigen/types.gen.go regenerated via make api-gen
backend/conformance/releaser_contract.go cross-backend contract text
The conformance limb is annotated rather than re-pinned: the respelling it
exercises is "-" -> "_", which this change does not affect, so it stays green
either way -- which is exactly why CI could not catch the stale text. Adding a
"--" limb there would pin new cross-backend behavior and is a wider change
than correcting a contract description.
This is the keep-in-sync obligation identity.go records under ga-5ksp5,
applied to the documentation half.
* docs(changelog): record the --/__ equivalence-class change under [Unreleased]
The actor-matching change is user-visible and silent: it moves which stored
spellings compare equal for ExpectedAssignee on release and update, and for
claim/close/unclaim authorization. "gastown--mayor" starts matching
"gastown/mayor" and stops matching "gastown__mayor" and "gastown-mayor".
The entry says the widening is the intended fix -- "gastown--mayor" is the
agent "mayor" on rig "gastown" while "gastown__mayor" is the dotted alias
"gastown.mayor", and matching them was wrong -- and then states the part a
reader actually needs to act on: any stored "--" spelling that is NOT a
gascity slash encoding changes equivalence class with no error to notice.
---------
Co-authored-by: Steve Yegge <steve.yegge@gmail.com>
* Publish PUT and DELETE /v0/beads/config/{key}, the write half of issueops.WorkspaceConfig (ga-098zm)
Settings are read-only over v0: `WorkspaceConfig.SetSetting` and `UnsetSetting`
have no wire operation, which leaves the infra-over-http surface able to see that
a workspace is configured and unable to configure it. These are those operations.
The role, its contract and all three legs already exist; this slice wires them.
Spec first, then `make api-gen`, then the handlers.
PUT AND DELETE ON THE KEY'S OWN PATH, and the methods ARE the argument rather
than a preference. The resource has a canonical URI, the caller names it, and the
request carries the value that becomes its whole state — that is what PUT already
means, and the write is idempotent in the strict sense. `POST /v0/beads/memories`
is the operation this is deliberately NOT: that one posts to the COLLECTION
because its key may be derived from the content, so the caller cannot always name
the resource it is creating. Here it always can. The removal is
`DELETE /v0/beads/memories/{key}`'s shape unchanged — one named resource, no body,
no flags — and all three rows share one pattern, differing only in method, which
ServeMux registers together.
THE KEY IS THE PATH'S AND APPEARS NOWHERE IN THE BODY, so `SetSettingRequest`
carries exactly one member. A body spelling the anchor a second time is one
request with two anchors and a question about what to do when they disagree; the
parity test asserts the absence from both sides.
## The redaction doctrine, and what the write half owes it
A KEY WHOSE NAME MARKS IT CREDENTIAL-BEARING IS WRITABLE, resolved from the
facade's actual behavior rather than from the shape of the read. `ValidateSettingWrite`
refuses an empty key, `issue_prefix` in either spelling, and a `status.custom`
that does not parse — and nothing else; `config.IsSecretKey` appears nowhere in
the write path. The CLI's own secret guard is `CheckSecretKeyGitSafety`, which is
gated on `IsYamlOnlyKey` and protects a git-tracked **config.yaml** — a different
plane with a different hazard, a credential in git history — and returns clean for
every key this operation reaches. The role states the asymmetry itself: the reads
are a firewall, the writes are not, and a write discloses nothing. Refusing here
would be a refusal the role does not have, invented by the projection, and it
would leave a workspace's credentials visible as PRESENT and permanently
unconfigurable through this door.
WHAT THE WIRE OWES INSTEAD IS THE RESPONSE. Redaction is caller-independent and
decided on the KEY, and `Setting.value` says in one place that a `redacted: true`
entry withholds a value that may well be stored — so a write answering with both
would make one schema mean two different things depending on which operation
produced it. The write is therefore projected by `wireSetting`, the SAME function
the read is projected by, and the test states that as an equality rather than as
two assertions that could drift: the body of a PUT is byte-for-byte the body of
the GET that follows it. It costs the caller nothing, because the role promises
the stored value equals the value sent for every key this plane accepts, so the
echo carries no information the caller does not already hold.
The removal publishes `key` and nothing else. No `removed` flag — the storage seam
discards the affected-row count on all three legs, so the member would be a value
one of them had to invent — and no `value`, which on the one settings operation
that withholds nothing would publish exactly the credential the read redacts.
## Absent-vs-empty, and the 404 that is not here
REMOVING A KEY NOTHING SET SUCCEEDS. This is where the operation parts company
with the memory delete it otherwise copies: that role reports Found, and `bd recall`
already has an exit-code contract for the miss. This one cannot — an absent key
and a key stored as the empty string are one answer on this plane, the same
conflation `GET /v0/beads/config/{key}` has no 404 for — so the operation states
an intended END STATE, and the same request twice is 200 and then 200. The
document also records what the removal does NOT undo: `status.custom`'s
projection survives the row it came from, on all three implementations
(bd-yby99.33), as does the protected key's write-refused/remove-permitted
asymmetry (bd-yby99.34).
The empty string is a legal VALUE and is stored, not read as a removal: a caller
that meant "remove it" has DELETE, and conflating the two would make one request
mean whichever the handler guessed.
## The one bound that is the write's alone
`config.key` is VARCHAR(255) and the PUT INSERTS into it, so an over-long key is
an error from the column — a 500 for a request the caller could have fixed. The
GET and the DELETE COMPARE the same value and never store it, so a key no column
could hold matches nothing and already has an answer, and refusing it there would
be a refusal the role does not have. That is `releaseExpectedAssignee`'s rule
applied to the other keyed plane, and the asymmetry is asserted in both
directions.
THE ROLE'S 400 CARRIES NO `param`, and that is the depguard rule doing its job
rather than a shortcut. Two of the role's refusals are reachable and they name
different members — the protected key, and a value that does not parse — and
telling them apart takes the role's protected-key VOCABULARY, which this package
cannot hold: `httpapi-transport-boundary` denies internal/workapi from every
non-test file here, precisely so a second copy of a shared rule cannot exist to
drift. `detail` carries the role's own sentence, which names what to send instead;
every refusal this handler owns names its member.
ONE STALE SENTENCE FIXED ON THIS SURFACE. `listSettings` justified redaction with
"this API has no authentication", which stopped being true when #5516 landed the
optional bearer and which #5545 rewrote everywhere except here; settings.go's file
comment carried the same sentence. Both now say what is actually load-bearing — a
configured bearer is a single shared token that decides WHO may call and never
what a caller who is let in may read — which is the statement this whole slice
depends on. `forgetMemory`'s description carries the same staleness and is left
for that surface's own change.
CENSUS +1 EACH, twice over: two spec paths on one existing path item;
SetSettingRequest and RemovedSetting; the document's no-query-parameter list and
its two counts; two route rows on the pattern the read already registers; two
capability tokens in the ContextResponse prose (the only hand edit — Capabilities()
is derived); OpSetSetting and OpUnsetSetting; two operationCodes rows
(getSetting's vocabulary, no code minted). NOTHING new in the role plumbing:
Config.Settings, sourceRoles, roleSourceNames and s.workspaceConfig() already
carry this role, and the hook decorator's WorkspaceConfig accessor deliberately
wraps nothing — the workspace hook vocabulary hands a script an ISSUE, and a
settings write has none to name, so there is no RoleFiresHooks case to add.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Bound the settings value at the edge, and pin PUT's idempotence and the no-leak in bytes
Review found this branch shipping the exact hazard its own key bound was written
to prevent, plus two properties driven live and pinned by nothing.
## `config.value` had no bound, and it is a TEXT column
`settingWriteKey` refuses an over-long KEY with a 400 naming the member, and the
comment on it says why: an over-long key would be "a 500 for a request the caller
could have fixed". The VALUE beside it had no such check and lands in a `TEXT`
column. Measured before the fix: a 100 KiB `PUT` is a generic 500 out of the
column — the one code that tells the caller nothing about how to fix it — on the
same operation, in the same PR.
Bounded at the edge, keyed on a storage constant rather than a literal, refusing
with `param: "value"` before the role is asked.
BYTES, NOT CHARACTERS, which is why this is `types.CheckTextLen` beside
`CheckFieldLen` rather than the same helper with a bigger number: MySQL and Dolt
bound a TEXT column by ENCODED length, so 40000 two-byte characters overflow it
while 65000 ASCII ones do not. A rune-counting bound would have accepted the
former and handed the 500 back. Both directions are pinned — exactly
`MaxTextBytes` is accepted and reaches the role, one byte more is refused, and
the multi-byte case is its own test — and all three mutations (bound removed,
runes instead of bytes, one byte too strict) fail it.
NOT WIDENED, deliberately, and this is the opposite call from the ephemeral
comment column in the commit before it. A comment is a DOCUMENT — a stack trace,
a diff, a transcript — and the two comment planes disagreeing about one was a
bug. A setting is a VALUE: nothing this plane holds is a megabyte of
configuration, so the narrow bound is the honest description of what a settings
row is for rather than a limitation to widen later. The spec now states the
number and the contrast instead of claiming the 1 MiB body cap is the only limit.
## Two properties that were driven live and pinned by nothing
PUT'S IDEMPOTENCE. The method's whole argument is that the same request twice
leaves the same row, and the E2E exercised it while no test asserted it. Now
pinned on both halves: the second response is byte-for-byte the first, and BOTH
calls reach the role — the second half matters because the role performs its
write and its projection unconditionally (a no-op detection would make repairing
a drifted table depend on the row having changed, which is the state that needs
repairing), so this surface must not short-circuit either. Verified with a
compiling short-circuit mutation, which the "want 2" assertion catches.
THE NO-LEAK GREP NOW READS RAW RESPONSE BYTES rather than the decoded map. The
integration test already greps marshaled JSON; the unit test was checking members
it had thought to name, which an extension member, a duplicated key or an echo
inside a `detail` string would all walk past. Demonstrated: a mutation that adds
a `stored_preview` member carrying the credential passes every member assertion
in that test and is caught only by the byte grep — which is also what a client, a
proxy log and an access log actually receive.
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>
* Publish POST /v0/beads/issues/{id}/comments, the wire half of issueops.Commenter (ga-rslox)
The commenter is one of the facade roles the ext-api-store audit lists with no
wire operation, and comment READS already ride `getIssue?include_comments=true`.
This is the write. The role, its contract and all three legs already exist; this
slice wires them.
Spec first, then `make api-gen`, then the handler.
IT IS A SUB-RESOURCE COLLECTION OF THE ISSUE, and the argument is
listRelatedIssues' applied to a write: the row this creates is the SAME pinned
`Comment` schema `GET /v0/beads/issues/{id}?include_comments=true` already carries
under `comments`, so the operation that appends one belongs on the resource whose
members it publishes. A PLAIN collection POST rather than a custom method, for
`POST /v0/beads/issues`' reason — creating one member of the collection a path
names is what POST already means — and the collision worth checking rather than
assuming is the POST wildcard: `/v0/beads/issues/{idop}` matches ONE segment after
`/issues/` and this path has two, so the dispatcher never sees a request for it.
Checked by driving the documented path, not by reading the pattern.
THE COLLECTION PUBLISHES NO GET, and that is a statement rather than a gap. No
role answers a comment PAGE: issueops.Commenter says reading the thread is a
second question with a cursor of its own, so a GET here would be this surface
inventing the role that declined to exist. A GET lands on the catch-all and gets
the 404 every method mismatch here gets; 405 is not in the v0 vocabulary.
`author`, NOT `actor`, AND IT IS STILL CALLER-ASSERTED. The two are not the same
member wearing a different name: an `actor` is the principal a mutation is
attributed to and is no part of what the mutation wrote, while this value IS part
of the row and is echoed back by every read of the thread — so it is spelled the
way the `Comment` element that carries it back spells it. It is NOT the
authenticated principal even where a bearer is required, on the claim's terms: the
token a deployment configures admits a client to the whole surface and names
nobody. A reader of the thread is reading a claim the writer made about itself.
THE TWO MEMBERS ARE VALIDATED TO DIFFERENT DEPTHS, and the difference is the
column. `author` lands in a VARCHAR(255) every renderer of the thread prints, so
it gets `actor`'s rules whole — trim, non-empty, 256 bytes, 255 characters,
no control runes — through validateNameMember, which is validateActor's body
parameterized by the member's spelling rather than a second copy of the bounds.
`text` lands in a TEXT column stored VERBATIM, so it is checked for SHAPE only:
no trim, no length bound, no character rule, because a comment is routinely a
stack trace or a diff and the newlines are the comment. Its one content rule —
blank after trimming — stays in the ROLE, rememberMemory's posture, so `bd comment`
and this endpoint refuse the same input with the same sentence.
A WISP IS A LEGAL TARGET, resolved from the facade body rather than assumed and
pinned against real Dolt: the anchor resolves across both planes, the comment
lands on `wisp_comments` and reads back from the ephemeral thread. Only the
DURABLE trace is absent — a comment on an ephemeral row records NO history entry,
because the wisp tables are dolt-ignored precisely so ephemeral work never ships.
NO CONFLICT CODE AND NO GUARD, and both absences are the contract. A thread is
append-only and this write touches no field of the issue, so there is no row state
for an `expected_version` to be stale about and no concurrent comment to collide
with. Not idempotent either — a retry appends a second row, because two identical
comments are a legitimate thread — and the proxied test asserts that against the
table rather than the handler.
ONE ARM IN THE FAILURE PATH, and the deleted one is evidence rather than taste.
There is no explicit ErrNotFound case: ClassifyError already carries that row, and
adding one back leaves the whole package green — measured, the way #5540 measured
the same redundancy. The 400 names `text` unconditionally because exactly one of
the role's three refusals is reachable: the edge refuses an empty author under
strictly stronger rules, and an empty id cannot arrive at all.
RoleFiresHooks DID NOT KNOW ABOUT THE COMMENTER, and publishing this operation is
what made that matter. hook_commenter.go has fired the update hook for every
comment it lands since it was written, and the switch that stops `bd serve` from
being handed a hook-firing role had no case for it — harmless only while no front
door took the role off a store. An unpeeled commenter runs the workspace's script
once per comment, which is exactly the write an agent makes in a loop. The case is
added and pinned from both ends.
CENSUS +1 EACH: spec path; AddCommentRequest schema; the document's no-query-
parameter list and its two counts; route row; capability prose (the only hand
edit — Capabilities() is derived); OpAddComment; operationCodes row
(getDependencyTree's vocabulary, no code minted); httpapi.Config.Commenter with
sourceRoles, roleSourceNames, the Server field, Listen and s.commenter();
timedProvider.Commenter and its CommenterSource assertion; checkedCommenter; and
the bd serve binding. Plus Commenter on serveRoleSource and both cmd/bd stubs,
which is #5539's return: a named build error in the file that has to grow a method.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Close the RoleFiresHooks blind spot as a CLASS, and finish 0049 on the ephemeral comment plane
Review found the first version of this branch overclaimed twice. Both claims are
now either true or gone, and both are held by a test rather than by prose.
## The hook guard was blind FOUR ways, not one
The commit said the commenter was "the one hook-firing role RoleFiresHooks did
not know about". It was one of four. `*hookReadyClaimer`, `*hookBatchCloser` and
`*hookBatchCreator` were outside the switch too, and all three are served over
PUBLISHED operations — `issues:claimNext`, `issues:batchClose`,
`issues:batchCreate` — through roles `httpapi.Listen` sweeps by way of that exact
switch. A store-derived value for any of the three was therefore ADMITTED and
served, running the workspace's scripts for the life of the process: once per
bead a polling drainer wins, once per landed item plus one for a chained claim,
and once per item of a batch — so a hundred-item create was a hundred
subprocesses inside one HTTP call.
Fixed: three cases, plus the same both-ends pins the commenter got. Store side,
the accessor really hands back a hook-firing value and `serveIssueRoles` peels to
exactly the layer beneath it (the peel-depth half matters — a peel two layers
deep also answers false and silently drops the telemetry span, so the assertions
check identity, not just the predicate). Server side, `Listen` really refuses each
one.
AND THE PROSE IS NOW TRUE BECAUSE A SCAN MAKES IT TRUE.
`internal/storage/hook_decorator.go` has carried the sentence "every case that
exists today is in the switch" while it was false four ways, because every one of
the four was found by hand by whoever happened to publish an operation over that
role. That is a discovery process, not a guarantee, and it left the others
standing each time. `TestRoleFiresHooksKnowsEveryHookFiringRole` now parses this
package's `hook_*.go` for every decorator that holds an `issueOperationHooks` and
requires a case that RETURNS TRUE for it. Source scan rather than reflection, for
the reason backend/conformance's role census gives: these types are unexported
and are never built except through their accessor.
It counts the RETURN, not the case label, which closes the second failure mode
this switch has actually had: a Go type switch does not fall through, so
`case *hookMetadataCAS:` with an empty body answers FALSE, and a rebase shipped
exactly that with the compiler, vet, lint and CI all green. Mutation-verified in
both directions — deleting a case and emptying a case each fail the scan by name.
## `wisp_comments.text` was still TEXT, so the document's bound was false
The spec said `text`'s only cap is the 1 MiB every body shares. That was true on
one plane. Migration 0049 widened `comments.text` to LONGTEXT and did not touch
`wisp_comments.text`, which has been TEXT — 65535 bytes — since 0021 created the
table. Measured live before the fix: a 102,000-byte comment is 200 against a
durable issue and 500 against a wisp. This operation resolves its anchor across
BOTH planes deliberately, so nothing above the storage seam could tell a caller
which side of the bound it was on until the write failed.
Widened rather than caveated: the two planes should not disagree about what a
comment may contain, and a caveat would have to be re-stated by every client. The
handler grows no length check — there was never one to add; the fix was the
column.
MIGRATION 0065 + ignored/0024, and the twin is required rather than offered:
`wisp_comments` is clone-local and dolt-ignored, so a fresh clone materializes it
from the ignored series while the main cursor arrives at-latest and 0065 never
runs there. That is check D of scripts/check-migration-hygiene.sh, and the same
fresh-clone door ignored/0021 — the wisps half of this identical 0049 gap —
already records. Both guarded on 0049's `COLUMN_TYPE = 'text'` probe, so they are
no-ops on an already-widened workspace and idempotent on replay; the `.down` is
0049's intentional no-op, because shrinking back would truncate.
Verified from both ends: red-first against real Dolt (the wisp 500 above, green
after), and `TestEmbeddedIgnoredSeriesConvergesWithFreshInitShape` — the
engine-level backstop behind check D — fails naming `wisp_comments.text` when the
twin is withheld.
### MIGRATION LANE NOTE, for the deployment checklist
THIS MOVES THE MIGRATION CEILING FROM 0064 TO 0065, and the ignored series from
0023 to 0024. Anything pinned to "latest is 0064" — a deployment checklist, a
pre-flight assertion, a fixture bundle — transfers to 0065 when this lands.
Migration files are frozen once merged (hygiene check C), so a follow-up cannot
edit these two; a fix would be a further migration. NOTHING IS DEPLOYED BY THIS
PR: it ships the files, and the schema moves on whatever schedule the deployment
checklist runs.
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>
* feat(list,ready,httpapi): reach the Brief projection from both front doors
Application half of #5546, stacked on the storage half. `--brief` on `bd list`
and `bd ready`, `brief` on `GET /v0/beads/issues` and `GET /v0/beads/ready`.
Defaults to false everywhere, so no payload changes for a caller that does not
ask; #4122 objects to default payload changes and #5078 records what the last
one cost.
ONE REGISTRATION PER COMMAND REACHES BOTH OF ITS ROUTES, because the two
gatherers are shared. `bd list` hands `in.ListRequest` to issueops.Reader.List
verbatim on the direct and the proxied route. `bd ready` uses the Reader role on
NEITHER: both routes pass the filter that gatherReadyInput built through
workapi.BuildReadyFilter, so `types.WorkFilter.Lite` is what has to carry it
there, and the CLI-hop tests assert the filter rather than the request for that
reason. The HTTP handlers build both requests independently of the CLI, so they
are wired separately.
REFUSED WHEREVER IT CANNOT BE HONORED, rather than accepted and dropped, which
is the silent no-op the storage half was written to close. `Lite` reaches a
driver through exactly two queries: the bare SearchIssuesInTx (#3906) and the
counts mega-query (the storage half). `GetReadyWork` and the by-ID hydration
behind the tree walk read neither, so:
- `bd ready --brief` requires --json, and is refused with --claim, --gated,
--mol and --explain. `bd ready` runs the counts query for --json alone; the
text routes call the bare GetReadyWork and the three specialized modes
answer with shapes of their own. The direct route dispatches those modes
BEFORE gathering, so each check appears in cmd/bd/ready.go as well as in
the gatherer, exactly as the --claim conflicts beside them already do.
- `bd list --brief` works in text mode too, since all of its page routes reach
Reader.List, and is refused with --watch, with --format, and with --parent
in the tree view. --tree defaults to true, so a bare --parent in text mode
is that same walk without the flag being typed.
--claim is refused for a stronger reason than the rest: no route can serve it.
ClaimNext refetches its winning row whole and returns ErrValidation for a
projected request. Catching it in the gatherer keeps the message about the two
flags the user typed, and leaves readyRoleRequest free to carry Brief for the
COUNT, which needs it.
--format is refused rather than annotated because a caller's template can print
any of the six dropped fields and there is nothing to hang a marker on.
`bd list --long` is the one built-in text rendering that prints one of them, and
it is allowed because it CAN say so: it now prints
"Description: (omitted by --brief)". That keys off types.Issue.IsLitePartial
rather than off the flag, so a row that arrived projected reads the same
whichever door set it.
THE JSON PAYLOAD CARRIES NO MARKER, and the flag help and both OpenAPI
descriptions say so plainly. types.Issue.IsLitePartial is `json:"-"` and
documented as internal-only by #3906, so an omitted field is indistinguishable
from an empty one on the wire; only the caller that sent the flag knows. #5549
deferred exactly this marker for brief_deps as its own change, and this follows
that, rather than changing a shared type's wire form on the way past.
`brief` is decoded in handleListReadyWork and NOT in readyFilters, the
vocabulary the ready listing shares with :count and :claimNext, because it
projects fields rather than selecting rows and neither of those returns rows to
project. That made TestClaimNextAdmitsExactlyTheListingsFilters fail, correctly:
its single hardcoded `limit` exception is now a `pageKnobs` table of the
listing's two page knobs, each still asserted ABSENT from claimNext, since a
documented parameter that is always a 400 is a trap. Both branches of that
assertion were verified by sabotage.
RED BEFORE GREEN on all nine new assertions, each verified and reverted: the two
request hops, the seven refusals, the long-format marker, and both branches of
the parity table.
Gates: go build ./..., go vet ./..., gofmt, cmd/bd, internal/httpapi,
internal/workapi, backend/conformance, internal/storage/issueops, issueops,
make api-check, ./scripts/generate-cli-docs.sh --check.
Refs: #5546, #3906
* fix(ready,changelog): close the review findings on #5586
THE THREE DIRECT-ROUTE REFUSALS WERE UNTESTED, and the review's mutation
proved it: deleting the --gated check left `go test ./cmd/bd/` entirely green
while `bd ready --gated --brief` silently ignored the flag on the direct route.
Nothing in the package drives readyCmd's RunE, so the gatherer's tested copies
were only ever guarding the proxied route. The PR body's "seven refusals, red
before green" covered five.
Taking the second of the two suggested fixes, since it removes the duplication
rather than testing it. The per-mode copies in ready.go are deleted. Their body
moves to briefModeConflict, which gatherReadyInput now calls, and RunE calls
once through briefModeConflictFromFlags, hoisted ABOVE the mode dispatch and
above the proxied branch so it is the single place a --brief conflict is
decided for this command on either route.
TestReadyCmdRefusesBriefBeforeItDispatches drives RunE directly, which is
reachable because that check now precedes every store access. Verified by
reproducing the review's own mutation: deleting the hoisted call fails the
--gated, --mol and --explain cases.
THE CHANGELOG ENTRY CONTRADICTED ITSELF, claiming --brief "marks each row
is_lite_partial" and then, in the same paragraph, that the response carries no
marker. The first half was written before the wire form was checked;
types.Issue.IsLitePartial is `json:"-"` and never serialized, so an agent
following that sentence would have grepped its JSON for the field and concluded
the feature was broken. The no-marker fact is now its own paragraph, and the
only marker the entry claims is the text one `bd list --long --brief` prints.
The entry cites #5554 and #5586 alongside #5546, matching the sibling
brief-deps entry.
Gates: go build ./..., go vet ./..., gofmt, cmd/bd, internal/httpapi,
internal/workapi, backend/conformance, internal/storage/issueops, issueops,
make api-check, ./scripts/generate-cli-docs.sh --check.
---------
Co-authored-by: sjarmak <t@t.co>