Commit graph

13 commits

Author SHA1 Message Date
Julian Knutsen
3862b03ff5
feat(http): gate await members on create and update over bd serve (#7589)
* 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>
2026-10-16 17:02:27 +00:00
Julian Knutsen
c4e667cb14
feat(http): list/show counts/dep tree/ping over http, the advertised external-dependency policy, one-lookup not-found (S6b/S6c/S6d) (#7471)
* 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>
2026-10-10 18:11:56 +00:00
Julian Knutsen
1f1e82ab08
fix(issueops): one default priority for every create path (#7426)
* 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>
2026-10-10 01:37:27 +00:00
Julian Knutsen
6d27a4f96e
fix(issueops): enforce the close guards on every close leg (#7425)
* fix(issueops): enforce the close guards on every close leg

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

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

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

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

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

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

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

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

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

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

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

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

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

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 18:30:42 +00:00
Julian Knutsen
f21e3a80f7
fix(issueops): templates are read-only on every update leg (#7427)
* 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>
2026-10-09 16:25:37 +00:00
Julian Knutsen
533f95295a
feat(httpclient): BatchApplier over HTTP — handshake cap, dep_add lineage on the wire, gc mappings (S5) (#7265)
* 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>
2026-10-09 01:05:39 +00:00
Julian Knutsen
6d21d337ad
feat(httpclient): OSS HTTP client store and roles + a served http conformance leg (contributed from bd-enterprise under MIT) (#7247)
* feat(httpclient): lift the HTTP client store and roles 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: the Store (DoltStorage over the wire), the
dial/register glue, the read roles (reader, querier, counters, edges,
relations, graph, tree, cycles, stats, config, memories, journal), the write
roles (lifecycle, claimer, releaser, deleter, dependency editor, metadata
CAS, commenter, batch closer/creator/applier, ready claimer, sweeper), and
their tests. The store transport seam (WireClient/WireDialer) and the
store-dependent tests deferred from the S2 lift are restored here.

Not lifted: the hosted gateway (httpgw/gwauth), box-login, storage profiles
and gasworks. dial.go only mentions the gateway in comments.

This commit is the mechanical lift and does NOT build yet. It references
enterprise-only APIs absent from OSS: issueops.ReadyLister,
journalops.Watcher, storage.ServerEnforcedPolicy, the
NonCommitGraphBackend/RemoteWorkspaceBackend markers, DoltStorage
differences, and BatchCloseRequest.claim_next. The following commits
reconcile it with OSS (S3/S4/S5).

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

* fix(httpclient): reconcile the bd-enterprise lift's compile-time API surface against OSS

The mechanical lift (02a9dad17) carried several bd-enterprise-only shapes
that do not exist in OSS beads:

- ReadyLister, journalops.Watcher/StreamWire, and ServerEnforcedPolicy have
  no OSS wire counterpart; drop the role, its served/journal-watch tests,
  and the policy enforcement path entirely rather than leave dead code that
  cannot compile against OSS's apigen types.
- claim_hook_gate_test.go exercised a hook surface OSS does not publish.
- recordingWire/fakeWire no longer embed a StreamWire double now that no
  read role can reach a watch stream; testTarget's two conflicting
  package-scope declarations (store_test.go and helpers_test.go) are split
  apart as pinnedProjectTarget vs. the generic helper.
- unsupported_gen.go is regenerated from scratch against OSS's actual
  storage.DoltStorage via a new, from-scratch reflection-based generator
  (internal/storage/unsupportedgen) rather than hand-copied from
  bd-enterprise's generated output; completeness_test.go's
  legitimatelyUnsupported map grows the handful of OSS-only or
  previously-missed methods (AddRemoteWithRef, RenameLabel, etc.) this
  regeneration surfaces.
- write_ledger_test.go and the divergence ledger doc gain the
  force_notes_overwrite and claim pending rows OSS's apigen.UpdateRequest
  and SweepRequest actually carry, and drop the Remaining/LiveDependent
  assertions SweepResult/SweepSkips have no wire member to ever populate.

go build ./... and go vet ./... are clean after this change. No behavior
beyond the removed surfaces changes here; read-role and write-role
reconciliation land in follow-up commits.

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

* fix(httpclient): stop sending listIssues a reverse/sort vocabulary OSS does not publish

The bd-enterprise lift's sortedPage pushdown assumed GET /v0/beads/issues
(listIssues) shared the same sort vocabulary and a reverse parameter with
GET /v0/beads/issues:query (handleQueryIssues) -- a different operation.
OSS's openapi.v0.yaml publishes listIssues a CLOSED two-value `sort` enum
(created, priority; deliberately smaller than the nine values :query
takes) and no `reverse` parameter at all. Sending either would earn an
unknown-parameter or invalid_value refusal from the real server, not a
silently-wrong answer -- which is why this only surfaces against a served
backend, not a Go-side unit test of the request builder.

Add listSortPushdownEligible to gate the pushdown fast path to the two
keyset orders listIssues can actually page, unconditionally refusing any
reversed request (listIssues has no parameter that names a reversed
direction, so a reversed request of any order walks and sorts
client-side). Drop the unconditional `reverse` send from sortedPage.

served_list_test.go's three affected cases encoded the wrong,
enterprise-only wire shape (expecting reverse=false on the fallback path,
expecting a reversed order to push down with sort+reverse, and expecting a
Go-side/SQL-side mix in listIssues' sort enum); corrected to match OSS's
actual, provable wire contract rather than left red. list_sort_test.go's
publishedParamEnum helper now reads the OpenAPI document via the
go:embed'd spec.OpenAPIV0() accessor instead of a relative os.ReadFile, so
it no longer depends on the test's working directory (this also fixes the
same test failing under Bazel's sandbox, which does not expose arbitrary
relative-path files).

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

* fix(httpclient): reconcile write-role tests against OSS's BatchClose/Update shapes

OSS's apigen.BatchCloseRequest and BatchCloseResponse publish no
claim_next/claimed_next member at all (ledger row
W-CloseBatchRequest.ClaimNext) -- bd-enterprise's claim-folded-into-close
shape has no OSS wire counterpart. Replace the three tests that exercised
decoding a served claim (TestBatchCloseRefusesAServedClaimCarryingNoIssue,
TestBatchCloseRefusesAServedClaimTheRequestNeverEarned,
TestBatchCloseKeepsTheClaimItEarned) with
TestBatchCloseRefusesClaimNextUnconditionally, which pins the actual OSS
behavior: a CloseBatchRequest naming ClaimNext refuses before any dial, on
both the unserved and served legs, regardless of what a server would
otherwise answer. Drop the now-dead "claim-next" case and helper claim
variable from TestBatchCloseServesTheSingleItemShapeAndRefusesTheRest.

Also:
- Add the ForceNotesOverwrite case to
  TestUpdateRefusesEveryMemberTheWireExcludes's hand-maintained member
  map -- a ledgered-pending UpdateRequest member (see
  W-UpdateRequest.ForceNotesOverwrite) the lift's test left uncovered.
- Remove write_roles_test.go's duplicate `ptr[T]` generic helper, which
  redeclared the one already in helpers_test.go and never compiled.

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

* test(conformance): pin post-write RowVersion propagation across Update/Close/Reopen

types.Issue.RowVersion is json:"-", so an implementation that forgot to
populate it on the way back from storage would still compile and still
pass every existing content assertion in lifecycle_close_reopen_contract.go
-- none of them read RowVersion. Add
RunLifecycleResultsCarryThePostWriteRowVersion, which chains each write's
result token into the next write's ExpectedVersion (Update -> Close ->
Reopen) with no intervening read, so a dropped or stale token fails closed
on the next write's optimistic-concurrency guard rather than passing
silently.

Register it in role_bundle_cases.go's roleContractCases dispatch table at
its declaration-order position -- TestRoleContractCasesCoverEveryContractCase
was failing because the function existed with no dispatcher entry.

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

* chore(bazel): sync BUILD files via gazelle for the S3 reconciliation

bazel run //:gazelle after the compile/read-role/write-role reconciliation
commits:

- internal/httpclient/BUILD.bazel: regenerate srcs/deps for the files
  added, removed and newly imported above (drops the deleted
  policy/journal-watch/readylister files, adds the spec dep for
  list_sort_test.go's embedded OpenAPI read). Manually add
  `data = glob(["*.go"])` to the go_test rule, matching the idiom already
  used by //internal/httpclient/encode: completeness_test.go and
  divergence_citation_gate_test.go read their own package's .go sources at
  runtime (a regex scan of unsupported_gen.go and an AST walk of the
  package directory), and Bazel's go_test sandbox only copies in files a
  rule declares as `data` -- `srcs` are compiled away, not left readable.
  A `# keep` directive protects the attribute across future gazelle runs
  (confirmed gazelle does not manage `data` on this rule).
- internal/storage/BUILD.bazel,
  internal/storage/unsupportedgen/BUILD.bazel: pick up the new
  from-scratch unsupportedgen generator package.

bazel test //internal/httpclient/... //backend/conformance/... now passes
all 4 targets (previously 4 of the package's tests failed only under
Bazel's sandbox: TestInterfaceCompleteness,
TestTheCountGroupVocabularyMatchesTheSharedOne,
TestFlaglessListSortIsTheSameOrderNamed,
TestDivergenceParkCitationsResolveToLiveLedgerRows).

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

* fix(conformance): close two pre-existing leg-wiring gaps found while registering http

- RunLifecycleResultsCarryThePostWriteRowVersion (added in 536561124) was
  never wired into dolt/embeddeddolt/uow's own lifecycle_close_reopen test
  tables, only into the http leg's. TestEveryLegWiresEveryRoleContract
  catches this once a fourth leg forces the test to actually run again;
  wire the missing t.Run into all three.
- The three StatsReporter "suppressed rows" cases (GateIssues/TemplateIssues
  breakdown) were never added to served_graph_aux_test.go even though the
  wire already carries both fields end-to-end (types.Statistics is shared
  verbatim by apigen.StatsResponse and the client's decode). Wire them; all
  three pass over HTTP with no server or client change needed.

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

* feat(conformance): register the http leg in the role-contract lock

Registers "http" (wiringRoot internal/httpclient) in contractLegRegistry.
The served-surface harness (served_harness_test.go + 16 served_*_test.go
files) already wired 495 of 576 role-contract entrypoints from the
bd-enterprise lift; this change:

- Waives the 3 RunCycleDetectorIncludeTracks* cases: issueops.
  DetectCyclesRequest.IncludeTracks has no plumbing on either side of the
  wire today (cycles.go always calls DetectCycles with a zero-value
  request; the client's DetectCycles ignores its request parameter). No
  slice through S13 adds one, so the waiver says a new slice is needed
  rather than pointing at an existing one.
- Sets adoptionCeiling: 75 for the remaining, not-yet-wired write-role and
  internal-plumbing entrypoints (lifecycle writes, DependencyEditor,
  MetadataCAS, Lease, Sweeper, VersionReconciler, Bootstrapper/
  InitVerifier, cross-record invariants) that S4 and later write slices
  pick up and ratchet down.
- Adds //internal/httpclient:go_srcs to storage_test's data: the leg's
  wiring root lives outside internal/storage, and the Bazel sandbox has no
  other reason to materialize those sources for a test that reads them at
  runtime.

TestEveryLegWiresEveryRoleContract, TestEveryRoleMethodHasAContractCase,
and RunUnsupportedContract (already wired pre-lift in
internal/httpclient/completeness_test.go) all pass for the http leg.

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

* fix(httpclient): close review's HIGH 2-5 gaps and reconcile their test doubles

HIGH 2 (BatchCloser), HIGH 3 (created_by stamping, absent-parent 404/400,
force_notes_overwrite carriage) and HIGH 4 (CapabilityError now unwraps to a
typed *storage.ErrUnsupported with Capability) were implemented in prior
commits on this branch; this change finishes HIGH 5 and the verification the
review asked for:

- role_reader.go's Reader.Get and bridge.go's raw GetIssue both now stitch
  Revision back onto Issue.RowVersion via parseRevision, so a guarded write
  built off either read carries the row's real token instead of a decoded
  zero. Both are pinned by round-trip served tests that guard a write with
  the read's token and require a stale-token replay to refuse.
- Fixed create_test.go's stale assertion that created_by must stay empty
  (contradicted the HIGH 3 stamping fix it predated).
- Fixed recordingWire's canned IssueDetails{} response (roles_test.go): it
  omitted Revision, which is a required field on every getIssue response
  per the OpenAPI spec, and the HIGH 5 stitch now reads it unconditionally.
- Synced internal/httpclient/wire/BUILD.bazel via gazelle: handshake_test.go's
  new internal/storage import had no corresponding dep.
- gofmt'd write_roles_test.go's stubWire struct tags.

Verified: served HTTP conformance tier (BEADS_TEST_EMBEDDED_DOLT=1
BEADS_HTTP_TEST_REQUIRED=1 go test ./internal/httpclient/, -timeout=40m)
600 PASS / 0 FAIL / 72 SKIP (all ledgered known-divergence waivers). One
TLS-handshake-timing test failed in that run and passed 3/3 in isolation
(unrelated file, pre-existing flake under machine load, not reproducible).
Also green: default go test (minus the pre-existing, unrelated
TestEngdocsAndRootMarkdownLinks doc-link drift and the environmental
internal/storage/uow dolt-server-spawn hang), bazel build/test for the
touched packages, make api-check, and gofmt/vet.

Live-mutated and reverted 3 guards to confirm their tests are load-bearing:
role_reader.go's RowVersion stitch, bridge.go's RowVersion stitch, and
lifecycle.go's force_notes_overwrite wiring.

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

* feat(ci): add served HTTP conformance as Tier 3 of the conformance gate

The served tier (internal/httpclient's served_*_test.go corpus) never ran
in CI, so HIGH 2-5's regressions (and any future ones) would merge
undetected. Add it as Tier 3 of scripts/conformance.sh, the existing
required entrypoint conformance.yml already runs on every PR/push/merge_group
(not a new workflow, not wired through ci-gate.sh's aggregation -- this
repo's convention for this gate is a single standalone job):

  CGO_ENABLED=1 BEADS_TEST_EMBEDDED_DOLT=1 BEADS_HTTP_TEST_REQUIRED=1 \
    go test -timeout=40m ./internal/httpclient/

Left unsharded: Tier 1 and Tier 2 are themselves single unsharded
invocations, and Tier 3 is one Go package, not a multi-package corpus the
repo's existing package-sharding scripts apply to. No Bazel-lane addition:
bazel-coverage's embedded/dolt_server outputs only ever substitute for
main.yml/pr-risk.yml jobs, never for conformance.yml's own job, so there is
no existing Bazel-lane relationship for this gate to extend.

Bumped the job's timeout-minutes 45 -> 100 (30m + 10m + 40m budgeted
sub-timeouts plus checkout/setup-go overhead) and updated the three policy
tests that pin this script/workflow byte-for-byte
(TestConformanceScriptUsesExplicitTimeoutBudgets,
TestConformanceScriptPropagatesGoTestFailures,
TestConformanceWorkflowHasOuterTimeoutBudget), re-included
internal/httpclient/** in both path filters (push and pull_request, kept
identical) since served_*_test.go files are the suite itself and would
otherwise be excluded by the shared !**_test.go negation, and documented the
new filter entry in ci_f7c_advisory_test.go's own-entries map.

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

* fix(httpclient): root-cause and fix the Happy-Eyeballs TLS flake in store_dependent_test.go

TestTransportForSucceedsWithEnvCAFile (and 3 Handshake-based siblings that
assert on a successful dial through a configured CA: SidecarCAFile,
CAFileEnvAgreeingWithSidecarSucceeds, DialWithNilTransportHTTPClientGetsCAInjectedOnACopy)
flaked once with "tls: first record does not look like a TLS handshake".

Root cause: our code, same class S2 already fixed for TransportFor's direct
callers (forceIPv4Loopback in ca_test.go/ca_wrong_ca_test.go). Every server
these tests dial is addressed by hostname "localhost" (ca.startServer
rewrites it there deliberately, so SNI is actually sent), which Go's
default dialer races a tcp6 dial to ::1:<port> against the real tcp4 dial to
127.0.0.1:<port> for (RFC 6555). An unrelated local process already bound to
a colliding ephemeral port on ::1 can occasionally win that race before the
real dial completes, and the client speaks TLS to that unrelated process
instead -- the misleading handshake error, not a real hang or a product bug.

These four tests go through Handshake with DialOptions{} (HTTPClient left
nil deliberately, since that is itself the nil-HTTPClient branch of DialWith
under test), so they never get a *http.Transport back to mutate the way
forceIPv4Loopback's existing callers do. Fixed via warmIPv4OnlyCATransport:
pre-build the target's CA-scoped transport through the same public
TransportFor the product code itself calls (so it lands in the exact
(path, content)-keyed cache transportForFile's cache hit returns), force
tcp4-only on that cached pointer, and let Handshake's own DialWith run
unchanged -- same branch under test, same cached transport, no sleeps, no
retries. Verified with -race -count=50 on all four: 200/200 pass.

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

* fix(httpclient): refuse DetectCycles(IncludeTracks=true) instead of silently ignoring it

roles_graph.go's httpCycleDetector.DetectCycles took its request as `_`,
forwarding nothing: a caller asking for the widened (tracks-following) walk
silently got the narrower default walk back with no error. listDependencyCycles
has no include_tracks wire parameter at all, so there is no way to honor the
field — only to refuse it loudly or drop it silently. Switch to the typed,
ledger-cited refusal (encode.RefusedError via refuse(), citing new row
"L-cycles-tracks") that CountEdges' own wire bound already uses, add the
ledger row and its Op, regenerate the auto-generated ledger doc, and pin the
behavior with a unit test (no served-tier case needed: the refusal is
pre-dial by design, same reasoning as the existing edge-count bound pin).

Also fix leg_contract_wiring_test.go's cycleTracksWireGapWaiverReason, which
had gone stale: it described the http leg as silently forwarding nothing for
this field, which was true before this change and is not after. The waiver
itself (the three RunCycleDetectorIncludeTracks* contract cases stay unwired
for the http leg) is unaffected — they were never wired, and still are not —
only the reason text needed updating to describe a typed refusal instead of a
silent ignore.

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

* fix(storage): name the http leg's permanent contract gaps instead of budgeting them

The http leg's role-contract adoption ceiling (internal/storage/contract_leg_registry_test.go)
sat at a flat 75, with a prose "adopting" note that bundled every skip into
one vague bucket — including MetadataCAS, which is in fact fully wired (0
missing cases), a false claim left over from an earlier wiring pass.

Twenty-six of the 75 skips are not S4-and-later work at all: they are
PERMANENT gaps that no future slice closes, because the contract itself has
no publicops role for an HTTP client to route through:

  - Importer (4 cases): uow is Importer's one accessor, same precedent the
    dolt and embeddeddolt legs already carry (importerOneAccessorWaiverReason).
  - RetentionFixture/EpochFixture (15 cases) and CrossRecordInvariantFixture
    (7 cases): both fixtures carry raw storage hooks (Resolve, Erase, Mint,
    CurrentEpoch, GuardedWrite, EnforceCrossRecordInvariant, ...) with no
    publicops field at all. dolt, embeddeddolt and uow wire these because
    they ARE the storage engine this address/epoch/retention and
    cross-record transaction bookkeeping belongs to; the http leg is a
    remote client with none of its own to report. There is no wire surface
    for this to ever route through short of a new role being designed from
    scratch — a new slice, not a missing test line.

These 26 are now named, reasoned waivers in unwiredContractEntrypoints
(two new reason constants: retentionEpochNoRoleWaiverReason and
crossRecordInvariantNoRoleWaiverReason), and the ceiling drops from 75 to 49
to match. The "adopting" note is rewritten to correctly name every remaining
category under budget (lifecycle writes, DependencyEditor, DualWrite,
Sweeper, VersionReconciler, Bootstrapper/InitVerifier, ExpectedRevision/
Refusal) and to drop the false MetadataCAS claim.

Also documents, at conformanceEntrypointsWiredBy, why a leg wiring a
conformance.RunX reference with every hook left nil would read as "adopted"
by this lock's static source grep while actually running as a skip —
matching the loophole internal/httpclient's divergence_citation_gate_test.go
already closes for skipKnownDivergence call sites. No leg currently does
this (verified by inspection); the note sets the review expectation for
future wiring rather than papering over the gap with no record of the policy.

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

* fix(licensing): scrub internal program/org naming and a leaked private ID from OSS-visible text

MEDIUM 8 of the S3 ship review: remove licensing-hygiene leaks found by a
read-only repo-wide survey, while leaving every legitimate "Contributed by
gascity from bd-enterprise ... to OSS beads under the MIT license." provenance
header and every genuine public gascity/gastownhall self-reference (the real
OSS org, beads.gascity.com docs domain, RBE infra) untouched:

- Delete release-gates/ga-7psli2-3-1-baseline-cmd-bd-fix-gate.md: the only
  file in release-gates/ keyed by a private `ga-` tracker ID instead of the
  directory's established public `be-` convention (30 other files), and the
  only one leaking internal filesystem paths (/home/jaword/...,
  gc-management/.gc/artifacts) and internal routing terms (mayor/mpr,
  "deployer session"). Not referenced from anywhere else in the tree.
- .golangci.yml: drop two private `ga-2ltro.12`/`ga-26w10` history citations
  used as nolint-comment justifications; reworded to the same explanatory
  content without naming a private tracker ID.
- Reword 19 "gc native-program" occurrences (14 files, comments and one
  design doc) to drop the internal program name while keeping the "S3
  reconciliation (2026-10)" dating they were attached to.
- cmd/bd/if_revision.go, if_revision_test.go, update.go,
  update_proxied_server.go: drop literal citations of gascity's private
  bdstore_conditional.go classifier (including a test function name,
  TestIfRevisionEnvelopeGascityContract -> ...DownstreamContract) while
  keeping the substantive explanation of why this envelope's shape is
  load-bearing for a downstream consumer.
- internal/httpclient/lifecycle.go: drop a citation of gascity's private
  internal/beads/bdstore.go.
- internal/httpclient/dial.go: drop the internal/enterprise/httpgw package
  path, keeping "a gateway dialer outside this repo".
- internal/httpclient/register.go: reword away from naming "the enterprise
  distribution" while keeping the build-tag-opt-in behavior it documents.

Verified: go build ./..., go vet ./internal/httpclient/... ./cmd/bd/...,
go test ./internal/httpclient/... and ./cmd/bd/... -run TestIfRevision all
pass; TestDivergenceLedgerDocMatchesLedger still passes (ledger.go and its
doc were edited in lockstep). gofmt -l reports no diffs on any touched file.

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

* fix(httpclient/wire): correct the CapExternalDependencies doc's implied false claim

MEDIUM 9 of the S3 ship review. The old comment on CapExternalDependencies
said this client "has no external-dependency policy layer to gate" and that
"OSS publishes no storage.ExternalDependencyQueryStore-backed client policy
... to compose" immediately after naming bd-enterprise's removed policy.go --
easily misread as "OSS has no external-dependency decorator at all." It does:
internal/storage/externaldeps's decorator is unconditional (no build tag) and
is wired into every local storage chain by cmd/bd/storage_chain.go.

Reworded to say precisely what is and is not true: the decorator exists and
runs for local backends; what this http client lacks is a client-side
composition of that decorator around a remote store, which is moot anyway
because a server advertising this capability already applies the policy
itself before answering. (Rolled in the same "gc native-program" wording
removal from the MEDIUM 8 commit, since both edits touch this comment block.)

A second claim from the same review item -- that OSS is said somewhere not to
serve events:watch -- could not be located despite an exhaustive repo-wide
search (this file, engdocs/, docs/reference/events-journal.md,
SERVE_RUNBOOK.md, the divergence ledger, CHANGELOG.md, and a dedicated
read-only research pass). internal/httpapi/events_watch.go,
routes.go's events.watch route entry, and internal/httpclient/wire/stream.go
all confirm OSS serves it unconditionally (gated only per-workspace by the
events journal setting, not by build/distribution). No corresponding false
claim exists in this worktree to fix; noting this rather than editing
something that already reads correctly.

Verified: go build ./internal/httpclient/..., go vet, go test
./internal/httpclient/wire/... pass. gofmt -l clean.

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

* test(unsupportedgen): add a freshness check for the generated shell

LOW item from the S3 ship review: internal/storage/unsupportedgen had no
tests of its own, so the generator could drift from the checked-in
internal/httpclient/unsupported_gen.go (a storage.DoltStorage interface
change, or a hand-written method added/removed on Store) with nothing to
catch it short of a human noticing the diff. TestInterfaceCompleteness
(completeness_test.go) already pins which methods belong in the shell by
name, but not whether the checked-in bytes match what the generator would
produce today.

TestGeneratedShellIsFresh runs the same scan-then-generate pipeline main()
runs for the registered DoltStorage/httpclient/Store consumer and diffs the
result against the checked-in file -- mirrors the existing
TestDivergenceLedgerDocMatchesLedger pattern in
internal/httpclient/encode/ledger_render_test.go. Added
TestScanHandWrittenMethodsExcludesOwnOutput alongside it to pin the
correctness property the freshness check depends on (scanning must not see
the generator's own prior output as hand-written).

BUILD.bazel: added the go_test rule by hand (gazelle cannot infer the
cross-package `data` dependency a relative-path os.ReadFile needs under the
Bazel sandbox) with data = ["//internal/httpclient:go_srcs"], following the
existing cross-package data pattern in
internal/httpclient/encode/BUILD.bazel. Placed go_test before the
go_srcs.py-managed filegroup block, which `make bazel-sync-check` requires.
Verified: `bazel run //:gazelle` leaves the rule untouched, `bazel test
//internal/storage/unsupportedgen:unsupportedgen_test` passes, `make
bazel-sync-check` is clean, go build/vet/test ./... all pass.

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

* fix(httpclient/encode): scrub a private tracker-ID cluster from the shipped divergence-ledger doc

Follow-up to the MEDIUM 8 licensing scrub: internal/httpclient/encode's
ledger_render.go header and ledger.go's comments/pinnedElsewhere constant/two
Why strings cited "ga-b8ddd.12/.19/.23/.30" by name. These feed directly into
engdocs/design/http-divergence-ledger.md -- a shipped, generated OSS design
doc, the most visible surface this private ID cluster reached (Fork A's
MEDIUM 8 survey found ~40 occurrences of "ga-b8ddd" across the httpclient
package; this commit addresses the subset inside package encode that is
checked-in prose/doc text, not test-fixture or assertion values). Reworded to
keep the same substantive explanation (what closed, what's still deferred,
which dual run resolved L17) without naming the private ID.

The remaining ~30 occurrences of "ga-b8ddd" outside package encode
(offrole.go, metadata.go, store.go, roles_test.go, wire/*_test.go,
served_*_test.go) are left for a follow-up pass: scrubbing them individually
needs the same per-file verification this commit did, and is a larger,
separate blast radius than was practical in this pass.

Regenerated engdocs/design/http-divergence-ledger.md via
`go test ./internal/httpclient/encode -run TestDivergenceLedgerDocMatchesLedger
-update-ledger-doc`; diff confirmed only the ga-b8ddd text changed. go build
./..., go vet ./internal/httpclient/..., and go test ./internal/httpclient/...
all pass.

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

* docs(httpclient): drop a private host reference from a test comment

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

* revert(licensing): keep the scrub to the contributed client code

The previous scrub also edited upstream files this PR doesn't otherwise
touch (.golangci.yml, cmd/bd --if-revision files from #7203) and deleted an
upstream release-gate record. Restore them; the provenance scrub applies only
to the code contributed from bd-enterprise.

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

* feat(httpclient): wire S8 count-scope fields on the client

Encode ParentID/NoParent/ExcludeTypes/ExcludeStatus onto countIssues
(table.go + encode.go), add issues.count.scope to the client capability
table (wire/handshake.go, wire/vocabulary_test.go), and refuse locally
before dialing when the server hasn't advertised the token and any scope
field is set (counter.go's refuseUnservedScope), returning a typed
*storage.ErrUnsupported{Capability:"issues.count.scope"} rather than
dropping fields or taking a guaranteed-400 round trip.

Adds encoding-parity coverage (counts_test.go), a masked-token skew test
proving the pre-dial refusal and zero dials (counts_test.go), roundtrip
and skew-table fixes for the newly-encoded fields (encode/roundtrip_test.go,
encode/skew.go), and wires S8's nine shared Counter conformance cases into
the served http leg (served_counter_test.go), including AddDependency so
the wisp/compose cases run instead of skipping. List stays nil on this
fixture since listTable() has pre-existing, unrelated permanent refusals
for ListRequest.NoParent/ExcludeTypes, so the three *MatchesListCardinality
cases skip here by design.

internal/storage's TestEveryLegWiresEveryRoleContract/http ceiling check
remains red (53 skipped vs ceiling 49) after this change, but strictly
improved: before this change the inherited baseline was 62 skipped (13
over ceiling), all nine of S8's new entrypoints unwired. This change wires
all nine, closing exactly that gap; the remaining 4-over are named
RunBootstrapper*/RunDependencyEditor* cases unrelated to count-scope,
pre-existing debt from other already-merged slices whose ceiling was
never bumped for them. Left the ceiling constant alone rather than
raising it to paper over debt this change doesn't own.

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

* fix(storage): close the http leg's role-contract ceiling regression

TestEveryLegWiresEveryRoleContract/http went red after the rebase (62
skipped, 13 past its ceiling of 49) before any work in this session; the
prior commit closed 9 of those (S8's Counter cases). The remaining 4-over
were RunBootstrapper* (9 entries) and RunDependencyEditor* (2 entries),
both newly-merged contracts this leg had never classified.

RunBootstrapper*: internal/httpclient/accessors.go already names
Bootstrapper PERMANENTLY UNSERVABLE over http (bd init resolves its
substrate identity entirely client-side, before any server exists to
dial) — add a new named waiver, bootstrapperPermanentlyUnservableWaiverReason,
covering all nine entrypoints. VersionReconciler and InitVerifier are
named permanently unservable by the same accessors.go comment but are
left under the ceiling for their own reviewed change, out of scope here.

RunDependencyEditor*: the OSS server already serves add/remove and the
http leg already wires nearly all of DependencyEditor's contract. The two
missing cases (SameTypeReAddWithChangedMetadataMintsOneVersion,
SameTypeReAddWithIdenticalMetadataIsANoOp) only needed
SetVersionedHistoryEnabled wired onto the fixture, the same way
SetJournalEnabled already is — wired it for real; both pass served.

With Bootstrapper waived and DependencyEditor fully wired, the leg's
unwaived-missing count drops from 53 to 42, so adoptionCeiling moves
from 49 to 42 to keep the ratchet exact, with the adopting prose updated
to match.

TestEveryLegWiresEveryRoleContract is green. Served tier (real, CGO +
embedded dolt): 611 PASS, 0 FAIL, 72 SKIP (up from 609). bazel build/test
and make api-check pass for the touched targets.

Co-Authored-By: Claude Sonnet 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/37307836753
(`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(conformance): pass -tags gms_pure_go to Tier 3's served httpclient run

scripts/conformance.sh:61 ran a bare `go test -timeout=40m ./internal/httpclient/`
for Tier 3 (served HTTP client/role conformance), which `make ci-pr-policy`'s
build-tag policy check refuses ("bare go test without -tags=gms_pure_go").
Pass the same -tags Tier 1 already does, and update
TestConformanceScriptUsesExplicitTimeoutBudgets' pinned argv to match.

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

* fix(bazel): give //internal/httpclient:httpclient_test room to run

The package takes ~350s under --config=ci (BEADS_TEST_SKIP=dolt, no
BEADS_TEST_EMBEDDED_DOLT) — mostly wall-clock wait on the CA tests'
dialer/keep-alive timeouts, not CPU — but the go_test had no size/timeout
override, so it inherited the medium default's 300s and timed out
intermittently under Bazel (and took "Go test equivalence" down with it).
Set size = "large", timeout = "long", matching
//internal/storage/embeddeddolt's go_test.

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

* fix(httpclient): fix data race in caContextHandler test helper

TestTransportForRaisesMaxIdleConnsPerHostForBursts drives caContextHandler
with 8 concurrent requests; handler() wrote requestSeen/host/sni from every
server goroutine with no synchronization, and the other nine callers (all
single-request) never exercised the race. go test -race reproduced it as
3x DATA RACE across repeated runs.

Guard the fields with a mutex and expose them only through accessor methods
(sawRequest/seenHost/seenSNI), updating every call site in
store_dependent_test.go accordingly.

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

* fix(unsupportedgen): canonicalize reflect-visible stdlib aliases

TestGeneratedShellIsFresh fails on Go >= 1.27: encoding/json.RawMessage
became an alias of encoding/json/jsontext.Value, and reflect only ever sees
an alias's underlying type, so formatType rendered
storage.DoltStorage.MergeMetadata's signature with the new, non-portable
name even though the signature itself did not change. A contributor on
1.27 following the freshness test's own advice ("go generate
./internal/httpclient") would commit a shell that does not compile on the
1.26.7 SDK this repo pins.

Add reflectAliasCanonical, a table mapping a reflect-visible alias target
back to the name a human wrote in source, consulted by namedType. Add an
entry here for any future stdlib alias this generator's output needs to
stay stable across.

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

* fix(httpclient): claimOnlyUpdate propagates the claim's RowVersion

bridge.go's GetIssue already stitches details.Revision onto
hydrated.RowVersion when claimOnlyUpdate rehydrates labels/CreatedBy onto
the claim response, but the claim response itself (issueops.Claimer's
bare-row contract) carries no revision at all, and the copy-back only
touched Labels and CreatedBy. So Lifecycle.Update({Actor, IssueID, Claim:
true}) — `bd update X --claim` — handed back Issue.RowVersion == 0 over
http where the local leg returns the real token, and feeding that into the
next write's ExpectedVersion got a spurious mismatch instead of none.

Copy RowVersion back too. Extend
RunLifecycleResultsCarryThePostWriteRowVersion (shared lifecycle/close/reopen
conformance contract) with a claim-shaped first link in the chain: claim,
then guard the next write with the claim result's own token, proving the
claim-only path populates the real version rather than a nonzero constant.

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

* fix(httpclient): stitch RowVersion on SearchIssues' exact-id fast path

resolve.go's getIssuesByExactID decodes the same IssueDetails shape
bridge.go's GetIssue does, but never parsed details.Revision the way
GetIssue's own stitch does, so SearchIssues(ctx, "<exact id>") answered
RowVersion 0 — a one-line gap: Issue.RowVersion is json:"-", so the decode
left it at zero, and only the explicit parseRevision stitch recovers it from
the response's own Revision string member.

Add TestSearchIssuesExactIDPopulatesRowVersionForAGuardedWrite, pinning the
same guarded-write round trip TestBridgeGetIssuePopulatesRowVersionForAGuardedWrite
already pins for the plain GetIssue path.

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

* fix(httpclient): route every write role's refusals through inexpressible

Review finding 7: write-side refusals were not uniformly *ErrUnsupported.
Read roles already wrap encoder refusals through Store.inexpressible, which
reaches both encode.RefusedError and encode.CapabilityError; the write side's
refuse() returned a bare *encode.RefusedError instead, so a caller doing
errors.As(err, &unsupported) caught the count-scope refusal but missed
Sweeper.Sweep(Limit), DetectCycles(IncludeTracks), ReadyClaimer.ClaimNext,
BatchApplier.ApplyBatch, BatchCloser.CloseBatch, Deleter.Delete,
DependencyEditor.AddDependencies, and BatchCreator.CreateBatch.

Give InexpressibleError a detail field that preserves the original error's
composite text (an "items[%d]..." or "Issue.%s:" prefix a deeper encoder
helper already adds) instead of collapsing the message to the bare ledger
row text, and wrap every remaining write role's exported method in a single
named-return defer calling store.inexpressible, matching the pattern
lifecycle.go's Create/Update/Reopen already use.

Add TestWriteRoleRefusalsMatchTheReadShape, pinning three write-side
refusals (Sweeper.Sweep Limit, CycleDetector.DetectCycles IncludeTracks,
ReadyClaimer.ClaimNext) now classify via errors.As(*storage.ErrUnsupported)
the same way a read-side refusal does.

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

* fix(cmd/bd): stop spelling out Status: StatusOpen on a markdown batch create

Review nit 8: batchcreator.go's refuseUnwirableIssue refuses a populated
Status (apigen.BatchCreateItem has no wire slot for it), and
buildMarkdownBatchRequest always set Status: types.StatusOpen explicitly, so
`bd create --file` refused on every call against an http-backed store.

PreparePublicCreateRequest already defaults an empty Status to StatusOpen on
every backend, including the http client store's own server, so the explicit
assignment here was never a different outcome - only a populated member the
wire can't carry. Leave it unset; the created issue is identical on every
backend, and the http leg's role-level accounting for why Status and
CreatedBy are excluded from its allowlists is documented on
batchCreateCarriedIssueMembers (internal/httpclient/batchcreator.go).

CreatedBy is left as-is: that member genuinely has no wire slot AND the
server does not yet stamp it from Actor (a gap already tracked in this PR's
Follow-ups), so its refusal is correct, not a bug to route around.

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

* docs(httpapi): correct create.go's CreatedBy comment to caller-asserted

Review nit 8: the comment claimed CreatedBy is stamped from the
"authenticated actor," but actor is parsed straight from the request body
(s.bodyActor) and never authenticated - exactly as this file's own doc
comment states a few lines above. Reword to "caller-asserted actor" and
cross-reference that doc comment so the two stay consistent. No behavior
change: the stamp itself and its test coverage were already correct.

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

* fix(httpclient): raise MaxIdleConnsPerHost for a supplied client's nil Transport

Review nit 8: DialWith's doc comment promises the raised MaxIdleConnsPerHost
ceiling on every dial, "whether or not a CA is configured," but the
opts.HTTPClient.Transport == nil arm only injected a transport when the
target's CA was configured (resolved.configured()). A caller-supplied
*http.Client with a nil Transport and no CA fell through untouched, so it
defaulted to http.DefaultTransport's own ceiling of 2 at request time instead
- silently exempting this one shape from the doc's promise and forcing a
fresh TLS handshake on most of a concurrent burst even once the pool is warm.

Route this arm through the same dialTransport helper the opts.HTTPClient ==
nil arm above already uses (the CA-scoped transport when a CA is configured,
the shared baseline otherwise), injected onto a copy so the caller's own
*http.Client fields (Timeout, CheckRedirect, Jar) stay untouched.

Add TestDialWithSuppliedClientNilTransportNoCARaisesMaxIdleConnsPerHost: an
end-to-end burst through wire.Client.Do, traced with httptrace, asserting the
connection pool settles into reuse at a burst size the default ceiling of 2
cannot sustain.

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

* docs(httpclient): stop citing nonexistent design docs from new source files

Review nit 8: several comments added by this lift cited
engdocs/design/http-client-backend.md, "D8 row N", and beads-design/slices.json
- none of which exist in this repository (the design lived in the
bd-enterprise-internal source this code was lifted from).

Point each citation at what actually ships in-repo instead:
engdocs/design/http-divergence-ledger.md (the generated, human-readable
rendering of the divergence ledger in encode/ledger.go) for the D7/D8/D9
discipline citations in encode.go, ledger.go, bijection_test.go,
write_ledger_test.go, wire/credential.go and store.go's package doc; and a
direct description of the wire-gap it records, rather than a slices.json
scope reference, in leg_contract_wiring_test.go's cycle-tracks waiver
rationale. Regenerate http-divergence-ledger.md from ledger_render.go (which
had the same stale citation) via
`go test ./internal/httpclient/encode -run TestDivergenceLedgerDocMatchesLedger -update-ledger-doc`
so the shipped doc and its generator agree.

No behavior change; comment and generated-doc text only.

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

* feat(httpclient): implement issueops.BatchGetter for the HTTP client leg

The rebase onto origin/main (item 9 of PR #7247's review) brought in
upstream #7248's new issueops.BatchGetter role on storage.DoltStorage,
breaking the HTTP client leg's interface satisfaction. This wires it up
as a read role (no actor, no version guard, writes nothing — dialed as
a POST only because MaxGetManyIDs ids cannot ride a GET query string),
mirroring Counter/Querier rather than the WriteWire-wrapped roles.

- wire/paths.go: add PathIssuesBatchGet ("/v0/beads/issues:batchGet").
- batchgetter.go: httpBatchGetter.GetMany dials the server and stitches
  each resolved issue's RowVersion from apigen.BatchGetIssue.Revision
  (the role's only wire spelling of the row token, since RowVersion is
  json:"-"). checkGetManyIDs pre-validates the cap and blank-id rules,
  in the same order internal/storage/issueops.ValidateGetManyRequest
  applies them, because batch_get.go's failBatchGetErr collapses every
  validation failure into one generic, code-less InvalidArgument the
  client could never decode back into *issueops.TooManyIDsError.
- accessors.go: add the BatchGetter() accessor (26th wire-backed role).
- unsupported_gen.go: regenerated, dropping the now-implemented stub.
- completeness_test.go: move BatchGetter into wireBackedAccessors and
  bump the asserted accessor-matrix total from 28 to 29.
- served_test.go / served_harness_test.go: both package-local "by hand"
  httpapi.Config builders (serveRoles, serveConfig) now wire
  cfg.BatchGetter, fixing ~56 served-tier tests that broke once
  BatchGetter joined httpapi.Listen's required role set.
- served_batch_getter_test.go: wire the HTTP leg into all 14
  backend/conformance.RunBatchGetterXxx cases, following
  served_graph_counter_test.go's pattern. This surfaced a real bug:
  GetMany built Missing via append([]string(nil), body.Missing...),
  which stays nil when the server reports no misses, violating the
  role's "Missing is never nil on success" contract — fixed to build
  via make([]string, len(body.Missing)) + copy.

Verified: go build/vet clean; internal/httpclient suite green
(including the embedded-dolt served tier); TestEveryLegWiresEveryRoleContract
holds the http leg's adoption ceiling at exactly 42 with no change needed;
TestInterfaceCompleteness and TestAccessorMatrixMatchesDesign pass.

Co-Authored-By: Claude Sonnet 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/37450731721
(`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.

* test(httpclient): lock contextServer.seen against concurrent handler goroutines

TestDialWithSuppliedClientNilTransportNoCARaisesMaxIdleConnsPerHost drives
the stub with bursts of 8 concurrent requests; the handler appended to
seen without a lock. Readers only look at seen after their requests return.

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

* build(bazel): sync go_srcs managed blocks for unsupportedgen after the main merge

The PR adds internal/storage/unsupportedgen on a base that predates #7320,
which gave every Bazel package a managed repo_files filegroup. On the merge,
`python3 tools/bazel/go_srcs.py --check` (TestBazelGoSrcsBlocksCurrent) found
3 stale blocks: the package's own repo_files block, its entry in the root
BUILD.bazel repo_files list, and its entry in tools/bazel/BUILD.bazel.
`make bazel-sync` regenerated exactly those; gazelle changed nothing else.

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

* fix(httpclient): refuse DepAddItem.HasSpawner and ThreadID on applyBatch after the main merge

Main's #7209 gave issueops.DepAddItem two members, HasSpawner and
ThreadID, and a conformance case, RunBatchApplyStampsSpawnerIDOnlyWhenNamed.
ApplyDepAddItem on the v0 wire publishes source, target, type and
metadata only, so on the merge the http leg dropped both silently and
two of the PR's gates went red:

- TestEveryWireExcludedWriteMemberCarriesALedgerRow: the reflective
  census found two wire-excluded DepAddItem members with no ledger row.
- TestEveryLegWiresEveryRoleContract/http: the new case left the leg
  at 43 unwired cases against its exact ceiling of 42.

applyDepAddItemBody now refuses each member where the role would store
something the wire cannot say, under two new KindRefuse rows,
W-DepAddItem.HasSpawner and W-DepAddItem.ThreadID. The spawner flag
refuses only on a waits-for edge, because the role ignores it on every
other type and stores the same row either way. The ledger doc is
regenerated (264 rows).

The served tier wires the new case as a park on W-DepAddItem.HasSpawner,
owned by the family's existing bead, which brings the http leg back to
its ceiling. With the skip removed the case fails on the client's
refusal; with the refusal also removed it fails on the drop the row
names: spawner_id "" where the role stamps the resolved target.

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): address #7247 relaunch review iteration 1

Review iteration 1 of the relaunched adoption raised six majors. This
commit fixes all six. Five are the majors the first adoption's
iteration 1 raised. Its fixup, 696803f250 (tag
adopt-pr/bd-f5illd/stranded-fixup-696803f250), fixed them but never
reached the branch. That fix is ported here onto the contributor's
current head, with its reasoning unchanged; the sixth is new.

Creates refused what the CLI sends. Every `bd create` carries
CreatedBy, a workspace whose config.yaml names a prefix also carries
IDPrefix, and the client refused both.
- The server stamps created_by from the actor on all three create
  shapes: batch_create.go and batch_apply.go now match create.go.
- The client sends a CreatedBy that names the actor and refuses any
  other value, which the server's stamp would silently replace.
  createIssue and the apply create item share
  refuseUnwirableIssueMembers.
- IDPrefix refuses only where the role would act on it: an explicit,
  unforced id.
- `bd create --file` stays refused over http. Dropping its Status was
  safe but not enough: the batch create still refuses its Provenance
  and Owner. The markdown.go and batchcreator.go comments that called
  it servable now say so.

keysetFilter ignored AfterPriority. It now compares priority first,
mirroring sqlbuild's KeysetPriorityCreatedAtIDPredicate, and a new
served case resumes a priority keyset position. AfterID or AfterPriority
without AfterCreatedAt no longer reads as a zero-instant position that
discarded every row (the AfterID minor).

Claim with a patch was refused on a false ledger claim. `claim`,
`force_assignee_transfer` and `force_close_policy` now ride updateBody
like `force_notes_overwrite`, so a claim with a patch or a version guard
is one updateIssue call. A claim ALONE sent to a server that predates
the member (#6890) falls back to claimIssue. The three ledger rows are
retired, and the served cases parked on them now run.

OpenReadOnly returns a writable store. It stays writable, as a
documented exception: backends.Backend.OpenReadOnly also serves the
root pre-run's classified reads, and `bd ready --claim` writes through
that store. The exception is named in the backends.Backend contract,
the store_factory invariant and the store doc, and
TestReadOnlyOpenServesTheClaimBdReadyMakes pins it. An OpenNonMutating
backend hook is the follow-up.

Security surface.
- http_target.json is in the doctor gitignore template and its required
  patterns.
- BEADS_HTTP_TOKEN and BEADS_HTTP_TOKEN_COMMAND are host-scoped with
  BEADS_HTTP_CA_FILE's "host[:port]=value" syntax. A value scoped to
  another server falls through to the next rung, and a command scoped
  elsewhere never runs.
- LoadTarget and SaveTarget refuse a url that carries userinfo, and
  Target.String drops userinfo.

The served Tier 3 had no CI home. The new target
//internal/httpclient:httpclient_served_test is an `embedded`-tagged
sh_test. It reruns httpclient_test's binary through
tools/bazel/go_test_variant.sh with the script's
BEADS_TEST_EMBEDDED_DOLT=1 and BEADS_HTTP_TEST_REQUIRED=1, in 24 shards
on the embedded lane's race build. bazel.yml's bazel-embedded job
already runs `bazel test //... --config=embedded`, so no workflow
changes.
- -test.timeout=19m, not the script's 40m: Go's own timeout then fires,
  and dumps every goroutine, before the action's 1200s limit.
- TestBazelRetiredLanesCannotBeNarrowed pins its args and env. The new
  TestConformanceServedTierRunsUnderBazel ties the script's Tier 3
  switches to the rule.
- The new untagged TestServedTierIsLinkedWhenRequired fails a required
  run built without cgo, which drops every served file (the sentinel
  minor).
- A first 12-shard run found two test defects; both are fixed.
  TestServedBatchApplyBoundsTheItemCount's 1000-item apply outlasts the
  client's 60s per-request timeout under -race, so a
  race_detector_{on,off}_test.go pair scales its "at bound" half to 150
  there, as embeddeddolt's TestBatchApplyContract does. And
  TestTheCompositionCatchesAWrongParameter's dropped-filter case leaned
  on rows earlier tests had seeded: run alone, or first in its shard,
  it failed. It now seeds its own row outside the scope.
- conformance.sh, its script test and
  engdocs/CI_REQUIRED_CHECK_TOPOLOGY.md name the target.

Deviations from the review's suggested fixes:
- A bare BEADS_HTTP_TOKEN(_COMMAND) fails closed rather than falling
  back, and the error does not echo the value: a bare token split at an
  "=" would put token text into the pattern half. Dropping the bare
  syntax is safe today: the backend has no Register call site and no
  docs/ page names the variables.
- Target.String drops userinfo instead of using url.URL.Redacted, which
  masks only the password, so a token used as the username would print.
- The pre-#6890 claimIssue fallback leaves RowVersion unset instead of
  borrowing the follow-up read's token. That read is a second snapshot,
  so its token could postdate a write this claim never saw and arm a
  guard that should miss; a guard built from the unset token fails
  closed. Against a current server the claim rides updateIssue, whose
  `revision` is stitched as for any update.

Also fixed: the nit about the completeness failure message, which now
says to regenerate the shell, and the offrole.go tombstone comment that
named a skip list which no longer exists. Left for follow-up (all
latent, since httpclient.Register has no production caller): vocabOnce
latching a failed fetch, snapshot holding s.mu across the handshake
dial, unchunked graph anchors, private tracker IDs in park owners, and
the bounded journal limit above 10000.

Validation:
- git diff --check; gofmt -l; go vet over internal/httpclient/... and
  scripts
- go test -tags gms_pure_go over internal/httpapi/...,
  internal/httpclient/..., internal/storage/backends/... and
  backend/conformance/...; the doctor gitignore tests; the cmd/bd
  events-journal construction guard; ./scripts
- bazel test --config=embedded
  //internal/httpclient:httpclient_served_test on the lane's remote
  executors: 24 shards, 702 top-level tests, 632 pass, 70 skip (69
  ledgered KNOWN DIVERGENCE, plus
  TestCAFileHygieneRefusesGroupWritableFile, which finds no
  supplementary group on the executor), 0 fail, 0 data races; slowest
  shard 283s. tools/bazel/check_testcases.py --bep passes.
- each of the 702 tests run alone (go test -run '^Name$', without
  -race): 0 fail
- the whole tier under go test without -race, with the script's
  switches and -timeout=40m, before the two test fixes: 633 pass, 69
  skip, 0 fail
- removing BEADS_HTTP_TEST_REQUIRED from the rule fails both policy
  tests
- bazel test --config=ci over //internal/httpclient/...,
  //internal/httpapi/..., //scripts/..., //test/docsync/...,
  //internal/storage/backends/..., //backend/conformance/... and
  //cmd/bd/doctor/...: 32 tests pass
- make ci-pr-lint: nogo native plus windows/darwin, 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>

---------

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>
2026-10-08 12:01:09 +00:00
Julian Knutsen
6cd1184687
feat(httpapi): opt-in large issues:batchApply envelope (≤1000 items, one transaction) (#7051)
* 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>
2026-10-01 08:32:56 -07:00
Isis Anisoptera
45a116d1a7
fix(update): fence unforced --notes overwrites behind --force across all surfaces (#5946)
* fix(update): fence unforced --notes overwrites behind --force across all surfaces

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

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

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

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

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

CI surfaced three gaps in the fence's reach:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

---------

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

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

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

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

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

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

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

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

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

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

Maintainer review fixup for #6893.

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

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

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

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

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
2026-10-01 00:51:06 -07:00
Julian Knutsen
b858a29e4a
fix(contracts): JSON contract fixes before 1.3.0 freezes them — string revision tokens, --set-metadata scalar typing, create --json nano timestamps (#6053)
* 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>
2026-08-29 05:20:27 +00:00
Julian Knutsen
413887be94
Publish the row-version guard on close, reopen and delete (#5506)
* Publish the row-version guard on close, reopen and delete

`expected_version` already existed on all three roles — `CloseRequest`,
`ReopenRequest` and, since the deleter slice, `DeleteRequest` — and none of
the three published it. `internal/httpapi/close.go` even carried the reason
in a comment ("a precondition would need a frozen conflict code for
ErrVersionMismatch and a `row_version` on the issue body for clients to
echo"). Both of those landed with `updateIssue`'s guarded members:
`precondition_failed` is frozen, `PreconditionFailed()` exists, and
`UpdateIssueResponse.revision` is the token clients echo. This retires the
comment by making it false.

Spec first, then `make api-gen`, then the handlers.

- `closeIssue` and `reopenIssue` take `expected_version` and answer with
  `revision`. The guard is checked BEFORE the idempotent re-close and before
  the non-done no-op, which is the role's own order; `force` bypasses close
  POLICY and never the precondition.
- `deleteIssues` takes `expected_version` under the role's SINGLE-ID rule: a
  guard beside more than one DISTINCT id is a 400 naming the member, refused
  at the edge so the client gets a member name the role's own ErrValidation
  route cannot give it. Duplicates collapse after trimming, matching
  workapi.NormalizeDeleteIDs; a blank id is refused first so the arity rule
  cannot steal a broken list's answer.
- Every precondition arm is matched TYPED and FIRST. ClassifyError has no row
  for ErrVersionMismatch and neither leg wraps it in ErrValidation, so below
  those arms all three would answer a generic 500. Verified by mutation.
- `applyInt64Member` becomes `applyVersionGuardMember` and names the member
  itself: five call sites, one spelling, and no unparam exclusion.

Two tests changed rather than being added to: reopen's "publishes no conflict
code" is now "publishes no POLICY conflict code", written as an exact set, and
`TestDeleteRequestMembersMatchTheHandler` is new — that handler's member list
was hand-rolled with nothing tying it to the document.

Gates: `make api-check`, `go build ./...`, `go vet ./...`, `gofmt -l` clean,
`golangci-lint run` on the touched packages and `--new-from-rev=origin/main`
(0 issues), and `BEADS_TEST_PROXIED_SERVER=1 CGO_ENABLED=1 go test ./cmd/bd/
-run 'TestProxiedServerServeClose|TestProxiedServerServeDelete'` green against
real Dolt. The pre-commit hook's `go run golangci-lint@v2.10.1` fails on this
host with a toolchain mismatch unrelated to this change, so the hook's contents
were run by hand before committing with --no-verify.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

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

* Record the compare-and-set rule where the next handler author will look

Five handlers now match ErrVersionMismatch typed before reaching failErr, and
each said why in its own words. That is five coincidences, not a rule: handler
author #6 reads ClassifyError, finds no row for the sentinel, and concludes the
shared mapping covers it.

State it at ClassifyError instead. That function CANNOT build a
precondition_failed — the refusal echoes the value the REQUEST guarded on and
ClassifyError is handed an error alone — so any operation publishing
expected_version, expected_status or expected_assignee must match the sentinel
typed in its own failure path. Forgetting is not a worse 4xx: neither storage
leg wraps these in ErrValidation, so the miss falls through the default arm and
every guard failure on that operation is a generic 500.

The three handlers this stack added now cite that rule rather than restating it.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

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

* lint: the last US spelling in problem.go

main was red on its own Lint job (misspell, locale US) from two words the
release slice added. `neighbour` has since been fixed upstream; `archaeology`
at problem.go:85 is the one left, and the PR workflow lints the whole tree with
only-new-issues: false, so every open PR inherits the failure until it goes.

Not this stack's breakage, and landed here only because this stack is what it
was blocking. Prose only; no behavior.

---------

Co-authored-by: Review Sim <ci@beads.test>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-09 17:02:53 -07:00
Julian Knutsen
e9e2c49431
Add issueops.BatchApplier: one plan, one transaction (#5480)
* Add issueops.BatchApplier: one plan, one transaction

A heterogeneous, ORDERED list of creates, updates, closes and edges applied
as one durable act. Each of BatchCreator, BatchCloser and DependencyEditor is
one verb repeated, so a caller that needs two of them needs two transactions
with a window in between; this role's unit is a PLAN.

The role, the two bodies, both decorators and the accessors on every
implementer. The wire half and the conformance contract land beside this.

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

* Close the empty-commit-message hole a no-op batch could open

ApplyBatchCommitMessage now reads the write as well as the result. The counts
are ItemResult.Changed, which is what a CALLER observes; a request can still
write a durable row with every count at zero — a same-type edge re-add
rewrites that edge row's metadata, a re-close can settle blocked state. An
empty message for one of those is an unlabelled Dolt commit on the store legs
and a rollback of a real write on the unit-of-work leg.

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

* Give BatchApplier the contract its two bodies justify

Thirty-nine cases over three legs and TWO independent bodies — the store legs
share issueops.ApplyBatchInTx, the unit-of-work leg cannot reach it, and the
contract header says so rather than claiming three backends agree.

The end-gate case is the one that could not have been written before: every
edge in it is legal when it is written, and only a re-validation against the
closure the whole request produced refuses the pair.

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

* Publish batchApply on v0, and delete batchCreate's false promise

The spec first, the types from it, the handler against the types. The item
union is a TAGGED single-shape object rather than a oneOf, because the
document's x-go-type doctrine forbids composition keywords; the create item
publishes sender, metadata, status, ephemeral and no_history, none of which
batchCreateIssues has — which is why no measured caller could use that one.

The wire result stays lean: ids, changed and a revision. The hydrated
snapshot on the Go contract is what the completion hooks consume, and hooks
never fire on this surface.

OQ2: batchCreateIssues' description claimed a dependency target could name an
earlier item of the same batch. It never could — the server mints the ids and
a wire item has no name — so the paragraph is deleted rather than qualified.

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

* Partition the two new dependency probes on the recorder's surface

The gate halves BatchApplier re-runs are repository PROBES — an ancestry walk
and a reachability walk — so recordingDepUC declares neither and the parity
test has to say so out loud rather than let embedding answer for it.

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

* Teach the proxied topology's capability golden about batchApply

The one expectation stored as data outside the package whose gates would
otherwise have caught it — which is what its own header warns about.

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

* Restore the CAS hook case, mint 409 already_exists, and stop over-claiming

Three fixes from review.

The rebase that brought MetadataCAS in left `case *hookMetadataCAS:` with an
EMPTY BODY: a Go type switch does not fall through, so RoleFiresHooks answered
FALSE for it and #5473's Listen refusal was silently disarmed. The compiler,
vet, lint and CI all pass on that. The case is restored and — because it had no
precondition of its own, which is why nothing caught it — serve_source_test now
pins CAS the way it pins the other four, with its peel assertion.

An occupied explicit create id becomes 409 already_exists rather than 400. The
body is well-formed and stays well-formed; what refuses it is state the client
must READ, and recovery is to look at that state. A dead 409 retires for free
where a narrowed 400 breaks clients.

Two headers claimed all three legs share the store body — every clause false,
one citing the contract header as agreeing when it says the opposite — and the
plan file gave a placement reason that is MetadataCAS's, not this role's. The
end-gate claim in ADDING_AN_ISSUEOPS_ROLE.md is narrowed to the true thing: the
two LEAF checks are shared, the orchestration around them forks.

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

* Give the scheduling-edge set one definition, in types

Four packages walked {blocks, conditional-blocks, parent-child} under four
names — isSchedulingEdge, isSchedulingDep, isSchedulingDependency, and the
isApplySchedulingEdge this branch added as the fourth. Adding a fifth
scheduling type was four edits with nothing to catch a missed one.

It goes in internal/types rather than the issueops leaf the review named,
because internal/storage/issueops imports internal/storage/domain, so domain
cannot import back and two of the four copies would have survived there. Beside
the Dep* constants themselves, every walker reaches it: nine call sites, one
definition, one edit for a fifth type.

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

---------

Co-authored-by: Review Sim <ci@beads.test>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-09 06:59:34 -07:00