Commit graph

29 commits

Author SHA1 Message Date
Julian Knutsen
2563f021ed
perf(httpclient): remember the server's external-dependency policy across processes (#7700)
* perf(httpclient): remember the server's external-dependency policy across processes

Every bd ready over an HTTP workspace fetched GET /v0/beads/context before
its listing. listReadyWork itself needs no handshake; the fetch came from the
external-dependency decorator asking ServerEnforcesExternalDependencyPolicy
whether the server already applies the policy. In a one-shot CLI that is one
extra round trip per process (about 54 ms at a 52 ms RTT) to relearn a bit
that only changes when the server is restarted with a different composition.

The store opened from a workspace now keeps that answer in the user cache
directory (beads/http-policy/), keyed by the server URL and the project the
workspace pinned at bd connect, for BEADS_HTTP_POLICY_CACHE_TTL (5 minutes by
default; off disables it). A fresh entry answers the probe without dialing; a
handshake this process already holds wins and refreshes the entry. A
workspace with no project pin, and a store an embedder opens through
OpenWith, are not cached. Writing the entry is best effort.

The staleness this allows is bounded by the TTL: a server restarted without
the policy within the window is still trusted to enforce it until the entry
ages out. Carrying the policy on every response would close that window but
needs a server change and does nothing for servers already deployed.

Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of gascity-agent
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(httpclient): claims and closes ask the server for the policy, never the cache

Review follow-up to the policy cache. The claim and close guards (direct
claim, claim-next, batch close, the lifecycle close and claim, and the legacy
ClaimReadyIssue and CloseIssueChecked) handshake anyway, and a stale cached
"the server enforces it" would stand down their client-side refusal of
externally blocked work. Those entry points now mark their context with
storage.WithLivePolicyProbe, and httpclient.Store answers such a probe from
the server, refreshing the cache entry. Reads keep the cached answer.

Tests: externaldeps TestClaimsAndClosesAskForALivePolicyProbe and
TestRemoteClaimsAndClosesAskForALivePolicyProbe pin which entry points probe
live (every claim and close) and which do not (ready listings), over a local
and a remote store; httpclient TestALiveProbeSkipsThePolicyCache pins the
store side; TestPolicyCacheRefusesEntriesItCannotTrust now also covers an
entry written for another server URL.

Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of gascity-agent
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-19 19:05:55 +00:00
Julian Knutsen
d097b6c8a4
perf(ready): skip the countReadyWork request when bd ready --json prints no total (#7699)
* perf(ready): skip the countReadyWork request when bd ready --json prints no total

Over a remote backend, bd ready --json sent GET /v0/beads/ready and then,
whenever the page came back with has_more, GET /v0/beads/ready:count, only to
put "of N" into the stderr hint. Without BD_JSON_ENVELOPE nothing else prints
the total, so that second request (about 120 ms at a 52 ms RTT) bought a
number no caller reads.

On a remote backend without the envelope, bd ready --json now lists one row
past the limit and says whether more exist without saying how many, in the
wording the proxied route already uses. A local store keeps the in-band total
it takes in the page's own transaction, and the envelope keeps
pagination.total. A --max-rows cap at or below the limit keeps the counted
listing, so the extra row never trips the cap.

Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of gascity-agent
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(ready): say "1 ready issue", not "1 ready issues", in the no-total hint

Review follow-up. The hint the remote --json path shares with the proxied
route now agrees in number; both routes take it from readyHiddenHint, so
they stay one wording.

Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of gascity-agent
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-19 18:15:57 +00:00
Julian Knutsen
9e2f25c322
fix(http): bd link over a connected HTTP workspace, through the DependencyEditor role (#7685)
* fix(http): bd link over a connected HTTP workspace, through the DependencyEditor role

bd link wrote through the store's raw AddDependencyWithOptions, which the
HTTP client refuses by design (D8), so every bd link failed on an HTTP
workspace whatever the type. Its direct route now writes through the
DependencyEditor role with the helper bd dep add uses
(addDependencyEdgesDirect), which serves local stores and HTTP workspaces
alike: over HTTP one dependencies:add request, and the server already takes
any 1-32 character type.

link keeps its own checks before the write (and before the dial): the
dotted-child rule and the type's length only, never bd dep add's
well-known-type list. The proxied-server route is unchanged.

backend/http TestE2E_LinkOverHTTP covers owned-by and the other roadmap
types, the empty and over-long type refusals (no write reaches the server),
and the typed conflict for an edge of another type.

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/39201892756
(`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.

---------

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>
2026-10-19 07:15:13 +00:00
Julian Knutsen
4450fe99bb
feat(http): bd blocked over bd serve (blocked.list), plus bd blocked --flags [--raw] (#7649)
* feat(http): bd blocked over bd serve (blocked.list) through issueops.BlockedLister

`bd blocked` refused against an HTTP workspace: it called the legacy
GetBlockedIssues, which the HTTP backend stubs as unsupported. It now runs
one role on every route, and bd serve publishes that role.

- Role: issueops.BlockedLister.ListBlocked(BlockedRequest{ParentID, Labels,
  LabelsAny, ExcludeLabels}) -> BlockedResult{Items}. One body,
  internal/storage/issueops.ExecuteListBlockedInTx over the unchanged
  GetBlockedIssuesInTx; labels normalized in the role (BlockedFilter);
  Items never nil and in a total order (priority, created_at desc, id).
- Legs: DoltStore (read tx), EmbeddedDoltStore (read conn), uow (read unit
  of work through the use case's GetBlockedIssues, so the
  external-dependency uow decorator applies). Census: storage.DoltStorage
  gains BlockedLister(); HookFiringStore passes it through (a read),
  telemetry wraps it, uow.notifyingProvider, externaldeps.uowProvider and
  httpapi.timedProvider build it.
- externaldeps.Store.BlockedLister is built over its own GetBlockedIssues,
  so local `bd blocked` output is unchanged. Over a remote store it takes
  the server's listing when the server advertises
  policy.external_dependencies, else decorates the server's listing here
  through EdgeReader and BatchGetter (decorateBlocked, factored out of
  GetBlockedIssues).
- Wire: GET /v0/beads/blocked (listBlockedIssues; parent, label,
  label_any, exclude_label) answering BlockedPage {items, has_more} with
  the new x-go-type-pinned BlockedIssue schema, behind the new
  blocked.list token. apigen and the wire-shape golden regenerated; the
  golden diff is additive only, so wire_revision stays 2.
  Config.BlockedLister is a required role, wired in bd serve.
- Client: httpclient.Store.BlockedLister dials through Store.dispatch, so
  an older server is refused BEFORE the dial with *wire.CapabilityError
  naming blocked.list. The legacy Store.GetBlockedIssues rides the role
  (page and row cap applied to its answer) and leaves the unsupported
  shell. Divergence ledger row F-blocked retired.
- CLI: `bd blocked` takes BlockedLister() from the store on the direct
  routes and from the provider's BlockedListerSource on the proxied route;
  runBlockedProxiedServer is deleted. --json output is the same rows in
  the same order, [] when empty.

Tests: backend/conformance RunBlockedLister (10 cases: direct blocker,
child attributed to its blocked parent, closed blocker, wisp plane, pinned
status, parent filter, label filters with normalization, order, empty
slice, request not mutated) on dolt, embedded, uow and the served HTTP
client; httpapi handler tests (mapping, unknown/repeated params,
projection, capability); httpclient stub tests (pre-dial refusal naming
the token, encoding, projection, legacy door paging); skew and vocabulary
counts; TestE2E_BlockedOverHTTP (served `bd blocked --json` equals the
local command's after mapping ids and timestamps, member order included,
external blocker named, older-server refusal with no dial); corpus
gc-blocked re-marked and gc-blocked-parent added, both pending until the
reference server advertises blocked.list.

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

* fix(blocked): pin server-side external decoration, refuse has_more, serve the legacy door over http

Review fixes for the blocked.list slice.

- Server-side external decoration is now pinned on the compositions bd
  serve answers from. TestWrapUOWProviderBlockedListerNamesExternalBlockers
  lists through the wrapped unit-of-work provider's own BlockedLister
  accessor (the bd serve provider path) and requires an external-only row
  and a mixed row to carry their external: refs; building that lister over
  the inner provider fails it. TestServedBlockedListerCarriesExternalRefs-
  WhenTheServerEnforces serves the store-shaped composition
  (externaldeps.Store.BlockedLister, policy advertised) and requires the
  operation's own answer, through the undecorated client role, to carry the
  refs, and the client's decorated chain to return it unchanged; serving
  the inner store's lister fails it.
- The client refuses an answer reporting has_more with the new typed
  httpclient.TruncatedListingError instead of returning a short listing:
  the operation has no cursor, and a caller reads a missing row as
  unblocked. The legacy door inherits it.
- externaldeps.Store.GetBlockedIssues over an http store reads the extra
  sources through the served roles (EdgeReader, BatchGetter) instead of the
  raw GetIssuesByIDs / GetDependencyRecordsForIssues the http backend
  refuses, and the decoration skips the source read when there is nothing
  to load. The legacy door on the CLI chain (bd mol stale, the wisp
  commands) now answers over http in both policy modes;
  TestServedLegacyGetBlockedIssuesThroughTheDecorator pins it, paging
  included. bd ready --explain still refuses on its other raw reads; the
  CHANGELOG says so.
- Docs: the spec and the retired F-blocked ledger row state that the
  listing is unpaged, bounded by the client's 32 MiB response limit
  (refused, never read in part), and that has_more is refused.
- Contract: new cases for waits-for and conditional-blocks blockers, no
  type exclusions (gate, epic), and a stale flag with no nameable blocker
  (on the legs that can write the column: dolt, embedded; skipped
  elsewhere with the reason). Order seeds explicit created_at values with
  five rows tied on priority and created_at, two of them wisps, so only the
  id tiebreak orders them; dropping the tiebreak now fails every run.

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

* feat(blocked): bd blocked --flags, the blocked flag per id from stdin

`bd blocked --flags [--json]` reads ids from stdin, one per line (blank
lines and repeats ignored), and prints the blocked flag bd holds for each:
with --json, [{"id","is_blocked"}] in the order the ids were first given,
omitting an id that names no row on either plane, [] for no input. It is
the readiness column a consumer otherwise had to read with `bd sql`, so no
such consumer needs a local-only command.

It is the FLAG, not the listing: `bd blocked` narrows the stored flag to
rows it can name a blocker for, and --flags does not, so a row whose flag
is set with no nameable blocker reads true here and is absent from the
listing. Where the external-dependency policy applies, an unsatisfied
external: blocker sets the flag, as it keeps the row out of `bd ready`.

One library entry on every route: issueops.BlockedFlags over the route's
BlockingAnnotator (the store's accessor on dolt, embedded and HTTP, the
provider's on the proxied route). Over HTTP that is listBlockingAnnotations
with is_blocked behind dependencies.blocking.isBlocked; a server without
that token is refused before the dial, naming it. No wire change. The
listing's filter flags are refused with --flags rather than ignored.

Tests: TestE2E_BlockedFlagsOverHTTP (served JSON equals the local command's
after mapping ids to titles, unknown id omitted, repeat collapsed, [] on
empty stdin, filters refused; a stale-flagged row with no blocker reads
true and is absent from `bd blocked --json`, which fails if --flags is
derived from the listing; an older server's handshake refused naming the
token with no dial); TestProxiedServerBlocked/flags_reads_ids_from_stdin on
the proxied route; corpus gc-blocked-flags, pending until the reference
server advertises the token. CHANGELOG entry.

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

* feat(blocked): bd blocked --flags --raw, the stored is_blocked column

`bd blocked --flags --raw [--json]` answers the stored is_blocked column
for each id read from stdin, exactly what reading is_blocked from the issues
and wisps tables returns, without the external-dependency policy: a row
blocked only by an unsatisfied external: ref reads false (the policy-aware
--flags reads true), and a stale flag reads true either way. Same output
shape as --flags. This lets a consumer move off a `bd sql` read of the
column with no change in what it reads. The default --flags is unchanged.

The role is taken from beneath every decorator: storage.UnwrapStore on the
direct routes, uow.UnwrapProvider on the proxied route. Over HTTP the
innermost store is the http client, whose annotation read is the server's
answer: against a server that does not advertise
policy.external_dependencies that answer is the column, and --raw is
served. A server that advertises it decorates the flag it answers, the v0
wire has no member asking it for the column, and the decorated flag cannot
be turned back into the column client-side, so --raw against such a server
is refused before the annotation read, naming the token, rather than
answered with the decorated flag. --raw without --flags is refused.

Tests: TestE2E_BlockedFlagsOverHTTP/raw_is_the_stored_column (served --raw
equals local --raw; the externally-blocked-only row reads true with --flags
and false with --raw on both; locally blocked rows agree; a stale-flagged
row reads true in both modes; --raw without --flags exits 1; a server
advertising the policy refuses --raw with no annotation request);
TestProxiedServerBlocked/flags_raw_is_the_stored_column; corpus
gc-blocked-flags-raw (pending until the reference server advertises
dependencies.blocking.isBlocked). Routing --raw through the decorated
annotator fails the e2e. CHANGELOG entry.

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

* docs(changelog): bd blocked --flags --raw is for the local and proxied routes

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

* test(blocked): give the e2e gate-kid its own priority; document --flags answers closed ids

TestE2E_BlockedOverHTTP seeded gate-parent and gate-kid at one priority, so
when both landed in the same second their order fell to the generated ids,
which differ between the local and the served workspace: the comparison
failed intermittently. gate-kid now has its own priority. Ten runs on the
embedded lane pass.

bd blocked --flags answers a closed id too, with its stored flag; a SQL read
of the column filtered on status <> 'closed' leaves it out. Said in the
command's doc and the CHANGELOG.

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

* fix(blocked): apply label filters to external-only blocked rows

The external-dependency policy appends a row blocked only by an
unsatisfied external: ref after the label query has run, so --label,
--label-any and --exclude-label never judged it: bd blocked and
GET /v0/beads/blocked listed it whatever its labels, on every route.
Both decorators now filter those rows by the request's labels. The uow
decorator reads them through GetMany, chunked at MaxGetManyIDs, so their
labels are hydrated; GetIssuesByIDs left them empty, which also printed
them unlabelled on the proxied route.

Review fixes (adopt-pr apply-fixes, iteration 1):
- major #1: label filters on external-only rows in the store and uow
  decorators, with absence-asserting arms in the unit, served httpclient
  (server- and client-enforced policy), e2e and proxied tiers; the spec
  and the role doc say such rows are narrowed like every other row.
- minor #2: the policy.external_dependencies token prose names the
  blocked listing (spec, routes.go, regenerated types.gen.go).
- minor #6: SERVE_RUNBOOK and the allowUnlimited comment record the
  blocked listing's unbounded whole-set answer and why.
- minor #10: BlockedLister telemetry-outermost and typed-unsupported pins
  beside the ReadyCounter pair, plus the externaldeps wrap pin.
- nit #9: F-blocked names --flags --raw's refusal against a server that
  applies the policy (ledger.go and the regenerated ledger doc).
- nit #11: the remote BlockedLister no longer builds a local lister it
  then discards.

Review fixes (adopt-pr apply-fixes, iteration 2; the review approved at
940 with one minor and two nits, none gating):
- minor (the --flags refusal list was unpinned): the new
  TestBlockedFlagsRefusesEveryListingFilter pins blockedFlagFilterFlags
  to the flags blockedCmd registers, in both directions. Every
  registered flag except --flags and --raw must be refused, and every
  entry must name a registered flag. The test walks Flags() rather than
  LocalFlags(), so it does not merge the root's persistent flags into
  blockedCmd, and it skips inherited root flags and cobra's --help.
  Mutants:
  - four fail it: a new filter flag left off the list, a dropped
    entry, a misspelled entry, and --raw added to the list;
  - a simulated earlier in-process run (merged root flags plus --help)
    stays green, and fails once either skip is removed.
- nit (the remote branch's span): the remote BlockedLister comment now
  says why that lister is not wrapped again. The inner lister already
  carries telemetry's span, so wrapping would nest a second span of the
  same name. The comment also says what runs outside that span.
- nit (duplicated order comparator): left as is. finishBlockedIssues
  predates this PR, so merging the two sorts would refactor existing
  code with no review pass left after this one.

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

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Co-authored-by: Eddie the Engineer <338826946+gascity-eddie[bot]@users.noreply.github.com>
2026-10-17 12:29:13 +00:00
Julian Knutsen
601be8a6bf
feat(list): bd list's remaining filters over http behind issues.list.filters (#7647)
* feat(list): bd list's remaining filters over http behind issues.list.filters

Over http every `bd list` filter beyond the created bounds and the title,
id and no-assignee scope refused (time bounds, priority range, text and external-ref
matches, spec, label pattern/regex, exclude-type, no-parent, no-labels,
empty-description, pinned/no-pinned, deferred, overdue, mol/wisp type).
The library entry already applied all of them: issueops.Reader.List via
workapi.BuildListFilter, shared by the CLI and the handler. This adds
only the wire.

- Server: GET /v0/beads/issues decodes 29 new optional parameters
  (listFilterParams, decode only; countIssues' names where it already
  spells the filter) into the existing ListRequest, behind one new
  behavior token, issues.list.filters. mol_type/wisp_type are closed
  enums refused by name (an empty value too). wire_revision stays 2;
  apigen and the wireshape golden are regenerated (additive only).
- Every RFC 3339 bound the listing and count decode is normalized to UTC,
  so an offset-bearing bound selects what its Z twin does on a zone-less
  timestamp column.
- workapi.BuildListFilter refuses PinnedFlag with NoPinnedFlag
  (ErrValidation, the CLI's own sentence) instead of letting PinnedFlag
  win; over http that is a 400 on no_pinned.
- Client: the encoder sends the members (encode.ListFiltersMembers, one
  list read by the encoder, the pre-dial gate and a spec-parity test).
  Against a server not advertising the token, httpReader.List refuses
  before dialing with ErrUnsupported naming issues.list.filters. The 29
  E-ListRequest ledger refusal rows retire; the ledger doc is updated;
  skew flag mappings added.
- Tests: handler decode/parity/enum/UTC/malformed/pinned-pair tests;
  encode member/gate/spec parity and bound encoding; per-member
  ride-behind-token and pre-dial skew refusal; two new Reader contract
  cases on every leg (dolt, embedded, uow, served): the eight time
  bounds at exact boundaries (strict, whole-second truncation, NULL never
  matches, +02:00 equals UTC) and one in/out row per remaining family;
  three served Reader cases unparked; TestE2E_ListFilterParityOverHTTP
  (served == embedded, masked server refuses naming the token, no dial);
  five corpus shapes marked pending until the reference server profile
  advertises the token.

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

* feat(list): exclude_status on listIssues, the 30th issues.list.filters member

issueops.ListRequest gains ExcludeStatus: statuses to leave out of a
listing, appended to the default exclusions (never re-admitting what they
hide), comma-separated or repeated, and validated against the workspace's
statuses by the same rule CountRequest.ExcludeStatus uses (an unknown name
is ErrValidation). The rule moves into one shared function,
workapi.ParseExcludeStatus, called by both builders. With AllFlag it reads
the active set without enumerating every status, so an http-backed caller
can list O(active) rows instead of the whole history.

- Server: listIssues decodes a repeatable `exclude_status` under the same
  issues.list.filters token (no new token); an unknown name is a 400 on
  exclude_status. apigen and the wireshape golden are regenerated
  (additive).
- Client: the encoder sends it and it joins encode.ListFiltersMembers, so
  the pre-dial gate asks for the token.
- It is refused together with ReadyFlag, like the other members the ready
  query cannot carry.
- No `bd list --exclude-status` flag yet (it would need the CLI docs
  regenerated); the member is reachable through the library and the wire.

Tests: builder unit test (append, AllFlag, comma split, unknown name);
handler decode and 400; encoder, round-trip and gate; Reader contract
cases on every leg (active set under AllFlag, repeated and comma values,
adds to the defaults, narrows an explicit Status, unknown name refused).

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

* fix(list): label_regex compile errors are 400s; review polish for list filters

- An invalid `label_regex` on GET /v0/beads/issues, /v0/beads/ready and
  /v0/beads/ready:count is now `400 invalid_argument` (`invalid_value` on
  `label_regex`) instead of `500 internal`. The database still compiles
  the pattern in its own dialect; a request that sent a regex and earned
  the engine's "regular expression is invalid" refusal is attributed to
  the parameter (failRegexReadErr). The same text on a request with no
  regex stays a server fault.
- mol_type and wisp_type refuse each other's vocabulary (tests pin
  `mol_type=heartbeat` and `wisp_type=swarm`), so the call-site
  allowlist, not just the spec enum, is covered.
- exclude_status with a workspace custom status: leg tests on the
  embedded store and over the served wire (accepted and applied; a name in
  no vocabulary refused). ReaderFixture cannot configure custom statuses,
  so these sit beside the count's twin rather than in the contract.
- The search e2e gains a positive arm: --desc-contains returns exactly the
  row whose description carries the token.
- Docs: `all` plus `exclude_status` keeps every status not named (pinned,
  hooked and custom done/frozen included unless named), not "the active
  set"; label_regex documents its 400. A corpus source line is made
  neutral; a test message says 30.

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

* fix(list): compose issues.list.filters with the --title-contains fold

#7631, now on main, folds `bd list --title-contains` onto listIssues
`title` and refuses the TitleContains left over from a --title and
--title-contains pair that differs, because the listing then had one
title parameter. This branch publishes `title_contains` behind
issues.list.filters, so that leftover now rides it beside `title` and
the server applies both. Neither half is dropped, and against a server
without the token the pre-dial gate refuses, naming issues.list.filters.

- encode.FoldTitleContains still runs first; its doc now says where a
  differing pair goes.
- Tests: the fold table expects `title` plus `title_contains` for a
  differing pair, including the ſ/s pair strings.EqualFold would match;
  the differing-pair refusal names issues.list.filters; the
  list_filters_test sweep pairs its TitleContains probe with a differing
  TitleSearch, since a lone one asks only for issues.list.title; the e2e
  differing-pair refusal becomes a listFilterShapes row that answers
  exactly child-a over http and embedded, and refuses before dialing
  without the token.
- The gc-polecat-closed-after corpus shape's pending reason also names
  issues.list.title. The CHANGELOG --title-contains entry no longer
  lists the differing pair and --closed-after as refused.

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

* build(bazel): auto-sync BUILD files

Applied from the bazel-sync-patch artifact of https://github.com/gastownhall/beads/actions/runs/39013611268
(`make bazel-sync`: gazelle, tools/bazel/go_srcs.py, bazel mod tidy).
Only BUILD.bazel, MODULE.bazel and MODULE.bazel.lock are ever pushed; see
scripts/bazel-autofix-push.sh.

* fix(list): serve --priority-max in search parity, refuse the parent pair

The proxied tier's search parity table still expected a remote
`bd search --priority-max 1` to refuse, because listIssues could not
carry it. This branch serves priority_max behind issues.list.filters,
so the remote route answered and the dolt-race shard went red in
TestProxiedServerSearchRoutesAgree. The row now expects the answer on
every route. It was the last wireCan=false row; the branch stays, with
a comment, for the next flag listIssues cannot carry.

- ParentID with NoParent: a served listing now carries no_parent beside
  parent, and ANDing the two answered only the edge-less rows under the
  parent's dotted id. BuildListFilter refuses the pair with
  ErrValidation, in the sentence bd list and BuildCountFilter already
  use, so issueops.Reader.List refuses it on every backend and the
  listing answers 400 on no_parent. Pinned by a builder test, a reader
  conformance case (dolt, embedded, uow, served http) and two httpapi
  tests.
- POST /v0/beads/issues:claimNext shares the ready listing's
  label_regex but answered a pattern the database cannot compile with
  500. It now gives the listing's 400 invalid_value on label_regex,
  through the helper the listing's mapping is split into.
- The descendant walk's ledger rows said listIssues publishes no
  parameter for members it now serves behind issues.list.filters. They
  now say the walk does not send them yet, and that --flat or --json
  asks listIssues directly. The ExcludeStatus, Pinned and ExcludeTypes
  rows, the parentwalk.go header, the walk table's doc and two walk test
  comments are corrected the same way, and the ledger doc is
  regenerated. parentWalkRefusals notes that a member moved off the list
  must check issues.list.filters itself, because the walk dials past
  the listing's pre-dial gate.
- Spec: the listing's no_parent documents the pair's 400, the count's
  exclude_status no longer says it has no listing counterpart, and
  claimNext's label_regex documents its 400. types.gen.go is
  regenerated. Comment-only: countFilters, and readyScopeFields'
  ExcludeStatus entry.
- CHANGELOG and README say the default `bd list --parent` tree view
  does not carry the new filters yet; the label_regex entry names
  claimNext, and a Changed entry records the parent-pair refusal.

Second review pass: docs and comments only, no behavior change.

- The prose copies of the issues.list.filters member set now match
  ListFiltersMembers: CapIssuesListFilters and wire.CapListFilters name
  the status exclusion, and the spec's capabilities text names
  label-regex.
- Every time bound on the listing and the count goes through
  q.timestamp, which normalizes it to UTC, and sqlbuild compares it
  strictly at whole-second precision. listIssues' created_before and
  created_after, and countIssues' created, updated and closed bounds,
  now say so in the words the new listing bounds use. The count's
  updated bounds also say what they filter, and its closed bounds say
  that a NULL closed_at never matches. types.gen.go is regenerated.
- README and CHANGELOG: `--flat` or `--json` applies the filters to the
  parent's direct children, not its whole subtree.
- The 29 listRefusal rows this branch serves stay deleted rather than
  kept as retired rows, as #7550 deleted its TitleSearch, IDFilter and
  NoAssignee rows when it served them. The CHANGELOG now says the rows
  are removed, not retired.

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

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Co-authored-by: Eddie the Engineer <338826946+gascity-eddie[bot]@users.noreply.github.com>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-10-17 11:21:18 +00:00
Julian Knutsen
925e26bc48
fix(http): serve bd list --title-contains by folding it onto title (#7631)
* fix(http): serve bd list --title-contains by folding it onto title

`bd list --title-contains X` refused against an HTTP workspace because
listIssues publishes no title_contains parameter. The store compiles
TitleContains and TitleSearch to the same predicate (LOWER(title) LIKE
'%v%'), so the client now folds TitleContains onto TitleSearch before the
pre-dial gate (encode.FoldTitleContains) when TitleSearch is empty or equal.
The request then rides the existing `title` parameter behind
issues.list.title, and against a server without that token it refuses before
dialing, naming the token. A --title and --title-contains that differ still
refuse: the listing has one title parameter and dropping either value would
widen the answer.

No wire change. The ledger row E-ListRequest.TitleContains narrows to the
differing pair.

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

* fix(http): fold case-only title pairs and qualify the CHANGELOG

Review fixups for #7631.

- FoldTitleContains also folds a pair that differs only in letter case.
  The store binds each value as '%' + strings.ToLower(v) + '%', so a pair
  equal under strings.ToLower is one predicate. It does not use
  strings.EqualFold, which matches pairs such as "ſ" and "s" that lower to
  different patterns. Unit cases pin both directions, and the served test
  answers a case-only pair like the single flags.
- CHANGELOG: name what still refuses over HTTP: a pair that differs other
  than in case, either flag with --parent in the default tree view, and
  --closed-after, which gascity's polecat pre-flight lookup of recently
  closed beads (step 3d) uses.
- Corpus: add gc-polecat-title-contains-closed-after, the 3d lookup,
  pending until the reference server advertises issues.list.title and
  listIssues carries closed_after (E-ListRequest.ClosedAfter).
- Drop two assertions that could not fail (a request passed by value
  cannot be mutated), and bring the e2e shape header, the
  tokenedListFilters comment, the encoder table comment and the
  E-ListRequest.TitleContains ledger row (doc regenerated) up to date.

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

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Co-authored-by: Eddie the Engineer <338826946+gascity-eddie[bot]@users.noreply.github.com>
2026-10-17 06:00:33 +00:00
Julian Knutsen
ae693ef7cc
fix(http): bd gate create, add-waiter and discover over a connected HTTP workspace (#7621)
* fix(http): gate create, add-waiter and discover through the library roles

bd gate create, bd gate add-waiter and bd gate discover wrote through the
legacy CreateIssue, AddDependency and map-based UpdateIssue, which the http
store does not implement, so over a connected HTTP workspace each failed
before any gate member reached the wire. They now run through the roles on
every route (direct, proxied server, http):

- gate create is ONE Lifecycle.Create carrying the gate members and a
  reverse blocks edge from the blocked issue to the new gate: atomic on
  every route, one createIssue over http behind issues.create.gates. The
  proxied-server route's private unit of work is gone; it uses the same
  role.
- gate add-waiter reads through Reader.Get, deduplicates, and writes the
  whole waiter list through Lifecycle.Update guarded by the row version it
  read, retrying up to three times on ErrVersionMismatch, so concurrent
  adders cannot lose each other's waiter. Over http: issues.update.gates.
- gate discover lists through issueops.ListGates and records the run ID
  through the same Lifecycle await_id patch gate check makes; bd close's
  gh:run persist (updateGateAwaitID) takes the same path.
- Against a server without the token, each refuses before any write,
  naming the token.
- gate discover skips template gates, as gate check already does, instead
  of recording a run ID on a proto every later pour copies.

Tests: unit tests for the one-Create shape, the refusal, the add-waiter CAS
retry, and discover over ListGates with its template skip;
backend/http TestE2E_GatesOverHTTP (advertised and masked); four served
corpus shapes, pending until the reference server advertises the gate
tokens (verified to pass against a profile that does). CHANGELOG.

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

* fix(gate): add-waiter backs off under contention; discover fails on a failed write

Review follow-ups to the gate CLI port.

- gate add-waiter's guarded write retried three times with no wait, so a
  convoy of workers registering on one gate at once failed all but a few
  (the proxied route's old unit of work had served them all). Each retry
  now waits a jittered, doubling backoff (10 ms to 400 ms, drawn from
  [d/2, d)), for at most 20 writes. The bound is attempts, not wall time:
  under a loaded server one round takes seconds, and a wall-clock budget
  failed the convoy after two or three rounds. A cancelled wait stops the
  loop. TestProxiedServerGateAddWaiterConvoy (direct SQL and
  proxied, real Dolt server) and TestE2E_GatesOverHTTP's concurrent case
  run 11 simultaneous adders (one duplicate): all exit 0, every waiter
  present once.
- gate discover counts only the gates whose run ID was recorded and exits
  non-zero when any matched gate's write failed; it used to print the
  refused gate as updated and exit 0. TestE2E_GatesOverHTTP covers
  discover with and without issues.update.gates (fake gh).
- TestServedGateCheckOverAwaitTypedGates masks issues.update.gates itself,
  so upgrading reference_server.json does not turn its gh:run case into a
  different test.
- The discover listing test asserts closed gates are not listed.
- CHANGELOG: discover's template skip and add-waiter's template refusal
  are behavior changes on the local routes; gate create refuses
  a negative --timeout; gate create/add-waiter follow dolt.auto-commit and
  use the role's commit messages; the proxied create no longer journals
  dependency_added.

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

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-17 02:15:07 +00:00
Julian Knutsen
47d5db39ff
feat(http): bd heartbeat over bd serve (issues.heartbeat), and close the re-arm orphan-lease race (#7600)
* feat(roles): issueops.Heartbeater role on the dolt, embedded and uow legs

Adds issueops.Heartbeater.Heartbeat(HeartbeatRequest{Actor, IssueID}) ->
HeartbeatResult{IssueID, Holder, HeartbeatAt, LeaseExpiresAt, Rearmed},
the lease refresh behind `bd heartbeat`, as its own role with its own
accessor.

- One body: internal/storage/issueops.ExecuteHeartbeatInTx validates
  (*HeartbeatFieldError for a blank/over-long actor or empty id), refuses
  a wisp, then runs RenewLeaseInTx, which is HeartbeatIssueInTx's body
  reporting the renewal. HeartbeatIssueInTx is now a wrapper, so the legacy
  HeartbeatIssue legs answer the same text and sentinels.
- The refresh is fenced on the holder AND on the live claim: after the
  holder-fenced UPDATE, a read in the same transaction requires the issue
  to be in_progress under the holder (the `update leases set` prefix and
  the one IF() the Postgres dialect rewrites are unchanged; a Postgres port
  should expect more serialization retries from that read). A refusal deletes the caller's orphaned lease
  row, and the legs commit that refusal.
- A refresh writes only the lease row: no row_lock, version, updated_at,
  event, journal entry, Dolt commit or hook. A re-arm (a live hand-doled
  claim with no lease row the caller holds) is recorded as a mutation:
  row_lock reminted, updated_at stamped, a lease_rearmed event, a journal
  entry, a version, a Dolt commit (LeaseRearmVersionCommit) and on_update.
  The remint makes a re-arm collide with a racing release or close instead
  of leaving an orphaned lease on an open or closed issue (a pre-existing
  race on every Dolt route). Rearmed is true only when a row was created:
  a same-second refresh (0 changed rows on embedded Dolt) or a holder
  spelled differently refreshes the existing row in place and keeps its
  granted_at/granted_node. Reported times are rounded to whole seconds,
  the stored values; the binds stay unrounded so a same-second refresh is
  never a 0-row UPDATE on Dolt.
- Typed refusals: an absent id is ErrNotFound; a foreign holder is
  *LeaseConflictError{Holder} wrapping ErrAlreadyClaimed; a wisp
  (Ephemeral) or no live claim is *LeaseConflictError wrapping the new
  ErrLeaseNotHeld, which also matches ErrNotClaimable.
- Legs: DoltStore and EmbeddedDoltStore through the issue-operation
  funnel (DOLT_ADD of the named tables, then DOLT_COMMIT -m, after the SQL
  commit); uow.NewHeartbeater through the new uow.RunTxScoped: a refresh or
  a refusal commits with the plain SQL COMMIT (no working-set scan, no Dolt
  commit, nothing another writer left uncommitted is swept), and a re-arm
  commits through the new ScopedCommitter (DOLT_ADD of exactly its tables,
  DOLT_COMMIT -m, never -Am). The legacy HeartbeatIssue doors commit a
  re-arm the same way and keep a refusal's orphan delete, and the
  proxied-server `bd heartbeat` route runs the role's body with the same
  scoped commit.
- Census: storage.Storage gains Heartbeater(); HookFiringStore wraps it
  (fires on_update for a re-arm only, RoleFiresHooks knows it), telemetry
  wraps it, httpapi.timedProvider, uow.notifyingProvider (records a re-arm)
  and externaldeps.uowProvider build it; the journal and version guards
  list the heartbeat family as entry points; the httpclient unsupported
  shell is regenerated and Heartbeater sits on its unsupported allowlist
  until the wire lands.

Conformance: RunHeartbeater* (18 cases) on dolt, embedded dolt and uow:
refresh post-state with the stored times pinned to the result; no
row_lock/current_revision/updated_at/events/journal/issue_versions/
version-control/hook change; a guarded write with the pre-heartbeat
revision still lands; foreign holder refused against an aged lease;
refused after close/release/reclaim/status move; wisp refused; hand-doled
claim re-armed as a mutation; same-second heartbeat is not a re-arm;
orphaned leases on released, closed and reassigned issues refused and
deleted; a refresh and a refusal against a dirty working set make no
commit and leave the other writer's change uncommitted, and a re-arm
commits only its own tables; absent id; request rules; no request mutation. The http leg is
waived until the wire lands.

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

* feat(httpapi): POST /v0/beads/issues/{id}:heartbeat behind issues.heartbeat

Publishes issueops.Heartbeater on bd serve as heartbeatIssue, the served
lease refresh behind `bd heartbeat`.

- Spec: the operation, HeartbeatIssueRequest {actor} and
  HeartbeatIssueResponse {id, holder, heartbeat_at, lease_expires_at,
  rearmed}; no `revision` (a refresh writes nothing to the row) and no
  expected_version (the fence is the holder and the live claim).
  issues.heartbeat joins the capability vocabulary and lease_not_held
  (409) the Problem.code list; `reason: ephemeral` qualifies it for a
  wisp. apigen and the wire-shape golden are regenerated; the golden diff
  is additive only, so wire_revision stays 2.
- Server: route row on the custom-method dispatcher, handleHeartbeat in
  heartbeat.go (claim's actor rules via bodyActor, unknown member and
  query refusals), Config.Heartbeater as a required role (sourceRoles,
  roleSourceNames, the per-request uow.HeartbeaterSource accessor).
  failHeartbeat maps *LeaseConflictError typed fields: a foreign holder
  is the claim's conflict shape (already_claimed + assignee +
  issue_status); no live claim, a wisp included, is the new
  lease_not_held (+ issue_status, + reason: ephemeral for a wisp), matched
  before the generic arms so ErrLeaseNotHeld's ErrNotClaimable never
  surfaces as not_claimable. Its detail names the one state the refusing
  transaction found (closed, open and not claimed, an ephemeral wisp, ...).
- bd serve wires the role from its peeled store (serveRoleSource gains
  Heartbeater); the serve stub stores, the corpus and e2e harnesses, the
  served harness and the encode oracle bind it.
- Wire client vocabulary: OpHeartbeatIssue/issues.heartbeat and
  MethodHeartbeat are CLASSIFIED (the capability set-equality gate),
  ReasonEphemeral is pinned to the server's, and lease_not_held rebuilds
  *LeaseConflictError{Status, Ephemeral} wrapping ErrLeaseNotHeld in the
  native words (the code-table set-equality gate). No accessor yet.

Tests: heartbeat_test.go (request mapping and projection, edge refusals,
every role refusal with its code, members and state-specific detail, the
code row, the capability). The served-http Heartbeater leg
(served_heartbeater_test.go, 18 cases) runs the contract against a real
bd serve through a test-local dial over the store's own dispatch, and the
http-leg waivers are deleted.

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

* feat(http): bd heartbeat over http through httpclient.Heartbeater

The client leg of the served lease refresh, and `bd heartbeat` on the
role for every route.

- httpclient.Store.Heartbeater (heartbeater.go) dials POST
  /v0/beads/issues/{id}:heartbeat through Store.dispatch, so
  issues.heartbeat is preflighted: an older server is refused BEFORE the
  dial with *wire.CapabilityError naming the token (unwraps to
  *storage.ErrUnsupported{Capability: "issues.heartbeat"}); it never falls
  back to a re-claim or a metadata stamp.
- The role's request rules are restated before the dial
  (validateHeartbeatRequest, pinned to
  storeops.ValidateHeartbeatRequest): blank/over-long actor, empty id, each
  a *HeartbeatFieldError.
- Problem mapping: already_claimed (which the shared table rebuilds as the
  claim's ClaimConflictError) becomes *issueops.LeaseConflictError naming
  the holder and wrapping ErrAlreadyClaimed, in the native words ("issue
  already claimed by <holder>"); lease_not_held already arrives as
  LeaseConflictError (Ephemeral from `reason`); not_found is ErrNotFound;
  invalid_argument on `actor` is the role's field error.
- Idempotent: true, the one write this client marks replayable (a repeat
  only moves the expiry later; a replay after a reclaim fails the fence).
- Legacy Store.HeartbeatIssue rides the role. Both leave the generated
  shell and completeness_test's unsupported allowlist.
- `bd heartbeat` takes Heartbeater() from the resolved store on the direct
  routes (dolt, embedded, http) and from the provider's HeartbeaterSource
  on the proxied route (exact id resolution in a read unit of work, then
  the role); runHeartbeatProxiedServer and heartbeat_proxied_server.go are
  deleted. Success output and exit codes are unchanged; refusal text
  changes per route (see CHANGELOG).

Tests: heartbeater_test.go (stub server: preflight refusal naming the
token with no POST, request/answer projection, each refusal's typed
mapping including the wisp's reason, the 503 replay, pre-dial validation,
validator parity, the legacy door). served_heartbeater_test.go runs the
18-case contract through env.subject.Heartbeater(), with
HookedHeartbeater wired off a HookFiringStore. TestE2E_HeartbeatOverHTTP:
real bd against an in-process serve: holder ok with revision and
updated_at unchanged and a guarded write with the pre-heartbeat revision
landing; a non-holder refused against an aged lease that stays untouched;
closed, wisp and unclaimed refused, each naming its own state; an older
server's handshake refused naming issues.heartbeat with no write. Corpus
shapes gc-heartbeat, -non-holder, -closed, -wisp pending until
reference_server.json advertises the token. CHANGELOG entry for the whole
track, including the orphaned-lease race fix.

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

* build(bazel): auto-sync BUILD files

Applied from the bazel-sync-patch artifact of https://github.com/gastownhall/beads/actions/runs/38875641041
(`make bazel-sync`: gazelle, tools/bazel/go_srcs.py, bazel mod tidy).
Only BUILD.bazel, MODULE.bazel and MODULE.bazel.lock are ever pushed; see
scripts/bazel-autofix-push.sh.

* fix(heartbeat): roll back a no-issue refusal; restate refresh vs re-arm

Review fixes for #7600 (adopt-pr apply-fixes, iterations 1-2).

Legacy HeartbeatIssue doors commit a refusal only when it read the issue.
The dolt and embedded HeartbeatIssue callbacks committed every
LeaseRenewalRefusal, including Found=false (the issue read failed). That
refusal deletes nothing, but it can follow a fast-path UPDATE that
already extended an orphan lease row's expiry, so committing it kept the
extension. issueops.LeaseRenewalRefusalCommits now gates the commit on
Found, the rule the Heartbeater role's HeartbeatRefusalCommits applies.
New tests on both legs pin both arms: a no-issue orphan's expiry is
unchanged, and a released issue's orphan is deleted.

Refresh vs re-arm contract docs. Comments, Long help, the OpenAPI spec
and the generated apigen still said every heartbeat writes only the
lease row, makes no Dolt commit and fires no hook. A re-arm is recorded
as a mutation: it remints the revision, records an event and a version
entry, commits once (LeaseRearmVersionCommit) and fires on_update
through the wrapping hook decorator. Restated in domain, uow, issueops,
storage.go (why RoleFiresHooks answers true, so bd serve takes the
heartbeater off a peeled store), cmd/bd heartbeat and serve, httpapi,
httpclient, the spec (apigen regenerated), and the conformance and
contract-test docs.

Minor review findings:
- The 409 already_claimed and lease_not_held details now end "nothing
  on the issue was written": the refusal may have deleted and committed
  the caller's orphan lease row.
- docs/multi-agent/federation.md and the CHANGELOG entry describe the
  spelling-mismatch heartbeat: the row is refreshed in place and keeps
  granted_at and granted_node; only a re-arm stamps this node. The
  embedded spelling test pins both columns, and the lease.go comments
  say "refreshed in place" instead of "re-arms".
- The refusal's orphan delete judges the holder under actorMatches, as
  the in-place refresh does (iteration 2). It matched holder = ? on the
  actor as sent, so a dead claim's orphan held under another spelling
  of the caller (gastown.mayor, heartbeat as gastown__mayor) survived
  the refusal until TTL. The refused closure now reads the row's holder
  and deletes that stored holder only when actorMatches(holder, actor).
  Both TestHeartbeatIssueCommitsARefusalOnlyWhenItReadTheIssue twins
  gain a cross-spelling arm (row deleted) and a control: another
  identity's row (gastown.dog-3) survives.

Not changed: `bd heartbeat --json` still omits `rearmed`, since adding
it changes a CLI JSON contract (follow-up). The federation.md paragraph
post-dates the v1.2.2 docs pin, so documenting this main-only behaviour
there is a maintainer call under
engdocs/decisions/2026-07-17-docs-release-pin.md section 1.

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

* fix(uow): run the scoped re-arm's Dolt commit after the SQL commit

The proxied-server heartbeat commits a re-arm with doltServerTx.CommitScoped,
which ran DOLT_ADD per table and DOLT_COMMIT('-m') INSIDE the open
transaction, before the SQL COMMIT. DOLT_ADD stages whole tables from the
session's transaction root, so that Dolt commit was built from the re-arm's
start snapshot: an issues row another session changed while the re-arm was
open (a write still only in the working set, as in batch mode or before that
writer's own Dolt commit) was staged at its old value, and HEAD disagreed
with the rows every reader sees. This is the LatentLabsSpace/NEXUS#92
ordering the DoltStore funnel (runIssueOperationTxWithMessage) already
avoids, and the review's major finding on this PR.

CommitScoped now commits the SQL transaction first, then stages exactly the
named tables (plus the versioned-history tables) and makes the Dolt commit on
the same pinned connection, the uow twin of doltAddAndCommitPostTx:

- a serialization failure of the SQL COMMIT is still returned, so
  RunTxScoped replays the unit of work;
- the Dolt commit runs detached on its own budget and replays only conflicts
  that leave nothing behind: serialization failures and Dolt's 1105
  "@autocommit transaction rolled back" (new isDoltAutocommitRollbackError,
  mirroring the DoltStore classifier of the same name);
- nothing staged, or "nothing to commit", is not an error: a concurrent
  writer's Dolt commit already took the row. A "nothing to commit" past the
  staged check is logged, as the funnel logs it, so the missing audit line
  is explicable;
- any other failure is logged, never returned. The data is committed, and
  returning it would make RunTxScoped replay a committed re-arm, which would
  then report a refresh. The session is poisoned rather than pooled, since
  its state is unknown. uow records no metrics, so that log line is the
  drop's only signal; bd.db.post_tx_commit_dropped counts only the funnel's.

Statements go through schema.DrainCall, retiring the local drainCall fork
(review nit).

Tests: five sqlmock tests pin the order (SQL COMMIT before any DOLT_ADD),
the swallow-and-poison path, the 1105 retry, the returned serialization
failure and the empty-commit tolerance; each fails against the previous
CommitScoped. TestIsDoltAutocommitRollbackError carries the DoltStore
classifier's table over to the uow copy, plus the prefix boundary; dropping
the prefix branch, the prefix's period, the 1105 check or the type check
each fails a case. TestHeartbeaterRearmKeepsAConcurrentWrite is the
real-Dolt regression: a change to another issues row made while the
re-arm's transaction is open must be at HEAD after the re-arm's Dolt
commit. Its working-set-only writer fails on the old ordering (dolt
2.1.8); the writer that Dolt-commits its own change passes on both and is
kept as coverage.

Review follow-ups folded in (comments, a file move and a test; the
absorption log line above is the only behaviour change among them):

- the freshRowLock invariant and its row_lock_guard_test.go mirror name the
  re-arm as the one deliberate remint without a lifecycle-field change,
  load-bearing for the release/close collision;
- httpclient: "a write is never retried" (wire/client.go, stall_retry.go)
  and "only a read's answer is yes" (dispatch.go) now allow for the
  Idempotent heartbeat, and httpHeartbeater and issueops.HeartbeatResult
  document that a replayed heartbeat can report Rearmed false after a
  committed re-arm, with the guarded write's revision check as the backstop;
- the proxied route moves back to cmd/bd/heartbeat_proxied_server.go, the
  file family cmd/bd/AGENTS.md prescribes;
- the ScopedCommitter and RunTxScoped docs no longer say every other
  writer's uncommitted change stays out of the commit: a staged table is
  committed whole, so such a change to a named table rides in the re-arm's
  commit, as it does in the funnel, and only other tables keep theirs;
- commitStagedTables says its drop is log-only, the absorption is logged,
  and the uow classifier gets its table test (see Tests).

Not folded in: the base-owned IssueUseCase.Heartbeat /
IssueSQLRepository.HeartbeatIssue door, dead in production since the
proxied route moved to the Heartbeater role. Its one caller is the
notifying hook-parity test (uow/notifying_test.go), and moving that case
onto the Heartbeater means re-deriving its RenewLease hook semantics, so it
is left for a follow-up.

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

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: Eddie the Engineer <338826946+gascity-eddie[bot]@users.noreply.github.com>
2026-10-16 22:38:23 +00:00
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
169c5fc499
perf(list): read only the listed issues' dependency edges (#7591)
* perf(list): read only the listed issues' dependency edges

`bd list`'s text renderings (the default tree, --deps, --parent, --format
and --watch) loaded every dependency record in the workspace through
GetAllDependencyRecords to draw one page. On a local store that is one
query. Over a connected HTTP workspace it is a walk of the whole workspace:
every issue id at 200 per request, then every id's edges at 100 per
request. `bd list --limit 20` against the ~3.8k-issue maintainer-city
workspace made 62 sequential requests and took ~5.7 s at ~50 ms a round
trip, where `bd list --json` makes 5.

Every rendering reads only edges a listed issue owns. The tree nests a
child under a parent only when both are listed, and looks the edge up
under the child. Sibling ordering, the --deps annotations and the gate
decoration read the listed node's own edges, and --format prints edges
between listed issues. An unlisted issue's edge onto a listed one, or a
parent off the page, is never read. listDependencyRecords reads exactly
those edges through the EdgeReader role, which every backend serves (the
http store refuses the raw GetDependencyRecordsForIssues batch method).
Over http that is one anchored listDependencies request per 100 listed
ids.

Through a logging proxy in front of the production bd serve, list
--limit 20 goes from 62 requests / 5.7 s to 6 / 0.49 s with
byte-identical output; every changed mode (--deps, --deps=all, --format
digraph/dot, --sort, --status, --ready, --limit 200, --limit 0, --parent)
prints the same bytes as before. On a local store a default page is as
fast or faster; a listing that covers most of a large durable store pays
batched reads instead of one table scan (+0.07 s at 1,000 rows, +0.46 s
at 4,000 on embedded Dolt).

Tests:
- backend/http TestE2E_ListTextRenderingsReadOnlyTheListedIssuesEdges:
  over a served workspace, the tree, --deps=all, a --limit cut, the
  --parent tree and --format digraph each make one listDependencies
  request naming exactly the listed ids, and at most one request more
  than the --json page. Failing first: the old read enumerated every id
  (all=true) and anchored the hidden closed issue too.
- cmd/bd: the page read equals GetAllDependencyRecords restricted to the
  page on Dolt server and embedded stores (both planes, every edge type,
  gates, external refs), and every text rendering prints the same bytes
  from either map; a runListCore spy pins one page read and no
  store-wide read; pure tests over an adversarial fixture (edges unlisted
  issues own pointing at listed ones, parents off the page, dotted
  children, a parent-child cycle) guard the renderers.

Refs: ga-nrnrlr.5

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

* test(http): seed the list page-edges e2e with one graph apply

TestE2E_ListTextRenderingsReadOnlyTheListedIssuesEdges ran 26 s on
http_served_test's round-robin shard in CI, which made that shard the
embedded lane's longest test action (172 s). Most of it was subprocesses:
five creates and a close to seed, plus a --json budget run per case.

The fixture is now one `bd create --graph` plus the close (the batch
create cannot carry a closed row's closed_at over the wire), and one
`bd list --json` run is the budget for every page case, since its request
count does not depend on the page size. 16 subprocesses become 9. All
five cases still fail against the old GetAllDependencyRecords call
sites: each edge read anchors the hidden closed issue, and the four page
cases make 7 requests against the --json page's 5.

Refs: ga-nrnrlr.5

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

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-16 16:05:24 +00:00
Julian Knutsen
dff9492c61
fix(http): gate check records a bead gate's sighting through Lifecycle.Update (#7604)
* fix(http): gate check's bead sighting goes through Lifecycle.Update (issues.update)

The bead-gate sighting was written through the legacy map-based
UpdateIssue, which the http store does not implement, so the refusal
happened client-side and no issues.update was ever sent: every open bead
gate with an open target failed on every sweep over HTTP.

- recordSeen and the gh:run await_id persist now go through the Lifecycle
  role (updateGateThroughLifecycle): a single-key metadata set for the
  sighting, an AwaitID patch for the run. The http client still refuses the
  await_id patch before the dial (W-IssuePatch.AwaitID); the gate's error now
  names the await_id update instead of a Go method.
- backend/http/corpus TestServedGateCheckOverAwaitTypedGates seeds
  await-typed gates in the served store and proves, through the reference
  proxy: --dry-run writes nothing, timers close, the bead sighting persists,
  merged gh:pr gates close, and the gh:run persist refuses by name with
  await_id untouched.
- CHANGELOG corrected.

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

* fix(cmd/bd): gate check skips template gates; narrow the await_id reword

Review fixes for the gate-check sighting change.

- A persisted proto's gates (bd cook --persist) are templates, and
  issueops.ListGates lists them with the open gates. bd gate check now
  leaves them out of its listing's query: GateListRequest gains
  ExcludeTemplates, which only listOpenGatesWith sets, and it adds
  `template=false` to the expression, so the cut at --limit counts only
  the gates that remain. bd gate list leaves it unset and still lists
  templates. Dropping them from the page after the cut would let a page
  of a proto's gates (newer than the live ones at the same priority)
  fill --limit: the sweep would print "No open gates found." and exit 0
  with the live gates unchecked. filterCheckableGates, which both the
  direct and the proxied-server routes select through, keeps the skip
  as a backstop. Before this, each route mishandled templates in its
  own way:
  - Direct route: the Lifecycle role refused the sighting and await_id
    writes, so the sweep failed every time, after a gh:run template had
    already queried GitHub. In a local workspace, an expired template
    timer gate was closed in the proto.
  - Over HTTP: bd serve refused the close with 409 template_read_only.
  - Proxied-server route: the template timer gate was closed and a
    sighting was stamped on the template bead gate, silently.
- persistGateCheckAwaitID rewords only the HTTP wire's
  W-IssuePatch.AwaitID refusal. The new message names the run, await_id
  and the bd serve URL, and advises checking the gate in a local
  workspace: giving it a numeric run ID would be the same await_id edit
  the wire refuses. The error chain is kept, so *storage.ErrUnsupported
  and the ledger row stay reachable. Every other error comes back as the
  role raised it, including a capability the server does not advertise
  (#7589's issues.update.gates) and a local backend's ErrUnsupported.
  Before, every ErrUnsupported got the same sentence.
- Tests:
  - Unit: the template skip for every type filter; a sweep over template
    gates beside a live one; ListGates putting `template=false` in the
    query under ExcludeTemplates, and gate check's listing setting it;
    the reword and its chain; the pass-through cases; the sighting patch
    matching its map form.
  - Embedded: a cooked proto's gh:run, bead and timer gates are
    untouched, and gh is never run. With --limit 1 behind that proto's
    gates, a live expired timer gate is checked and closed.
  - Proxied-server: template timer and bead gates stay open and
    unstamped. With --limit 1 behind two newer template timer gates, the
    live one is checked and closed.
  - Served: the template gates are untouched, and the gh:run error names
    the server. --dry-run --limit 3 behind three template gates checks
    three live gates.
  - Each --limit case first shows, through bd gate list, that a template
    leads the listing.
  - Against the PR-head bd, the embedded, proxied and served template
    cases fail. Against a bd that skips templates after the cut, the
    three --limit cases fail, printing "No open gates found." and
    exiting 0.
- bd_test gains the //internal/httpclient{,/encode} deps (gazelle-checked).
  The embedded shard manifest lists both TestEmbeddedGateCheck* tests.
  The CHANGELOG notes the template skip, that templates take no row of
  --limit, and the new wording.

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

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Co-authored-by: Eddie the Engineer <adopt-pr@gascity.com>
2026-10-16 15:14:53 +00:00
Julian Knutsen
b126a7d1d2
fix(http): bd gate check over HTTP through issueops.ListGates (#7578)
* fix(http): bd gate check over http through issueops.ListGates

gate check listed its open gates with a raw SearchIssues filter (gate type,
closed excluded, --limit), which the HTTP backend refuses, so the command
failed before reading a gate on a remote scope and gc's core gate-sweep order
(bd gate check --type=timer --escalate) failed every tick there.

The listing now goes through issueops.ListGates over openQuerier on the
direct and proxied routes, the same entry bd gate list took in S20 (#7549):
the same question, served as queryIssues by every deployed server. The close,
the bead-gate target read and sighting, the pure timer arm and the gh/gt execs
are unchanged. The gh:run discovery's await_id persist still refuses on the
wire and counts as that gate's error.

The served corpus gains mc-gate-check-timer, mc-gate-check-gh (gate-sweep's
argv) and gate-check-all. No seeded gate carries an await type, since no wire
create accepts await_*, so these prove the listing is served.

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

* docs(gate): name both refused gate check writes; close gate's filter hole

Review fixes for #7578 (apply-fixes, iteration 1).

CHANGELOG, minor (taken): the entry said a bead gate's sighting was
already served over HTTP. It is not. evaluateBeadGate records the first
sighting (await_seen) through recordSeen, which calls the raw
store.UpdateIssue (cmd/bd/gate.go:675). The HTTP Store has no UpdateIssue
override, so its embedded unsupportedDoltStorage refuses the call in the
client before any request is sent (internal/httpclient/unsupported_gen.go),
exactly as it refuses the gh:run discovery's await_id persist. "Refuses on
the wire" was wrong for the same reason. The entry now names both writes
and keeps "counts as that gate's error" (applyGateCheckResults counts
r.err). The sighting is written only when the check finds the awaited
bead, not yet closed, in the gate's own store; inspectBeadGate sets
seenHere only there.

CHANGELOG, nit (taken): `bd gate check --limit -1` used to list every
open gate on the direct and proxied routes, because the raw search
emitted no LIMIT clause for a negative limit. The listing now goes
through issueops.ListGates, whose Querier rejects a negative limit as
ErrValidation, and the HTTP server rejects it too
(internal/httpapi/query.go). The entry says so.

.golangci.yml, minor (taken): at this head cmd/bd/gate.go and
gate_proxied_server.go name no filter type (one each at the base), so
their slot in the cmd/bd forbidigo family only kept a hole open. `gate`
leaves the alternation, with a "LEFT this list" note like the ones for
search, status and count. gate_discover keeps its own hole:
findPendingGates still builds the raw filter.

Declined:
- bd gate discover still refuses over HTTP in findPendingGates (minor):
  the synthesis' first remedy is no change in this PR, and the file is
  not in this PR's diff. Finalize files the follow-up to move it onto
  ListGates.
- the proxied listing is not pinned on its own (nit): it calls the same
  listOpenGatesForCheck as the direct route (gate_proxied_server.go:106),
  and the synthesis calls accepting the gap defensible.
- listOpenGatesForCheck/listOpenGatesWith naming (nit): the remedy is
  "leave as is".

Verified:
- git diff --check: clean.
- bazel build --config=nogo -- //cmd/bd:all on the edited config: 16
  targets, exit 0.
- Probe, then reverted: a types.IssueFilter literal in gate.go and a
  types.WorkFilter literal in gate_proxied_server.go each failed nogo
  with forbidigo's "do not write a filter here", so the hole is shut.
- git merge-tree against the heads of all 102 other open PRs that touch
  CHANGELOG.md or .golangci.yml (today's census): this commit changes
  no conflict count in either file. 43 PR/file pairs already conflict
  with or without it.

Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning 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>
2026-10-16 09:20:24 +00:00
Julian Knutsen
b303d494df
perf(http): answer a command's repeated reads from one response; bd show --json makes 1 request (port of bd-enterprise e626072b8) (#7588)
* perf(http): answer a command's repeated reads from one response (port of bd-enterprise e626072b8)

Over an http workspace, bd show <id> --json made three identical
GET /v0/beads/issues/<id> requests: the id resolver's exact probe,
routed.go's GetIssue and show's detail read all build the same URL. Text
show made six. Over a gateway each one is a sequential round trip, so the
request count is the command's latency floor (mc-5dkzp).

This ports bd-enterprise e626072b8 (bts-xpw.3.14.6, #217) verbatim, except
cmd/bd/main.go, where OSS still opens the identity preview inline, and
bd-enterprise's httpgw dialer test, which has no OSS counterpart:

- httpclient.WithSharedConnections: the identity-gate preview and the real
  open share one transport, so a write makes one handshake.
- httpclient.WithReadMemo and a wire.Client read memo, for one-shot
  commands only (not bd serve, --watch or --follow): identical getIssue,
  getSetting and listSettings reads are answered from the response already
  received. An entry ages from the server's answer (5 s), any write clears
  the memo, a read that overlapped a write is not stored, and expired
  entries are swept.
- bd list's three vocabulary reads come from one memoized listSettings.
- bd update --status / --if-status skips the custom-status read for a
  built-in status.
- The hook decorator skips its post-write re-reads when no executable hook
  exists for the event.
- bd dep add reads its confirmation titles before the write, from the memo.

Against a loopback bd serve: show --json goes from 3 requests to 1, text
show 6 to 3, update 5 to 3, close 6 to 4. Dolt and the other registered
backends receive the same ctx and ignore it.

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

* feat(http): BD_HTTP_READ_MEMO=0 turns the per-command read memo off

An operator who suspects a stale read can rule the memo out without a
rebuild. Any other value, or none, leaves the default.

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

* test(http): pin bd show to one fetch per issue (mc-5dkzp)

TestE2E_PerCommandRequestBudget allowed show two requests, and a read
that drifts to a URL of its own (a mutant whose reader spells
brief_deps=false) fits that ceiling on both handshake shapes. These guards
pin the single fetch instead:

- TestE2E_ShowFetchesTheIssueOnce: the exact requests, path and query, of
  show --json, show --json --id, show --short, show of two ids and text
  show, against both handshake shapes, plus a BD_HTTP_READ_MEMO=0 step
  that must read the row more than once.
- TestDefaultIssueReadsShareOneMemoKey: the resolver's exact probe,
  GetIssue, GetDependenciesWithMetadata, GetLabels and IssueReader().Get
  build one URL, checked without a server.
- TestE2E_CloseRereadsItsOwnWrite: against the MC handshake, closing a
  lone molecule re-reads its own closed row from the server after the
  write, and prints no false "completed molecule" note.
- Corpus shapes can pin `requests:`, counted on the served run alone (not
  setup, verify or {rev:ID} reads). The seven gc and mc show shapes pin
  1, 4, 1, 1, 3, 1 and 3.

Also: TestReadMemoOptInReadsTheRealPollingFlags holds the opt-in to the
real show/list --watch and -w, events tail --follow and bd serve; the
show budget drops from 2 to 1; requestCounter records each request's
query; and ledger row L-read-memo records the memo's bounded difference
from local reads.

Mutation runs against this tree: brief_deps=true on GetIssue and
brief_deps=false on the reader's Get each fail the e2e list and the unit
test; show opting out of the memo fails the e2e list; writes that leave
the memo standing fail the read-your-own-write e2e; a memo keyed by path
alone fails the e2e list; dropping the kill switch fails its unit test
and the e2e step.

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

* docs(config): list BD_HTTP_READ_MEMO

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

* fix(http): memoize a read's answer only once it has decoded

wire.Client.Do stored a memoable read's 2xx before it checked the body,
so an empty or undecodable 200 would have answered every identical read
in the command for the memo's whole TTL with the same failure, instead
of asking the server again. The answer is now stored only after it
decodes; a read that decodes nothing (out == nil) is not stored, and
every memoable read in this package decodes its answer.

TestReadMemoKeepsOnlyAnswersThatDecoded pins it (empty body, truncated
body, undecoded answer). Ledger row L-read-memo says so.

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

* test(http): pin the read memo's 5xx, write-method, per-client, in-flight-write and hook-gate behavior

Review follow-ups for the per-command read memo (mc-5dkzp):

- TestReadMemoNeverKeepsA5xx: a 503, 500 or 502 is not memoized and the
  2xx after it is. TestDispatchRetryOfABusyMemoizedReadAsksTheServer
  holds the same through dispatch's retry loop over a real wire.Client:
  the retry reaches the server instead of replaying the 503.
- TestReadMemoIsDroppedByAnyWrite covers POST, PUT and DELETE, not just
  PATCH.
- TestReadMemoIsPerClient: in either order, one client's read is never
  answered from another's memo, and opting one client in opts in no
  other. (A shared memo was otherwise caught only by test-order
  pollution.)
- TestReadMemoDropsAnAnswerReadWhileAWriteWasInFlight pins the clear on
  the write's way back: a read that starts and ends while the write is
  on the wire is not answered again once the write has returned.
- TestHookFiringStoreReReadsOnlyForAnEventWithAHook pins hookConfigured's
  probe: the decorator asks the runner about the event it fires, and
  re-reads the row to build a payload only when a hook for that event
  exists, through a probing double and through a real hooks.Runner.

Each was run against a mutant of the code it pins and fails there:
5xx stored before the status check; only PATCH clearing; one memo
shared by every client; no clear after the write returns;
hookConfigured answering true, false, or about the wrong event.

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

* docs(changelog): note the per-command http read memo

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

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-16 04:26:37 +00:00
Julian Knutsen
773b537c75
fix(httpclient): dial a large batchApply under the server's extended budget (#7582)
* fix(httpclient): dial a large batchApply under the server's extended budget

bd serve runs an issues:batchApply over largeApplyItemThreshold (100) items
under DefaultLargeApplyCeiling (5m) on a context detached from the client,
but the wire client capped every request at DefaultTimeout (60s). A large
apply on a slow or loaded server therefore failed client-side with
"Client.Timeout exceeded while awaiting headers" while the server went on
to commit it: an error for an apply that landed.

wire.Request.Timeout now raises (never lowers) a bounded client's
per-request ceiling for one request, through a shallow copy of the
*http.Client that shares its Transport and forced CheckRedirect. ApplyBatch
sets it to LargeApplyTimeout (6m) once the plan exceeds
LargeApplyItemThreshold. The stall-retry deadline uses the same per-request
ceiling.

Tests:
- wire: a slow fake server times out an at-threshold apply under a short
  ceiling and completes an over-threshold one; httpClientFor only raises a
  bounded client and keeps its Transport and CheckRedirect.
- httpapi: TestTheClientLargeApplyBudgetCoversTheServer pins the redeclared
  threshold to the server's and holds LargeApplyTimeout above request read
  + large-slot wait + ceiling + drain grace (5m45s).
- httpclient (served tier): a 101-item apply against a BatchApplier delayed
  DefaultTimeout+5s, dialed through DialWith + DialOptionsForTarget like
  the product, commits and returns success (71s). With the raise disabled
  it fails at 60.03s with Client.Timeout.

Ported from bd-enterprise (gascity/bd-enterprise#195).

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

* test(httpclient): pin the raised stall-retry deadline; document the 6m large-apply ceiling

Review fixups for #7582.

- wire: TestARaisedRequestTimeoutAlsoBoundsTheStallRetry pins the one
  OSS-only hunk of the port, the stall-retry deadline read through
  httpClientFor(r). Reverting that line to c.hc.Timeout left the whole wire
  package green; the new case fails on it, because the retry then runs out
  at the client's own ceiling instead of the request's raised one.
- backend/http: Options.HTTPClient said the client is used as given except
  for redirect handling. A batch apply over 100 items now raises a Timeout
  shorter than 6 minutes for that request, so the public doc says so.
- README and CHANGELOG: the HTTP backend's write bound is no longer 60s for
  every request. A batch apply over 100 items gets 6 minutes, and a server
  whose --large-apply-ceiling is raised past about 5m15s can still outlast
  it.
- engdocs/SERVE_RUNBOOK.md: the same limit, next to the stop-grace sizing
  an operator reads before raising --large-apply-ceiling.
- served_batch_apply_test: the race-build comment blamed the client's 60s
  timeout for shrinking the 1000-item apply. A plan that size now gets
  wire.LargeApplyTimeout; it stays shrunk because the embedded tier measured
  it at 903-945s under -race.

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

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-15 23:43:54 +00:00
Julian Knutsen
ea0f6e1a46
feat(http): advertise issues.update.claim and route claims by it (S24a/b) (#7555)
* feat(http): advertise issues.update.claim and route claims by it (S24a/b)

updateIssue has served `claim` (upstream #6890), resolved on both planes so
a wisp is claimable, with no capability token: a client could only find it
by eating the skew 400, and gc's wire_compat preflight (which lists
issues.update.claim as an optional token) never saw it, so gc claimed every
wisp through claimIssue, whose Claimer role excludes the wisp plane.

Server: CapIssuesUpdateClaim ("issues.update.claim") joins
behaviorCapabilities. The spec names it on UpdateIssueRequest.claim and in
the context capabilities prose (apigen regenerated, descriptions only). No
request or response member changes; wire_revision stays 2.

Client: Lifecycle.Update reads the token from the cached handshake before
the dial. With it, every claim is one updateIssue call and its answer is
final (no fallback on any error). Without it, a claim alone goes straight to
claimIssue (no doomed 400 first; a wisp still refuses by name,
W-ClaimRequest.Wisp, whose Why now names the token), and a claim beside a
patch, a guard or a force override is refused before the dial with
ErrUnsupported{Capability: issues.update.claim}. serverPredatesUpdateClaim
(the error-sniffing fallback) is gone.

Tests: the four capability lists (routes.go, wire/handshake.go,
server_test, wire vocabulary_test) move together; unit tests for both
routes (pre-dial refusal dials nothing; with the token nothing falls back);
served tests claim a wisp through updateIssue with the token (zero claimIssue
dials, post-claim revision stitched), refuse it by name without it (zero
updateIssue claims, one claimIssue), and refuse a claim beside a patch
without the token while the same request claims and patches the wisp with
it. Live-mutated: ignoring the token fails the unit test.

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

* test(http): count only ready --claim's requests in the claim-next check

TestE2E_AdvertisedExternalPolicyIsPassedThrough counted every request
since counter.reset(), so its "no by-id claim" check also saw the earlier
`update <other> --claim` step. The MC handshake mask does not advertise
issues.update.claim, so this PR routes that claim to claimIssue
(POST /v0/beads/issues/<id>:claim) by design, and the check failed in
Bazel / embedded Dolt tier (//backend/http:http_served_test shard 6 of
7), turning CI Gate / Required red.

Count from the snapshot length taken just before `ready --claim`, so the
check covers only the requests that command issues. The counter is not
reset: the close-policy check below scans the same history.

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

* fix(http): refuse a token-less template claim on the client's pre-read

Against a server without issues.update.claim, Lifecycle.Update sends a
claim alone to claimIssue (claimWithoutUpdateClaim) and returns before
applyTemplateGuardForServer runs. claimIssue's role has no template check
(bd-jkp9v3), so `bd update <template> --claim` against every server
without the token claimed the template. The base refused it before any
write: on the client's pre-read against a server without
issues.update.allowTemplate, and in updateIssue's own guard against one
with it.

claimWithoutUpdateClaim now pre-reads the row and returns
AuthorizeTemplateUpdate's refusal before the claimIssue dial, whatever the
handshake says about allowTemplate: that token means updateIssue guards
templates, and this route never dials updateIssue. Any other row goes on
to claimIssue as before (a wisp to its refusal by name), and so does an id
the pre-read cannot find, so claimIssue's not-found stays the one reported.

TestUpdateClaimRefusesATemplateWithoutTheToken (stub wire) and
TestServedUpdateClaimRefusesATemplateWithoutTheToken (served tier) pin it
under an allowTemplate-only and a neither-token handshake. Both go red
without the pre-read; the allowTemplate-only legs also go red if the
existing guard is only moved above the claim branch.

TestUpdateClaimFailsClosedWhenThePreReadFails pins the pre-read's third
arm under the same two handshakes: a read that fails other than as
not-found returns that failure and never dials claimIssue, since the
row's template bit is unknown then. A best-effort pre-read (that failure
falling through to the claim) passed go test ./internal/httpclient/ and
its served Claim|Template tier before this test, and goes red on both
legs with it.

A claim beside AllowTemplate is refused before the dial with
ErrUnsupported naming the token, like a claim beside a patch, a guard or
a force override (isClaimOnlyUpdate already excluded it), but no prose
said so: claimWithoutUpdateClaim's doc, CapIssuesUpdateClaim's doc, the
test doc and the CHANGELOG entry now list it, and a
TestUpdateClaimAgainstAServerWithoutTheToken row pins it. Dropping
!req.AllowTemplate from isClaimOnlyUpdate passed the same unit and served
runs without that row and goes red with it.

The prose now follows the handshake rule too: the W-UpdateRequest.Claim
ledger row (and its re-rendered md) no longer calls claimIssue the
fallback for a server that 400s the member, Update's doc names
claimWithoutUpdateClaim instead of the nonexistent claimRouteForServer,
wire.UpdateFlags.Claim drops the "safe to read as skew" rationale no
caller relies on anymore, and the CHANGELOG entry says a template is still
refused on the token-less route.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 11:47:45 +00:00
Julian Knutsen
eaed71fbba
fix(http): bd promote over http through issueops.Promote and issues.update.persistence (S21b) (#7554)
* fix(http): bd promote over http through issueops.Promote and issues.update.persistence (S21b)

`bd promote` refused over a connected HTTP workspace: it called the raw
PromoteFromEphemeral, which the http backend stubs, and updateIssue's patch
did not publish persistence. MC's PR-intake formula
(mol-normalized-issue-pr-v1) runs `gc bd promote <id> --reason ...`, so this
blocked the HTTP cutover.

- One library entry, issueops.Promote(ctx, PromoteRoles{Reader, Lifecycle,
  Commenter}, PromoteRequest{Actor, IssueID, Reason, Provenance}): read the
  row, refuse a non-wisp (*NotAWispError, the sentence bd promote always
  printed), move it with ONE Lifecycle.Update whose patch is Persistence =
  persistent (the role's atomic plane move: same id, labels, deps, events and
  comments carried), then write the promotion comment (a comment failure is
  reported, the promotion stands). A no-op move is a lost race and reports
  NotAWispError without a second comment.
- cmd/bd: the direct route runs it over the store's own role accessors, so a
  connected http workspace and a local one take the same entry. The history
  label is "bd: promote <id>" where the store carries caller labels.
- bd serve: IssuePatchBody.persistence (persistent|ephemeral|no_history,
  anything else a 400 naming patch.persistence) on PATCH
  /v0/beads/issues/{id}, behind the new additive behavior token
  issues.update.persistence. wire_revision unchanged. Spec, apigen and the
  wire-shape golden regenerated; the handler only decodes and passes it to
  the role.
- httpclient: Lifecycle.Update sends patch.persistence only to a server
  advertising the token, and otherwise refuses BEFORE the dial with
  *wire.CapabilityError naming it (unwraps to *storage.ErrUnsupported with
  Capability set). The batchApply item still refuses it
  (W-IssuePatch.Persistence now reads "ON issues:batchApply").
- Conformance: RunLifecycleUpdatePersistentPromotesAWisp on dolt, embedded,
  uow and the served http leg; the served
  PersistentPreservesUnversionedClass case is unparked.
- Served e2e TestE2E_PromoteOverHTTP: the mc-promote shape end to end
  (label kept, comment written, one PATCH, re-promote refused), and under
  the MC server mask a pre-dial refusal naming the token with no write.
- Corpus: mc-promote stays pending, relabelled SRV-1 with the reference
  profile's exact refusal (the 1.3.0 server lacks issues.update.persistence).

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

* fix(promote): run the proxied-server route through issueops.Promote (bd-4y73m9)

The adoption review found (major) that the proxied-server route still
promoted through the old engine, IssueUseCase.PromoteWisp in one
transaction with the comment, while the PR's docs said every route runs
issueops.Promote. Converge rather than reword: runPromoteProxiedServer
resolves the id, then runs issueops.Promote over the provider's own
notifying role accessors (proxiedIssueReader, proxiedIssueLifecycle,
proxiedCommenter), the entry the direct route runs. Both routes now share
promoteFailure (the error mapping) and reportPromotion (the comment
warning and the output), so neither contract can drift.

What a script sees change on the proxied-server route:
- the move is the persistence branch of Lifecycle.Update, so the child
  counter moves with the row: a promoted parent's next
  `bd create --parent` mints .3 after .1/.2 instead of failing with
  "issue already exists";
- on_update fires twice, for the move and for the comment, as on the
  direct route (it fired once, for the comment);
- a promotion is two Dolt commits, "bd: promote <id>" and
  "bd: comment <id>" (it was one);
- a comment that cannot be written leaves the promotion standing behind
  a warning, as on every other route, instead of rolling it back;
- a dual-plane id is refused rather than merged, the update role's
  template guard applies, and a lost race reads "<id> is not a wisp
  (already persistent)".

The PromoteWisp exemption in TestRecordingIssueUseCaseCoversItsSurface
stays, with its reason corrected: no route calls PromoteWisp now, and
its DoltStorage twin fires no hook either. The doc comments on the old
engine (PromoteFromEphemeral on DoltStore and the db layer, PromoteWisp)
no longer say bd promote uses it.

CHANGELOG: the promote entry now names what a script can see on the
direct and proxied-server routes: the hook firings, the comment row
`bd comments` lists, the child-counter carry, the two-commit shape, and
a comment failure that warns instead of rolling back.

Tests:
- TestEmbeddedPromoteMovesAWispParent promotes a wisp parent with .1/.2
  children, a dependency and a comment under a counting on_update hook:
  the hook fires twice, the dependency and the children's parent edge
  survive, `bd comments` lists the old comment and the promotion reason,
  and the next child is .3. At the pre-PR base it fails (the hook fired
  0 times).
- The proxied journey pins the two commits, and new subtests pin the
  child counter (the child_counters row, next child .3) and the two hook
  firings. Against the contributor head each fails: one commit, no
  counter row and a failing create, one firing.

Review iteration 2:
- TestEmbeddedPromoteMovesAWispParent gets its row in the embedded cmd
  shard manifest (shard 64 of 100, from the generator's incremental
  --write). Without it //scripts:go_test_sources_test fails both the
  NotStale and the bare-write guard, and the generator's --check fails.
- notifying.go no longer lists the promotion comment as a divergence.
  The direct route now writes that comment through st.Commenter(),
  which HookFiringStore wraps, so an embedded promote fires on_update
  for it (TestEmbeddedPromoteMovesAWispParent counts both firings). The
  list counts four, and the empty-commit note becomes the fifth item.
- batchapplier.go no longer says persistence is absent from both patch
  bodies: the update body publishes it behind issues.update.persistence,
  and only batchApply refuses it (W-IssuePatch.Persistence).
- Three comments still tied promotion to the old engine: the
  conformance fixture's PromoteWisp no longer claims to do what
  `bd promote` does, the CLI differential's promote scenario names
  issueops.Promote, and export_source's wisp-relations note names
  issueops.MoveIssuePersistenceInTx.
- The Promote unit test compares the whole update patch with
  reflect.DeepEqual. The helper it replaces checked 9 of the patch's 22
  members, so a Promote that also set Description passed it.

Review iteration 3:
- A refused persistence move answered 500 `internal` over http and
  emitted request_error, though the caller could fix the request. The
  role now returns two refusals as ErrValidation, so bd serve answers
  400 invalid_argument and the client maps that back to ErrValidation:
  an unversioned row asked for ephemeral or no_history (the role wraps
  types.ErrUnversionedWispMove, a new sentinel NormalizePersistenceMode
  returns for that case alone, with its message unchanged), and a
  demotion of a row with retained snapshots. A row that breaks its own
  persistence invariants still answers 500.
- RunLifecycleUpdateWispModesRefuseAnUnversionedRow pins the refusal on
  every leg (dolt, embedded dolt, the unit of work, served http): both
  wisp modes match ErrValidation and leave the row durable, unversioned
  and off the wisp plane. Without the wrap the dolt leg fails, and the
  served leg fails on "answered 500 internal".
- TestMoveIssuePersistenceInTxRefusesDemotionWithRetainedSnapshots is
  the first test of the snapshot refusal, and fails without its wrap.
  The unversioned unit test now requires both sentinels. The types tests
  pin the sentinel, its unchanged message, and that no row-invariant
  error matches it: checking the unversioned class ahead of the
  invariant checks fails them.
- CHANGELOG: the promote entry counts five script-visible changes, the
  fifth being the lost-race refusal sentence, and says the two refusals
  now answer 400 over bd serve and gain a `validation failed: ` prefix
  locally.
- NotAWispError's doc comment records that a no-history wisp is refused
  too: the gate reads the Ephemeral flag, as bd promote always has, and
  `bd update --persistent` is the move for that row.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 05:51:53 +00:00
Julian Knutsen
048f5e5192
fix(httpclient): bound response-header waits and retry stalled reads on another connection (#7553)
* fix(httpclient): bound response-header waits and retry stalled reads on a new connection

The maintainer-city shadow run saw 22 requests sit out the full 60s client
timeout, each on one silent HTTP/1.1 connection while other connections to
the same serve kept answering.

wire.Client now bounds an idempotent request's wait for response headers
(15s default; BEADS_HTTP_RESPONSE_HEADER_TIMEOUT or
DialOptions.ResponseHeaderTimeout; "off" disables), separately from the 60s
overall timeout, and stops the timer once headers arrive so a streaming body
is never cut. A read (GET/HEAD/OPTIONS, or a Request marked Idempotent: the
POST batch get) that stalls or has its connection reset is retried once: the
stalled attempt's cancellation closes its connection and idle connections are
dropped, so the retry dials fresh. Every retry is counted
(wire.StallRetryCount) and reported (OnStallRetry; the dialer's default logs
one stderr line with the count).

Writes are never retried and get no header timer, because bd serve answers
a write only after it commits (a large batch apply can legitimately take
tens of seconds). A write whose overall timeout fires before its headers
fails with a typed *wire.ResponseHeaderTimeoutError (inside *ConnectError)
naming the host and saying the outcome is unknown.

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

* fix(httpclient): retry a stalled read within the overall timeout (bd-p1wzpi)

Adoption review of #7553 found three defects in the header timer and its
retry. This maintainer fixup sits on top of the contributor commit and
supersedes three of its claims: that the timer bounds a read's every
attempt, that idle connections are dropped before the retry, and that any
write whose overall timeout fires before its headers is typed.

A slow but healthy read is no longer cut short. The 15s timer cannot tell
a silent connection from a serve still working on the read (serve writes a
read's headers only after waiting up to 10s for a database slot and running
the query), and the retry ran under a fresh 15s timer, so a read slower
than 15s failed at about 30s after sending two requests where it used to
succeed within 60s. The timer now bounds only the first attempt. The retry
has no header timer and runs under a deadline of when the first attempt was
sent plus the client's overall Timeout, the moment that Timeout itself
counts from, so it finishes such a read and no read waits longer than the
60s it could before. The request is built and stamped once and each
attempt sends a copy of it, so the credential source is consulted once,
before any clock starts, and a cold token command costs the retry none of
its budget. What is left: a read whose headers take longer than the timer,
and whose retry then needs more than what remains of the 60s (about 45s)
for its headers and body together, now fails at 60s where it used to
succeed, and the server also gets the abandoned first request. A read whose
first attempt already spent the whole Timeout (the timer off) is not
retried at all and keeps its typed timeout.

A request is typed *ResponseHeaderTimeoutError only once it was written.
Any Timeout() error on a write used to be typed, including the baseline
transport's dial and TLS handshake timeouts where nothing reached the
server, and the message then said the write "may or may not have been
applied", gave the overall timeout as the wait, dropped the transport's
error, and Temporary() was true. The timer is now armed from httptrace's
WroteRequest (where http.Transport.ResponseHeaderTimeout starts its own
clock), which also records that the request went out. A timeout is typed
only for a written request whose caller's context is still alive; a dial
or TLS timeout stays a plain *ConnectError. After is the measured wait,
Err is printed, Temporary() reports Replayable (false for a write), and a
retried read says why its first attempt was abandoned (Reason). Arming at
the write also stops a slow credential source (BEADS_HTTP_TOKEN_COMMAND may
take 30s) from being reported, counted and retried as a server stall.

No idle-connection flush. CloseIdleConnections ran on a transport shared
by every no-CA dial in the process (baselineTransport), so one stalled read
dropped idle keep-alives to every host. Canceling the stalled attempt
already closes its connection (net/http never pools a canceled HTTP/1.1
connection), so the retry rides another one.

Also:
- wire.Request.Replayable (GET/HEAD/OPTIONS, or Idempotent) is now the one
  predicate behind both the wire's stall retry and dispatch's bounded 503
  retry, so the batch get, a read on POST, is retried on a 503 too.
  dispatch's doc comment no longer says the wire never resends.
- The docs, the error and the stall line say the retry goes out on
  "another connection", not a "new" one: the idle pool may hand it one
  already open. dialStream's doc says the events:watch connect gets
  neither the timer nor the retry.
- BEADS_HTTP_RESPONSE_HEADER_TIMEOUT takes bare seconds ("30") as
  BEADS_GATE_WAIT_TIMEOUT does, and "off" in any case. "off" or 0 turns off
  only the timer: a reset connection is still retried and a written request
  that times out is still typed.
- README says "each read" and spells out the above, bounding the retry by
  its headers and body together; it no longer says a streaming body is
  never cut off (the header timer never does, the 60s bound still does).
  The CHANGELOG entry moves from Added to Fixed and states the same bound.
- CredentialProvider's doc, in wire and on the public bdhttp alias, says
  Authorize runs once per request, not once per attempt: the stall retry
  resends the stamped headers up to the overall timeout later, so a
  single-use or short-lived credential may draw a 401 there, which reaches
  Refresh like any other.

Tests: a read queued behind a LimitListener backlog finishes once a slot
frees; a read slower than the timer on every connection finishes on its
retry; a slow credential source is not a stall, and one that takes the
whole Timeout to resolve still leaves the retry its budget (starting the
deadline before the stamp, or re-stamping the retry, fails it); a write
whose dial times out is a plain *ConnectError; a stall leaves another
server's idle connection on a shared transport alone; a retry after a
reset names the reset; the stall-twice case is bounded by the overall
timeout and pins After, Reason and the message; dispatch retries a read
on POST on a 503, and GetMany's batch get is sent as one (dropping its
Idempotent fails that); the env knob takes "30", " 1.5 " and "OFF" and
refuses "-3". A read whose first attempt spent the whole Timeout is not
retried and keeps its typed error (dropping the spent-budget check fails
it; no other test did). A stall retry that draws a 401 refreshes once and
authorizes only the re-issued request, so Authorize runs twice, not three
times (re-stamping the retry fails it).

Not covered, as before, and now said in README and the CHANGELOG: the
events:watch stream's connect (dialStream) has no header timer or retry.
Nor is a reset on Windows: stallReason matches syscall.ECONNRESET, which a
Windows reset (WSAECONNRESET) is not, so there a reset connection is
retried only when it surfaces as EOF.

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>
Co-authored-by: Eddie the Engineer <adopt-pr@gascity.com>
2026-10-14 05:04:19 +00:00
Julian Knutsen
e7ad85bcff
fix(http): bd export over http through issueops.ReadExport (S21) (#7551)
* fix(http): bd export over http through issueops.ReadExport (S21)

bd export read through raw SearchIssues and the bulk label, dependency and
comment reads, which the HTTP backend refuses (B3 #16), so gc's JSONL export
order (gc bd export --all) failed on every remote scope.

issueops.ReadExport composes role reads every deployed server publishes: an
unlimited Reader.List for rows, labels and counts, EdgeReader.ReadEdges for
dependency records, and Reader.Get with comments for rows that have any. The
remote route feeds it into the same runExportFromSource the direct and
proxied routes use. A failed read fails the export. gc-export-all passes
against the reference profile; mc-promote stays pending (S21b) with its exact
reason: it needs a new server capability.

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

* fix(export): read remote memories from the memory plane, pin unmarked no-history rows (bd-o4qlui)

Review fixes for #7551, attempts 1 to 3.

Attempt 3. No test reached roleExportSource.ExportMemories's error
path. A unit test now drives it with a fake store: a memory role that
cannot be reached, and a listMemories that fails, each end the export
with that error and no map. Rewriting either branch to degrade to an
empty map would bring back a remote `bd export --all` that exits 0 with
no memory in it.

Declined in attempt 3, for finalize to file: an unlimited HTTP listing
that stops on a has_more page with no next_cursor returns the rows it
has with HasMore false, so ReadExport's refusal cannot fire over HTTP.
Only a server that breaks the spec's has_more/next_cursor pairing gets
there; this repo's server always sends a cursor with a non-empty
has_more page. The walker (fetchIssuePages) is unchanged since #7247
and shared with bd list, so the fix needs its own PR that checks bd
list's callers first. The remote route also has no single snapshot: a
comment changed between List and Get can make the written count
disagree with the bodies kept. That belongs in one follow-up with the
bounded retry declined in attempt 1, as a count/body consistency check.
The --include-infra e2e leg stays declined. The wire does carry the
knob: the client sends include_infra and include_templates on
listIssues, and the server decodes both. The GetInfraTypes nil-store
guard stays declined, and auto-export's own GetAllConfig memory read
predates this PR.

Attempt 2. A remote export dropped every memory. Over HTTP, `bd export
--all` and `--include-memories` exited 0 without a memory record, where
the base refused with exit 1. The memory lines came from GetAllConfig,
which over HTTP is listSettings, and the server's settings enumeration
withholds every kv.* row, memories included. gc's JSONL export runs
`gc bd export --all`, so its archive lost them without a word.

The exportSource seam now asks each source for its memories
(ExportMemories), not for the whole config table. The local and proxied
sources still take them from their config table. The remote source reads
the served memory plane, store.Memories().List (listMemories), which the
deployed bd 1.3.0 server advertises as memories.list. httpMemories.List
refuses a page that reports has_more: ListResult has no cursor, so a
truncated plane would pass for the whole one. The memory error now says
"failed to read memories"; nothing in beads or gascity matches the old
text.

TestE2E_ExportOverHTTP seeds two memories with `bd remember` over HTTP.
It requires exactly those two in --all, in --include-memories and in the
local re-export of the imported file, and none in the default export. A
unit case pins the has_more refusal. The CHANGELOG entry says where
remote memories come from, so its "Nothing is dropped" holds. The
WispPlaneIDs doc no longer says the listing refuses an id set, which
stops being true once a server advertises issues.list.ids (#7550).

Attempt 1. The remote route's WispPlaneIDs doc and the CHANGELOG had the
effect of the missing wisp_plane marker backwards. They said import then
routes a no-history row by its flags. A current import does the
opposite: it pins an unmarked no-history row to the durable plane
(applyImportWispPlane). So a genuine no-history wisp in a remote export,
which gc's session, wait and order beads are by default, re-imports onto
the Dolt-versioned issues plane, and gc's JSONL archive keeps it.

The route still stamps nothing. No served read publishes plane
membership: listIssues rows carry no plane field, however the listing is
scoped. Inferring the marker from the flags would re-plane a durable row
that still carries the flag and drop its relations (bd-r9uce), and
refusing the export would re-break gc's remote JSONL export. The doc and
the CHANGELOG now state the real consequence, and serving the membership
is bd-1lbvas. TestE2E_ExportOverHTTP pins it. A no-history row is
exported without the marker by --all and by the default export. A fresh
local workspace imports it onto the durable plane, against a locally
created control row that the local route does mark.

Attempt 1 minors and nits: ReadExport refuses a listing page marked
HasMore, as the uow source does, and unit cases pin that and a failed
comment read. The exportSource interface doc names ExportIssues and its
contract. The export error now says "failed to read the export set"
rather than "failed to search issues"; nothing in beads or gascity
matches the old text. roleExportSource.GetInfraTypes says it is unused
on this route.

Declined, for finalize to file: a bounded retry of ReadExport when a row
vanishes between the reads (a design change; today's fatal behavior is
pinned), and e2e rows for pinned, gate, template and infra-typed issues,
including an --include-infra leg over HTTP. Also declined: a nil-store
guard on roleExportSource.GetInfraTypes. The method is dead on this
route, and the source's other store readers (ExportIssues, GetConfig,
ExportMemories) dereference the store unguarded too.

Validation, attempt 3: git diff --check, the go.mod-pinned gofmt, go
vet, gazelle (no change) and the go_srcs check. The new test passed with
no skips. Three mutants were killed. An empty map with no error on a
failed listing, and the same on an unreachable role, each fail their own
subtest. An empty map returned beside the listing error fails the no-map
assertion; export.go discards the map on error today, so that case pins
the interface's "fail rather than return a partial set" contract, not
visible output.

Validation, attempt 2: git diff --check, gofmt and go vet. The
httpclient memory tests passed, 23 of them: 4 units and 19 served. So
did TestE2E_ExportOverHTTP on embedded Dolt with
BEADS_HTTP_TEST_REQUIRED=1 and no skips. Two mutants were killed: a
remote source that reads the settings listing fails 3 e2e assertions,
and dropping the has_more refusal fails the unit case. Export parity
passed with no skips on the classic (memory determinism, byte
stability), embedded and proxied tiers, including the proxied-versus-
classic byte identity with memories. The PR is now behind main, which
added #7549 and #7550, and conflicts with it textually in CHANGELOG.md,
backend/http/BUILD.bazel and issueops/BUILD.bazel. With those resolved
by union, the merge with main e6a891b900 builds and vets. On that merge,
in CI's pinned-shard layout, the served http tier passed 49 of 49,
including #7550's list-scope e2e. The command corpus ran 128 shapes: 113
pass, 3 allowed, 12 pending and 0 fail. gc-export-all passes without its
pending mark, the one shape that moved. The issueops ReadExport and
ListGates tests passed, as did the embedded and proxied export tiers.

Validation, attempt 1: the issueops ReadExport tests, with two mutants
killed; TestE2E_ExportOverHTTP with a flag-stamping WispPlaneIDs mutant
killed on three assertions; the cmd/bd export tests in a scrubbed env.

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-14 03:59:35 +00:00
Julian Knutsen
e6a891b900
feat(list): bd list --no-assignee, --title and --id over http behind per-parameter tokens (S15b) (#7550)
* feat(list): bd list --no-assignee, --title and --id over http behind per-parameter tokens (S15b)

Over http `bd list --no-assignee`, `--title` and `--id` refused: the list
encoder had no listIssues parameter for ListRequest.NoAssignee,
TitleSearch or IDFilter (B3 #11). All three are maintainer-city cutover
blockers: gc's default on_boot hook runs
`bd list --no-assignee --status=in_progress ...` on every agent boot, the
PR-intake formula lists by `--title "$SUBJECT"`, and the pr-review skill
by `--id <ids>`.

The library entry is unchanged: issueops.Reader.List, whose bodies
already apply all three through workapi.BuildListFilter, the same entry
the local route reads through.
- Server: GET /v0/beads/issues decodes `no_assignee`, `title` and `id`
  into those ListRequest members (`id` handed over as written; the role
  splits, trims and de-duplicates, as countIssues already does). Each is
  behind its own new behavior token, issues.list.noAssignee,
  issues.list.title and issues.list.id (additive, wire_revision stays 2):
  each is a separate caller's dependency, and a refusal names exactly the
  one it needed. The spec parameters cite their tokens; apigen and the
  wire-shape golden are regenerated.
- Client: the encoder maps the three members to their parameters, and
  httpReader.List refuses a request carrying one BEFORE dialing, with
  ErrUnsupported{Capability: <token>}, unless the handshake advertises
  that token (refuseUnservedSearch generalised to one table,
  tokenedListFilters, with bd search's `q`). Never a round trip an older
  server answers unknown_parameter, never a wider listing.
- ErrHTTPUnsupported's text names the capability when it has one, as the
  portable sentinel does, so `bd list` says which token the server lacks.
- The three E-ListRequest ledger rows retire; the ledger is re-rendered.

The id scope unparks the served Reader contract: the sixteen cases parked
on E-ListRequest.IDFilter now run against the in-process server. Twelve
pass as written; four still park, each now on the member it actually
needs (Offset twice, PinnedFlag, ExcludeTypes). The served refusal sweep
asserts SpecPrefix where it asserted IDFilter.

Tests (failing first): handler test that each parameter reaches the
storage filter; client tests that each member rides its parameter behind
its token and refuses pre-dial, zero dials, naming its token, against a
server lacking it; round-trip and vocabulary gates; capability lists.

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

* test(backend/http): the four maintainer-city list shapes end to end; corpus marks relabelled SRV-1 (S15b)

TestE2E_ListScopeFiltersOverHTTP runs the corpus shapes gc-list-on-boot,
gc-list-on-boot-workflow, mc-list-title and mc-list-id through the real
bd against the in-process server (which advertises the three new tokens)
and requires each to answer an embedded workspace's rows and exactly the
rows it names: --no-assignee leaves out an assigned in-progress row on
the same lane, --title is case-insensitive, --id lists a closed id under
--all. Against the MC production server's handshake shape each shape
exits non-zero naming its token and never dials listIssues.

The corpus suite masks the served side to reference_server.json, the
deployed bd 1.3.0 surface, which advertises none of the tokens, so the
four shapes now get the named pre-dial refusal there. Their marks move
from S6c+S15b to SRV-1 with that reason, like mc-search. With a scratch
profile that adds the three tokens and parameters (not committed) exactly
these four shapes report "now passes; remove the pending mark" and
nothing else changes.

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

* fix(list): adopt bd-enterprise's listIssues `id` contract: repeatable, issues.list.ids (S15b)

bd-enterprise already publishes listIssues `id` (E9-S2): a REPEATABLE
parameter, one id per value, behind `issues.list.ids`, with its client
sending IDFilter split into one value per member. The first cut of S15b
took ONE comma-separated `id` behind `issues.list.id`, so the same
parameter name had two incompatible meanings: an OSS client's "a,b" is a
400 on an enterprise server, and the enterprise rebase onto main would
collide. OSS now publishes enterprise's contract unchanged:
- Server: listIDFilter (ported verbatim) decodes the repeated `id` into
  ListRequest.IDFilter's comma set; more than 200 values, an empty value,
  a comma, leading or trailing whitespace, a control character or an
  over-long id is a 400 `invalid_argument` on `id`. The spec parameter is
  enterprise's (array, maxItems 200); apigen and the wireshape golden are
  regenerated.
- Token: CapListIDs = "issues.list.ids", the enterprise spelling and name
  on both sides.
- Client: the encoder splits the set the way the role does (splitIDSet)
  and sends one `id` per member; the pre-dial gate fires only when the set
  names an id.
- Tests: list_ids_test.go is enterprise's id cases (the exact set reaches
  storage, the 200 bound is served, every refusal beside its control, the
  spec bound matches the constant); the handler, client, round-trip and
  e2e cases move to the repeated shape and the new token.

`no_assignee` and `title` are unchanged. Served tier, http e2e (including
TestE2E_ListScopeFiltersOverHTTP) and corpus_served_test pass; with a
scratch reference profile advertising the three tokens exactly the four
S15b shapes report "now passes".

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 00:18:00 +00:00
Julian Knutsen
d4ca89369f
fix(http): bd gate list over http through issueops.ListGates (S20) (#7549)
The workspace-wide gate listing built a raw SearchIssues filter, which the
HTTP backend refuses (B3 #15), so gc's renudge-stale-human-gates order
(gc bd gate list --limit 0 --json) failed on every remote scope.

issueops.ListGates asks the Querier role (queryIssues, served by every
deployed server) for type=gate, closed hidden unless --all: the rows the raw
filter selected, on both planes. The direct, proxied and remote routes all
call it through openQuerier. The corpus seed gains an open, a closed and an
ephemeral gate, and mc-gate-list (the order's argv) plus mc-gate-list-all
pass on the served side.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 23:13:29 +00:00
Julian Knutsen
308fd38ca2
test(corpus): seed served/embedded sides concurrently; size served shards from CI timings (#7538)
* test(bazel): shard http_served_test and corpus_served_test (embedded lane critical path)

Both served targets ran as one shard each (235-597s) and were the embedded
lane's longest action in most executing runs; every other embedded shard
ends by ~90-155s.

- http_served_test runs through go_test_pinned_shard.sh like
  httpclient_served_test: the 19 TestE2E_* cases >= 3s are pinned onto 6
  shards (pin_shards.py from three lane runs' test.xml plus one local run,
  <= ~88 measured seconds each), the ~28 fast tests round-robin in a 7th.
- corpus_served_test: TestServedCorpus becomes TestServedCorpusPart1..4.
  Shapes are dealt round robin in corpus order; each part starts its own
  server and seeds its own pair of workspaces. The shapes are independent:
  every check is served-vs-embedded parity after the same commands, each
  write owns its target ids, and order preservation keeps each part's reads
  ahead of its writes. TestCorpusPartsDealEveryShapeOnce checks the deal
  (every shape once, in order, no empty part); the manifest pins part k to
  shard k, with a 5th round-robin shard for the engine-free tests, and
  scripts TestCorpusPartsArePinnedOnePerShard ties corpusParts, the
  manifest and shard_count together. BEADS_CORPUS_REPORT now accumulates
  every part the process ran.
- pinnedShardTargets and the retired-lane args pins list both targets;
  go_test_sources_test gets the two packages' manifests as data.

Embedded goes from 172 to 182 test actions; the dolt-race/dolt-int union
budgets do not include the embedded tag and are unchanged.

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

* test(corpus): seed the served and embedded sides concurrently in each part

Each TestServedCorpusPartN paid the server start and both seeds serially
(about 100-150s of a 190-220s shard in #7537's CI). The embedded side now
runs bd init and the seed on a goroutine while the test goroutine starts
the server and proxy and seeds the served side.

- prepareSide attaches one side (connect or init), writes its assets and
  runs the seed in order, returning failures as errors (execBD, runBD
  without the testing.T) so it is safe off the test goroutine; a failing
  side cancels the other, and a deferred cancel+Wait keeps the goroutine
  from outliving the test or its TempDirs.
- The sides share no directory, env or bd process; shapes, their order and
  every assertion are unchanged. Each part logs its setup time.
- bazel.yml's embedded lane uploads the served targets' test.xml on every
  run (bazel-embedded-served-testxml), so their pinned shards can be sized
  from a sharded run of the lane.

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

* test(bazel): corpus in 3 parts; re-pin http_served_test from a sharded CI run

Measured on this PR's first embedded-lane run (test.xml from the new
bazel-embedded-served-testxml artifact):

- corpus_served_test with concurrent seeding: parts 1-4 ran 135/140/144/114s,
  of which setup (part time minus its shapes) was 76/76/76/62s and the 127
  shapes 242s together. The setup floor is still ~70s+, so corpusParts goes
  from 4 to 3 (round robin; the measured split is 85/81/76s of shapes) and
  the manifest and shard_count follow (4 shards: 3 parts + round-robin).
- http_served_test: #7537's pins were sized from single-shard runs, and the
  sharded shards ran 73-184s against ~88s estimated. served_pinned_shards.txt
  is regenerated with pin_shards.py from that sharded run's per-test
  durations: 119/118/120/128/132/123 measured seconds per pinned shard.

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

* test(bazel): pin http_served_test on the max over two sharded CI runs

The second run of the lane on this PR ran the same tests at 0.2-1x their
first-run times (executor load, not the tests), and its re-pinned shards
came out 36-118s against 118-132s estimated. pin_shards.py now takes each
test's maximum over both runs' test.xml, the same rule the other pinned
targets use: 123-135 measured seconds per pinned shard.

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

* test(corpus): guard part wiring; seed metadata on e2e-t-ifa (review of #7537)

- testServedCorpus fails (before the engine gate, so in every lane) unless
  the test's name is TestServedCorpusPart<part>: a TestServedCorpusPart3
  calling testServedCorpus(t, 2) would run part 2 twice and silently drop
  part 3's shapes. TestCorpusPartNameMustMatchItsPart covers the check and
  that servedCorpusParts lists Part1..N in order. Mutation (Part3 -> 2)
  fails //backend/http/corpus:corpus_test with "TestServedCorpusPart3 runs
  corpus part 2; only TestServedCorpusPart2 may".
- e2e-t-ifa is seeded with metadata seeded=keep. The parts seed separately,
  so the two refused (exit 13) conditional updates no longer always follow
  gc-update-if-assignment's k=v; their verify show again holds that a
  refusal keeps existing metadata. Mutation (served verify output's
  seeded=keep rewritten) fails both stale shapes at
  $[0].metadata.seeded.

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

* test(bazel): back to 4 corpus parts (served long pole over test-seconds)

maintainer-city-c3's call on the measured trade-off. With concurrent
seeding, 4 parts ran 114-146s each (run A) and 3 parts ran 170-180s (run D).
3 parts save one ~75s setup, about 75 test-seconds per executing run, but
the longest part is the embedded lane's served long pole. That pole is on
the gate's critical path (forks' above all), and 4 parts cut it by ~34s.

corpusParts=4, TestServedCorpusPart4, manifest part 4 on shard 4,
shard_count=5. The part-name guard is unchanged and covers Part4.

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

* ci(bazel): served-timings upload is telemetry; corpus part bounds and ctx

Review of #7538 (maintainer-city-c3):
- "Upload served test timings" gets continue-on-error: true and
  timeout-minutes: 2, like the CI analytics upload. An artifact-service 5xx
  or stall no longer fails the required embedded lane or holds it until the
  job timeout. TestBazelWorkflowSecretsAndFailureSurface allows that
  continue-on-error only on this exact step
  (bazelServedTimingsContinueOnErrorPath, which also pins its name,
  artifact, path and timeout; TestBazelEmbeddedServedTimingsUploadIsTelemetry).
- corpusPartNameErr also refuses a part outside 1..corpusParts, so a stray
  TestServedCorpusPart5 fails instead of running no shapes. Two new cases.
- expand takes ctx: prepareSide's {rev:} lookups run under the seeding
  context, so a cancel stops them as well.

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

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-13 12:30:52 +00:00
Julian Knutsen
4e27523c0b
test(bazel): shard http_served_test and corpus_served_test (embedded lane critical path) (#7537)
* test(bazel): shard http_served_test and corpus_served_test (embedded lane critical path)

Both served targets ran as one shard each (235-597s) and were the embedded
lane's longest action in most executing runs; every other embedded shard
ends by ~90-155s.

- http_served_test runs through go_test_pinned_shard.sh like
  httpclient_served_test: the 19 TestE2E_* cases >= 3s are pinned onto 6
  shards (pin_shards.py from three lane runs' test.xml plus one local run,
  <= ~88 measured seconds each), the ~28 fast tests round-robin in a 7th.
- corpus_served_test: TestServedCorpus becomes TestServedCorpusPart1..4.
  Shapes are dealt round robin in corpus order; each part starts its own
  server and seeds its own pair of workspaces. The shapes are independent:
  every check is served-vs-embedded parity after the same commands, each
  write owns its target ids, and order preservation keeps each part's reads
  ahead of its writes. TestCorpusPartsDealEveryShapeOnce checks the deal
  (every shape once, in order, no empty part); the manifest pins part k to
  shard k, with a 5th round-robin shard for the engine-free tests, and
  scripts TestCorpusPartsArePinnedOnePerShard ties corpusParts, the
  manifest and shard_count together. BEADS_CORPUS_REPORT now accumulates
  every part the process ran.
- pinnedShardTargets and the retired-lane args pins list both targets;
  go_test_sources_test gets the two packages' manifests as data.

Embedded goes from 172 to 182 test actions; the dolt-race/dolt-int union
budgets do not include the embedded tag and are unchanged.

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

* test(corpus): guard part wiring; seed metadata on e2e-t-ifa (review of #7537)

- testServedCorpus fails (before the engine gate, so in every lane) unless
  the test's name is TestServedCorpusPart<part>: a TestServedCorpusPart3
  calling testServedCorpus(t, 2) would run part 2 twice and silently drop
  part 3's shapes. TestCorpusPartNameMustMatchItsPart covers the check and
  that servedCorpusParts lists Part1..N in order. Mutation (Part3 -> 2)
  fails //backend/http/corpus:corpus_test with "TestServedCorpusPart3 runs
  corpus part 2; only TestServedCorpusPart2 may".
- e2e-t-ifa is seeded with metadata seeded=keep. The parts seed separately,
  so the two refused (exit 13) conditional updates no longer always follow
  gc-update-if-assignment's k=v; their verify show again holds that a
  refusal keeps existing metadata. Mutation (served verify output's
  seeded=keep rewritten) fails both stale shapes at
  $[0].metadata.seeded.

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

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-13 11:35:34 +00:00
Julian Knutsen
ec55baa425
fix(http): bd show --current, recompute-blocked and search over http through issueops entries (S6e/S25/S26) (#7528)
* fix(show): --current through issueops.FindCurrentIssue over the Querier role; no swallowed refusal (S6e)

Over http `bd show --current` printed the WRONG issue, exit 0.
resolveCurrentIssueID asked the raw SearchIssues method for the actor's
in_progress and then hooked work; the http backend refuses that method, the
refusal was taken for "nothing found", and the command fell back to the
last-touched issue. The proxied route had its own copy of the lookup, read
inside its unit of work, with the same swallow.

One library entry now: issueops.FindCurrentIssue(ctx, Querier, actor). It
asks the Querier role (queryIssues over http, which every deployed server
publishes) for `status=<s> AND assignee="<actor>"`, limit 1 — exactly the
raw filter, answered in the store's default order, so the same row comes
first on every backend — in_progress, then hooked. A failed read is an
error; "" (two reads that answered and found nothing) is the only miss. The
actor is a quoted, escaped query value; the query language reads
`assignee=none`/`null` as "unassigned", so such an actor (or an empty one)
is not asked about.

Both CLI routes call it with their route's Querier (store.Querier() or the
proxied provider's) through one cmd/bd helper; what stays in the CLI is the
actor and the last-touched fallback (a workspace file). The proxied route
resolves --current before it opens its unit of work, and its duplicate
in-transaction lookup is deleted.

Tests: issueops unit tests (order, failure is an error on either read,
quoting, unaskable actors, each expression evaluates to exactly the raw
filter); cmd/bd fallback tests; served e2e TestE2E_ShowCurrentOverHTTP
(in-progress beats a later-touched issue, hooked when nothing is in
progress, last-touched only when neither). Against the old code the e2e
fails with exactly the reported bug.

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

* fix(recompute-blocked): one library entry, storage.RecomputeBlocked; a no-op on a remote backend (S25)

`bd recompute-blocked` refused over http ("storage backend does not support
is_blocked recompute"), and gc's BdStore.RecomputeBlocked issues it.

is_blocked is server-derived. Every write a remote client makes is committed
by the server's own store, which keeps the flag under
issueops.BlockedStateInvariant's local-write clause (targeted, inside the
write's transaction; a Postgres-family server has no full recompute at all
and runs a no-op readiness strategy for the same reason). A client cannot
leave the flag stale and holds no copy of it. The invariant's merge clause
(a recompute skipped after a pull, bd-6dnrw.37; a migration that over-set
it, beads#7037) happens to the SERVER's database, and its repair is this
command in the server's workspace.

So the decision is in the library, not the CLI: storage.RecomputeBlocked
(internal/storage/blocked_recomputer.go) is the one entry every backend goes
through. A local store (storage.BlockedRecomputer) recomputes its column; a
store implementing storage.ServerMaintainedBlockedState — the http client,
whose BlockedStateMaintainedByServer answers true — recomputes nothing and
reports MaintainedBy "server". No wire operation: a whole-column rewrite any
bearer of a workspace credential could trigger, for state no client can have
caused, is not one to publish. The proxied route keeps its pinned-connection
plumbing around the same versioncontrolops body the stores run.

--json keeps rows_corrected (gc requires the member; wh-bridge-sync reads the
exit code) as 0 and adds maintained_by: "server"; the text says where the
repair runs.

Tests: storage unit tests (local repair runs, server-maintained wins even
over a local repair and runs none, neither refuses); served e2e
TestE2E_RecomputeBlockedOverHTTP (exit 0, JSON shape, text, ready set
unchanged). With the server-maintained branch disabled the e2e fails with
the old refusal.

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

* feat(search): every bd search route through Reader.List with issueops.SearchListRequest; listIssues `q` behind issues.list.search (S26)

`bd search` called the raw SearchIssues method with its text, which the http
backend refuses ("partial-id search is not available over HTTP"), and its
direct and proxied routes each mapped the flags onto a storage filter by
hand. No served operation could carry search's meaning (title OR id contains
the text, case-insensitively; an id-shaped text also matches exact id, id
prefix and external ref): TitleSearch is title-only and the query language
has no title-or-id predicate.

The library entry is issueops.Reader.List:
- issueops.ListRequest gains Query, SearchIssues' free-text argument as a
  member. Both Reader bodies (workapi/storereader and the uow reader) pass it
  to SearchIssuesWithCounts where they passed "". It narrows and lifts no
  default exclusion; the ready arm refuses it (readyScopeFields).
- issueops.SearchListRequest(query) is search's scope as a request: Query,
  every status (AllFlag), every kind of row (the four Include*), and the
  store's default order (SortBy priority), so --limit keeps the rows a raw
  read kept.
- CLI: ONE runSearch for the direct, proxied and remote routes. One builder
  (searchListRequest) maps the flags onto SearchListRequest; the route only
  picks the reader (store.IssueReader() or the proxied provider's).
  --sort/--reverse reorder the page as before. search_proxied_server.go and
  its hand-built filter are deleted, and search leaves the forbidigo
  filter-writing exemption.
- Server: GET /v0/beads/issues decodes `q` into ListRequest.Query and calls
  the same Reader role, behind the new issues.list.search behavior token
  (spec parameter cites it; additive, no wire_revision bump; apigen and the
  wire-shape digest regenerated).
- Client: the encoder maps Query to `q`; httpReader.List refuses a request
  carrying Query BEFORE dialing, with ErrUnsupported{Capability:
  issues.list.search}, unless the handshake advertises it — never a round
  trip an old server would 400, never the unsearched listing passed off as
  the search. CapListSearch mirrors the server token. Flags listIssues
  publishes nothing for are put on the request so the encoder refuses them
  rather than widening the search.

Tests: Reader contract case RunReaderListQueryMatchesTheTitleOrTheID (also
pins SearchListRequest's scope) on all four legs — dolt, embedded dolt, uow,
served http (label-scoped, so the served leg runs it as written); handler
test that `q` reaches the seam as the search text, not TitleSearch; client
tests for `q` and the pre-dial refusal (zero dials); round-trip and
vocabulary gates; TestSearchRoutesAgree runs the same twelve flag sets on
the direct, proxied and remote routes and requires identical answers
(remote is bd serve over the proxied database, so ids and order too); served
e2e TestE2E_SearchOverHTTP. The remote legs skip with the
SearchIssuesWithCounts refusal until S6c's externaldeps reader passthrough is
underneath (loud refusal, never an empty or wrong answer); with S6c
cherry-picked all three routes agree.

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

* build: resync BUILD srcs and the embedded storage shard manifest for S6e/S25/S26

gazelle picks up cmd/bd/show_current.go, cmd/bd/search_remote.go, the three
backend/http e2e files and internal/httpclient/list_search_test.go; the
embedded storage shard manifest gains
TestEmbeddedReaderListQueryMatchesTheTitleOrTheID
(scripts/ci/gen_embedded_storage_shard_manifest.py 15 --weights=duration
--write).

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

* style: gofmt list_show_filter_modes.go (trailing blank line)

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

* test(backend/http/corpus): drop the show --current and recompute-blocked marks S6e and S25 retire

With S26 folded in, `bd show --current` resolves through
issueops.FindCurrentIssue over the Querier role and `bd recompute-blocked`
goes through storage.RecomputeBlocked (a no-op on a remote backend), so
gc-show-current and gc-recompute-blocked lose their pending marks.
mc-search stays pending, relabelled S6c+SRV-1: bd search now asks listIssues
with q behind issues.list.search, which the reference server profile does
not advertise, so the client refuses before dialing.

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

* test(cmd/bd): split the bd search route agreement into the embedded and proxied lanes

TestSearchRoutesAgree skipped unless BEADS_TEST_EMBEDDED_DOLT=1, then ran
its proxied and remote legs only under BEADS_TEST_PROXIED_SERVER=1, and
its name matched neither lane's discovery (TestEmbedded* in
*_embedded_test.go, TestProxiedServer*/TestServerMode*). No CI lane ran
it, which main's #7468 guard (TestProxiedGatedTestsRunInTheProxiedLane)
now fails on.

Split it:
- TestEmbeddedSearchRoutesAgree (search_routes_embedded_test.go): the
  direct route, embedded lane.
- TestProxiedServerSearchRoutesAgree (search_routes_proxied_test.go): the
  proxied route and the remote route (bd serve over the proxied
  workspace), gated only on BEADS_TEST_PROXIED_SERVER. The remote route
  must still answer the proxied one row for row, ids and order included,
  and refuse the flag listIssues cannot carry.

Neither lane can run the other's workspace, so the shared helper
(search_routes_parity_test.go: the seed, the twelve flag sets, and
checkSearchRoute) holds every route to one expected answer per flag set;
agreeing with it is agreeing with each other. The remote leg's "needs
S6c" skip is gone: S6c is on main, so a refusal now fails.

Both manifests regenerated incrementally (embedded 100-shard block, shard
71; proxied 34-shard block, shard 23). Bazel: bd_embedded_part2_test
(--config=embedded) and bd_proxied_test (--config=doltserver-proxied)
pass and run the new tests; //scripts:go_test_sources_test passes.
Swapping the title-sort expectation fails both routes of the proxied
test.

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

* fix(search): keep an infra type's durable rows, expand --type aliases, fail the S26 e2e on refusal (bd-1ejjv6)

Review fixes for #7528, attempt 1: the three majors and three minors of
the synthesis.

`bd search --type <infra type>` dropped the type's durable rows (a
promoted wisp, an issue retyped after it was created), exit 0. The shared
listing (workapi.BuildListFilter) narrowed an infra --type to its
ephemeral rows unconditionally, so SearchListRequest's IncludeEphemeral
did not bring back what raw SearchIssues used to return. The narrowing
now applies only without IncludeEphemeral, in BuildListFilter and in the
count lockstep (applyCountIncludeInfra), and the http parent-walk
recognizer reads an infra type's Ephemeral back as the include_ephemeral
intent. This also fixes `bd list --type <infra type> --include-ephemeral`
and GET /v0/beads/issues, which shipped the narrowing in v1.3.1. Pinned by
workapi tests and by template, gate, wisp and promoted-message rows in the
Reader conformance Query case (new ReaderFixture.PromoteWisp) on the
dolt, embedded, uow and served backends; the issueops Reader/Counter docs
and the openapi descriptions say the same.

`bd search --type` handed the raw string to the Reader: an alias (feat,
mol, mr, ...) answered nothing and an unknown type an empty result. It is
now expanded with utils.NormalizeIssueType as `bd list` does, and an
unknown type exits 1. The help text and the CHANGELOG say so, and the
CHANGELOG also records the additive comments_omitted field in
`bd search --json` rows.

TestE2E_SearchOverHTTP skipped on the very SearchIssuesWithCounts refusal
it exists to catch; it now fails. The route agreement seeds "kinded"
template, gate, wisp and promoted-message rows and pins the alias, the
unknown-type refusal and the infra rows on the direct, proxied and remote
routes.

Minors: the CHANGELOG states the proxied `bd show --current` miss
fallback; the CommentsOmitted contract names `bd search --json`; the
storage.RecomputeBlocked and `bd recompute-blocked` comments name the
deliberate --proxied-server bypass.

Validation: go vet and gofmt on every changed package; make api-check;
workapi, issueops, httpclient/encode, types and storage unit tests; the
Reader conformance on dolt, embedded, uow and served; the embedded and
proxied route agreements (remote included), the embedded search tests,
TestProxiedServerSearch, TestProxiedServerRecomputeBlocked, the http e2e
search/show/recompute tests; docs flag, freshness and docsync checks; and
a hand-run bd search/list/count against a scratch workspace.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 04:12:54 +00:00
Julian Knutsen
a2d43e6792
fix(mol): molecule reads, auto-close and close --continue over http through issueops entries (S16) (#7513)
* fix(create): let a remote backend mint the --parent child id

`bd create --parent` always called the raw GetNextChildID first, which the
http backend does not serve, so every child create on a remote workspace
refused before writing anything. The Lifecycle role already mints
<parent>.<n> for a create that carries a ParentID and no id of its own, on
every backend and inside the create's own transaction; conformance
RunIssueOperationsCreateUnderAParentMintsTheNextChildID pins it on every leg,
the served one included (and the bd-enterprise postgres leg the MC server
runs). So the create route needs no new capability token: on a registered
Remote backend the client skips the raw reservation and lets the server mint.
The local route keeps its reservation so its Dolt commit staging is
unchanged, and an explicit --id beside --parent is still refused up front.

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

* fix(mol): molecule reads, auto-close and close --continue over issueops roles

Over the http backend three molecule paths failed, and two of them
silently:

- `bd mol current` / `bd mol progress` without an id answered "no molecules"
  because the in_progress listing (a raw SearchIssues shape) and the parent
  walk (raw GetDependencyRecordsForIssues) were refused and the refusal was
  swallowed; with an id they refused on raw GetMoleculeProgress.
- The molecule auto-close after `bd close` never ran: findParentMolecules
  swallowed the same refused edge read into "not part of a molecule".
- `bd close --continue` claimed the next step in a raw RunInTransaction.

The direct route now reads molecules through roleMolStore, which answers
through roles every backend serves: EdgeReader (batched at the wire's 100
anchors) for the parent walk, BatchGetter for the roots (Get per id where a
server does not publish issues.batchGet), Relations for the step rows (full
rows; the raw dependents read over http is getIssue's shallow projection,
which zeroed step assignees) and the progress counts, and Reader.List for the
in_progress/hooked listings. The auto-close closes the root through
Lifecycle.Close, and the --continue claim is one Lifecycle.Update guarded by
ExpectedStatus=open.

No refusal is swallowed any more: findParentMolecules, the molecule finders
and the hooked scan return their errors; `mol current/progress` report them;
the auto-close stays best effort but warns on stderr; AdvanceToNextStep only
moves on to the next ready step when the claim LOST a race (status mismatch,
not claimable, already claimed) and returns anything else. The one heuristic
still skipped is the id-pattern heal in loadDescendants, and only for an
ErrUnsupported backend that cannot express an id-prefix search; other
failures now surface. `mol current`/`mol progress` leave the
types.IssueFilter forbidigo hole, since they no longer build a filter.

gc does not depend on bd's molecule auto-close: it runs its own
(cmd/gc/molecule_autoclose.go, from the bd on_close hook and the
controller's bead-close events). Its worker prompts do run `bd mol current`.

Served e2e (TestE2E_MoleculesOverHTTP): create --parent mints <root>.1/.2,
mol current <id> is non-empty with the full in-progress step, mol progress
counts, close --continue auto-advances, closing the last step auto-closes
the root. `mol current` without an id now refuses out loud on this stack
(asserted: never an empty list); its non-empty assertion is skipped until
S6c (externaldeps reader passthrough) is underneath.

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

* fix(mol): list molecule candidates with the four wire knobs, drop the S6c skip

On top of S6c the in_progress listing behind 'bd mol current' (no id)
reaches the v0 wire encoder, which refuses ListRequest.IncludeAllTypes.
Ask for templates, gates, infra and ephemeral rows explicitly, which the
wire publishes, and run the 'mol current without an id' served case.

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

* feat(issueops): one library entry each for molecule auto-close, advance and reads

The molecule rules lived only in cmd/bd, in copies that disagreed: two
auto-close implementations that closed the root through different
library entries outside the step close's transaction, a `close
--continue` claim that set no assignee and could take a step another
agent held on the direct and http routes, and three progress counts.
Every molecule rule now has one implementation in the public issueops
package, composed over three roles every backend serves (BatchGetter,
Relations, EdgeReader): MoleculeRoots, LoadMolecule, AnalyzeMolecule,
ViewMolecule, ReadMoleculeProgress, ActiveMoleculeIDs,
CompletedMolecule. Membership is the parent-child edge.

Auto-close: CloseRequest.AutoCloseMolecule and
CloseBatchRequest.AutoCloseMolecule (opt-in, so gc's own auto-close is
not doubled) close the molecule root a close completed IN THE SAME
TRANSACTION, unforced and guarded on the root revision read there:
storageissueops.CloseCompletedMoleculeInTx on the store backends (the
role bodies bound to the caller's tx, TxMoleculeReader) and
uow.CloseCompletedMoleculeInUOW on the unit of work. It replays on an
idempotent re-close, reports the root on CloseResult/CloseOutcome
.AutoClosedMolecule, and a root its own close policy refuses stays open
and is reported (MoleculeAutoCloseRefusal) without failing the step.

Advance: a new MoleculeStepper role (storage.DoltStorage accessor,
uow.MoleculeStepperSource) whose one implementation,
issueops.NewMoleculeStepper, claims the next ready step through the
Claimer (Lifecycle.Update's Claim for a wisp step): assignee set, a step
another actor holds skipped, never taken.

HTTP: closeIssue/batchCloseIssues carry auto_close_molecule behind the
issues.close.autoCloseMolecule behavior token, and POST
/v0/beads/issues/{id}:advanceMolecule (issues.advanceMolecule) serves
the stepper. Handlers only decode, call the role and encode. The client
sends the member and dials the operation only where advertised; against
an older server it DEGRADES rather than refuses — it runs the same
library rule over its own roles (issueops.CloseCompletedMolecule after
the close, NewMoleculeStepper for the advance), so the outcome is the
same in more round trips. The capability fallbacks that lived in
cmd/bd move into the client: BatchGetter answers one getIssue per id
without issues.batchGet, and EdgeReader splits past the operation's 100
anchors.

Conformance: RunMolecule* on dolt, embedded, uow and http (the http leg
twice: served, and against a server with the tokens struck out).

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

* refactor(cmd/bd): molecule commands and create --parent through the library entries

`bd close`, `bd close --continue`, `bd mol current`, `bd mol progress`,
`bd ready --mol` and `bd create --parent` now call the one library entry
for each rule on every route (direct, proxied server, remote):

- close (batch, --if-revision, proxied) sets CloseRequest/
  CloseBatchRequest.AutoCloseMolecule and only reports what the library
  closed in the step close's transaction. autoCloseCompletedMolecule,
  autoCloseProxiedCompletedMolecule and closeCompletedMoleculeRoot are
  gone, and so is the separate post-close write.
- --continue is the route's MoleculeStepper role: a real claim (the
  assignee is set) that skips a step another actor holds. Before, the
  direct and http routes flipped the status only and could take it.
  AdvanceToNextStep, ClaimStepIfOpen and its two implementations are
  gone.
- mol current / mol progress / ready --mol read through
  issueops.ViewMolecule, ReadMoleculeProgress, ActiveMoleculeIDs and
  LoadMolecule/AnalyzeMolecule over the route's roles. Over http this
  fixes the missing step assignee on `ready --mol` (corpus mark
  mc-ready-mol). The proxied route's SearchIssues fallback, the role
  store, the third progress count and the cmd/bd copy of the readiness
  analysis are deleted; only presentation stays here.
- create --parent asks the create role to mint the child id on every
  route (the local CLI reservation is gone) and to inherit the parent's
  labels (InheritLabelsFromParent) inside the create. The dry-run
  preview still shows the labels, and a failed label read there is
  reported, not swallowed.

TestProxiedServerMoleculeLifecycleAgreesOnEveryRoute runs one molecule
lifecycle through the real binary on the direct, proxied and remote
(`bd connect` to `bd serve`) routes and requires the same rows and the
same JSON on all three. The served e2e now also pins the held-step skip,
the claimed step's assignee and the full rows of `ready --mol`.

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

* fix(httpclient): refuse molecule auto-close and advance before dialing an older server

The client used to DEGRADE against a server without
issues.close.autoCloseMolecule / issues.advanceMolecule: it closed the step
without the member and ran a second, client-side copy of the auto-close
(issueops.CloseCompletedMolecule) in its own transactions, and composed the
stepper over its own roles. That kept two executions of each rule alive.
Now the rule runs in ONE place, the server's library: a close or batch close
that sets AutoCloseMolecule, and an Advance, refuse before anything is dialed
with the typed capability error (storage.ErrUnsupported, Capability naming the
token). The composed single-item batch leg now carries the member too.

- issueops.CloseCompletedMolecule (the role-composed form) is gone.
  MoleculeRootClose is the one root close request (unforced, the auto-close
  reason, the session, guarded on the root revision read), and both
  in-transaction bodies (storage issueops CloseCompletedMoleculeInTx, uow
  CloseCompletedMoleculeInUOW) build from it.
- MoleculeView.Ready is `bd ready --mol`'s list (every analysis-ready node,
  hydrated), so ready --mol and mol current derive from ViewMolecule alone.

Tests: unit pre-dial refusal and member pins (httpclient molecule_test.go),
TestServedMoleculeRefusesAgainstAnOlderServer (step stays open, nothing
claimed) replacing the degraded contract arm.

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

* fix(cmd/bd): ask for the molecule auto-close only where the route serves it

The refuse-before-dialing client made every `bd close` over http fail
against a server that does not advertise issues.close.autoCloseMolecule
(an older bd serve, or the MC server shape, whose orchestrator owns the
molecule lifecycle): the CLI always set AutoCloseMolecule.
storage.ServesMoleculeAutoClose answers, through every decorator, whether a
store's closes may carry the flag (MoleculeAutoCloseProber, implemented by
httpclient.Store from its handshake; every local backend serves it). The
direct batch close and the --if-revision close set the flag from it; the
proxied route always serves it. Against a silent server the close goes out
without the member and the server's side owns the auto-close.

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

* test(backend/http): scope the advertised-policy check to reads before the close

The close policy check is the client-side policy's last chance: it runs
before the close request, so only the reads up to that request count. A
read after the close (the old-server molecule notice reads the closed
step's edges) is not the external-dependency policy.

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

* test(backend/http/corpus): drop the six marks S16 and S19 retire

With the molecule library entries underneath, mol current (with and
without an id, json and text), mol progress and ready --mol read through
issueops.LoadMolecule over the roles, and create --parent lets the server
mint the child id. Those six shapes pass on the reference profile.

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

* fix(cmd/bd): never silent against a server without the molecule tokens

Against a server that advertises neither issues.close.autoCloseMolecule
nor issues.advanceMolecule (an older bd serve, or one whose orchestrator
owns the molecule lifecycle):

- `bd close --continue` closed the step and only then found the advance
  refused, leaving the step closed and the next step unclaimed. It now
  asks storage.ServesMoleculeAdvance (a MoleculeAdvanceProber the http
  store answers from its handshake; local backends always serve it)
  BEFORE the close and refuses up front, saying nothing was closed.
- `bd close` went out without auto_close_molecule and said nothing. When
  the closed step belongs to a molecule (issueops.MoleculeRoot), a notice
  on stderr now names the molecule and the missing token: its auto-close
  is the server's to run. The batch and --if-revision closes both say it.

The served e2e masks both tokens out of the handshake and checks the
up-front refusal (the step stays open) and the notice; the httpclient
unit test pins ServesMoleculeAdvance to the handshake.

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

* refactor(cmd/bd): mol show through issueops.LoadMolecule on every route

`bd mol show` still loaded the molecule through cmd/bd's
loadTemplateSubgraph (raw GetIssue, GetDependentsWithMetadata and
GetDependencyRecords, plus an id-pattern child probe), while mol current,
mol progress and ready --mol read through the library. It now loads
through issueops.LoadMolecule over the route's molecule roles (the direct
store's, or the proxied provider's), so membership is the parent-child
edge everywhere and the http route reads through roles the server serves.
The served e2e checks mol show's root and step count.

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

* docs: the molecule auto-close fails the step's close on a non-policy error; stale comments

CloseRequest.AutoCloseMolecule and CloseCompletedMoleculeInTx now say what
changed when the auto-close moved into the close's transaction: a root
close the close policy refuses still leaves the root open and is reported,
but any other failure (a storage error, a lost race on the root's revision)
fails the step's close with it, where the CLI used to close the root
afterwards and only warn.

Stale: the advanceMolecule vocabulary entry said the client composes the
stepper over its own roles when unserved (it refuses before dialing), and
the graph-create collision probe called itself best-effort by transport
(the http GetIssue miss is storage.ErrNotFound like every other store's).

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

* docs(changelog): the molecule tokens and the S16/S19 behaviours

Entries for issues.close.autoCloseMolecule and issues.advanceMolecule, the
issueops molecule entries, the auto-close inside the step's close (and a
non-policy failure of it failing the close), the real claim behind
close --continue, the molecule reads on every route, the notice and the
up-front --continue refusal against a server without the tokens, and
create --parent / mol reads over http.

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

* fix(httpclient): regenerate unsupported_gen.go for MoleculeStepper

The PR adds MoleculeStepper() to storage.DoltStorage (200 -> 201
methods). httpclient implements it by hand, but the generated shell's
trailer still counted 200, so
//internal/storage/unsupportedgen:unsupportedgen_test
(TestGeneratedShellIsFresh) failed in Bazel / test and
Bazel / integration, turning CI Gate / Required red.

Regenerated with `go generate ./internal/httpclient`; the only change
is the trailer count (143 of 201 methods generated; 58 left).

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

* fix(molecule): auto-close refusals, write skew, close --json, docs

Review fixes for #7513, numbered as in each iteration's review
synthesis.

Iteration 1:

F1: a close guard's refusal of the root (TemplateReadOnlyError,
PinnedError, CloseNotAssigneeError) is an auto-close refusal, like the
close policy's: the root stays open and is reported, and the step's
close stands. Pinned by the new conformance case
RunMoleculeGuardedRootKeepsTheStepClose on dolt, embedded, uow and the
served http client.

F2: two closes that finish a molecule's last two steps in concurrent
transactions each read the other's step as open, so neither closed the
root and both committed. Every auto-close now rewrites the root's
coordination cell before it decides the root (local_metadata
molecule-coordination/v1/<shard>, the dependency coordination idiom and
sharding with a FreshRowLock value), in both twins
(CloseCompletedMoleculesInTx and CloseCompletedMoleculesInUOW). Two
deciders of one root now conflict at commit (1213), and the retry reads
the winner's close and closes the root. This is the synthesis's option
(c), applied through a coordination cell instead of the root row; it
needs no post-commit second transaction and no engine lock. The
deterministic two-transaction regression fails without the touch and
passes with it on dolt and uow; the concurrent-close tests end with the
root closed in every round, reported by exactly one close.

F3: the auto-close checks the root's eligibility before walking any
step, MoleculeStepsClosed stops at the first open step, and a batch
decides each root once and reports it on the first item under it.

F4: ErrVersionMismatch on the root is not a refusal; it fails the
step's close with it. The classifier unit test pins this. A conformance
case cannot stage that race deterministically through the public roles.

F5: storage.ServesMoleculeAdvance answers (bool, error), and bd close
--continue refuses before closing anything when the handshake cannot be
read.

F6: the CHANGELOG and the stepper and batch-closer doc comments say
what the code does.

F7: the unserved-auto-close notice fires only when the close left an
auto-closing molecule with every step closed and its root open
(issueops.CompletedMolecule): again on a re-close, once per root in a
batch, never for a step under an ordinary epic or an unfinished
molecule. Proxied mol show, mol current and mol progress again report a
read unit of work that cannot be opened as itself, not as a molecule
that was not found.

F8: the write-ledger comment says the close is refused before dialing.
The dead FirstClosed/LastClosed guards in mol progress pre-exist on main
and are left as they are.

Iteration 2:

F1: on the proxied route, bd ready --mol reported a read unit
of work it could not open twice: once as itself, then as "molecule
'<id>' not found", which under --json is a second error document on
stdout. It now returns moleculeNotResolved, as mol show, mol current and
mol progress do. TestProxiedReadyMolReportsAnUnopenableReadOnce drives
runMoleculeReady with a provider whose NewUOW fails and wants one Error:
line, or one JSON document; both subtests fail with the old return.

F2: the coordination cell serializes every concurrent close of a step
under an open auto-closing root, not only the closes that finish the
molecule. That is the price of deciding the root in the step's
transaction, so it is documented (TouchMoleculeCoordinationInTx, the
UOW twin, CloseRequest.AutoCloseMolecule, the CHANGELOG) and pinned on
dolt and uow: two sibling closes with a third step still open conflict
(both commit when the touch is removed, on either twin), and a six-step
fan-out closes every step through the store's retry, with the root
closed and reported by exactly one close. The synthesis's alternative,
a post-commit recheck by any close that read a step open, is not taken:
it is a second, best-effort transaction after the step's commit, the
shape this PR exists to remove.

F3: MoleculeRootClose's doc no longer promises that a step reopened
between the completion read and the root close fails the step's close.
The guard is the root's RowVersion, which a step reopen never writes;
the doc now says what the guard covers and that this race goes
undetected (it is inherited from the CLI's old post-commit auto-close).

F4: the user docs describe the auto-close. docs/workflows/molecules.md
replaces "Closing the last child does not close the molecule root"
with which roots close and which stay open, the refusal warning, the
unserved-server note and the --json members, and documents the claiming
--continue and parent-child step membership;
docs/reference/json-schema.md gains a bd close --json section. These
are main-only behaviors on pages pinned to v1.2.2 (docs/cli-docs.pin):
a maintainer call against §1 of
engdocs/decisions/2026-07-17-docs-release-pin.md, as in #6508, #5855,
#5997 and #5092. The auto-close itself shipped in v1.2.2
(cmd/bd/close.go autoCloseCompletedMolecule), so the old sentence was
already wrong at the pin. docs/cli-reference/ is generated from the
pinned release and is not hand-edited; the bd close and bd mol show
help texts carry the same facts and reach it at the next pin bump.

F5: bd close --json reports the auto-close. The entry of a close that
completed a molecule gains auto_closed_molecule (the root it closed) or
molecule_auto_close_refusal (why the root stayed open), the HTTP API's
names, on the direct, proxied and --if-revision routes. The members sit
beside the issue's own rather than wrapping the output in an object the
way --suggest-next does: an object would change the output's shape
exactly when a close completes a molecule and break every consumer that
reads an array, while members leave each entry decoding as the closed
issue, compose with `closed` under the flag objects, and leave a plain
close's bytes unchanged. Pinned on the embedded and proxied tiers
(TestEmbeddedCloseJSONReportsMoleculeAutoClose, TestProxiedServerClose2B
json_reports_*, and both --if-revision replay tests), all red without
the change.

F6: cmd/bd's BeadsTemplateLabel is issueops.MoleculeTemplateLabel, so
the template commands and molecule membership cannot drift apart.

F7: the UOW twin's revision probe says that it writes nothing,
and the BatchCloseRequest.auto_close_molecule spec description has its
verb back (apigen regenerated, no drift).

Iteration 3:

F1: on the unit-of-work route (bd serve, the proxied CLI), a refused
root's molecule_auto_close_refusal and warning carried the use case's
and repository's wrapping ("close <id>: db:
IssueSQLRepository.CloseChecked <id>: ...") around the refusal, where
the tx twin and the docs give the refusal alone. Both twins now report
it through RefusedMoleculeAutoClose, which answers the refusing guard's
or policy's own sentence. RunMoleculeRefusedRootKeepsTheStepClose,
RunMoleculeGuardedRootKeepsTheStepClose and the embedded and proxied
close --json tests want that exact sentence; the uow conformance leg
and the proxied test fail without the unwrap.

F2: the docs no longer promise ErrVersionMismatch for a write to the
root that races its auto-close. The root's read and its revision check
share one transaction snapshot, so that write conflicts with the root
close at commit and the retry decides the root again; the close fails
only if it still conflicts when its retry budget runs out
(MoleculeRootClose, IsMoleculeAutoCloseRefusal,
CloseRequest.AutoCloseMolecule, the tx twin's comment, the CHANGELOG
and the OpenAPI description, apigen regenerated).

F3: TestEmbeddedCloseJSONReportsMoleculeAutoClose moves above
TestEmbeddedCloseConcurrent's doc comment, which documents its own test
again.

F4: bd mol progress counting direct steps while the auto-close counts
every descendant predates this PR; it is left for a follow-up.

F5: cmd/bd's molReader drops GetMoleculeProgress, which nothing called
once mol progress read through issueops.ReadMoleculeProgress.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 19:50:34 +00:00
Julian Knutsen
b630f96f5b
fix(httpclient): unlimited ready/query/list reads over http, client-capped (S15) (#7497)
* fix(httpclient): unlimited ready/query/list reads over http, client-capped

An unlimited read never puts limit=0 on the wire, which a non-loopback
bd serve refuses ("unlimited reads are loopback-only"):

- bd ready --limit 0 (the WorkFilter bridge) sent no limit at all, so the
  server's 100-row ready default silently capped every routed-pool queue.
- Reader.Ready and Querier.Query with Limit 0 sent limit=0 and got a 400
  from a non-loopback server.

listReadyWork and queryIssues publish no cursor, so an unlimited read is
one request bounded at the client cap plus one (one server read, so one
snapshot). listIssues keeps its cursor walk, now bounded by the same cap
(per-page reads; the snapshot semantics are documented in
unlimited_read.go). Past BEADS_HTTP_UNLIMITED_READ_CAP (default 10000) the
read is refused with *UnlimitedReadCapError, never truncated; a server that
reports has_more below the requested bound is refused the same way. A
dispatch tripwire refuses limit=0 on the three listing operations, so a new
path that forgets fails loudly instead of only off loopback.

Served tests run against a server in --allow-non-loopback mode with 150
rows: ready (role, bridge, bridge+total), query and list at limit 0 return
every row with a bounded limit on every request, and the cap refuses with
the typed error.

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

* test(backend/http/corpus): drop the three marks S15 retires

With unlimited reads served (one request bounded at the cap plus one for
ready and query), gc-ready-unlimited, gc-ready-pool-demand-unlimited and
gc-query-wisps-unlimited return every row on the reference profile instead
of the server's default page or the loopback-only refusal. mc-list-id stays
pending on S15b (--id).

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

* docs(changelog): unlimited reads over http and BEADS_HTTP_UNLIMITED_READ_CAP

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

* fix(httpclient): uncap the list walk and bound the ready-count fallback

Review fixes for #7497 (review loop iterations 1 and 2).

F1 (major): the client cap no longer applies to an unlimited list.
listIssues publishes a keyset cursor, so no response is larger than a
page; the walk is back to base, bounded only by --max-rows /
BEADS_MAX_ROWS as on every local backend. The cap stays on the
cursorless reads (ready, query), whose whole answer is one response the
server buffers. The CHANGELOG, unlimited_read.go and the env doc say so.

F2 (major): externaldeps.CountReadyWork's no-counter fallback, which an
http store reaches whenever its server does not apply the
external-dependency policy (every released server), asked for the whole
ready set to report one number: over http, up to the cap's full rows,
and a refusal past it that text `bd ready` swallows into a missing
footer. It now asks for a one-row Lite page; the bridge pairs it with
the server's countReadyWork, and refetchedReadyTotal still sizes the
externally blocked case.

F3: TestCheckUnlimitedPage pins a full cap+1 page that also reports
has_more as the cap's refusal, not a truncation, and the env test
accepts the inclusive 1000000 bound. Served: the cap test adds the
unlimitedRows-2 case (the server's 149 rows with has_more), the list is
pinned as uncapped with MaxRows its only bound, and the bridge's
MaxRows-vs-cap precedence is pinned with the limit on the wire.

F5: readyBridgePage sends MaxRows+1 rather than cap+1 when MaxRows is
the tighter bound (tightenUnlimitedPage). The MaxRows check still runs
first, so an answer past it keeps its *ErrTooManyRows attribution.

F6: the decorator and test comments describe the cap+1 bound; the
refusal reads "narrow the query or raise BEADS_HTTP_UNLIMITED_READ_CAP";
the Ready and Query Limit contracts name the http exception; mc-list-id's
pending reason drops the S15 --limit 0 clause and keeps the --id refusal.

F7: unlimited_read.go states that the tripwire guards Store.dispatch
only, so a direct wire.Client caller (readyClaimPage) must send a
positive limit itself.

Not taken: F4 (an unlimited walk that meets has_more with no cursor ends
as a success rather than a ServerTruncated refusal). After F1 the walk
is base code again, the shape needs a skewed or older peer, and the
change would land in fetchIssuePages (cyclomatic 21, cognitive 34),
turning an untouched base function into a changed one in the major
complexity band. Left as a follow-up.

Iteration 2, N1: F5 reached only the raw bridge. `bd ready` reads
through the external-dependency decorator, and against a server that
leaves that policy to the client, one externally blocked issue made
readyExclusion take MaxRows off the unlimited inner query. The bridge
then asked for cap+1 rows: past the cap it refused with the read cap's
error (exit 1, "raise BEADS_HTTP_UNLIMITED_READ_CAP") rather than
--max-rows' (exit 2), and under it fetched the whole ready set to refuse
on the rows kept. An unlimited inner query now keeps MaxRows plus one
row per blocked issue: past that many rows more than MaxRows are kept
whatever the drop takes, so the bridge sizes the request by it under the
cap, and innerCapError hands the refusal back as the caller's own cap.
The suggested inner Limit of MaxRows+blocked+1 was not taken: a bounded
request skips the cap and its server-truncation check, so with any
external blocker a --max-rows above the cap would fetch past it.
TestServedReadyBridgeMaxRowsSizesTheRequest pins the request and the
refusal through externaldeps.New with one blocker, the cap still in
force past MaxRows plus the blocked rows;
TestServedReadyMaxRowsCountsTheRowsKept adds an unlimited case whose
refusal names the caller's cap on all three decorator reads.

N4: QueryRequest.Limit's "NOTHING BACKSTOPS IT" names the http
exception in its lead, as ReadyRequest.Limit does.

Not taken in iteration 2, as non-gating follow-ups: N2
(refetchedReadyTotal's Limit = total+blocked read sits outside the cap;
pre-existing), N3 (the list walk's has_more-without-cursor end, the
deferred F4), N5 (prefixing the malformed-cap error with its operation;
it already names the variable and its value).

Validation: the served tier (BEADS_TEST_EMBEDDED_DOLT=1
BEADS_HTTP_TEST_REQUIRED=1) for internal/httpclient and the command
corpus; go test for externaldeps, issueops and workapi. Each new test
was mutation-checked red: the zero-limit count, the tightening removed,
the MaxRows check removed, the PR's list cap restored, and a cap+1
has_more page read as a truncation. Iteration 2: the served
internal/httpclient ready, unlimited-read and external-policy tests (34
PASS, 0 SKIP) and go test for externaldeps, issueops and workapi; the
new pins go red with MaxRows taken off again (the pre-fix code), with no
re-attribution, with no growth by the blocked rows, with the suggested
inner Limit, and with Found left unadjusted.

Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning 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-12 09:02:22 +00:00
Julian Knutsen
225ed7f7bb
test(backend/http/corpus): served MC command corpus against the reference server profile (S23) (#7483)
* test(backend/http/corpus): served command corpus against the reference server profile

Add the S23 suite: every distinct bd command shape gc and its packs and
formulas issue against a work store (124 shapes in testdata/corpus.yaml),
run by the real bd binary against an in-process bd serve and compared
with the same command on an embedded workspace.

The server is bound in non-loopback mode with bearer auth. A reference
proxy masks it to a deployed bd 1.3.0 server's wire surface
(testdata/reference_server.json): exactly that server's capabilities and
handshake members (no wire_revision), a 404 for operations it does not
publish, and a 400 unknown_parameter for query parameters and request
members it does not declare. Every bd run sets BEADS_ACTOR and
CLAUDE_SESSION_ID.

A shape passes when the served run exits like the embedded run, carries
no refusal, and matches its output (json/ids/count/text) and its verify
reads. Known gaps are marked `pending` with the slice that fixes them.
A pending shape still runs, and it fails once it passes, so removing the
mark is how a slice proves itself. Permanent refusals are listed in
testdata/allowlist.yaml with reasons.

A limited listing that cuts through a tie set (same priority, created_at in
one second) lands on different rows on two workspaces seeded seconds apart;
such a shape names its unlimited form in `prefix_of`, and each side's
limited rows must be an ordered prefix of that side's own unlimited listing.

//backend/http/corpus:corpus_test takes //cmd/bd:bd_for_tests (size large,
timeout long), so under bazel the suite runs instead of skipping on a
missing BEADS_TEST_BD_BINARY.

Stacked on S6b/c/d, whose marks this file no longer carries: besides the
S6b/S6c/S6d marks, seven list shapes once marked S6c+S15 (their --limit 0
list walks the keyset cursor without S15) and the S6c+S16 last-step close
(an ordinary epic root never auto-closes) already pass on it.

On S6b/c/d (bazel, BEADS_TEST_EMBEDDED_DOLT=1): 97 pass, 25 pending,
3 allowlisted.

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

* test(backend/http/corpus): hand the corpus server the LeaseReclaimer role

main gained the LeaseReclaimer role (issues.reclaim) after S23 was written,
and httpapi.Config needs it when built from roles rather than a Provider, so on the restacked
S6bcd TestServedCorpus could not bind its in-process server ("no database
source"). The harness now passes s.LeaseReclaimer() with the rest, as
backend/http's e2e harness does. The reference proxy still masks the
issues.reclaim token, so gc-reclaim stays pending.

On the restacked S6bcd (bazel, BEADS_TEST_EMBEDDED_DOLT=1): 97 pass,
25 pending, 3 allowed, unchanged from before the restack.

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

* test(backend/http/corpus): run the corpus in CI, hold allowlisted shapes

Review fixes for #7483 (review attempt 1): both majors, and four of the
seven minors and nits.

No CI lane ran TestServedCorpus. corpus_test sets neither
BEADS_TEST_EMBEDDED_DOLT nor BEADS_HTTP_TEST_REQUIRED, so the suite
skipped everywhere. corpus_served_test, an embedded-tagged sh_test over
go_test_variant.sh like http_served_test, runs it with both set and with
Bazel's prebuilt bd, and pr_risk_bazel_coverage_test pins its args and
env. Every other file in the package builds only under cgo, so a new
cgo-free test fails a BEADS_HTTP_TEST_REQUIRED=1 run that would otherwise
pass having run nothing. README.md and engdocs/TESTING.md say which lane
runs the suite.

The allowlist branch returned before the embedded exit check, so an
allowlisted shape was never held to what it says on the embedded
backend. The embedded run is now checked against the shape's expect_exit
and expect_stderr before the allowlist branch, and an embedded mismatch
fails as a corpus bug whatever the shape's pending mark or allowlist
entry. TestCorpusFileIsWellFormed requires an allowlisted shape to state
expect_exit and to carry nothing the allowlist would skip (compare: exit,
no verify). The three allowlisted shapes now pin their embedded refusals,
and the bd sql reasons say the command needs a sql-server workspace
instead of calling it local-only.

Minors and nits taken:
- two stale-guard shapes (--if-assignee nobody, --if-status open) expect
  exit 13 on both sides; each kills a client that drops that guard;
- defer_until and due_at are compared as given instead of scrubbed to
  <ts>, which kills a client that shifts --defer;
- gc-reclaim's pending mark names SRV-1 alone: the reference profile
  does not advertise issues.reclaim, so the client refuses at its
  capability preflight;
- refusalMarkers matches "does not advertise capability" unquoted, which
  also catches the JSON-escaped preflight error.

Declined:
- a failure on empty-vs-empty comparisons, which needs an allow_empty
  opt-in. Review attempt 2 seeded rows for two of the three ready shapes
  that compared two empty lists (below); gc-ready-graph-anchor still
  does;
- the context route's query check in the reference proxy: the server
  already answers an unknown query parameter there with a 400
  unknown_parameter, which the proxy passes through, so the served run
  still fails; only the proxy's own refusal note is missing;
- a shared server constructor for the two e2e harnesses, which the review
  marks optional.

Review attempt 2: four of its six minors and nits.
- gc-ready-ephemeral-assignee-unlimited and gc-ready-assigned-tier
  compared two empty lists, so a client that sent the wrong assignee or
  dropped --include-ephemeral passed both. Two seed rows assigned to the
  worker, an open task (P2) and an open wisp (P1), give them
  [e2e-wisp-wr e2e-wr] and [e2e-wisp-wr]. The priorities differ, so
  --limit=1 cuts no tie. A client that rewrites the assignee, or drops
  include_ephemeral, now fails both shapes; without the rows it passed
  them.
- templatePattern looped forever on a profile path with an unclosed "{",
  growing its pattern without bound. It now returns an error, which
  loadReferenceProfile reports with the operation and path, and
  TestCorpusFileIsWellFormed loads the profile, so corpus_test catches a
  bad edit without the embedded engine.
- TestCorpusFileIsWellFormed compiles every expect_stderr and every
  allowlist refusal, and runShape compiles expect_stderr once and fails
  the shape as a corpus bug instead of panicking on a bad pattern.
- README.md documents the stdin, setup, ordered and ignore_fields
  fields.

Not in this commit:
- the PR description (shape counts, allowlist reasons, gc-reclaim's
  SRV-1 mark, the Bazel run line) is brought up to date when this commit
  is pushed;
- hoisting runBD, minimalBDEnv, buildBD and the skip gate into
  internal/testutil, or cross-reference comments in their three copies,
  which the review marks optional and which reaches outside this
  package.

The full corpus gives 127 shapes: 99 pass, 25 pending, 3 allowed, with
no shape changing status from the attempt 1 fixup, on this tree and
merged with main at 0a163ca285.

Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning 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-11 05:34:51 +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
6c1848a77e
feat(backend/http): per-open credential is the only credential (S6f) (#7469)
* feat(backend/http): per-open credential is the only credential (S6f)

One process may open several beads HTTP projects, on one server or many,
each with its own credential (gc G7: per-city/per-rig credentials). The
ambient ladder is keyed by host[:port] and read from process-global env,
so two projects behind one host would share a token.

- bdhttp.Options gains Credential (CredentialProvider). Open, Handshake
  and Connect with it set go through the new httpclient.DialWithCredential
  / HandshakeWithCredential: no bearer ladder (BEADS_HTTP_TOKEN,
  BEADS_HTTP_TOKEN_COMMAND, credentials file), CA pinned to Target.CAFile
  (never BEADS_HTTP_CA_FILE), and the plaintext grant only from
  Target/DialOptions (never BEADS_HTTP_ALLOW_INSECURE).
- httpclient.OpenWith takes the same explicit path for a
  ProvidedCredential in backends.OpenOptions.
- Register panics on a non-nil Options.Credential: its dialer is
  process-wide.
- All package env reads go through one getenv seam so a test can prove
  the explicit door reads none. No process-wide credential cache exists;
  the provider lives on the store's own wire client.
- Package doc gains a "Credentials: one per open, never one per host"
  section.

Tests: two stores on one host (direct door and registry OpenWith) each
send their own token; explicit credential overrides poisoned ambient
token/command/credentials file; explicit open and handshake survive a
broken ambient env; Handshake with a Credential; getenv spy sees no reads
on the explicit door; Register refuses a credential.

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

* fix(httpclient): S6f review fixups for the explicit door's plaintext refusal

Apply the two minor findings and two nits from the review of #7469:

- The explicit-credential door (DialWithCredential: OpenWith with a
  ProvidedCredential, and backend/http's Open and Handshake with
  Options.Credential) never reads BEADS_HTTP_ALLOW_INSECURE, but its
  plaintext refusal still said to set it. That refusal now names
  Target.AllowInsecureCredential (what `bd connect --allow-plaintext`
  records) and says an explicit credential takes no plaintext grant from
  the environment. The ambient ladder's refusal is unchanged.
- Pin that property at each production door. Every explicit-door test
  dialed loopback, where the guard returns before it reads the variable,
  so a door reverted to the env-consulting DialWith left them all green.
  TestExplicitCredentialIgnoresTheEnvPlaintextGrant drives OpenWith, Open
  and Handshake against a plain-http, non-loopback stand-in with
  BEADS_HTTP_ALLOW_INSECURE=1: each refuses before the wire and names the
  grant it honors, each sends its token once with
  Target.AllowInsecureCredential, and an ambient control shows the same
  environment does grant the built-in ladder. Reverting any one door to
  DialWith now fails that door's subtest, and the guard unit test checks
  the refusal text.
- Narrow the "reads no environment" docs to what holds: getenv is the
  reader for the variables that choose or grant a credential, and the
  explicit door reads none of them. The proxy variables, and on !unix with
  a CA file BEADS_ALLOW_INSECURE_CA_FILE_PERMISSIONS, are still read on
  every door; neither chooses a credential or grants plaintext.
- TestExplicitCredentialReadsNoEnvironment checked GetMetadata's error,
  which is nil on a failed handshake; it now checks the project id.

Behaviour change against main: OpenWith with a ProvidedCredential to a
plain-http, non-loopback server is refused even with
BEADS_HTTP_ALLOW_INSECURE=1, which main honored there. Grant it per
target with Target.AllowInsecureCredential (`bd connect --allow-plaintext`
records it in the workspace sidecar).

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 15:16:14 +00:00
Julian Knutsen
8dbbe78e9a
feat(backend/http): public HTTP backend door, OSS registration, and bd connect (S6) (#7288)
* feat(backend/http): add the public HTTP backend door, cmd/bd registration, and bd connect

internal/httpclient (S1-S5) had no production caller for the per-open
backends.OpenOptions.Credential seam and no way for a workspace to actually
select it. This slice (S6) closes both gaps in OSS's own idiom, without
carrying over anything from bd-enterprise's gateway/box-login/storage-profile
machinery:

- backend/http (bdhttp) is the public, out-of-tree extension door: Register
  adds "http" to the backend registry and installs its transport, Open/
  Handshake dial a server directly with no workspace on disk, and the
  registered OpenWith hook threads a per-call credential through
  beads.OpenBestAvailableWith for a multi-tenant embedder.
- internal/httpclient/open_with.go is the backends.Backend.OpenWith hook
  itself: a fresh dial per open (opts.Credential/HTTPClient/UserAgent),
  distinct from the process-wide registered dialer Open/OpenReadOnly use.
- cmd/bd/http_backend.go registers the backend for the OSS binary, so a
  workspace whose metadata.json names "http" opens through the ordinary
  OpenBestAvailable path; any other unregistered backend name still refuses.
- cmd/bd/connect.go adds the minimal `bd connect <url>` command: a handshake
  that must succeed before anything is written, a per-user activation
  sidecar (.beads/http_target.json, never git-tracked), a plaintext-to-
  non-loopback refusal without --allow-plaintext, and a backend-switch
  refusal without --force. No credential is ever accepted on the command
  line or written to disk.
- cmd/bd/doctor/gitignore.go requires the new http_target.json /
  http_local_metadata.json sidecars be git-ignored, the same way the
  proxied-server client info already is.

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

* fix(storage): keep external-dependency blocking over http unless the server enforces it

bd ready / bd close / claim hard-failed against the new http backend with
"GetAllDependencyRecords not supported by the http backend": cmd/bd's
storage chain wraps every opened store in the externaldeps policy
decorator, which needs either the narrow ExternalDependencyQueryStore
interface or the broad GetAllDependencyRecords fallback to resolve
blocking state, and the http client implemented neither.

The decorator now stays on for a remote store. It is skipped only when the
server's handshake advertises policy.external_dependencies (the server
enforces the policy before answering). Without that capability the client
resolves blocking itself from the listing and chunked dependency reads, so
an issue with an unresolvable external: dependency stays out of bd ready
exactly as it does on a local backend; it is never silently skipped
(DESIGN 3.6). Server-side enforcement is slice S10.

storage.RemoteBackendStore marks a DoltStorage that is a pure network
client of a remote bd serve; the http backend's Store satisfies it.

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

* fix(cmd/bd): suppress the CreatedBy stamp on create against a remote backend

bd create failed against the http backend with "Issue.CreatedBy: ... is not
expressible on the v0 wire": the http client's create role deliberately
refuses any POPULATED CreatedBy/CreatedAt (the creation stamp belongs to the
server's own journal entry, not a value the caller supplies), but
cmd/bd/create.go unconditionally stamped getActorWithGit() onto every
created issue regardless of backend. The refusal only fires on a non-zero
field, so suppressing the stamp for a registered remote backend is wire-
compatible by construction, not a workaround.

Add isRemoteBackendWorkspace()/creationActorStamp() to backend_support.go,
reusing the existing resolveCommandBeadsDir(dbPath) +
backendNameForErrorFraming(beadsDir) + backends.IsRemote(name) pattern
already used elsewhere in that file, and use creationActorStamp() at both
create.go call sites (the dry-run preview and the real create).

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

* test(backend/http): add an embedder linkage test over public packages only

Prove the one promise S6 makes to an out-of-tree embedder (gc is the
motivating case): importing nothing but github.com/steveyegge/beads,
.../backend, and .../backend/http is enough to register the http backend,
open a workspace through it with a per-call credential
(beads.OpenBestAvailableWith), and read through the role-accessor surface
(IssueReader().Ready) against a stand-in server — with no internal/...
import in the test file, which is itself the thing under test.

Written fresh for OSS beads S6; no bd-enterprise source copied.

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

* docs: document the HTTP backend, bd connect, and the public backend/http door

Add a README section with bd connect usage, the credential ladder, and the
plaintext/force refusals, plus a CHANGELOG entry for the new cmd/bd
registration, bd connect command, and the public backend/http package.

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

* fix(httpclient): address bee-ghosttrack review on #7288 (connect --clear restore, persisted --allow-plaintext)

Closes the CHANGES_REQUESTED items on the HTTP backend door PR:

- Must-fix: `bd connect --force` over a workspace with its own local
  (dolt) identity now has writes succeed instead of tripping "workspace
  identity mismatch detected" — validateWorkspaceIdentity (cmd/bd/main.go)
  and the sidecar (internal/httpclient/metadata.go) now compare against
  the http backend's own pinned project id. New e2e regression test
  TestE2E_ForceConnectWritesSucceedDespiteDifferingLocalProjectID
  (backend/http/e2e_cli_test.go), confirmed to fail without the fix.

- Should-fix 1: `bd connect --clear` now restores metadata.json's
  backend selection to whatever it was before this workspace connected,
  instead of leaving it pinned to "http" with no sidecar to dial.
  Target.PreviousBackend (internal/httpclient/target.go) is recorded by
  Attach (backend/http/attach.go) and round-tripped through the sidecar;
  connect.go reads it back on --clear. New tests in
  backend/http/attach_test.go and internal/httpclient/target_test.go.

- Should-fix 2: `bd connect --allow-plaintext` is now remembered in the
  sidecar (Target.AllowInsecureCredential), scoped to the target it was
  granted for, so every later ordinary command's dial honors the grant
  without also needing BEADS_HTTP_ALLOW_INSECURE=1 set
  (internal/httpclient/dial.go). Fixed BearerProvider.warnInsecure's
  wording (internal/httpclient/credential.go), which used to assert a
  token was being sent immediately above a refusal saying the opposite.
  New test TestDialWithWiresTargetAllowInsecureCredentialThroughToTheGuard.

- Should-fix 3: README no longer claims HTTP mode works "exactly as
  with a local database" — it lists what round-trips and points at the
  divergence ledger (engdocs/design/http-divergence-ledger.md) for what
  differs.

- Verified, no code change needed: Attach already handles an existing
  metadata.json project_id coherently (only cfg.Backend is touched); bd
  show's isNotFoundErr already matches a http 404 (issueops.ErrNotFound
  is storage.ErrNotFound, the same sentinel a local miss uses), so it
  reads as "not found" rather than an unsupported-operation error.

- Doc fix: guardInsecureCredential's doc comment and refusal message
  were stale against should-fix 2's own change — they named only
  DialOptions.AllowInsecureCredential and the env var as ways to get
  past the guard, not the newly-persisted target.AllowInsecureCredential
  or `bd connect --allow-plaintext` itself.

Gates run clean on this branch: go build/vet, go test over
internal/httpclient, backend/http (including the full e2e suite under
BEADS_TEST_EMBEDDED_DOLT=1) and cmd/bd, make api-check, make
ci-pr-lint, make bazel-sync-check, bazel run //:gazelle -- -mode=diff,
and internal/storage's TestEveryLegWiresEveryRoleContract.

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

* test(backend/http): give the e2e server the BatchGetter role #7248 added to the required set

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

* fix: exact http ready totals, connect capability row, doc corrections

Ready totals over http (review major). externaldeps drops externally
blocked rows client-side for a store that cannot express ExcludeIDs
(today httpclient.Store). dropBlockedIssuesWithCounts compacted the
fetched rows in place (`kept := rows[:0]`), and
readyWorkWithCountsAndTotal then re-scanned `rows` to count the blocked
rows it had dropped. By then the compaction had overwritten them, so
whenever a blocked row came back ahead of a kept one the re-scan
undercounted the drops: `bd ready --json`'s total and text-mode `bd
ready`'s count (CountReadyWork) overstated ready work against any server
that does not advertise policy.external_dependencies. Both drop helpers
now copy into a fresh slice, and dropBlockedIssuesWithCounts reports how
many rows it dropped, so nothing re-scans `rows`.

fakeStore gains an excludeIDsUnsupported switch that, like
httpclient.Store, refuses any ExcludeIDs. The new
TestReadyTotalsWhenStoreCannotExpressExcludeIDs puts the blocked issue
first and checks the page and total for an unlimited filter, a Limit
whose bumped window holds the whole set, and one the set outgrows, then
CountReadyWork. TestServedReadyExcludesUnsatisfiedExternalDependencyWithoutServerCapability
now also checks the total and count against a real in-process bd serve.
Against the previous decorator the unit test's unlimited case reports
total and count 3 beside a 2-row page, and the served test 2 beside a
1-row page.

Review minors, all wording:
- `bd connect --clear` pointed at `bd config set backend dolt`, which
  writes the database's config table rather than metadata.json and, in
  the state that prints the advice (metadata.json says http, sidecar
  gone), fails the pre-open identity check. It now says to reconnect, or
  to set "backend" in metadata.json.
- CHANGELOG described the superseded skip-at-wrap design; it now
  describes the always-wrap decorator with its capability probe and
  client-side drop.
- RemoteBackendStore's docs no longer name a consumer; nothing in-tree
  checks it.
- creationActorStamp's comment pointed at backend/http/lifecycle.go; the
  refusal lives in internal/httpclient/lifecycle.go.

Capability row. TestProxyCapabilityRegistryCoversCommandTree fails at
60b7128204: the command tree walk finds `connect`, which this PR adds,
with no row in cmd/bd/capability_registry.go ("1 command(s) have no
proxied-server capability row: connect"). The test predates the PR
(#6582 is an ancestor of its base) and passes at the base dabf20ef07.

connect opts out of store init (skipStoreAnnotation) and never reaches
the store factory, so it belongs in proxyPermittedPaths beside init and
setup. The row is runtime-neutral: validateProxyRegistryBeforeProvider
returns nil both for a permitted row and for a path with no row, so
this only records the policy decision the coverage test asks for.

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

* docs(httpclient): regenerate the divergence ledger doc after the S5 rebase

The rebase onto feat/http-client-batch-apply's rebased head (S3/S4 merged to
main) left the ledger doc's summary line at a conflict-resolution placeholder
count. Regenerate it from internal/httpclient/encode.Ledger() so
TestDivergenceLedgerDocMatchesLedger passes against the merged ledger.go.

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

* fix(backend/http): host-scope S6's test BEADS_HTTP_TOKEN values

Rebasing onto feat/http-client-batch-apply's rebased head pulled in main's
#7247 review-fix round, which made BEADS_HTTP_TOKEN/BEADS_HTTP_TOKEN_COMMAND
host-scoped (host[:port]=value, scopedEnvValue/parseScopedEnv in
internal/httpclient/credential.go) after S6's own tests were written against
the unscoped form. Five S6 tests across backend/http/open_test.go,
backend/http/register_test.go and
internal/httpclient/insecure_credential_guard_test.go set a bare token and
now hit the new ladder's "an unscoped token would be used for whatever
server..." refusal. Scope each to the test server's actual host
(127.0.0.1 for the httptest.Server-backed recording servers,
nonLoopbackTestHost for the insecure-credential-guard integration tests)
so they exercise the same ladder rung as before.

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

* build(bazel): resync go_srcs/repo_files for the new backend/http and test/embedder packages

make bazel-sync-check failed after the rebase: tools/bazel/go_srcs.py's
managed repo_files filegroups for backend/http and test/embedder (new in
this slice) hadn't been generated, and the root BUILD.bazel / tools/bazel's
release_cross_build target list hadn't picked up the new package either.
Regenerate with `python3 tools/bazel/go_srcs.py`; `bazel run //:gazelle --
-mode=diff` reports no further drift.

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

* fix(cmd/bd): route swarm's create paths through creationActorStamp after main's currentActor change

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

* fix: police http's served roles, refuse close --claim-next, exact totals

External-dependency policy over http (review blocker). cmd/bd wraps
every store, http included, in the externaldeps decorator, and its role
accessors rebuilt each role over legacy methods httpclient.Store refuses
(SearchIssuesWithCounts, GetDependencyTree, ClaimReadyIssue, IsBlocked,
GetDependencyRecordsForIssues, BatchCloserWithPolicy). Over http `bd
list`, `bd dep tree`, `bd ready --claim` and a policed `bd close`
therefore exited 1, even in a workspace with no external dependency.
Over a store that reports storage.RemoteBackendStore, each accessor now
starts from the inner store's served role and layers the policy around
it (remote_roles.go):

- IssueReader serves List and Get from the served reader; Ready and a
  ready-flagged List go through the policy reader.
- IssueClaimer refuses an externally blocked claim before the served
  one.
- ReadyClaimer uses the served claim-next while no issue, closed ones
  included, holds an unsatisfied external ref. Otherwise it claims down
  the policy's filtered ready page through the served Claimer, because
  claimNext cannot exclude ids.
- BlockingAnnotator and TreeWalker merge external blockers into, or add
  external leaves to, the served answer. They read only the named
  issues' edges through the served EdgeReader, 100 anchors per call.
- BatchCloser refuses externally blocked open items and sends the rest
  to the served closer as one request. --force keeps the base path, and
  a next claim is refused whole (below).

RemoteBackendStore now only chooses this composition. Whether the policy
runs is still ServerEnforcesExternalDependencyPolicy's answer (design
3.6), and the storage and httpclient docs say so. remote_roles_test.go
drives each role over a store that refuses the legacy methods.
TestServedRolesKeepTheExternalDependencyPolicy runs every role over a
real http server. TestE2E_BDOverHTTP adds `bd list` (JSON, text and
--deps), `bd dep tree`, `bd ready`, `bd list --ready`, `bd ready
--claim`, a refused `bd close --claim-next`, and a refused then forced
close of an externally blocked issue. At the fixup before the
composition, the role tests then written (bar one pin of the next-claim
refusal, since replaced) and the e2e's list, dep tree, claim and close
steps of that round were red.

Close with a next claim over http (review major). batchCloseIssues has
no member for a next claim, so httpclient refuses any ClaimNext before
the dial (ledger W-CloseBatchRequest.ClaimNext). Over http `bd close
--claim-next` therefore always exited 1 and closed nothing. With an
external ref anywhere in the workspace (a closed holder or --force
included) the decorator's base path failed first, with an opaque
`BatchCloserWithPolicy` unsupported. remoteBatchCloser now refuses a
next claim whole, before it reads or closes anything, and the error
says nothing closed: close without --claim-next, then run `bd ready
--claim`. A request that is invalid on every backend is still
ErrValidation first, and a server that enforces the policy itself gets
the request unchanged.

Composing close-then-claim was not taken. The role closes and claims in
one transaction and answers with an error or with outcomes, never both,
so a claim that failed after the closes committed could not report
them; httpclient refuses the same request for that reason. A CLI-level
close then claim that can report a partial result is the follow-up.
The review also suggested leaving closed holders out of the blocking
state. They stay in, as on every backend: a closed issue is never a
claim candidate, so they change no claim, and leaving them out would
cost a status read per holder because the wire has no batch read.

TestRemoteBatchCloserRefusesANextClaim covers an open holder, a closed
one, none, --force, and a server that enforces the policy; with the
previous remote_roles.go the first four are red.
TestRemoteBatchCloserValidatesANextClaimFirst keeps ErrValidation ahead
of the refusal. Dropping the filter check, or loading the blocking
state before refusing, is each caught. TestE2E_BDOverHTTP runs `bd
close --claim-next` while the holder is open and again after it is
closed; with the previous remote_roles.go both steps are red and print
`operation "BatchCloserWithPolicy" not supported`. Ledger F-close no
longer says --claim-next is served, and no longer names a
renderEscapedHTTPRefusal that does not exist. L14 says the decorator's
claim leg applies while any issue, closed or not, holds an unsatisfied
ref. The README and CHANGELOG mention the refusal, and the decorator's
IsBlocked, IsBlockedBatch and CloseIssueChecked say they refuse over a
store that serves its roles.

Ready totals with external blockers (review majors, both rounds).
CountReadyWork asks for Limit=0, and readyWorkWithCountsAndTotal took
any Limit<=0 to mean "the window held the whole ready set". Over http a
zero limit never reaches the wire: the server answers with its default
page (workapi.DefaultReadyLimit, 100 rows) while the bridge reports the
full total, so past 100 ready issues text-mode `bd ready` kept counting
externally blocked issues beyond the first page. Exactness is now judged
from the rows that came back (total <= len(rows)). A window that holds
only part of the set no longer subtracts every externally blocked id in
the workspace either: that set includes closed issues and ones the
filter excludes, none of them in the total, so the count came out low.
It refetches the filtered ready set, ids only, and subtracts the blocked
rows in it; the old bound is left as the fallback for a refetch that
comes back truncated too.

fakeStore gains the bridge's shape: a defaultPage for a zero Limit,
with GetReadyWorkWithCountsAndTotal still totalling the whole set.
TestReadyTotalsWhenAnUnlimitedFetchComesBackAsOnePage (a blocked issue
past the first page) and
TestReadyTotalsIgnoreExternallyBlockedIssuesOutsideTheReadySet (a
blocked issue outside the ready set) have served counterparts,
TestServedReadyCountExcludesAnExternallyBlockedIssuePastTheDefaultPage
and TestServedReadyTotalIgnoresAnExternallyBlockedIssueOutsideTheFilter
(an assignee filter). The first pair is red on the Limit<=0
condition, the second on the subtract-every-blocked-id branch.

Docs: ledger L8 now says which decorator paths take the chunked
GetAllDependencyRecords scan and which read only named edges, and L14
records the decorator's composed claim leg; http-divergence-ledger.md
is regenerated. The README names the verified commands, and the README
and CHANGELOG say how cross-repo dependencies behave over http.

Minors from the reviews:

- Drop creationActorStamp/isRemoteBackendWorkspace and restore the base
  stamps at all 11 sites. The arm guarded a refusal the http create
  role does not make: since #7247 (actorStampedCreateMember) it accepts
  a CreatedBy naming the actor. Because the arm keyed on the CWD
  workspace, a create routed from an http workspace into a local one
  (--repo) stored an empty created_by. TestE2E_BDOverHTTP checks
  created_by for a direct and a routed create; the routed check is red
  with the arm restored. The CHANGELOG sentence describing the arm goes
  with it.
- bdhttp.Attach decides a reconnect from the raw metadata.json backend.
  GetBackend() reads an unregistered "http" as the dolt default, so in
  an embedder that never called Register a reconnect recorded dolt as
  the backend --clear restores. The reconnect test now seeds postgres
  (TestAttachOnAReconnectKeepsTheEarlierPreviousBackend) and is red
  with the old check.
- README, CHANGELOG and `bd connect --help` document the host-scoped
  BEADS_HTTP_TOKEN=host[:port]=<token> form (and _COMMAND), and say why
  a bare value is refused.
- bdhttp.Attach also gitignores http_local_metadata.json, the per-user
  file the store writes on first use, so an embedder activating through
  Attach alone gets the coverage `bd connect` already had.
  TestAttachGitignoresBothPerUserFiles pins it.
- ServerSnapshot.WireRevision's doc names the handshake's actual check
  instead of a comparison `bd connect` never makes.

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

* test(backend/http): give the e2e server the LeaseReclaimer role #7412 added to the required set

main's #7412 made LeaseReclaimer part of httpapi's required role set and
updated main's own binders, but backend/http's e2eServeConfig predates it,
so every TestE2E_* that binds the in-process server failed with
"httpapi: no database source". Same shape as e63f7da36a for BatchGetter.

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

* fix(externaldeps): lead the --claim-next refusal with the wire fact; pin the L14 leg and connect --clear

Review i4 minors/nits on the stranded fixup, carried as a separate commit:

- remoteBatchCloser's --claim-next refusal now says the served batch close
  cannot carry a next claim (the real cause), rather than blaming
  externally blocked work a workspace may not have. The test asserts the
  reason, that nothing closed, and the remedy.
- GetDependencyTree's doc says a served store refuses its reads and that
  bd dep tree goes through remoteTreeWalker.
- README no longer gives `bd ready --claim` local semantics everywhere; it
  names when ledger row L14's two-step claim applies.
- TestE2E_BDOverHTTP claims once more after the external-ref holder is
  closed, pinning L14's composed leg (a mutant whose composed leg claims
  nothing turns only that step red).
- New TestE2E_ConnectClearRestoresThePreviousBackend: --clear restores
  the prior dolt backend with its identity intact, removes the sidecar,
  and a second --clear changes nothing.

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

* test(backend/http): run the served e2e under bazel

//backend/http:http_test declared no bd binary, so under bazel the e2e
files (bazeltest.PrebuiltBD) failed on BEADS_TEST_BD_BINARY with
BEADS_HTTP_TEST_REQUIRED=1 and only "passed" by skipping otherwise. It now
takes //cmd/bd:bd_for_tests (visibility added), size large / timeout long:
the served cases run 4-5 minutes on the farm under BEADS_TEST_EMBEDDED_DOLT=1.

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

* test(backend/http): run the e2e tier in the embedded lane as http_served_test

The previous commit gives //backend/http:http_test the bd binary, but no
lane sets BEADS_TEST_EMBEDDED_DOLT for it, so its TestE2E_* cases still
skipped in CI. http_served_test runs the same test binary through
//tools/bazel:go_test_variant.sh with BEADS_TEST_EMBEDDED_DOLT=1 and
BEADS_HTTP_TEST_REQUIRED=1 (a skip fails it). It is tagged embedded, so
the --config=embedded lane runs it and prcore/ci keep their current
shape, the same split as //internal/httpclient:httpclient_served_test.
Under plain --config=embedded all 8 TestE2E_* cases run, none skipped.

TestBazelRetiredLanesCannotBeNarrowed pins every embedded-lane target's
args and env; the new target is added to that pin list.

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

* fix(externaldeps): cap the ready rows kept, not the bumped http window

An http store cannot carry ExcludeIDs on listReadyWork, so readyExclusion
fetches the unfiltered ready set, widened by len(blocked) under a limit,
and drops the externally blocked rows client-side. The http ready bridge
enforced MaxRows on the rows it fetched rather than the rows kept. So
`bd ready --limit N --max-rows N` exited 2 whenever more than N issues
were ready and any workspace issue held an unsatisfied external blocker
(a closed one counts), even with no blocked row in the window, and a
blocked row in the page counted against the cap although the caller
never sees it. Locally neither can happen: issueops enforces the cap on
the filtered page it delivers, after the Limit trim
(finishReadyWorkWithCounts).

The client-side path now takes MaxRows off the inner query and enforces
the caller's cap on the rows it keeps, after the trim, in all three
listings. The inner query keeps the cap whenever nothing is dropped
client-side. MaxRows never rode the wire, so the fetch is the size it
was; refetchedReadyTotal already clears the cap on its own over-fetch.

TestServedReadyMaxRowsCountsTheRowsKept runs the decorator over a served
http store holding three free issues and one externally blocked one: a
cap equal to the limit, a cap under a wider limit, an unlimited listing,
and a kept page wider than the cap, which must still return
ErrTooManyRows with the caller's cap and source. Each case runs through
GetReadyWork, GetReadyWorkWithCounts and GetReadyWorkWithCountsAndTotal.
Leaving the cap on the inner query fails the first three cases in all
three methods, dropping the re-applied cap fails the fourth, and
enforcing it before the Limit trim fails the first.

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

---------

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
Co-authored-by: Eddie the Engineer <adopt-pr@gascity.com>
2026-10-10 07:19:18 +00:00