Commit graph

70 commits

Author SHA1 Message Date
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
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
d90823480a
ci(bazel): split //scripts:scripts_test by what it reads; partition //:repo_files (#7414)
* ci(bazel): split //scripts:scripts_test by what it reads; partition //:repo_files

//scripts:scripts_test declared //:repo_files (the whole checkout), so every
PR re-ran it, and it took ~181s on rbe-west. Most of that (60-79s) was
TestBazelGatedLanesNeverRetryFlakyTests line-regexping the --run_under
wrapper's pinned dolt binary (tools/bazel/hermetic_bin/dolt, in every
test's runfiles); it now skips binary files, as git grep -I does.

tools/bazel/go_srcs.py's per-package repo_files block now partitions each
package's files into repo_go_srcs, repo_go_test_srcs, repo_doc_files and
repo_other_files, aggregated at the root; //:repo_files is their union
(same 4679 files). The //scripts tests are split into go_test targets by
what they read (traced per test with strace over a runfiles-shaped tree):

  scripts_test          CI/Bazel policy: //:repo_other_files (+1 Go file)
  shell_scripts_test    script fixtures: //scripts files, a few root files
  go_test_sources_test  _test.go scans: //:repo_go_test_srcs + shard files
  go_sources_test       check-testing-short.sh: every .go file
  tracked_files_test    every tracked file: //:repo_files

Shared helpers move to helpers-only files; TestScriptsTestTargetsPartition-
TheTests fails on a test file in no target or in two. //test/docsync and
the //scripts/repochecks slices declare partitions or single files instead
of //:repo_files where they can.

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

* ci(bazel): skip only the non-checkout hermetic_bin dir in the flaky-retry walk

Skipping every binary file also stopped scanning tracked binaries (images,
.binpb fixtures). Skip just tools/bazel/hermetic_bin, the --run_under
wrapper's runfiles directory, which is not in the checkout, so the walk's
coverage of tracked files is unchanged.

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

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-09 05:13:07 +00:00
Bee
c3a97e172d
show/list: render a derived GATED decoration when an open gate holds the bead (#6606)
* wy-j2upyy: render the derived GATED decoration on bd show and bd list

A bead an open gate blocks is excluded from `bd ready` but rendered
`[P2 · OPEN]` by `bd show` and with a plain ○ by `bd list`, so the human
surfaces disagreed with the readiness query.

The decoration is DERIVED, never stored: no status write, no --status
filter change, no existing JSON field reshaped.

- internal/types/gated.go: IsActiveGate, the ONE predicate — a gate-typed
  dependency reached over a blocking edge (blocks / conditional-blocks /
  waits-for) whose status is neither closed nor pinned. That is the
  is_blocked recompute's blocking leg restricted to gates, so a rendered
  GATED and a `bd ready` exclusion cannot disagree. GateDescription /
  GateReason own the reason's round trip with `bd gate create`.
- bd show: `[P2 · OPEN · GATED]` plus one `Gated by: <id> (<type>[:
  <reason>][, awaiting <await-id>])` line per gate, beside Deferred:. The
  dependency read the DEPENDS ON section already made is hoisted, so the
  decoration costs no extra query.
- bd list: ⊘ in the glyph column (circle family, distinct from ○ and ❄),
  and a legend entry when the page carries one. Batched by id set —
  at most two extra queries per listing, one in the tree view where the
  edge map is already loaded.
- --json: additive `gated_by: [{id,type,reason}]` on the detail view,
  omitted when empty; documented in the OpenAPI IssueDetails schema.

Tests (red first): cmd/bd/gated_render_embedded_test.go drives real
bd show/list/--json over an embedded rig — gated, resolved, deferred+gated,
JSON additivity — plus pure unit tests for the predicate and formatters.

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

* wy-j2upyy: document the additive gated_by field in the JSON schema reference

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

* wy-j2upyy: cover the flat list route's own batched gate read

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

* wy-j2upyy: make GATED the readiness rule's gate clause, both halves

The adversarial review found the "one predicate shared with bd ready" claim
false on two axes, and both were reproducible by hand:

BLOCKER 1 — waits-for is not the status rule. The is_blocked recompute applies
"target not closed and not pinned" only to its blocks / conditional-blocks
legs; the waits-for leg goes through waitsForGateBlockedSQL, a fanout over the
target's open parent-child children (or an also_blocks spawner). A plain
`bd dep add X G -t waits-for` onto an open childless gate therefore leaves X
in `bd ready` while every new surface called it GATED. Mirroring that leg in
Go would be a second implementation of a rule the database owns, so the edge
clause now names the two legs it really mirrors (types.IsGateEdge) and the
test that pinned the wrong direction is flipped.

BLOCKER 2 — the subject half was missing and spelled three different ways.
unmarkAllBlockedSQL forces is_blocked=0 for a closed or pinned subject
whatever its edges say, so `bd ready` never withholds one on a gate's account;
show and workapi filtered nothing, cmd/bd/gated.go filtered closed only, and
list_format.go filtered closed at two more sites. A force-closed bead rendered
[CLOSED · GATED] with gated_by on show while list showed a plain row — show
and list disagreeing about one bead, which is the drift this was meant to
prevent. The clause is now types.SubjectCanBeGated, asked once in
types.GatesHolding (which replaces ActiveGates and takes the subject) and once
in the listing helper that has no hydrated deps; the formatters re-ask the SAME
exported predicate rather than inventing a fourth spelling.

SHOULD 3 — agent mode computed the gate reads and threw them away, in every
CLAUDE_CODE seat, i.e. the population that filed the bug. Decorating it is the
real fix, so gatesByIssueID now returns the gate IDS and formatAgentIssue
carries "gated by: <id>" in the parenthetical it already prints. A gate is
also a blocker, so its id appears under both "blocked by" and "gated by": the
first says what to wait on, the second says which of those nobody can clear by
doing more work. --long and --format render no gate and no longer pay for the
reads.

NOTE 5 — a pinned+gated row kept ⊘ instead of 📌; with the subject clause a
pinned bead is not gated at all, so the pin survives by construction.
NOTE 6 — the cost comments claimed "two queries" / "exactly ONE"; the id-set
readers are a few round trips each. The bound that is real (per page, never
per row) is what the comments now say.

Tests, red-first: the flipped waits-for case; TestGatesHoldingSubjectStatus and
TestSubjectCanBeGated (open/in_progress/deferred yes, closed/pinned/nil no);
TestFormatIssueCompactGated and TestFormatAgentIssueGated; and four embedded
arms — a waits-for edge that bd ready lists and no surface decorates, a
force-closed subject and a pinned subject that render nothing and publish no
gated_by, and the agent line naming its gate. Each was watched to fail against
the pre-fix predicate before it passed.

Ran: go test ./internal/types/ -run 'TestGateIsHolding|TestGatesHolding|
TestSubjectCanBeGated|TestGateDescriptionRoundTrip|TestGateRefsProjection';
go test ./cmd/bd/ -run 'TestFormat*Gated|TestFormatIssueCompact*|
TestFormatDependencyInfoWithParent|TestListRoles*|TestDisplayPrettyList*';
BEADS_TEST_EMBEDDED_DOLT=1 go test ./cmd/bd/ -run TestEmbeddedGatedRendering
(11/11 subtests); gofmt -l (empty), go vet and golangci-lint on cmd/bd,
internal/types, internal/ui, internal/workapi; scripts/ci/pr-policy.sh.

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

* wy-j2upyy: render GATED on the proxied `bd show` text route

SHOULD 4 of the review, and required for this rig: the constellation runs
proxied-server, where `bd show --json` already carried gated_by (uow
issue_reader -> workapi.BuildIssueDetails) while the TEXT renderer called the
plain formatters. The same bead read two ways from the same server disagreed.

proxiedRenderIssue now hoists the outgoing-edge read it already did for the
DEPENDS ON section above the header — the gates are the gate-typed subset of
that very set, so the decoration costs no extra query — and passes them to
formatIssueHeaderWithGates / formatIssueMetadataWithGates. The proxied LIST
routes were wired in the previous commit.

TestProxiedServerGatedRendering covers all five text surfaces plus the JSON
one beside them (header + Gated by line, pretty glyph, compact glyph + "gated
by", agent line, and a closed subject that renders nothing). Watched red first
with the proxied decoration stubbed out: four of six subtests failed, and the
--json arm passed, which is exactly the asymmetry the review reported.

Ran: BEADS_TEST_PROXIED_SERVER=1 go test ./cmd/bd/
-run TestProxiedServerGatedRendering -count=1 (6/6, 37.8s).

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

* wy-j2upyy: put cmd/bd/state.go on the shared "Reason:" marker

NOTE 7 of the review: types' gateReasonMarker was not gate-private —
cmd/bd/state.go wrote the same "\n\nReason: " into state-change EVENT
descriptions from its own literal. No live collision (events are not
gate-typed), but the constant's doc claimed GateReason returns "" for every
gate not made by `bd gate create`, and that is false for any description
carrying the marker.

The previous commit exported the constant as types.ReasonMarker, reworded
GateReason to say what the pair really guarantees (a round trip, not a
provenance check) and pinned the honest behavior in
TestGateDescriptionRoundTrip. This commit is the second writer: state.go now
builds its event description from the same constant, so the two cannot drift
apart by accident.

Ran: go build ./...; go test ./internal/types/ -run TestGateDescriptionRoundTrip
-count=1; gofmt -l cmd/bd/state.go (empty); go vet ./cmd/bd/.

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

* wy-j2upyy: alias types.GateRef in package backend

gated_by on IssueDetails makes GateRef reachable from the public backend
contract; TestPublicSurfaceComplete requires every such type to carry an
alias here.

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

* wy-j2upyy: build(bazel): register gated.go and its tests in cmd/bd and internal/types

The rebase onto e766da5ed carried the new source files but not their
BUILD.bazel entries, so every Bazel lane failed to compile internal/types
(undefined: GateRef). This is CI's own bazel-sync patch for 9ad7eb96c3,
applied unchanged.

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

* wy-j2upyy: compute gated_by AFTER the dependencies read in BuildIssueDetails

The be-lpi merge (#6352) moved src.Dependencies() below the cardinality
counts so the unresolvable-edge delta reads count-first. That hunk merged
cleanly, which left details.GatedBy computed on the still-nil slice, and
both CI shards' show_json…carries_gated_by subtests went red (PR Risk
Embedded Dolt Cmd 20/20, Proxied Dolt Cmd 4/15 at d21237f3dc).

Move the GatedBy line to directly after details.Dependencies = deps, still
before the BriefDeps trim that rewrites the slice, and pin the ordering with
a workapi unit test over both DetailSource seams and BriefDeps on/off (red
on the pre-fix code, green after).

Ran: go test ./internal/workapi; go vet ./internal/workapi;
BEADS_TEST_EMBEDDED_DOLT=1 go test ./cmd/bd -run TestEmbeddedGatedRendering;
BEADS_TEST_PROXIED_SERVER=1 go test ./cmd/bd -run TestProxiedServerGatedRendering.

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

* ci: register #6606's gated-rendering tests and gated_by wire shape with main's generated gates

Maintainer fixup for adopt-pr #6606. The adopted head merges the PR head
(c43eb567d2) into main (800d43eb8d). The PR's merge-base (02f05340f6)
predates three generated artifacts on main that every PR adding a cmd/bd
tier test or a wire member has to keep current, so the merged tree is red
on them even though the PR's own CI cannot see them:

- .github/scripts/embedded-cmd-test-shards.txt: the Bazel-only 50-shard
  block must name every TestEmbedded* test exactly once, or
  TestCmdEmbeddedShardManifestGeneratorNotStale fails `go test ./scripts/`.
  `gen_embedded_cmd_shard_manifest.py 50 --weights=duration --write`
  (incremental) placed TestEmbeddedGatedRendering on shard 16 and moved
  no existing assignment; the frozen 20-shard block is untouched.
- .github/scripts/proxied-cmd-test-shards.txt: likewise for the 30-shard
  block and TestProxiedServerGatedRendering (shard 2), via
  `gen_proxied_shard_manifest.py 30 --weights=duration --write`, so
  TestProxiedShardManifestGeneratorNotStale passes.
- internal/httpapi/wireshape/testdata/golden.json: TestWireShapeDigest
  (#7182) pins every response member. `go run
  ./internal/httpapi/wireshape/cmd/gendigest` recorded the PR's new
  IssueDetails.gated_by array and its id/type/reason members as four pure
  additions (+25/-0), so no wire_revision bump is owed.

The PR's own files are unchanged.

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

* docs(gated): state gated_by one way, mark --watch as undecorated, fix stale refs

Review follow-ups for #6606. Comment and doc text only; no behavior change.

- gated_by is now documented in one direction. internal/types/types.go,
  internal/types/gated.go and docs/reference/json-schema.md said the list
  is nonempty EXACTLY when `bd ready` withholds the issue on a gate's
  account. Only one direction holds: the is_blocked recompute also blocks
  a child whose parent is blocked (its parent-child legs), so a child of a
  gated parent leaves `bd ready` with an empty gated_by. All three now say
  "nonempty means withheld", as the OpenAPI text already did, and name the
  parent-child case.
- bd list --watch passes a nil gated map on both routes
  (runListProxiedWatch, displayWatchedIssueList), so a bead the one-shot
  listing marks with the gated glyph keeps its plain status glyph while
  watched. Watch is out of this PR's scope; the three call sites now say
  so instead of reading as a forgotten argument.
- show_format.go named types.ActiveGates, which does not exist; the
  predicate is types.GatesHolding.
- gated.go's best-effort note compared the gate read with `bd list`'s
  blocking annotation, which only the direct route swallows. It now scopes
  that comparison to the direct route and names the proxied route's
  failing read (A-blk-1).
- proxiedGatedIssueIDsOwnUOW now notes that its unit of work is a second
  snapshot, so one render can name a just-resolved gate under "blocked by:"
  but not "gated by:".

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

* fix(list): hydrate proxied gate candidates from both planes (bd-p8k7dm)

The proxied list resolved gate candidates through the use case's
GetIssuesByIDs, which reads the issues table only, while the edges it
resolved came from GetForIssueIDs, which reads both dependency tables.
A wisp gate (`bd mol wisp` clones a formula's gates as wisps, held to a
wisp step by a blocks edge) therefore hydrated to nothing. Its step
listed undecorated in pretty, --flat and agent output while `bd show`,
`--json` and `bd ready` called it gated.

Read the wisps beside the issues, the two-plane idiom
ready_proxied_server.go and uowMolReader already use. A failed wisps
read keeps the durable candidates. Correct the cost-bound comment that
claimed the id-set readers partition the planes on both routes.

Tests: a wisp-step + wisp-gate case in TestProxiedServerGatedRendering
and TestEmbeddedGatedRendering asserts the pretty, --flat and
CLAUDE_CODE=1 rows of `bd list --include-ephemeral`, and
TestProxiedGatedIssueIDsHydratesBothPlanes pins both planes plus the
failed-wisps-read fallback.

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

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-authored-by: Eddie the Engineer <adopt-pr@gascity.com>
2026-10-08 10:37:51 +00:00
Julian Knutsen
b1fe68e63a
ci(bazel): run pr.yml's repository guards as Bazel tests (#7329)
fast-checks, PR Policy, and the Linux leg of check-doc-freshness-platforms
ran repository guards on GitHub runners. They now run as Bazel tests in
bazel.yml's `test` lane (remote, cached), each over only the files it reads:

- tools/bazel/repo_subset.bzl picks a narrow, path-selected slice of
  //:repo_files at analysis time. scripts/repochecks/run_check.sh copies that
  slice into a throwaway git checkout and runs the unchanged guard there.
- //scripts/repochecks: build_tags, workflow_tags, go_install_guidance,
  winget_portable_alias, migration_hygiene (checks A and B),
  fmt (registered SDK gofmt), doc_freshness, workapi_frontend_boundary,
  types_gen_drift (`make api-check` drift, oapi-codegen from go.mod).
- //scripts:doc_freshness_required_test (integration lane, -required-suite)
  and //scripts/gitattributespolicy:gitattributespolicy_required_host_test
  cover the Linux doc-freshness leg.
- check-versions stays covered by //internal/versioncheck:versioncheck_test.
  check-testing-short stays covered by //scripts:scripts_test.

pr-policy-wrapper is deleted. fast-checks keeps only the two checks that
need the PR base: migration hygiene's delta half (MIGRATION_HYGIENE_SCOPE=
delta) and the .beads diff. check-doc-flags stays, because it builds bd from
the pinned release tag. The example Go modules leave .bazelignore so gofmt
and the grep guards see them. check_testcases.py now accepts --not-go
//pkg:all.

Refs: ga-96smfk.20

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-07 00:59:18 +00:00
Julian Knutsen
0500fc6f40
ci(bazel): run the scripts and source-walking tests remotely; retire their go test legs (#7320)
//scripts:scripts_test and //scripts/check-versions:check-versions_test
drop their host-tools/no-remote-exec/no-remote-cache tags and run on the
rbe-west workers like every other target (the worker image ships bash, git,
python3, jq, yq, curl, openssl, unzip and coreutils; a missing tool fails the
test under Bazel rather than skipping it). Go comes in hermetically as the
registered SDK; check-versions.sh's `go build` is stood in for by the
Bazel-built checker.

The tests that walked the source checkout now get it as data:
tools/bazel/go_srcs.py keeps a managed `repo_files` filegroup in every
package and aggregates them into //:repo_files (exactly the tracked files
Bazel can see; make bazel-sync-check fails on a package without one).
scripts_test and docsync_test take it instead of hand-listed filegroups,
and every TEST_SRCDIR/IsBazel skip and go-test-only block in them is gone.
The release formula under .bazelignore'd .beads/ comes in through a
@beads_formulas local repository; npm-package/ and .claude/ are visible to
Bazel again (only their node_modules/worktrees stay ignored), so the npm
manifest release check and the AGENTS.md skill links run under Bazel too.
TestZZStdioNotLeaked falls back to TestMain's pre-run streams instead of
skipping in a shard without its baseline.

tools/bazel/equivalence_allowlist.txt shrinks from 20 skip entries to the
two cmd/bd tests of plain go test's own bd build fallback, which Bazel never
takes; pr-preflight-platforms now runs them on Linux, macOS and Windows. The
scripts-go-checks scripts-test and allowlisted legs, their scripts
(scripts-go-test.sh, allowlisted-go-tests.sh, run_allowlisted_go_tests.py)
and main.yml's --compile-only warm for them are removed. The vet leg stays
(ga-96smfk.18).

Refs: ga-96smfk.16

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-06 22:20:16 +00:00
Julian Knutsen
4af58c97fd
feat(count): Counter scope — ParentID, NoParent, ExcludeTypes, ExcludeStatus (issues.count.scope) (#7199)
* feat(httpapi): wire-shape signal — wire_revision, floor header, golden digest, param tokens

S0 of the HTTP role-parity program: give a client a single place to learn
whether this build's wire shape has moved under it, and give CI a gate that
catches an undocumented move.

- GET /v0/beads/context reports wire_revision (bumps only on a non-additive
  response-shape change) and min_client_wire_revision. An optional
  Bd-Wire-Revision request header lets a client declare the revision it was
  built for; checkWireRevision refuses a declared revision below the floor
  with 400 invalid_argument/reason=wire_revision_unsupported and a
  min_wire_revision field, on every route but /healthz (wireRevisionExempt) —
  including the identity handshake, where catching the mismatch is cheapest.
  Absent header is today's behavior; malformed value is invalid_value, never
  wire_revision_unsupported. The floor lives in Server.minClientWireRevision
  (defaulting to the MinClientWireRevision constant) so a test can raise it.
- internal/httpapi/wireshape: a golden digest over every response's every
  content-type schema (including application/problem+json) across the whole
  spec, keyed by schema+member. TestWireShapeDigest fails closed when a
  member's JSON name or type changes without wire_revision bumping to match;
  regenerate with `go run ./internal/httpapi/wireshape/cmd/gendigest`.
- GET /v0/beads/issues' `sort` parameter now carries the issues.listSort
  capability token, the same convention `capabilities` entries use.
  TestNewParameterOnExistingOperationHasABehaviorToken requires every new
  parameter on an existing operation to carry one, checked against a
  write-once grandfather baseline (testdata/pretoken_parameters.json) of
  parameters that predate the rule; TestUntokenedParameterRuleFires proves
  the checker itself against a synthetic fixture.
- Docs: engdocs/design/bd-serve-v0.md gets a "The wire-shape signal" section;
  CHANGELOG.md gets an Added entry.

Live-mutated and reverted three RED demonstrations during development:
retyping api_version in the spec failed TestWireShapeDigest; short-circuiting
checkWireRevision's floor comparison failed
TestWireRevisionBelowFloorRefusesEveryEnforcedRoute; adding an untokened
query parameter to listIssues failed
TestNewParameterOnExistingOperationHasABehaviorToken. All three now pass
against the unmutated tree.

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

* fix(httpapi): rename issues.listSort to issues.list.sort, harden token rule

Opus review of 12c5144ca (HIGH-1, MEDIUM-5):

- Rename the capability token issues.listSort -> issues.list.sort to match
  bd-enterprise's client (httpstore/wire/handshake.go:121, DESIGN.txt S4e),
  and widen capabilityToken to accept an optional third segment.
- untokenedParameters() now requires the extracted token to be one
  Capabilities() actually serves, not just backtick-shaped text. This
  catches real false positives that existed in the spec already
  (workapi.DefaultReadyLimit, status.custom) which only shape-matched the
  old regex; they're added to the pretoken baseline as genuinely
  pre-existing untokened parameters.
- Extend the rule to request body members (new
  testdata/pretoken_request_body_members.json baseline) and exempt
  brand-new operations via a frozen testdata/pretoken_operations.json
  snapshot.
- Add TestPretokenBaselinesNeverGrow pinning all three baseline sizes so
  a future change can't hand-add an exemption instead of a token.
- Update spec prose for the widened rule scope.

go test ./internal/httpapi/... and the reviewer's pmut.py all pass as
expected: plain/bogus modes go RED, reuse (real-but-unrelated token) stays
green, matching the review's literal ask ("a token must be one advertised
by Capabilities()").

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

* fix(wireshape): close four digest-coverage gaps, add gendigest write guard

Opus review of 12c5144ca (HIGH-2, MEDIUM-4). The digest only tracked
Type/Format/Enum/Required on direct properties, missing:

- nullable: true (never read at all)
- array item shape (Issue.labels items string->integer was invisible;
  only object-shaped items got recursed into)
- additionalProperties value shape (IssueCount.groups)
- request bodies entirely (Compute() only walked responses, so
  DeleteIssuesRequest.expected_version string->integer, the other half
  of #6053, was invisible)

Also added defensive oneOf flattening alongside the existing allOf merge
(dormant today -- grep confirms this spec uses oneOf nowhere -- but no
longer silently invisible if that changes).

Extracted the golden-vs-computed comparison into wireshape.Compare(),
shared by TestWireShapeDigest and the new wireshape.SafeToWrite(), which
gendigest now calls before writing: it refuses to overwrite golden.json
with changed/removed entries unless the candidate's wire_revision is
strictly greater than the existing golden's. Pure additions always write.
TestSafeToWrite exercises both guard directions.

golden.json is regenerated. This single regen is a one-time exception to
the new guard, done by writing the digest directly rather than through
gendigest: confirmed via a throwaway diff (not checked in) that every one
of the 57 "changed" entries differs only in the NEW fields the wider walk
now populates (ItemType/ItemFormat/Nullable/AdditionalProps*) -- every
pre-existing Type/Format/Required/Enum value is byte-identical. Nothing on
the wire changed; the measurement got more precise. Bumping
CurrentWireRevision for this would have written a false "the protocol
changed here" entry into the revision history table. Going forward, any
REAL change the guard now reports uses the normal bump-then-regenerate
path, same as before.

Verified against the reviewer's mut.py: nested_type, nullable,
nullable_issue, array_items, addlprops, request_body and format all go RED
on TestWireShapeDigest, each reverted after confirming.

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

* fix(httpapi): make bd_version wire_revision inference advisory

Opus review of 12c5144ca (HIGH-3). The spec told a client inferring
wire_revision from bd_version to use the release cutoff >= 1.3.0, and said
nothing about what happens when that inference is wrong -- which it
demonstrably is for real builds already in the field:

- main builds up to commit b3ef65c85 report bd_version 1.2.2 (below any
  1.3.0 cutoff) while already sending the string-typed revision/
  expected_version shape (#6053).
- 1.3.0-rc.N pre-release builds sort BELOW the release cutoff 1.3.0 under
  plain string comparison despite already carrying the string shape.
- The bd-enterprise compatibility line at d3ab32773462 reports bd_version
  1.1.0 while also sending strings.

Moved the cutoff to >= 1.3.0-rc.1 (compared as semver-with-prerelease,
which at least captures the rc builds), documented both named exceptions
inline, and made the whole inference explicitly ADVISORY: a client must
accept revision/expected_version as either a string or a number whenever
wire_revision is absent (or probe directly) rather than let the inferred
value choose a decoder, and must never refuse solely because the inferred
revision is 0. Mirrored into engdocs/design/bd-serve-v0.md.

This is spec/doc prose only -- there is no server-side inference code to
change, since this server always sends wire_revision directly; the
inference is guidance for clients reading a pre-signal server's response
(this server, past builds, or an unrelated implementation).

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

* fix(httpapi): LOW-7/8/9/10 review follow-ups for wire-revision signal

LOW-7: WireRevisionUnsupported now also sets Problem.wire_revision (this
server's CurrentWireRevision) and Problem.bd_version on the
wire_revision_unsupported refusal, alongside the existing
min_wire_revision, so a client logging the refusal has this server's
full self-description without a second /v0/beads/context call.

LOW-8: gazelle + make bazel-sync add the BUILD.bazel entries the prior
commits were missing: wire_revision.go/wire_revision_test.go in
internal/httpapi's srcs, new BUILD.bazel files for wireshape and
wireshape/cmd/gendigest, and a testdata glob on httpapi's go_test so
the pretoken_*.json baselines are visible under `bazel test`. Verified
with `bazel build //internal/httpapi/...` and
`bazel test //internal/httpapi/... --test_env=BEADS_TEST_SKIP=dolt`
(both green) and `python3 tools/bazel/go_srcs.py --check` (clean).

LOW-9: narrowed CHANGELOG.md and engdocs/design/bd-serve-v0.md to
describe the digest's actual final coverage (format/enum/required/
nullable, array items, additionalProperties, request bodies, $ref/
allOf/oneOf recursion, the SafeToWrite revision-bump guard) and the
token rule's actual final shape (three pinned baselines, request-body
members, Capabilities()-membership validation, new-operation
exemption) instead of the original, narrower claims.

LOW-10: Bd-Wire-Revision now parses via a strict decimal-only
parseStrictNonNegativeInt (no leading '+', no leading zero except a
bare "0") instead of strconv.Atoi alone, so two different header
bytes can no longer name the same revision. New malformed-header test
cases: "+1", "01", "007".

Regenerated apigen/types.gen.go (make api-gen) for the new Problem
fields and wireshape/testdata/golden.json (go run
.../wireshape/cmd/gendigest) for the two new additive Problem members;
the latter wrote cleanly through SafeToWrite itself, since both are
pure additions.

go test ./... and bazel test //internal/httpapi/... both green.

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

* fix(httpapi): re-review LOW follow-ups — retirement test, gendigest -init, docs

1. TestRetiredRevisionsStayBelowTheFloor pins the PRESENCE guarantee the
   wire_revision property doc relies on: CurrentWireRevision >= 2 (so 0
   and 1 stay permanently retired) and MinClientWireRevision <=
   CurrentWireRevision (so this build's own floor never refuses every
   request against itself).

2. gendigest now refuses to create a golden.json that does not exist yet
   unless run with -init. Previously a missing file (moved testdata,
   wrong path, accidental delete) was indistinguishable from a real first
   run and silently wrote a fresh golden with no revision history checked
   against anything. writeGolden() is extracted out of main() so this is
   covered directly: TestWriteGoldenRequiresInitWhenMissing,
   TestWriteGoldenInitCreatesWhenMissing,
   TestWriteGoldenIgnoresInitWhenGoldenExists (the existing-golden path is
   still governed only by SafeToWrite, -init or not).

3. Narrowed the two remaining stale claims that still described the
   digest's original, narrower coverage: the wire_revision property's
   prose in openapi.v0.yaml (regenerated into apigen/types.gen.go via
   make api-gen) and wireshape/doc.go now both list nullable, array item
   shape, additionalProperties value shape, request bodies, and
   $ref/allOf/oneOf recursion, plus the new -init guard.

go test ./internal/httpapi/... and make api-check both green;
bazel test //internal/httpapi/... (httpapi, wireshape, and the new
gendigest test target) green; python3 tools/bazel/go_srcs.py --check
clean.

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

* feat(wireshape): cover operation parameters in the wire-shape digest

The digest previously walked only response and request-body schemas, so a
type, enum, required, or removal change on one of the spec's 138 operation
parameters (123 query, 14 path, 1 header) passed the gate silently — the
open item from PR review on #7182.

Each parameter is now recorded as its own Entry, keyed by
"param:"+operationId / location+":"+name (operation-scoped, not
schema-scoped, since two operations' same-named parameter are independent
wire contracts), capturing type, array item shape, enum, required, style,
explode and default. Adding a parameter stays additive; removing,
retyping, narrowing its enum, or changing required/style/explode/default
now trips SafeToWrite exactly like a response or request-body change.

Verified against the live spec: retyping listIssues' `limit` query
parameter from integer to string now fails TestWireShapeDigest (confirmed
red, then reverted — not part of this commit). golden.json regenerated via
gendigest; the new parameter entries are a pure addition, no wire_revision
bump needed. Added TestParameterMutationsAreCaught (remove/retype/narrow-
enum against real golden entries) and updated wireshape's doc.go, the
`wire_revision` spec prose, and the CHANGELOG to describe the new
coverage.

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

* fix(wireshape): review fixes — stale-golden and lowered-revision arms, effective param serialization, digest boundary

Maintainer fixup from the adopt-pr review loop (iterations 1 and 2), on
top of e17ba924f.

- goldenDrift (A, I): TestWireShapeDigest's comparison moves into a
  goldenDrift helper. An addition alongside a moved wire_revision no
  longer passes with a stale golden: it asks for a regenerate, as a
  changed or removed entry after a bump already did. Every message now
  names response/request-body members AND parameters, and TestGoldenDrift
  pins each arm. This takes only the test half of the stranded fixup
  (adopt-pr/bd-47kdge/stranded-fixup-528cd6095); its doc half, which says
  parameters are outside the digest, is false since e17ba924f and is not
  replayed (J).
- Lowered wire_revision (D): a CurrentWireRevision LOWER than the
  golden's is a wrong constant, not a stale golden, so goldenDrift says to
  restore it instead of regenerating, and SafeToWrite (so gendigest)
  refuses any write at a lower revision, whatever the entries.
- Effective style/explode (B): walkParam records style and explode with
  OpenAPI 3.0's defaults filled in (form for query/cookie, simple for
  path/header; explode defaults to style == form). Adding `explode: false`
  to a query array that relied on form's implicit explode is now a
  changed entry, while spelling out a default changes nothing.
  testdata/golden.json is regenerated with -init: 111 parameter entries
  change only in style/explode (96 to form/true, 15 to simple), 828
  entries before and after, wire_revision stays 2. The golden is new in
  this PR and unreleased, so this needs no bump.
- TestWalkParam (H): a package-internal table test
  (wireshape_internal_test.go) pins every field walkParam extracts,
  through a computeFrom(document, revision) seam that Compute now wraps:
  per-location defaults, $ref'd parameters and items, format, nullable and
  default, content parameters, and the nil returns.
  TestEffectiveSerializationIsCompared pins B end to end through Compare
  and SafeToWrite. BUILD.bazel embeds the library in the go_test, which is
  gazelle's own output.
- Required inputs and the digest boundary (C, E, F; docs only): all five
  prose surfaces (openapi.v0.yaml's wire_revision description and the
  regenerated apigen/types.gen.go, wireshape/doc.go, CHANGELOG.md,
  engdocs/design/bd-serve-v0.md) now say that a new REQUIRED request
  input is recorded as an ordinary addition and needs its own review,
  that value constraints and member-level composition are outside the
  digest, and that object and content parameters are recorded only as
  their container. bd-serve-v0.md also gains the parameter coverage it
  was missing.
- G: a brand-new operation is permanently exempt from the
  capability-token rule; its own review decides its capability story.
- Iteration 2 (nit): walkParam's comment now says that the location
  default it records as a `content` parameter's style and explode is a
  placeholder, since OpenAPI 3.0 applies style and explode only to a
  parameter described by `schema`. All 138 operation parameters in the
  spec use `schema`, so the golden does not change.

Validated: go test ./internal/httpapi/... (gms_pure_go), make api-check,
go vet for linux/windows/darwin, gofmt, git diff --check, gazelle on the
package (no drift), make bazel-sync-check, and bazel test
//internal/httpapi/wireshape/... in the local processwrapper sandbox
(2 of 2 pass). Overlay mutation probes: dropping the added-after-bump
arm, the lowered-revision arm, SafeToWrite's lowered check, or the
effective-default fill each turns the new tests red.
Iteration 2 changes only that comment; go test
./internal/httpapi/wireshape/... (gms_pure_go), go vet, gofmt and git
diff --check pass again.

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

* feat(count): add Counter scope fields (S8) — ParentID, NoParent, ExcludeTypes, ExcludeStatus

Extends issueops.CountRequest with ParentID, NoParent, ExcludeTypes and
ExcludeStatus, closing the gap where bd count could not express the
filters bd list already has, forcing downstream consumers like gc to
fall back to listing everything just to get a count.

- issueops.Counter: four new CountRequest fields, documented against the
  List equivalents they mirror (ParentID/ExcludeTypes) or newly define
  (NoParent, ExcludeStatus has no List counterpart). Status "all" is
  pinned as equivalent to unset, matching BuildListFilter's own "all" and
  preserving count/list cardinality parity (the role's reason to exist).
- internal/workapi.BuildCountFilter: maps the four fields onto the one
  types.IssueFilter builder all three storage legs (dolt, embeddeddolt,
  uow) already share via internal/storage/issueops and sqlbuild, so no
  per-leg storage code was needed.
- cmd/bd: --parent, --no-parent, --exclude-type, --exclude-status flags.
- HTTP: adds parent/no_parent/exclude_type/exclude_status to GET
  /v0/beads/issues:count, behind the new issues.count.scope behavior
  token (routes.go), wired in reads.go's countFilters, documented in
  openapi.v0.yaml with per-parameter tokens and an extended capabilities
  description. gendigest confirms a byte-identical golden.json: query
  parameters are outside the wire-shape digest's scope, so this is a
  zero-diff, no-revision-bump change as expected.
- backend/conformance: four new Counter contract cases (ParentID scoping,
  NoParent's edge-only semantics vs ParentID's edge-or-dotted-id match,
  ExcludeTypes composing with include_infra's own exclusions, and
  ExcludeStatus), run identically against all three storage legs via a
  new CounterFixture.AddDependency hook shared with ReaderFixture.

Verified: go build ./...; go test ./internal/httpapi/... ./internal/workapi/...
./issueops/... and the Counter contract on all three legs (dolt via
testcontainers, embeddeddolt, uow via local dolt binary); make api-gen
(additive-only apigen diff) and make api-check; go vet and golangci-lint
clean; gofmt clean; gazelle diff empty (no new files/imports). Mutation
testing: dropping issues.count.scope from behaviorCapabilities turns
TestCapabilitiesAdvertiseEveryImplementedOperation,
TestSpecCapabilityVocabularyMatchesTheRouteTable and
TestNewParameterOnExistingOperationHasABehaviorToken red; no-op'ing
ExcludeStatus in BuildCountFilter turns
TestBuildCountFilterExcludeStatusTakesNamesAsWritten and the
embeddeddolt ExcludeStatusNarrowsThePredicate conformance case red. Both
reverted and reconfirmed green.

Deviation: DESIGN.txt's literal text would make count --status all an
ErrValidation; shipped behind a test and a doc comment instead, since
"all" already means "every status" on both count and list and rejecting
it would break the count/list parity this role exists to guarantee.

S3/S4 note: no OSS HTTP client exists yet to enforce capability-token
skew. A doc comment on CapIssuesCountScope in routes.go specifies the
required behavior once one lands: check issues.count.scope against the
cached handshake capabilities and refuse locally with a typed
ErrUnsupported{Capability} before sending any of the four new params to
an older server.

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

* fix(count): S8 review follow-ups — refusal parity, exclude-status validation, doc fixes, parity tests

Addresses the Opus review's six required changes for S8 (bd count scope
fields):

1. BuildCountFilter now refuses ParentID+NoParent together as ErrValidation,
   matching bd list's CLI refusal wording; wired through the role, the CLI,
   and invalid_argument classification in internal/httpapi/reads.go.
2. Status:"all" is documented in DESIGN.txt as every status, matching List's
   no-filter reading (count/list cardinality parity) — a coordinator decision
   recorded in beads-design/DESIGN.txt, outside this worktree.
3. ExcludeStatus names are now validated against the workspace vocabulary
   (built-in statuses plus workspace-custom ones); an unknown name is
   ErrValidation instead of a silent no-op, since a typo here would overcount.
4. Fixed openapi.v0.yaml and issueops/reader.go doc claims about bd list
   --parent's default tree-walk vs. the one-level role answer that bd count
   --parent agrees with (confirmed by tracing list_show_filter_modes.go); fixed
   an Oxford-comma nit in routes.go and the spec.
5. Added storage-level count == len(List) parity tests for ParentID, NoParent
   and ExcludeTypes (List has no ExcludeStatus counterpart), plus wisp-child
   and closed-child contract cases, across all three backends (dolt,
   embeddeddolt, uow). CounterFixture gained a List hook for this.
6. Extended the routes.go skew note: gc's ErrCountUnsupported fallback to List
   is now named explicitly, with a note that S3/S4 must add a skew test that
   masks the token and asserts the fallback fires.

Also fixed RunCounterExcludeStatusNarrowsThePredicate's now-stale "unrecognized
status excludes nothing" assertion to expect ErrValidation instead.

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

* fix(count): PR #7199 review follow-ups — exclude-status config load, ParentID doc swap

Addresses bee's REQUEST-CHANGES on gastownhall/beads#7199 (S8):

1. BLOCKER: storecounter.filter and uow.countFilter only loaded the
   workspace list config when IncludeInfra was set, so BuildCountFilter's
   ExcludeStatus validation refused a workspace's own custom status unless
   the caller also passed the unrelated IncludeInfra flag. Both legs now
   load the config when IncludeInfra OR len(ExcludeStatus) > 0, with
   comments corrected to say so. Added leg-level regression tests (the
   conformance fixture cannot drive a workspace-configured custom status)
   on embeddeddolt and uow, reproducing the reviewer's CLI repro directly,
   plus an HTTP-level probe in cmd/bd's real-Dolt proxied count test.
2. issueops.ReadyRequest.ParentID's comment had been overwritten with the
   one-level direct-children wording that belongs to ListRequest.ParentID;
   Ready actually walks all descendants via GetDescendantIDsInTx (GH#3396).
   Restored the descendants comment on ReadyRequest.ParentID and moved the
   one-level explanation to ListRequest.ParentID, which had none.

Verified: make api-check; dolt-server, embeddeddolt and uow Counter
contract legs (BEADS_TEST_DOLT_SERVER=local with a pinned dolt binary for
uow; Docker for the dolt-server leg); the new proxied HTTP exclude_status
probe (BEADS_TEST_PROXIED_SERVER=1).

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

* chore(wireshape): add the countIssues scope parameters to the wire-shape golden

#7182 now digests operation parameters. The four new issues:count parameters
(parent, no_parent, exclude_type, exclude_status) are additive entries, so no
wire_revision bump is needed; regenerated with gendigest.

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

* test(conformance): register the S8 count-scope cases with RunRoleContracts (adopt-pr #7199)

The PR adds nine RunCounter* contract cases to counter_contract.go and wires
them into the three in-tree TestCounterContract legs, but not into the
Counter row of roleContractCases. TestRoleContractCasesCoverEveryContractCase
derives the expected set from source, so it fails on the PR head, and an
external backend running RunRoleContracts would never see the new cases.

Register them in source-declaration order (after
RunCounterAnUnknownStatusMatchesNothing), which the same guard enforces.

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

* docs(count): correct the S8 scope docs the review found wrong (adopt-pr #7199)

Comment and spec-description fixes only; no behavior change. Review-loop
iterations 1 and 2 of the #7199 relaunch.

- ListRequest.ParentID (issueops/reader.go) said "DIRECT children only
  ... the same one-level clause". The sqlbuild clause has two arms and
  neither walks: the parent-child edge arm stops at one level, but the
  dotted-prefix arm (`id LIKE CONCAT(?, '.%')` for rows with no
  parent-child edge) reaches every edge-less dotted id at any depth, which
  RunReaderListParentReachesEveryDescendantAndOnlyItsOwn pins with an
  edge-less X.1.1. State both arms, and say the CLI tree view re-runs the
  clause against the store once per level (findAllDescendants calls
  SearchIssues, not the role). Document ListRequest.NoParent, which had no
  doc. The contributor's ReadyRequest.ParentID text is kept; only its
  cross-reference to this field changes from "one-level" to "non-walking".
- CountRequest.NoParent (issueops/counter.go) and the count flag comment
  (cmd/bd/count.go) said NoParent counts rows with "neither" an edge nor a
  dotted prefix. Its SQL checks only the edge table, so an edge-less X.1
  is counted by both --parent X and --no-parent, as bd list lists it.
- RunCounterExcludeStatusNarrowsThePredicate's header said an
  unrecognized name "excludes nothing rather than failing" while its body
  asserts ErrValidation. The header now matches the body.
- The OpCountIssues entry in problem.go's operationCodes said the role has
  "exactly one reachable refusal". It has three: an invalid metadata key,
  an unrecognized exclude_status name, and parent with no_parent (named
  no_parent), all classified by invalidFilterParam. The code set is
  unchanged.
- BuildCountFilter's header said cfg is "only read under IncludeInfra".
  It is also read to validate ExcludeStatus against the workspace's
  custom statuses, which is why both callers load it when ExcludeStatus is
  non-empty.
- The countIssues `parent` description in openapi.v0.yaml carried the
  same one-level claim as ListRequest.ParentID; it now states both arms.
  types.gen.go is regenerated (make api-gen); make api-check passes.

Review fixes (iteration 2), still comment and spec text only:
- The iteration-1 problem.go rewrite called all three count refusals
  ErrValidation. Only the exclude_status and parent-with-no_parent
  refusals wrap issueops.ErrValidation (internal/workapi/count.go). The
  metadata-key refusal is ValidateMetadataFilters' plain fmt.Errorf
  chain, so errors.Is(err, ErrValidation) is false for it; it reaches the
  wire as a 400 only because invalidFilterParam matches message prefixes.
  The comment now says that, so a later move to typed errors cannot trust
  it and demote the metadata-key refusal to a 500. The sentinel itself is
  not added here: ValidateMetadataFilters is shared with the list and
  ready builders.
- invalidFilterParam's comment on the count rows pointed at the
  metadata-key rows as "above"; they come after it in the switch.
- The countIssues `parent` description said the CLI tree mode walks
  "every edge-linked descendant". findAllDescendants re-runs the full
  two-arm predicate per level, so it also descends through edge-less
  dotted ids; it now says "every descendant reachable through either
  arm". types.gen.go is regenerated; make api-check passes.

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

* chore(wireshape): re-record the count scope params under the base's param digest (adopt-pr #7199)

The base branch (feat/wire-revision-signal, #7182 be1f0bad72) now digests
the effective style/explode of scalar query parameters. This PR's golden
entries for countIssues query:parent and query:no_parent were written by
the old algorithm, so after the base refresh TestWireShapeDigest reported
them as "changed without a wire_revision bump".

No bump is owed: all four count-scope entries (parent, no_parent,
exclude_type, exclude_status) are additions this PR introduces and are
absent from the base golden. golden.json was reset to the base copy and
regenerated with `go run ./internal/httpapi/wireshape/cmd/gendigest`. The
result is four pure additions against the base (+35/-0); parent and
no_parent gain "style": "form" and "explode": true, and wire_revision
stays 2.

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

* ci: place the PR's new embedded counter test in the shard manifest

TestCounterExcludeStatusAcceptsAWorkspaceCustomStatusWithoutIncludeInfra,
added to internal/storage/embeddeddolt in f23bf5ddbf, is a new top-level
embedded storage test. The 15-shard block of
.github/scripts/embedded-storage-test-shards.txt must list every
discovered test exactly once. Without the entry,
TestStorageEmbeddedShardManifestGeneratorNotStale (scripts/) fails, both
on the reviewed head 89a387de6c and on the merge. CI never ran the check
on this PR: pr.yml runs only for PRs based on main, release/** or
hotfix/**, and this PR was based on feat/wire-revision-signal until the
retarget.

Generated with
`python3 scripts/ci/gen_embedded_storage_shard_manifest.py 15 --weights=duration --write`.
The incremental write adds this one line, in shard 4, and moves no other
test.

Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Gas City Adopt-PR

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

---------

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
Co-authored-by: Eddie the Engineer <adopt-pr@gascity.com>
Co-authored-by: Eddie the Engineer <adopt-pr@gascity.local>
2026-10-05 02:57:14 -07:00
Rongjun GENG
5db60f42ac
fix(purge): preserve transitive live dependents (#7041)
Propagate sweep protection through closed candidates so an open descendant
keeps every candidate ancestor in its protecting dependency chain. Cover the
shared helper, dry-run, real sweep, and all storage contract wirings.

Agent-Signature: codex-gpt-5-unknown-reasoning on behalf of Rongjun GENG
2026-10-04 20:01:35 -07:00
Vishnu J
b0c3c8f497
fix(epic): do not treat duplicate/wontfix closes as complete (#5138)
* fix(epic): do not treat duplicate/wontfix closes as complete

GetEpicsEligibleForClosure counted any closed child as complete work.
An epic whose only child was closed as duplicate (or wontfix/superseded)
was flagged "complete-but-unclosed" and doctor suggested bd close — even
when the epic still had unfinished scope (GH#5026).

- Fetch close_reason with status; only completing closes count for eligibility
- IsNonCompletingClose for duplicate/wontfix/superseded/obsolete keywords
- Soften doctor/mol stale copy: review scope before closing

Fixes #5026

* fix(epic): word-boundary close-reason matching + conformance coverage (GH#5026)

Review follow-ups from maphew on #5138:

- IsNonCompletingClose now matches close_reason on word boundaries via a
  precompiled regexp instead of raw strings.Contains. Bare "dup" is dropped
  (redundant with duplicate/dupe, only added false positives on "dedup").
  Bare "obsolete" is dropped in favor of "obsoleted" — "removed obsolete
  migration shim" is completing work, not a redirect, and was silently
  making such epics ineligible forever with no explanation.
- testAuditEpicsEligiblePartial (conformance, runs on every backend) gains
  an ee-4 epic whose only child closes with reason "duplicate of ee-1",
  asserting {Total:1 Closed:1 Eligible:false} — the dcr-tf2 regression from
  #5026 end to end. Its doc comment now states the invariant this PR
  actually enforces (Total == completing-closed), not the one it broke.
- cmd/bd/info.go and cmd/bd/doctor/maintenance.go no longer advertise the
  retired "complete-but-unclosed" framing.

Generated CLI docs (docs/CLI_REFERENCE.md, docs/cli-reference/) are left
untouched: docs/cli-docs.pin freezes them to the released v1.1.0 tag, so
regenerating with the pinned build (matching CI's check-doc-flags job) is
a no-op regardless of source changes on this branch, and overriding the
pin pulls in ~100 files of unrelated accumulated drift. Verified via
scripts/check-doc-flags.sh against a CI-equivalent CGO_ENABLED=0 build.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015AfaSMkMRF5BTzuPNFnqHY

* fix(epic): match hyphenated wont-fix and curly-apostrophe won't fix (GH#5138)

Maintainer review on GH#5138 found the close-reason regexp missed two
forms of the already-handled wontfix keyword: a hyphen between "wont"
and "fix" (the ` ?` quantifier only tolerates a space, not a hyphen),
and "won't fix" written with the U+2019 typographic right single
quote instead of the ASCII apostrophe.

Extend the regex directly rather than normalizing the whole
close-reason string: `wont[- ]?fix` accepts a hyphen, a space, or
neither, and `won['\x{2019}]t fix` accepts either apostrophe form.
Scoping the hyphen tolerance to just this keyword pair (rather than
folding all hyphens to spaces) avoids the risk of turning unrelated
hyphenated prose into a false match.

Adds table cases for both forms plus a negative case confirming
ordinary hyphenated prose ("not-yet-planned") still doesn't match.

* style: gofmt maintenance.go after comment split the struct alignment

The GH#5026 wording comment inside the DoctorCheck literal splits gofmt's
alignment group, so Name/Status align independently of Message. CI's
"Check gofmt" caught this on the rebase; main's copy is clean, so the
violation is ours.

Whitespace only: `git diff -w` is empty.

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

* fix(epic): compose wont-fix separators, sync epic_closeable classifier (GH#5138 review)

bee-ghosttrack's desk review on PR #5138 raised two asks:

1. The hyphen and curly-apostrophe fixes didn't compose: "won't-fix" and
   "won't-fix" (curly quote) still matched as completing. The apostrophe
   alternative in nonCompletingCloseRegexp required a literal space after
   "fix"; give it the same [- ]? hyphen tolerance the plain "wont[- ]?fix"
   alternative already had.

2. epic_closeable (internal/workapi/detail.go) computed closeable as raw
   total==closed, disagreeing with issueops.GetEpicsEligibleForClosureInTx's
   real classifier — an epic whose only child closed "duplicate of X" read
   epic_closeable=true in `bd show --json`. Moved IsNonCompletingClose from
   issueops into the leaf internal/types package (issueops already imports
   workapi, so workapi importing issueops back would cycle) and had
   applyEpicProgress apply the same classifier. That also surfaced a second
   bug on the way: shallowDep, which every dependent row passes through
   before applyEpicProgress ever sees it, was dropping CloseReason along
   with the other free-form text fields — so the classifier was reading an
   always-empty string. Fixed by keeping CloseReason (short, not a hub-scale
   blob) in the shallow copy.

Regression test in workapi added and verified to fail without the
shallowDep fix and pass with it (both outputs recorded in review).

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

* fix(epic): apply the eligibility classifier to bd show and doctor --deep (#5138 review)

Review iteration 1 (synthesis: request_changes, 1 major + 1 nit).

Major (Change Impact / Blast Radius) — two surfaces still computed epic
closeability from their own raw closed counts, so after this PR they
contradicted the eight sites that read the shared EpicStatus.EligibleForClose:

- cmd/bd/show_format.go: printEpicChildProgress gates only the
  "— eligible for close" suffix on types.IsNonCompletingClose. The
  closed/total figure stays raw, matching the deliberate raw ClosedChildren
  convention pinned by the conformance test.
- cmd/bd/doctor/deep.go: checkEpicCompleteness routes through
  issueops.GetEpicsEligibleForClosureInTx instead of its own SQL, so one
  classifier remains and `bd doctor --deep` agrees with `bd doctor`'s Stale
  Molecules check by construction. Side effects, both improvements: the local
  LIMIT 20 is gone (the reported count is now exact), and the shared query's
  isTableNotExistError tolerance replaces a LEFT JOIN that required the
  optional wisps/wisp_dependencies tables unconditionally.
- cmd/bd/doctor.go: the --deep help text no longer says "all children closed".

Nit (Behavioral Correctness) — internal/types/non_completing_close.go spells
the keyword "not[- ]?planned", giving it the same per-keyword separator
tolerance the "wont fix" pair already had. The comment no longer rests the
space-only spelling on the "not-yet-planned" counterexample, which an
intervening word blocks under either spelling.

Bazel: gazelle had never been run for this PR's new files, so //internal/types
omitted non_completing_close.go and the Bazel build failed with
"internal/workapi/detail.go:275: undefined: types.IsNonCompletingClose".
`bazel run //:gazelle` adds those rows and the new cmd/bd test src.

Tests (each new pin mutation-proved: reverting the fix reds exactly the
intended case and nothing else):
- cmd/bd/show_format_test.go (new): first coverage for printEpicChildProgress;
  asserts both halves — raw progress preserved, suffix gated.
- cmd/bd/doctor/deep_test.go: a duplicate-closed-child epic is not reported
  ready to close and ships no `bd close` Fix line; the three pre-existing
  cases pass unchanged.
- internal/types/non_completing_close_test.go: "not-planned"/"notplanned"
  classify as non-completing; "not-yet-planned" still does not.

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

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
2026-10-01 05:19:33 -07:00
mtccressall
652c29b805
fix(show): disclose dependency edges the listing cannot represent (be-lpi) (#6352)
* fix(show): disclose dependency edges the listing cannot represent (be-lpi)

`bd show --json` emitted a self-contradicting payload on any issue with a
cross-repo or `external:` dependency:

    {"id":"hq-cv-ftcra","dependency_count":1,"dependencies":null}

and `bd show` in text mode rendered no dependency section at all, so
`bd dep add x liveop-y` reported success and the `bd show x` a caller ran
straight after was indistinguishable from the edge never having been written.

THE COUNT IS CORRECT. THE ENUMERATION IS THE DEFECT.

`GetDependenciesWithMetadataInTx` reads the edge rows, resolves each far end,
then does a bare `continue` past any id with no local row. An `external:` or
cross-repo target HAS no local row by construction: `IsExternalDepTarget`
routes exactly the ids this database cannot hold into `depends_on_external`,
the one target column with no foreign key into issues. The count queries have
no such join. So the count keeps the edge and every listing drops it, and the
difference is precisely the set of edges that are real, stored, and
unrenderable from here.

Reported as a phantom count on convoy beads. It is neither phantom nor
convoy-specific: `hq-cv-ftcra` carries a real `tracks` edge to
`external:liveop:liveop-kmf`, and convoys are simply the only producer of
external targets in that store (77 external edges, all `tracks`). The
`bd list --json` zero the report also cites is correct by design and unrelated
— that count is blocks-only per `SearchCountsSQL`, and the edge is `tracks`.

Publish the difference instead of leaving the caller to infer it, following
the `comments_omitted` precedent (ga-clgh):

  - `IssueDetails` gains `unresolvable_dependencies` / `unresolvable_dependents`
  - `BuildIssueDetails` sets them, so every frontend — CLI `--json` and the
    HTTP detail view — gets it at once
  - text mode says the same thing on stderr, never stdout, so the rendered
    issue is byte-identical for the common fully-local case; that is the
    choice `warnDroppedDepEdges` already made in dep.go for this same gap
  - the notice helper is shared with the watch-mode render so the two cannot
    drift apart in what they disclose

Set ONLY when the row list was actually read and came back short: the
dependency read's error is now kept rather than discarded, because a FAILED
read and a SHORT read both leave the slice empty and must not collapse into
one signal. `unresolvable_dependents` only under `IncludeDependents`, where
the rows exist — without them the slice is nil by design and a delta would
report every dependent an issue has as unresolvable.

Deliberately NOT done: making the count match the listing. The count is right
and the edge is real, so zeroing it would delete the only signal these edges
exist. Nor does `GetDependenciesWithMetadata` synthesise placeholder issues
for external targets — it has 14 non-test call sites including the Linear,
GitLab, Jira and ADO sync paths, which would then map a fabricated issue onto
a remote tracker.

`bd dep list` needed no change: bd-mtla already warns there and points at
`bd dep list <id> <id>`, which prints the raw edge record. The installed
v1.2.2 predates that fix, which is why the bead's measurements saw a bare `[]`.

Tests. `internal/workapi/detail_unresolvable_test.go` pins the arithmetic
against a source whose counts and rows are set independently, with negative
controls for a fully local store, a failed row read, a failed count read, and
count-only mode. `cmd/bd/show_unresolvable_deps_embedded_test.go` drives the
production path — init, create, `dep add`, `show` — for both target shapes
plus a fully local control, and asserts the notice reaches stderr and not
stdout. Verified the scratch fixture's stored columns are identical to the
production row rather than merely similar. Sabotage control run on both tiers:
removing the guard turns each red, and the negative controls stay green.

`docs/reference/json-schema.md` is intentionally untouched — it is
hand-written and documents the pinned release (`docs/cli-docs.pin` is v1.2.2),
not main. Follow-up filed as be-soj.

Agent-Signature: claude-code-claude-opus-5[1m]-unknown-reasoning on behalf of Marc Cressall
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017B2Z4eQi2a9Cgfumj2RRnR

Executed-By: beadsrig/polecats/toast

* fix(show): do not read a failed dependency listing as unresolvable edges (be-lpi)

Codex review of the previous commit, and it is right.

`bd show` renders dependencies best effort and discarded the listing error:

    depsWithMeta, _ := issueStore.GetDependenciesWithMetadata(ctx, issue.ID)

so when that read FAILED while the count query succeeded, the new notice
reported every counted edge as cross-repo/external. A transient backend error
was rendered as a claim about the data, which is the more expensive of the two
mistakes — the user goes looking for edges that are simply unread.

This is the distinction `BuildIssueDetails` already draws with `depsErr` on
the JSON side, and it is the reason that error is kept there. The text path
did not draw it at all, so the two planes disagreed under failure: `--json`
stayed silent and the human render accused the data.

Carry each direction's rows and error together in a `depListing` and require
BOTH reads to have succeeded before reporting a difference. Rendering stays
best effort; only the diagnosis is gated. A failure in one direction no longer
suppresses the other, which is a case the single-error shape could not express.

`cmd/bd/show_unresolvable_deps_unit_test.go` pins it: 10 cases including the
two the review found, a fully local negative control, a failed count read, and
one direction failing while the other stays reportable. Sabotage control —
relaxing the guard back to `countErr != nil` alone fails exactly the two
listing-read-failed cases and nothing else.

Reuses the existing race-safe `captureStderr` from test_helpers_pure_test.go
rather than a second copy.

Agent-Signature: claude-code-claude-opus-5[1m]-unknown-reasoning on behalf of Marc Cressall
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017B2Z4eQi2a9Cgfumj2RRnR

Executed-By: beadsrig/polecats/toast

* fix(show): read the dependency counts before the row listings (be-lpi)

Second codex finding on this change, and it is real on the path `bd show`
actually uses.

The unresolvable-edge difference is computed from two reads. Where the source
is not snapshot-consistent, a write landing between them skews it — and with
the listing read first the skew was the expensive direction: a freshly added,
perfectly ordinary local edge came back as `unresolvable_dependencies: 1` and
as a stderr notice accusing the data.

Only the store-backed source is exposed. `uow.issueReader.Get` wraps the whole
build in `RunTxRead`, so the UOW path shares one snapshot; `storereader` — what
`EmbeddedDoltStore.IssueReader` returns, and therefore what `bd show` runs on —
issues a connection per call.

Read the counts FIRST. An edge added in the window then leaves the count
stale-LOW, the difference goes negative, and nothing is reported. The text path
gets the same order structurally: the helper is split into `readDepCounts`,
called before the listings, and `warnUnresolvableDepEdges`, called after, so
the ordering is visible at both call sites rather than buried.

THIS IS AN ORDERING MITIGATION, NOT A FIX, and the code says so. A concurrent
DELETE still leaves the count stale-HIGH and produces a spurious notice. Closing
that needs a shared snapshot across the two reads, or a store method that counts
edges whose target has no row directly — either is a new seam across both
backends and the domain path, out of proportion to an advisory field. Filed
separately. Deletion of a dependency edge is also far rarer than addition, which
is why this ordering is strictly better rather than merely different.

The first version of the JSON-side test DID NOT PIN THE ORDER. It used a source
returning fixed values, so reversing the two reads still passed — a test
pinning arithmetic while claiming to pin an order, and the sabotage run is what
caught it. Replaced with `mutatingSource`, where whichever read runs first sees
one edge and the second sees two; swapping the reads in `BuildIssueDetails` now
fails with exactly the false report the review described. The text-side case is
relabelled to say it covers the subtraction only, since the call-site order is
not in its scope.

Agent-Signature: claude-code-claude-opus-5[1m]-unknown-reasoning on behalf of Marc Cressall
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017B2Z4eQi2a9Cgfumj2RRnR

Executed-By: beadsrig/polecats/toast

* fix(show): disclose unrenderable dep edges in proxied render (be-lpi)

`bd show` has three text renders and be-lpi closed two of them.
usesProxiedServer() returns at show.go:45 before any of the fixed code,
and runShowProxiedDefault binds the shared issueops.Reader -- hence
BuildIssueDetails, hence unresolvable_dependencies -- only when
`jsonOutput && !in.shortMode`, so plain text falls through to
proxiedRenderIssue, which rendered both dependency sections from
proxiedListDeps with discarded errors and said nothing. On a
server-backed repo the change`s own symptom survived: a cross-repo or
`external:` dependency still rendered as no dependency at all.

Call warnUnresolvableDepEdges from that route too, counts before the
listings, taking the counts through workapi.NewUOWDetailSource. The
domain use cases behind a proxied UOW are per-table, so proxiedDepCounter
carries the isWisp flag the DetailSource counts take. That flag is
arithmetically inert on this path, and the earlier claim here that the
store seam "resolves" it was the wrong mechanism: the repository read
seam discards it outright -- CountByID forwards only Direction and Types
to CountDependencyEdgesInTx, and ListWithIssueMetadata forwards only the
source id to Get{Dependencies,Dependents}WithMetadataInTx
(dependency.go:888-917) -- so both sides span `dependencies` and
`wisp_dependencies` alike and only the mutating paths pick a table.
The conclusion is unchanged and is what the notice depends on: the
arithmetic is the same on both routes, because
CountDependencyEdgesInTx counts `dependencies` plus `wisp_dependencies`
with no join to `issues`, and proxiedListDeps runs the very
GetDependenciesWithMetadataInTx the direct route runs, so the difference
means here what it means there. --refs and --children stay out of scope:
an alternate query with no count beside it to contradict. The precedent
this design cites, warnDroppedDepEdges, covers both of its own routes
(dep.go:1148, dep_proxied_server.go:457), which is the in-repo standard
applied here.

Pinned by TestProxiedServerShow2/show_discloses_unresolvable_dep_edges
with a fully-local negative control. Measured, not assumed: deleting the
new call reds the first and leaves the control green.

Also from the same review, all non-gating:

- The recovery pointer is outbound-only now. `bd dep list <id> <id>`
  reaches raw edge records through the duplicate-id form, which
  dep.go:1101 selects on `batchMode && direction == "down"`, and
  dep.go:1144 says in the repo`s own words that "up" has the same gap
  with no inbound EdgeReader role to close it. An issue short only on
  dependent edges was handed a command that cannot show them, and now
  gets a line saying so instead.

- The ordering comment no longer advertises a guarantee nothing holds.
  Splitting readDepCounts from warnUnresolvableDepEdges makes the
  counts-first order readable at the call sites; it does not pin it.
  Measured: reversing it at all three sites leaves this package green,
  including the embedded production-path test, because the unit test
  drives warnUnresolvableDepEdges directly and no CLI test can land a
  write inside the window. The only automated pin is one tier down, on
  TestBuildIssueDetails_ConcurrentAddIsNotReportedAsUnresolvable. A CLI
  test that could fail on the order would have to own that window, which
  is out of proportion for an advisory notice, so the comment now states
  its scope rather than overstating it.

- The plane asymmetry is documented rather than changed: text mode reads
  dependents unconditionally and always discloses the inbound direction,
  while unresolvable_dependents needs include_dependents (--json only).
  The per-field restriction is the correct half -- without the rows a
  delta would call every dependent unresolvable -- so the godoc and the
  spec description record the disagreement.

One correction to be-lpi`s own commit message, which cannot be amended
from here: enumerating the edges via issueStore.EdgeReader() is not "a
new seam across both backends and the domain path" on the CLI path.
EdgeReader() sits on the variable that path already holds
(storage.go:235, used at show.go:177). The concurrent-DELETE residual
still stands on the two-reads argument alone, which remains true of
ReadEdges plus a set difference.

Review iteration 2 adds the BUILD-file sync the required Bazel lane
needs, plus one comment correction:

- cmd/bd/BUILD.bazel and internal/workapi/BUILD.bazel now list the three
  test files this change adds. The relevant failure is not a broken
  build: bazel.yml`s "BUILD files in sync" step (:382-406) runs
  `make bazel-sync` and exits 1 on a non-empty `git status --porcelain`,
  and that step`s job is BAZEL_TEST, one of seven Bazel rows in
  pr.yml`s CI_GATE_REQUIRED (:1496-1524, mapped at :1551), so the drift
  reds a required lane rather than merely leaving the files invisible to
  Bazel. The repo`s own fixture agrees: scripts/ci_workflow_test.go`s
  bazelLaneGateIDs holds bazel-test, and bazelAdvisoryLanes retains only
  bazel-integration.

  The rows are gazelle output rather than hand-written. `make bazel-sync`
  on this head proposes five; init_git_bootstrap_routing_test.go and
  init_role_environment_test.go are base staleness that origin/main
  already lists, and a run on the merge target proposes them not at all,
  so only the three this change owns are committed.

  Certificate, run on the merge target rather than argued: merge
  origin/main into this head, resolve, `make bazel-sync`, then
  `git status --porcelain --untracked-files=all` is empty -- which is
  exactly the gate step`s own test, and it also confirms the resolution
  is byte-identical to what gazelle emits. `bazel build //cmd/bd:bd_test
  //internal/workapi:workapi_test` on that tree completes successfully,
  so the widened srcs lists compile.

  These rows do introduce a merge conflict this change did not have
  before: origin/main added show_watch_loop_test.go into the same slot of
  the same sorted srcs list in cmd/bd/BUILD.bazel. It is an add/add with
  an empty base -- neither side edits shared text -- and the resolution
  is the sorted union of all three rows, which is what gazelle emits and
  what the certificate above was run against.

- The ordering comment`s measurement clause named show.go and
  show_display.go while the claim was true of three call sites, the
  third being the show_proxied_server.go site this fixup added. It now
  names all three, re-measured at this head: reversing readDepCounts
  below its listings at every site leaves the selector green -- 35
  subtests across TestWarnUnresolvableDepEdges,
  TestEmbeddedShowUnresolvableDeps and TestProxiedServerShow2.

Maintainer fixup for PR #6352, review iterations 1-2.

---------

Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
2026-10-01 01:29:36 -07:00
Julian Knutsen
8995f2471e
test(count): pin --include-ephemeral as the plane bit alone, and fix the plane prose (post-merge #6240) (#6998)
* test(count): pin include_ephemeral as the plane bit and nothing else

PR #6240 added `bd count --include-ephemeral` so a count can reach the
wisps table without IncludeInfra's other three changes: dropping
templates, dropping gates, and routing an infra type to the ephemeral
tier. Nothing asserted that second half. Routing IncludeEphemeral
through the builder's infra branch, or mapping `include_ephemeral` onto
IncludeInfra in the HTTP handler or the CLI, passed every existing test.

- workapi: TestCountIncludeEphemeralIsThePlaneBitAndNothingElse, the
  count twin of the list pin. IncludeEphemeral (no type, a named type,
  an infra type) leaves IsTemplate, ExcludeTypes and Ephemeral unset;
  IncludeInfra still sets all four.
- httpapi: TestCountForwardsTheEphemeralPlaneParameter sends each plane
  parameter alone and asserts the exact request the role receives.
- cmd/bd: TestCountIncludeEphemeralFlagShape pins the flag, its false
  default, and that --include-ephemeral alone leaves IncludeInfra false.

Each new test fails against its mutant, and it is the only test that
does:
- builder: `if in.IncludeInfra || in.IncludeEphemeral`
- handler: `IncludeInfra: q.boolean("include_infra") || q.boolean("include_ephemeral")`
- CLI:     `IncludeInfra: includeInfra || includeEphemeral`

Post-merge review follow-up for #6240.

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

* docs(count): name include_ephemeral where the plane prose said include_infra alone

#6240 added a second way to reach the wisps tier, but several statements
still said only include_infra could reach it:

- spec, countIssues "Planes": "DURABLE-PLANE ONLY unless include_infra
  is set" now names both knobs and says what include_ephemeral changes.
- spec, include_infra: "Unset, the count is durable-plane only" now holds
  only with include_ephemeral also unset (types.gen.go regenerated).
- issueops.CountRequest: the same "Unset" sentence on IncludeInfra and on
  IncludeEphemeral, each now conditional on the other knob.
- workapi.applyCountIncludeInfra: "a count without IncludeInfra keeps its
  durable-only semantics" now allows for IncludeEphemeral.
- httpapi countFilters: the "plane switch" comment named one knob;
  IncludeEphemeral now has its own comment saying why it is never folded
  into IncludeInfra.
- count_test.go: the default-plane comment names both zero values, and
  the stale "25 filters" / "26th filter" literals are dropped (the
  struct has 26 fields).

Comment and spec-prose only; `make api-check` is green.

Post-merge review follow-up for #6240.

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

---------

Co-authored-by: Eddie the Engineer <adopt-pr@gascity.local>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 01:14:25 -07:00
Harry Miller
dfdedf5dfb
fix(status): disclose the counted rows bd list will not show (#5763)
* feat(stats): count the rows the default listing suppresses

bd status counts the issues table; bd list hides gates and templates on
account of what they are. The two therefore disagree, and nothing
reconciles them: a teardown driven by bd list leaves a gate behind and
status reports a total the operator cannot account for from any listing.

Break the suppressed rows out as their own counts. TotalIssues keeps
counting the database, which is what a command titled "Issue Database
Status" should report; these say how much of that total no default
listing will show. Every backend's statistics path funnels through
ScanIssueCountsInTx, so one query serves all of them.

Infra types need no counterpart here: they live on the wisp plane, which
this query does not read.

* fix(status): disclose the counted rows bd list will not show

bd status reported "Total Issues: 2" for a workspace whose every listing
showed one, because gates and templates are suppressed from a default
bd list. Nothing connected the two numbers, so the remainder read as a
phantom -- most visibly after a teardown driven by bd list, which leaves
its gates behind and then cannot see them.

Report the suppressed rows under the summary they qualify, naming the
flag that reveals each kind. The breakdown is printed rather than a
single hidden-total, since a template gate would otherwise be counted
twice. Nothing is printed when there is nothing suppressed.

Stacked on the statistics counts that make this reportable.

* docs(api): put gate_issues and template_issues on the Statistics schema

The Statistics schema is pinned to types.Statistics, so the two new
counts were on the wire the moment the struct grew them, and
TestWireTagBijection fails the openapi gate until the spec says so:

    Go fields with no spec property: [gate_issues template_issues]

Document both as a breakdown of total_issues rather than an addition to
it — they count rows the default `bd list` suppresses, which
total_issues already includes — and warn against summing them, since a
row can be both a gate and a template.

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

* fix(status): give --assigned the same disclosure, and test the behavior

Three points from review.

1. `bd status --assigned` never printed the line. AssigneeStats does not
   go through ScanIssueCountsInTx - it folds one actor's rows through
   workapi.FoldStatsAssigneeSummary, which left both new fields zero. That
   route's filter sets only Assignee, so IsTemplate stays nil and the
   actor's gates and protos really ARE in those rows while
   `bd list --assignee` suppresses both: the same reconciliation gap, one
   scope down. The fold now counts them, and its doc says they are set
   deliberately rather than borrowed from a workspace-wide answer.

2. The infra-type suppression is now explained rather than asserted away,
   and the answer is that a durable infra row is NOT unreachable, so the
   third breakdown is filed as GH#6439 rather than dismissed. Both the
   plane routing and the listing's exclusions read the workspace-configured
   types.infra set, and writing that key only invalidates a cache
   (dolt/config.go) - it never moves rows already written. So durable rows
   created while a type was not infra stay durable once it becomes one, and
   a type evicted from the set creates durable rows outright, which the
   create contract already pins ("evicted infra type",
   issue_operations_contract.go). Counting them needs that configured set,
   which ScanIssueCountsInTx - portable SQL with no config seam, called
   from six backend sites - cannot reach; guessing with the built-in names
   would be wrong in exactly the workspaces where it matters.
   suppressedTypeSummary's doc now carries that reasoning.

3. The behavior itself had no test - both existing cases exercised a pure
   string formatter, and would pass with the render call site deleted. Now:

   - TestRenderStatusEmitsTheSuppressedRowsLine captures renderStatus's
     stdout, asserts the line and both parts, and asserts it sits after the
     totals it reconciles rather than in the extended block. It fails with
     the call site removed ("renderStatus did not emit the disclosure
     line"), plus a companion asserting the line is absent when there is
     nothing to disclose.
   - Three conformance cases in stats_reporter_contract.go, wired into all
     three role wirings (dolt, embeddeddolt, uow), so the new SQL is
     checked cross-backend rather than at one call site:
     BreaksOutTheRowsTheDefaultListingSuppresses (with the negative rows a
     loose predicate would also move), BreaksOutAGateThatIsAlsoATemplate
     (the two suppressions are independent, so a proto's gate step counts
     in both), and AssigneeStatsBreaksOutTheSuppressedRows for the fold.
     statsReporterCounts and assertStatsReporterDelta carry the two fields.
     All three are behavioral reds against zeroed counts, not compile
     errors:

         GateIssues moved by 0 (0 -> 0), want 1
         TemplateIssues moved by 0 (0 -> 0), want 1
         GateIssues = 0, want 1 - the actor's gate is in this answer but
           not in `bd list --assignee`

4. Nit: pluralCount takes both spellings instead of appending "s", so a
   caller with an irregular plural is not silently mis-served.

Also adds the CHANGELOG entry the behavior change was missing, including
the GH#6439 gap.

Reported-by: bee-ghosttrack
Agent-Signature: claude-code-opus-5-unknown-reasoning on behalf of Harry Miller

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

* fix(conformance): declare the new stats cases in the order the table runs them

TestRoleContractCasesCoverEveryContractCase checks more than coverage: the
roleContractCases table has to list cases in the order their contract file
DECLARES them, because that is the order the unit-of-work leg's runners use
and the order its config-writing cases depend on.

I declared all three new cases together, then registered the assignee one
with the other assignee cases in the table, so the two orders disagreed:

    roleContractCases is out of declaration order at position 449: table
    has RunStatsReporterAStatusOutsideTheTalliesIsCountedOnlyInTotal,
    source has RunStatsReporterAssigneeStatsBreaksOutTheSuppressedRows

Fixed by moving the declaration rather than the table entry, since the
assignee case belongs beside the other assignee-scoped ones anyway - the
grouping the table already had was the correct one. Caught by CI because I
ran go vet over backend/conformance but not its tests; both now pass.

Agent-Signature: claude-code-opus-5-unknown-reasoning on behalf of Harry Miller

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

* docs(changelog): move this PR's entry under [Unreleased]

The 1.3.0 cut renamed the old [Unreleased] block, so the entry this branch
added there now merges cleanly into the released [1.3.0] section (#6643).

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

* fix(status): complete the disclosure's remedy and pin its population

Maintainer review fixes for PR #5763 (adopt-pr iteration 1). Four of the
five review findings taken; the nit is declined with its measurement.

Finding 2 (minor, gate impact minor) - the printed remedy was incomplete.
The two counters come from the same scan as TotalIssues and are status-blind
with it, but the flags they named lift only the TYPE exclusion, so a CLOSED
gate was counted while `bd list --include-gates` still would not show it.
Gates are closed as the work they guard completes, so that is the ordinary
case rather than an edge.

Took the "complete the hint" arm over the "scope the counters" arm. Every
other field ScanIssueCountsInTx fills is workspace-wide; the disclosure
exists to account for TotalIssues, a database number printed three lines
above it; and scoping these two to the listing's population would leave them
explaining nothing about the total they are broken out of. `--all` "replaces
the status exclusions only" and lifts no type exclusion of its own
(backend/conformance/reader_contract.go:487), so the two flags together are
exactly the remedy. Recorded the population in the types.go field comment,
the status.go doc, and the CHANGELOG, which printed the old example verbatim.

Finding 3 (minor) - the three new conformance cases seeded only open rows,
so a backend counting over every status and one counting only the listing's
population returned identical numbers on all of them. Added a closed gate and
a closed proto to the first case. Proved it now decides the question: scoping
both SQL SUMs with `AND status <> 'closed'` reds exactly that case
("GateIssues moved by 1 (0 -> 1), want 2") while the all-open sibling
BreaksOutAGateThatIsAlsoATemplate stays green.

Finding 4 (minor) - the normative role doc in issueops/statsreporter.go
enumerated only the six prior counts. Added the two to that scan's bullet and
corrected two statements this PR had falsified: the headline "six counts of
one set", and the AssigneeStats bullet's "the fold ... tallies the five
statuses and nothing else", which stopped being true when the fold gained the
two increments.

Finding 1 (minor, gate impact minor) - ran `make bazel-sync`. It proposed
exactly one line, `+ "status_suppressed_test.go"` in cmd/bd/BUILD.bazel, and
nothing else, confirmed by porcelain rather than by bazel-sync-check.
Generator-owned, not hand-edited.

Finding 5 (nit) - declined. The three helpers already in package main
(pluralIssue, pluralize, plural) all DERIVE the "s" and cannot render a
caller-chosen pair; the tree's one two-form helper, pluralWord, is unexported
in internal/storage/issueops, and exporting it so a CLI string could reach it
would add exported surface to a storage role for a cosmetic. Recorded that
trade in pluralCount's doc comment instead.

Validation: `go build ./...` and `go vet` (6 pkgs) clean, gofmt clean,
`git diff --check` clean; cmd/bd 4/4 named PASS, internal/httpapi
TestWireTagBijection|TestSpec* PASS, internal/workapi PASS,
internal/storage/uow TestStatsReporterContract 18/18 subtests PASS. Both new
pins are mutation-proved: reverting `--all` reds all four table cases, both
flag subtests and the render-path pin, while the absence assertion stays
green.

Not done here: the PR body carries the same stale example line
("1 gate (--include-gates)"). Review iterations do not touch the PR surface,
so that correction is stamped for finalize.

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

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
2026-09-30 15:44:40 -07:00
Karel Bourgois
e8f318316f
feat(count): --include-ephemeral, the plane knob bd count never had (#6240)
* feat(count): --include-ephemeral, the plane knob `bd count` never had

`bd count` can admit the wisps table only through `--include-infra`, which
makes four changes at once. This adds the flag that makes just the first one,
mirroring the `--include-ephemeral` that `bd list` gained in #6098.

## Why the plane is unreachable on its own

The write path routes on STORAGE CLASS, not type — dolt's `useWispsTable` is
`Ephemeral || NoHistory || WispType != "" || IsInfraType`. So a `no_history`
task lives in the wisps TABLE while remaining ordinary durable work, and a
default `bd count` never sees it.

Recovering it today means `--include-infra`, which this repo's own doc calls
"FOUR changes at once and not one": it admits the plane, drops the infra-type
exclusions, changes the template treatment, and reconciles cardinality with
`bd list --all`. Its template exclusion then silently drops template rows of
the named type — so a caller who wanted the plane trades one silent undercount
for another.

`ListRequest.IncludeEphemeral` has been the narrow answer on the listing side
since #5476, and #6098 gave it a CLI flag. `CountRequest` had no equivalent
field at all. This is the missing half of that pair.

## The change

- `issueops.CountRequest.IncludeEphemeral` — the plane knob alone: exactly the
  first of `IncludeInfra`'s four changes, with none of the other three.
- `internal/workapi/count.go` — one line, `} else if !in.IncludeEphemeral {`.
- `cmd/bd/count.go` — flag registration, matching `bd list`'s wording.
- `internal/httpapi` — `include_ephemeral` on `countIssues`, in the spec; the
  generated `types.gen.go` is `make api-gen` output, not hand-edited.

Unset, the count is durable-plane only: the historical answer, unchanged. Every
default is untouched.

It does NOT promise a count and a listing agree. They already differ on
TEMPLATES without this flag and still do with it — a count includes template
rows unless `IncludeInfra` excludes them, a listing excludes them unless
`IncludeTemplates` admits them. That predates this and is unchanged by it; only
`IncludeInfra` sets out to reconcile cardinality, and it pays with three
changes beyond the plane.

## Verification

    ok  github.com/steveyegge/beads/internal/workapi
    ok  github.com/steveyegge/beads/internal/httpapi
    ok  github.com/steveyegge/beads/issueops
    --- PASS: TestEmbeddedCountIncludeEphemeral (39.71s)
    --- PASS: TestCountIncludeInfraFlagShape
    --- PASS: TestParseCountRequestCarriesEveryFilterFlag

`TestEmbeddedCountIncludeEphemeral` was run with `BEADS_TEST_EMBEDDED_DOLT=1`
and really executed — 39.71s, not a skip. The default fast tier would have
skipped it and reported `ok`.

`make api-gen` reproduces `types.gen.go` byte-for-byte from the spec hunk, so
the two cannot drift apart in review. `go build ./...`, `go vet` and `gofmt`
clean.

Claude-Session: https://claude.ai/code/session_01X1jMLQTSrCwtzFRS1xeUC6

* count: reframe the comments for this repo, not the fork they came from

Review on #6240 (bee-ghosttrack): five comment blocks were written from the
fork's point of view and become false once merged here — "belongs upstream",
"the half that still has to go upstream", "the fork's old wide default",
and "upstream's default" meaning the current default.

Find-and-replace, as asked: the reasoning is kept, only the frame of reference
changes. "upstream's default" -> "the default before this change"; the bd
list sibling "landed in #6098"; the infra-type divergence is "pinned, not
fixed, here" with the reason; the embedded test's fork-maintenance history is
replaced by what it actually pins. No code changes.

* build(bazel): list the two test files this PR adds in their go_test srcs

Maintainer review fixes for #6240, review iteration 1. The synthesis and the
quality scorecard both returned approve with no required changes; this commit
takes the one minor whose subject is the PR's own added files.

Taken:

- Change Impact / Blast Radius (minor, gate impact minor). The PR adds
  cmd/bd/count_include_ephemeral_embedded_test.go and
  internal/workapi/count_skipwisps_test.go, but neither was listed in its
  package's explicit go_test srcs, so the PR's own assertions were invisible to
  `bazel test`. Both rows are now listed.

  Gazelle's verdict, not a hand-guess: `make bazel-sync` was run (bazel 9.2.0 is
  available here) and it produced exactly these two entries. Its full output
  also rewrote 12 other BUILD.bazel files -- pre-existing base drift from other
  PRs' files, plus dep/select churn -- which is out of scope for this PR, so the
  generated result was reverted and only the two rows this PR is responsible for
  were re-applied, at the slots gazelle chose. Both srcs lists remain sorted
  with no duplicates (cmd/bd bd_test 637 entries, internal/workapi workapi_test
  24 entries).

  The cgo build tag on count_include_ephemeral_embedded_test.go does not exempt
  it: the repo lists tag-gated *_embedded_test.go files anyway (99 of the 101 in
  cmd/bd are listed, and the sampled ones are simultaneously listed and tagged).

Declined:

- Test Evidence Quality (nit, gate impact none). The filing lane itself marked
  it optional and explicitly said not to gate on it, and its own reasoning holds:
  internal/storage/dolt/counts.go and internal/storage/embeddeddolt/counts.go
  both delegate to the same issueops.CountIssuesInTx, differing only in
  transaction acquisition.

Validation: go build ./... and CGO_ENABLED=1 go vet on cmd/bd, internal/workapi
and issueops all clean; go test ./internal/workapi/ ./issueops/ ok. No
production code changed -- the commit is two generated-list rows.

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

---------

Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-29 16:56:23 -07:00
postoso
9017d33745
feat(count): accept --has-metadata-key (#6282)
bd list, bd ready and bd search all take --has-metadata-key. bd count did
not, so counting the rows that merely carry a key meant listing them and
measuring the page. This is the last metadata-filter parity gap between
count and the listings.

The storage layer already carries the filter: types.IssueFilter has
HasMetadataKey and sqlbuild.AppendMetadataClauses consumes it. What was
missing is the role field, the builder wiring, the CLI flag and the HTTP
contract, so this is one change rather than a stack.

Parsing matches list_input.go and ready_input.go, including the key
validation. BuildCountFilter now passes the key to ValidateMetadataFilters
instead of the empty string it passed before, which makes the role's
existing refusal reachable from the count surface; failReadErr already
classifies that error as a 400 on has_metadata_key.

apigen types are regenerated from the spec via go:generate, not hand
edited. The pinned CLI docs are untouched.

Fixes #6160

Co-authored-by: postoso <postoso@users.noreply.github.com>
Co-authored-by: Gas City Adopt-PR <noreply@example.com>
2026-09-29 13:16:37 -07:00
Julian Knutsen
2ec0b2f072
feat(purge): live-dependent protection, --wisps-plane selector, hour-precision --older-than, --limit (#6883)
* feat(purge): live-dependent protection, --wisps-plane selector, hour-precision --older-than

An orchestrator's wisp retention step deletes every closed row in the
wisps table older than N hours, except a closed wisp that an
open/hooked/in_progress wisp depends on through parent-child, tracks or
blocks. `bd purge` could not express that: it selected the ephemeral
TIER (so closed --no-history beads, which live in the wisps table, were
left behind), it deleted a closed molecule root whose step was still
open, and it floored --older-than hours to whole days (36h swept rows
24h old). All three land together so `bd purge --wisps-plane
--older-than 168h --force` covers that step.

Live-dependent protection (issueops.SweepRequest.ProtectLiveDependents,
SweepSkips.LiveDependent): a candidate is held back when a live row
depends on it through a SweepLiveDependentEdgeTypes edge (parent-child,
tracks, blocks), read from both dependency tables. "Live" is the same
not-done set the reference scan uses, custom statuses included, so it
is a superset of open/hooked/in_progress. `bd purge` always asks for it
(no opt-out: removing live work's root is `bd delete`'s job); `bd prune`
does not. Reported as live_dependent_skipped in --json.

Wisps-plane selector (issueops.SweepWispsPlane, `--wisps-plane`): the
candidates are every closed row in the wisps TABLE, whatever its
ephemeral/no_history/wisp_type values, via a new single-plane search
(issueops.SearchWispsPlaneInTx) that the store backends call directly
and the unit-of-work provider reaches through
IssueUseCase.SearchWispsPlane, so embedded, server and proxied share one
body. It reaches durable-tier (no-history) rows, so it carries the
durable tier's require-a-filter gate.

--older-than (purge and prune): day values keep their meaning (7, 7d,
2w); anything else is a Go duration taken exactly (36h, 168h, 90m).

Tests: three new Sweeper contract cases (wisps plane clears the whole
table, wisps plane requires a filter, protects live dependents) run on
dolt, embeddeddolt and the uow provider; workapi unit tests; a CLI
retention scenario run in embedded, shared proxied and managed-local
proxied modes (fails against origin/main); TestParseOlderThan.

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

* test(uow): classify IssueUseCase.SearchWispsPlane as a read in the notifying parity partition

TestRecordingIssueUseCaseCoversItsSurface requires every IssueUseCase
method to be either wrapped by the notifying decorator or exempted with
the reason it fires no hook. SearchWispsPlane reads state and changes
none, like SearchIssues beside it.

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

* fix(purge): refuse out-of-range --older-than; add --limit for bounded drains; cross-plane protection test

Review follow-ups on #6883.

--older-than: a day count past what a time.Duration holds (213504d,
30501w) used to wrap silently — 213504d became 25m26s, which on a
destructive command selected almost every closed row. It is now refused
as out of range; ParseDuration already refused oversized h/m/s values.

--limit N (issueops.SweepRequest.Limit, SweepResult.Remaining): one
purge deletes at most N rows, oldest closed_at first (then id), after
every protection, and reports the rest. --json adds remaining and
has_more when --limit is given. At ~15ms/row on the proxied path a
single unbounded sweep of a large backlog can outlive a caller's
deadline, roll back, and never clear; a bounded loop cannot. Negative
limits are ErrValidation at the role and refused at the CLI.

Tests: TestParseOlderThan out-of-range rows; contract cases
LimitTakesTheOldestClosedFirst and ProtectsLiveDependentsAcrossPlanes
(a live issues-table bead depending on a closed wisp via parent-child,
tracks and blocks keeps it) on dolt, embeddeddolt and uow; workapi
units for the ordering and the negative-limit refusal; the CLI
retention scenario now drains with --limit 1 and checks the overflow
refusal. CHANGELOG notes that sub-day Nh values used to round UP to a
day (12h is now taken exactly) and lists the protection under Changed.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 00:57:24 -07:00
Julian Knutsen
f66375459f
test(bazel): runfiles helpers + declared inputs for scan-guard tests (#6828)
* test(bazel): add internal/testutil/bazeltest runfiles helpers

Repository-path resolution for tests that works identically under plain
go test (package cwd, full checkout), bazel test locally, and remote
execution (declared runfiles only):

- IsBazel, RepoRoot (BEADS_TEST_REPO_ROOT, then the runfiles workspace
  root, then a go.mod walk), OverrideRoot (drop-in condition for existing
  helpers; empty under plain go test), CallerDir
- Runfile for $(rlocationpath) values, GOROOT for type-checking tests
- ShardFreeEnv for helpers that re-exec a test binary

Every helper reduces to the pre-Bazel behavior under go test.

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

* test(bazel): declare source/data reads for 14 scan-guard targets

Source-scanning and repo-file tests read files their Bazel targets never
declared, so they failed under `bazel test` (and could not run on remote
workers at all). Declare narrow inputs as `data` and resolve paths through
bazeltest where the test located the tree via runtime.Caller:

- tools/bazel/go_srcs.py (run by `make bazel-sync` after gazelle) keeps a
  managed `go_srcs` filegroup in the packages whose Go source tests scan,
  plus `//internal/storage:tree_go_srcs` for the storage-tree walk. Bazel
  globs stop at package boundaries, so the aggregate needs one filegroup
  per package; the script keeps it in sync and gazelle-stable.
- Hand-written narrow inputs: //internal/storage/schema:migrations,
  //:docsync_files, //plugins/beads:plugin_files, and exports of
  .gitattributes, .claude-plugin/marketplace.json, cmd/bd list.go and
  ready.go, testutil/testdoltcommon.go, scripts README.md and the release
  catalog, each visible only to its consumer.
- runtime.Caller-based roots in backend, backend/conformance,
  internal/storage, internal/formula and test/docsync now go through
  bazeltest.CallerDir / OverrideRoot; relative-path tests need data only.
- integrations/ leaves .bazelignore (it is still gazelle-excluded) so the
  docsync link check can declare integrations/beads-mcp/PYPI.md.

Under --config=prcore every target reports the same PASS/SKIP/FAIL test
set as `go test -race -short` for its package, locally and remotely.
Plain `go test` behavior is unchanged.

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

* test(bazel): guard generated go_srcs and harden bazeltest root override

- tools/bazel/go_srcs.py: add --check (print diff, exit 1 on stale blocks);
  new `make bazel-sync-check` target runs it.
- scripts/bazel_policy_test.go: under go test, assert every tree_go_srcs
  (//internal/storage) lists exactly the BUILD.bazel packages below its
  root, run go_srcs.py --check, and forbid BUILD files under docs/ and
  engdocs/ (they would cut subtrees out of //:docsync_files).
- bazeltest: honor BEADS_TEST_REPO_ROOT only when it holds go.mod
  (RepoRoot fails loudly otherwise); drop the unused GOROOT() helper,
  whose compiled-in branch could never fire under rules_go.
- scripts/ci/lib/test-env.sh: unset BEADS_TEST_REPO_ROOT.
- Document the hand-listed out-of-tree link targets in //:docsync_files.

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

* build(bazel): re-sync BUILD files with main

Regenerated with make bazel-sync after commits that landed while the
scaffold PR was in CI (new internal/execenv, gitenv, gitignore packages
and new sources/deps).

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

* test(bazel): declare init_safety_help.go for docsync

TestInitSafetyCLIHelpCoversReCloneGotchas (#6431) reads
cmd/bd/init_safety_help.go; export it to //test/docsync only.

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-09-27 08:24:08 -07:00
Julian Knutsen
57ef364501
build(bazel): side-by-side Bazel scaffold + policy tests (#6798)
* build(bazel): add side-by-side Bazel scaffold (module + gazelle)

Add a Bzlmod Bazel build alongside the Go toolchain. `go build` and
`go test` are unchanged; nothing in CI invokes Bazel yet.

- MODULE.bazel: rules_go 0.63.0, gazelle 0.53.0, Go SDK 1.26.7 (matches
  the go.mod toolchain directive), go_deps from go.mod.
- ICU policy (engdocs/ICU-POLICY.md): a go-mysql-server gazelle_override
  selects the pure-Go regex backend and excludes regex_cgo.go, and
  .bazelrc builds with --@rules_go//go/config:tags=gms_pure_go, so no
  target depends on go-icu-regex or links libicu.
- third_party/patches: three module_override patches for dolt deps that
  ship WORKSPACE-era BUILD files, adapted from the gascity project.
- .bazelrc: prcore/ci test configs (inert for now; they match pr-core's
  test selection, not yet its environment isolation) and a generic
  remote-exec config with a bounded remote timeout. Executor endpoints and
  TLS credentials come only from a gitignored .bazelrc.local/user.bazelrc
  or a CI rc outside the workspace.
- .bazelversion pins Bazel 9.2.0; .bazelignore skips separate modules,
  non-Go trees, nested agent worktrees (.claude, .worktrees) and local
  data/output dirs (.beads, .dolt, dist, .runtime, tmp), so a primary
  checkout neither builds nor gazelle-rewrites nested worktree copies.
- Gazelle-generated BUILD.bazel files for every Go package.
- Makefile: `make bazel-sync` (gazelle + bazel mod tidy).
- .gitignore: bazel-* output symlinks and machine-local rc files.

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

* test(bazel): policy tests for the Bazel configuration

Add scripts/bazel_policy_test.go, plain Go tests that run under both
`go test ./scripts` and `bazel test //scripts:scripts_test`:

- MODULE.bazel go_sdk.download version equals the go.mod toolchain.
- ICU policy: .bazelrc sets gms_pure_go for build, the go-mysql-server
  gazelle_override excludes regex_cgo.go, and the root BUILD.bazel
  carries `# gazelle:build_tags gms_pure_go`.
- .bazelversion pins an exact Bazel release.
- .bazelrc.local and user.bazelrc are gitignored (parsed from .gitignore
  and cross-checked with git check-ignore when in a checkout).
- No remote-execution endpoints or credentials in committed bazelrc-like
  files, Markdown docs or .github/**: remote/BES/TLS flags
  (--remote_executor, --remote_cache, --bes_backend, --remote_header,
  --tls_client_certificate, ...) with a literal value, with or without a
  URL scheme, and non-loopback gRPC URLs in rc/.github files. Placeholders,
  $VARIABLES, and loopback are allowed; Markdown gRPC URLs (OTel exporter
  docs) are not flagged. Skipped outside a git checkout, e.g. in the Bazel
  sandbox.

Each check is a pure function also exercised against fixtures that break
the invariant. The files the tests read are declared as data via
//:bazel_policy_files so they resolve from runfiles under Bazel.

scripts/check-build-tags.sh now treats Bazel invocations as governed by
.bazelrc: the shell command segment that invokes Bazel (split on &&, ||,
;, |, $( and backticks) is exempt from the per-line `go` tag check, while
a bare `go` in another segment of the same line is still flagged. When
any scanned file invokes Bazel (or .bazelrc exists) .bazelrc must set
--@rules_go//go/config:tags=gms_pure_go for build.
scripts/check_build_tags_test.go covers both in a temp repository.

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

* fix(scripts): split bazel lines in pure bash so check-build-tags works with BSD sed

BSD sed (macOS) does not expand \n in s/// replacements, so the segment
split never happened and the Bazel-exemption tests failed on macos-latest.

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

* test(scripts): skip check-build-tags tests when bash lacks mapfile

macOS runners use /bin/bash 3.2, which has no mapfile; check-build-tags.sh
has always required bash >= 4, so the new tests are skipped there.

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

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-27 03:41:02 -07:00
mtccressall
d14ed67f71
fix(list): expose comment bodies in bd list/show --json (be-73x) (#6473)
* fix(list): expose comment bodies and mark the omission in bd list --json (be-73x)

`bd list --json` reported comment_count and carried no comment text and no sign
that any was missing. The consequence is not a missing field: a content search
over a listing answers with a well-formed, NON-EMPTY result set whose matching
rows are absent, and nothing about that answer invites a second look. An empty
result invites suspicion; eight rows do not.

Two halves, and the second is the one that fixes what was actually reported:

  1. --include-comments on `bd list` populates each row's comments with the
     full bodies, the list twin of `bd show --include-comments`. Opt-in: it
     costs one query per row that has comments.
  2. Every row with a nonzero comment_count whose bodies were NOT hydrated now
     carries comments_omitted=true, by default, with no flag. A flag nobody
     knows to pass does not fix a silent hole; a marker on the row does.

The bodies ride on types.Issue.Comments, which already carried the `comments`
key for export/import and was simply never populated on this path, so the only
new field is the marker.

Hydration is one shared body (workapi.HydrateListComments) called from BOTH
issueops.Reader.List implementations, the store-backed and the unit-of-work
one. Those are separate bodies that have answered one contract method
differently before; it runs in the page epilogue beside FinishPageAt, after the
trim, so a page never pays for rows it is about to drop.

The source parameter is a CONSTRUCTOR rather than a source, and that is
load-bearing. Building the unit-of-work comment source eagerly made a
capability only the opt-in path uses into a requirement every caller had to
satisfy, and turned `GET /v0/beads/issues` into a 500 on a provider without a
comment use case — on requests that had asked for no comments. A count-only
listing now constructs nothing, pinned by a test that fails if the constructor
is called.

Tests pin each implementation separately rather than duplicating: unit tests
over a fake source, an embedded-dolt test over the real CLI on the direct
route, and a proxied-server test over the real CLI on the unit-of-work route.
Sabotage-controlled three ways — no-op the shared body and all three suites go
red; unwire either reader alone and only that reader's CLI test fails, which is
what proves neither integration test is redundant.

Not addressed, deliberately: gt-mfp5 (bd comment does not advance updated_at,
the orthogonal recency axis) and be-ozp (bd ready --json carries no marker; it
does not route through Reader.Ready).

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XK4B7N2CrgfKGEQvDTPM4D

Executed-By: beadsrig/polecats/dag

* fix(list): do not read a skipped comment count as proof of no comments (be-73x)

Codex review of the parent commit, correctly.

`IncludeComments: true` combined with `SkipCounts: true` returned a page with
no comment bodies at all — no error, no marker, nothing — while
`IncludeComments` documents a guarantee to populate them. The hydration loop
skipped any row whose CommentCount was zero as an optimisation, and SkipCounts
zeroes every count: `issueops.ListRequest.SkipCounts` says in its own doc that
a zero then means UNKNOWN rather than none.

That is this bead's own failure mode reintroduced one layer down by the fix for
it: a silent, well-formed, empty answer to a request that asked for content.

I had considered the interaction and resolved it wrongly, in a comment reading
"the count is authoritative here because the JSON route never sets SkipCounts".
True of today's CLI callers, and not a property of the contract — issueops
.ListRequest is a PUBLIC request type and permits both fields at once. A
comment saying "X cannot happen because of how callers behave today" on a
public type is a bug with a justification attached, and worse than no comment,
because it tells the next reader the case was checked.

countsKnown is now a parameter rather than an assumption; call sites pass
!req.SkipCounts.

  countsKnown true   a zero count proves a row has nothing; skip its query.
  countsKnown false  query every row, because nothing proves otherwise, and
                     mark no row omitted, because comments_omitted asserts a
                     nonzero count the page cannot support.

The second half is the mirror defect on the marker path — the same conflation,
the other direction — which the review did not name.

No behaviour change on any current CLI path: the JSON route never sets
SkipCounts, so it passes countsKnown true, and the text route asks for no
comments and marked nothing before either. Verified: `bd list --json` output
identical, and text output identical with and without the flag.

Regression tests HonorsIncludeWhenCountsAreSkipped and
MarksNothingWhenCountsAreSkipped. Sabotage-controlled: restoring the
count-authoritative skip fails the first with "issued 0 comment reads, want 2".

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XK4B7N2CrgfKGEQvDTPM4D

Executed-By: beadsrig/polecats/dag

* fix(list): resolve the comment plane by residence, not by the row's flags (be-73x)

Maintainer review fixup for #6473, iteration 1. Both review lanes reached the
same major independently and the synthesizer re-verified it against the tree.

The new list hydration derived the comment table from the row's own
Ephemeral/NoHistory flags - issueops.IsWisp's rule, which is right for routing a
record being WRITTEN and wrong on a read. `bd import` pins a `no_history` record
to the DURABLE table while preserving the flag on the row, because clearing it
would change the content hash and break export->import->export byte-identity,
and every clone materializes its database by importing JSONL. So a promoted
no-history bead that has been through a round-trip is a durable row whose flags
say wisp:

  bd list --json --include-comments   read wisp_comments, found nothing, and
                                      returned comment_count=N beside an empty
                                      `comments`, with no marker and no error
  bd comment, bd show                 write and read that same row's comments on
                                      the issues plane, by found-table

That is be-73x's own failure mode reintroduced under the flag whose contract is
"gets them or gets an error", and a cross-role divergence: `bd list` and
`bd show` disagreed about one row. The mirror case is real too - an import
record whose `wisp_plane` key pins it to the wisps table with neither flag set
reads back as durable - so no flag-based rule gets both directions right.

The plane now comes from the seam that knows it. HydrateListComments takes a
CommentPlanes lookup instead of inferring; the unit-of-work reader answers it
from the wisps TABLE (IssueUseCase.GetWispsByIDs, the call edgeReader.ReadEdges
already makes for the same question), once per page, inside the page's own read
transaction. The store-backed seam passes SourceRoutesCommentPlanes because its
source routes ids itself (DoltStore.GetIssueComments picks the table from
isActiveWisp) and would buy a lookup for an argument it ignores. isWispPlane is
deleted: nothing on this path infers a plane any more. A nil lookup is an error
rather than a silent "durable", so a third seam has to answer the question
rather than inherit the default this bug was.

A MISSING WISPS TABLE STAYS "NO WISPS" rather than a failed listing, classified
through the same two helpers the counts query that produced the page uses
(dberrors.MissingTableName + sqlbuild.OptionalWispTable). Any other failure of
the lookup fails the call: a guessed plane answers with the wrong table's
contents and nothing in the response shows it.

Tests. The unit table now asserts residence AGAINST the flags, with each row's
comments present only on the plane it lives on, so a wrong-table read shows up
as missing TEXT and not merely as a wrong flag in a recorded call. Restoring the
flag inference reds exactly the two rows where flags and table disagree
(durable-carrying-no_history, wisp-table-carrying-no-flags) and leaves the two
agreeing rows green. The old `override_wins_over_flags` case is gone:
WispPlaneOverride is `json:"-"` and set only by import, in memory, so no scanned
row can carry it and that branch was unreachable on this path - which is what
made the suite look sufficient (Codex's separate minor, folded in here as the
same root cause). New seam-level tests drive the real uow Reader.List over both
shapes, and pin that a listing without the flag resolves no planes at all, that
a missing wisps table is tolerated, and that any other lookup failure
propagates; emptying the residence answer reds the wisp-row leg.

Also from the review, non-gating:

- types.IssueWithCounts.CommentsOmitted and the OpenAPI property stated the
  marker rule unconditionally on a type Reader.Ready and the claim response also
  return, neither of which calls the epilogue. Both now scope the rule to the
  List surfaces and cite be-ozp, which is where the parent commit deliberately
  left the ready surfaces. (`bd ready --json` does not route through
  Reader.Ready; GET /v0/beads/ready and ClaimNextResponse.claimed do.)
- GET /v0/beads/issues gained no `include_comments` parameter, so its
  description now says so and points at the detail read, in the idiom the
  `revision` paragraph above it already uses.
- One internal/httpapi list test for the new wire field: the marker present for
  a commented row, absent for an uncommented one. It was asserted only by the
  spec file; the detail twin has get_issue_test.go. Neutering
  markCommentsOmitted reds it.

Validation: go build ./...; go vet over the changed packages and again with
CGO_ENABLED=0; make api-check clean, so the spec edits oblige no regeneration;
go test ./internal/workapi/... ./issueops/... ./internal/types/;
TestBothReaderImplementationsAgreeOnTheListEpilogue plus the new plane tests in
./internal/storage/uow/; BEADS_TEST_PROXIED_SERVER=1
TestProxiedServerListComments 3 PASS and BEADS_TEST_EMBEDDED_DOLT=1
TestEmbeddedListComments 4 PASS.

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

---------

Co-authored-by: Julian Knutsen <julianknutsen@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-27 02:12:13 -07:00
Julian Knutsen
a1bc167b54
fix(ready): keep the ReadyCounter span through externaldeps, and announce the interface break (#6748)
Maintainer review fixups for #6731. The review found no blocker and no major;
these are its two gate-impact minors plus two nearby nits.

- externaldeps.Store.ReadyCounter built a fresh store-backed counter, so the
  documented storage.ReadyCounter.CountReady span stopped being emitted for
  every text-mode `bd ready` in the cmd/bd chain (hooks -> externaldeps ->
  telemetry -> store). PR-introduced: at base this decorator had no
  ReadyCounter at all, so the embedded passthrough reached the instrumented
  layer -- and this PR edits the very otel document that lists the span. The
  accessor cannot simply recurse, because the exclusions live on this store, so
  it now hands the finished counter to the inner store's WrapReadyCounter,
  which telemetry already exported for exactly this case and had no caller for.
  Pinned by TestExternalDepsReadyCounterSurvivesThisLayer, which fails with the
  old body (verified by reverting it).

- CHANGELOG: GetReadyWorkWithCountsAndTotal is a new REQUIRED storage.Storage
  method with no optional-interface fallback, so an out-of-tree `backends`
  registrant stops compiling on upgrade. The entry names the method, the
  contract an implementer owes, and why the compile-time posture is deliberate.

- The ready probe's facts now record each index as its column is appended.
  Two conditional columns were read back through a mix of literals and a
  computed `next`, so the two conventions disagreed inside one function and a
  future column inserted above would silently mis-read a different fact.
  Behavior-identical; the four excludeDeferred x wantCollision combinations are
  covered by the embedded filter matrix.

- The combined family count wraps as `count ready work: issues+wisps:`, so it
  is distinguishable from the issues-only retry beneath it, and
  storereadycounter's package doc no longer claims only two importers.

Validation: go build ./...; go vet and go test on issueops, externaldeps,
telemetry; BEADS_TEST_EMBEDDED_DOLT=1 TestReadyWorkPageTotal,
TestReadyWorkPageTotalFilterMatrix, TestReadyWorkStatementBudget
(embeddeddolt) and TestEmbeddedReady (cmd/bd).

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-25 13:53:47 -07:00
Julian Knutsen
b3d17caa6d Merge release/1.3.0 into main (post-tag forward-port)
Forward-ports the 38 commits that shipped on release/1.3.0 (tagged v1.3.0 at
f45b249ce) into main, as RELEASING.md mandates after a tag. None of them had
ever been forward-ported. Recorded as a merge so main becomes a superset of
the release branch and the lineage is in the history.

Migration ordinal collision (the reason this needed a human-shaped merge):
both branches independently claimed clone-local ignored slot 0026 under
different filenames, so git merged both in with no conflict and left the
series with two migrations at ordinal 26 — a single-integer cursor cannot
address that, and migrationSource.list() panics on it.

Main's ignored/0026_add_wisps_current_revision is renumbered to 0027.
Release's 0026_dep_rekey_dedup_marker is in the shipped v1.3.0 tag, so field
stores have already recorded it at 26 and it can never move; main's twin has
never shipped in any release, so it is the one that is free to move. 0027 was
unused in the ignored series (both sides topped out at 26).

This trips check-migration-hygiene.sh Check C (frozen migrations), which has
no exemption mechanism. That is expected and accepted: breaking the collision
requires a rename, and the ignored series' cursor table is itself dolt-ignored,
so its content hashes are clone-local and never participate in the cross-clone
ContentHashSkew comparison that Check C exists to protect. Main's 0067 body is
deliberately NOT edited for the same reason in reverse — it is main-plane and
its hash IS compared across clones.

Conflicts resolved:

  CHANGELOG.md                       release's finalized [1.3.0] section kept
                                     byte-identical; main's two unreleased
                                     entries (#6023, #5859) moved up under
                                     [Unreleased] where they belong
  cmd/bd/init_safety.go              union — release's added paragraph is
  cmd/bd/init_safety_help.go         accurate against the merged code (three
                                     exit-12 sources, incl. init.go:3147)
  internal/storage/uow/dolt_sql_provider.go
                                     kept main's newProvider refactor AND
                                     release's readOnly field/assertion;
                                     newProvider gained readOnly: opts.readOnly
                                     so release's read-through-refused-migration
                                     behavior survives main's refactor
  .github/workflows/main.yml         single -timeout=30m per release's #6091
  scripts/ci_workflow_test.go        design (flag on the invocation, not in
                                     matrix.test-flags); the shadowed 25m in
                                     matrix.test-flags removed
  scripts/migration-test/lib/versions.sh
                                     union — main's darwin/arm64 corpus plus
                                     release's v1.2.2 linux/amd64 entry
  integrations/beads-mcp/uv.lock     ruff 0.16.5 (release, newer); block is
                                     internally consistent, uv lock --check ok
  default.nix                        vendorHash left at main's value and is
                                     KNOWN STALE — see below

Version stamp lands at 1.3.0 (main had been sitting at the previously-released
1.2.2, this project's between-releases pattern). check-versions.sh: 24/24.

Known follow-up: default.nix vendorHash. The merged go.mod/go.sum is a genuine
union (release's kin-openapi/oapi-codegen bumps + main's newer Dolt stack) and
matches neither side, so neither recorded hash is correct. It must be
regenerated with scripts/update-nix-vendorhash.sh. The repo's automatic fixer
(update-vendor-hash.yml) is dependabot-only and will not run on this PR.
2026-09-15 22:09:13 +00:00
Vishnu J
f5a20fb66b
fix(list): honor --status when combined with --ready (#5924)
* fix(list): honor --status when combined with --ready (#5832)

`bd list --status X --ready` silently dropped --status and returned the
unfiltered ready set (typically open issues). BuildListFilter pinned
StatusOpen whenever ReadyFlag was set, and ReadyFilterFromIssueFilter
hard-coded the same pin, so a custom status or in_progress selector
never reached GetReadyWork.

--ready without --status still defaults to open. An explicit --status
is now the ready-work status selector, matching how other list filters
already compose with --ready. `--status all` remains the no-filter
spelling and keeps the open default.

* fix(list): status-aware --ready footer and honor-path contract docs (#5832)

The query intersection from the prior commit is unchanged. Round-1
review asked the ReadyFlag/Statuses contract comments and the text
footer to describe the honor path: default --ready is still open,
an explicit --status is named instead of "excludes in_progress".
2026-09-02 18:12:07 -07:00
postoso
267085264d
feat(count): support --metadata-field filtering (#6024)
* feat(count): support --metadata-field filtering

* fix(count): review refusal docs, guard test, and changelog

---------

Co-authored-by: postoso <postoso@users.noreply.github.com>
2026-09-02 17:25:57 -07:00
Denis Redozubov
5f56ab2a53
fix(deps): enforce external capability blockers across ready/claim/close (#4769) (#4753)
External (cross-project) dependency blockers are now enforced everywhere a bead's readiness or closability is decided: `bd ready` / `--claim`, `bd blocked`, `bd close` / done-status `bd update` (direct and proxied), `bd dep tree`, and served HTTP ready/claim. The policy is a storage-boundary decorator (`internal/storage/externaldeps`) applied on both the DoltStorage chain and the UOW provider, with full capability-forwarding parity, `Unwrap` at every level, and the backend's advisory defer-wake preserved on the claim path.

Review trail: maphew rounds 1–4 (Jul–Aug), bee rounds 1–4 (Sep 2): D1 recording-parity exemption, D2 ready-filter goldens, D3 UOW-level Unwrap for the proxied importer, D4 claim-path defer wake. Verified at head 3468d62f on a clean merge with current main; CI fully green at that head.

Fixes #4769.
2026-09-02 16:56:23 -07:00
Julian Knutsen
b858a29e4a
fix(contracts): JSON contract fixes before 1.3.0 freezes them — string revision tokens, --set-metadata scalar typing, create --json nano timestamps (#6053)
* fix(metadata): restore v1.2.2 scalar typing for --set-metadata values

8ebd53e88 moved the CLI's metadata-edit helpers into
internal/storage/metadata.go and, in the move, replaced v1.2.2's
toJSONValue inference with a MetadataEditValue that always json.Marshals
the value as a string. The intent was GH#4146 (a numeric-looking id or a
version like "1e3" came back as a JSON number, breaking map[string]string
Go consumers), but it silently changed the shipped CLI contract:
`bd update --set-metadata k=5` started storing "5" instead of 5. That
regression shipped only in the deprecated/superseded v1.2.1, never in
v1.2.2, and 1.3.0 would freeze it.

Restore v1.2.2's inference body-for-body inside MetadataEditValue, so the
parity claim stays checkable against `git show v1.2.2:cmd/bd/update.go`:
"null" is JSON null, "true"/"false" are booleans, a spelling that scans
as a float AND is valid JSON on its own is emitted as that literal
(5 -> 5, 1e3 -> 1e3, 0.50 -> 0.50, while 05, +5 and NaN stay strings),
and everything else is a string. Every --set-metadata caller funnels
through this one function: embedded (cmd/bd/update.go ->
storage.ApplyMetadataEdits), proxied (parseSetMetadataFlags) and the
update executor's []string path.

GH#4146's concern is served by the explicitly typed routes, which are
untouched: --metadata / --metadata-json on the CLI (MergeMetadataJSON)
and the typed set map on the HTTP/Go path (applyTypedMetadataEdits).

No data migration: a "5" written by an in-window build is
indistinguishable from a string a user set intentionally through the
typed paths, so normalizing stored metadata would corrupt intended data.
Re-running the same --set-metadata k=5 retypes any given key.

Tests: new table in internal/storage/metadata_edit_value_test.go pinning
the v1.2.2 matrix plus an ApplyMetadataEdits end-to-end; the tests that
pinned the string-always behavior are flipped (domain/db mergeops suite,
update_lifecycle patch mapping, cmd/bd toJSONValue table) and the
embedded + proxied CLI suites now assert a stored JSON number. The
contract corpus is regenerated: its update/list/ready goldens run
`--set-metadata phase=2`, so `"phase": "2"` becomes `"phase": 2` and
nothing else moves.

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

* fix(create): echo full-precision timestamps from bd create, not the DATETIME(0) re-read

b92442d1a routed `bd create` through issueops.Lifecycle, whose executors
build their result by re-reading the row they just wrote
(HydrateIssueOperationResult -> GetIssueInTx). created_at/updated_at are
DATETIME(0) columns, so that snapshot comes back at whole-second
precision and cmd/bd/create.go echoes it. v1.2.2 returned the caller's
own in-memory struct, which PrepareIssueForInsert stamps with
time.Now().UTC() including nanoseconds, so `bd create --json` used to
print e.g. 2026-08-28T12:34:56.789012345Z. Agents that create several
issues in a burst order them by exactly that fraction; rounded to the
second they all tie.

Restore the echo with OverlayCreateTimestamps: after hydration, put back
the created_at/updated_at (and closed_at, when the write set one) the
INSERT actually sent. Everything else on the snapshot stays DB-truth,
which is the facade's contract — only create, and only these fields.

Applied at every create body, not just the two the CLI reaches:
issueops.ExecuteCreate and ExecuteCreateBatch behind the dolt and
embedded-dolt stores, and the unit-of-work provider's own Create,
CreateBatch and batch-apply create item, which is what the proxied server
and POST /v0/beads/issues run on. Fixing only the shared executors would
have left the two bodies disagreeing about the same promise.

What is NOT changed, because it is not a regression: `bd show --json` and
`bd list --json` answered whole seconds in v1.2.2 too — they read the
column — and update/close/reopen re-read after writing there as well.
Widening the columns to DATETIME(6) would give reads sub-second times
too, but that is a schema migration on user Dolt DBs and touches paths
that deliberately compare at second precision; it is a 1.4 change.

The accepted skew, which predates this and stays: the engine ROUNDS to
the column rather than truncating, so a later read of the same row can
sit up to half a second either side of the create echo.

Tests: two new conformance cases, run on all three backends —
RunLifecycleCreateEchoesSubSecondTimestamps (a caller-supplied
nanosecond stamp must survive to the result exactly; the auto-stamped arm
stays a bounded smoke check, since requiring a non-zero fraction off the
clock is flaky by a billionth) and RunBatchCreatorEchoesSubSecondTimestamps
(per item, since both bodies build the result one snapshot at a time).
Plus a cmd/bd embedded test asserting `bd create --json` prints a
fractional part, and one httpapi assertion that the wire does not round
the role's snapshot on the way out. All four fail on the pre-fix tree.

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

* fix(httpapi,types)!: revision / expected_version tokens are opaque JSON strings

The optimistic-concurrency token is minted by freshRowLock over the FULL
int64 range (crypto-random, non-zero) and published on the wire as a JSON
number: `revision` on responses, `expected_version` on guarded requests.
A JSON number does not survive a consumer that decodes into an IEEE-754
double — JavaScript's JSON.parse, Go's `any`, Python's `float`, jq. Live
tokens run past 5e17, where a double's ulp is already 64, so such a
client reads back a value NEAR the token, echoes that as its guard, and
earns a 409 against a row nobody else touched. The spec already carried
"DECODE IT AS A 64-BIT INTEGER" paragraphs telling clients to work around
this; that is a workaround for a wire type that should not have been a
number.

Emit and accept the token as a decimal STRING instead. It is documented
as opaque and EQUALITY-ONLY — compare it, never order or interpret it —
and a string round-trips exactly in every JSON consumer. It also leaves a
future backend free to mint a token that is not an int64 at all.

Internals are untouched: freshRowLock, the row_lock BIGINT column, its
migration, types.Issue.RowVersion and the ExpectedVersion *int64 guards
on the issueops requests all stay int64. Only the wire projection moves,
through the one spelling of the encoding — types.RevisionToken and
types.ParseRevisionToken.

STRICT STRING ONLY, with no transitional number-or-string acceptance.
This API already refuses unknown members by name and keeps one spelling
of the guard, and a number is precisely the shape a double-based client
has already rounded before it left the client — accepting it would
preserve the defect. A numeric guard is a 400 naming the member.

Chosen over clamping freshRowLock to 53 bits: a clamp does not fix rows
already minted with full-range tokens by in-window builds, so a JS
consumer reading one still rounds past 2^53 — repairing that would need a
row_lock normalization sweep over issues and wisps, a migration days
before a tag.

Surface: types.IssueDetails.Revision (what `bd show --json` prints and
GET /v0/beads/issues/{id} returns), the five hand-assigned httpapi
response fields, applyVersionGuardMember (now the reader for the batch
update item too, ahead of its typed decode, so a mistyped token still
earns a 400 naming the member), Problem.expected_version, and 14 OpenAPI
members regenerated through `make api-gen`. actual_version goes with them
— it is documented as "the `revision` the row was found holding", so
leaving it an integer would make the expected/actual pair disagree about
its own type; it is declared but never populated, so nothing changes
behaviorally.

Nothing shipped in a tagged release ever carried this member: v1.2.2 has
no internal/httpapi at all and no `revision` anywhere on the wire, so the
whole surface is in-window and can still be changed compatibly. Legacy
migration-0054 rows read as the string "0" with the same CAS semantics.

Corpus goldens are UNCHANGED: the canonicalizer already replaced any
`revision` value with the string "<REVISION>" whatever its JSON type.

Tests: types-level pins that the marshaled member matches `"revision":
"-?\d+"` and that RevisionToken/ParseRevisionToken round-trip MinInt64,
MaxInt64 and 2^53+1, plus a JS-realistic decode of 2^53+1 with a float64
control proving the token really is one a number would corrupt; httpapi
refusal tests for a numeric guard on update, close, reopen, delete and
both batch item kinds; a 409 echo asserted as the string; and the proxied
serve integration tests now splice the response's own token back in
verbatim rather than re-rendering a parsed one.

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-29 05:20:27 +00:00
Julian Knutsen
8aaefe2d4f
feat(httpapi): serve bd list's order with sort on listIssues (#5666)
* feat(httpapi): serve `bd list`'s order with `sort` on listIssues

The issue listing served one order, `(created_at DESC, id ASC)`, because the
cursor is a keyset position in it. The spec stated the constraint in its own
words: "the sort order is welded to the cursor contract, and a new order needs
new surface." That welding put the cost on every client wanting `bd list`'s
ordering — the only way to get it was to page the whole result set and sort
locally, which is the one cost on this surface that grows with the project.

Measured against a real `bd serve` over 1400 rows at the 200-row page an HTTP
client actually uses: walk-and-sort is 7 requests plus a client-side
comparator, `?sort=priority` is 1. Both are checked against `bd list --json`
row for row, because the claim that matters is not "fewer requests" but "the
same order".

`sort` takes `created` and `priority` and nothing else. Each value is a keyset
contract — a position shape, a strictly-after predicate, an index — not a
display preference, and both keys are provably total (priority and created_at
are non-null, id is unique) so a page boundary inside a run of equal keys
resolves on id. The seven other orders `bd list --sort` takes have no such key:
`id` is natural-numeric and no database expresses it, `updated` moves on every
write, `closed` is nullable, and status/title/type/assignee are mutable and
unindexed. `priority` here is (priority ASC, created_at DESC, id ASC), which is
both `bd list`'s flagless order and what `--sort priority` produces — a stable
priority sort over the created order is the same sequence — so one served order
retires the walk for both.

Absent `sort` still means `created`, permanently: it is the compatibility
contract for every client written before the parameter existed.

THE CURSOR NOW CARRIES ITS ORDER. This is the half that makes the parameter
safe rather than merely useful, and the obvious implementation gets it wrong.
The token was base64 of `{t,i}` with no binding, so a created-order cursor
replayed under `sort=priority` decoded perfectly and was read as a position in
a different total order — a page that skips and duplicates rows, served with a
200, undetectable by the client. Tokens are now `v2` with an explicit order
member, and decode takes the wanted order as a parameter so a mismatch is
unrepresentable at the seam rather than merely detectable past it. Outstanding
`v1` tokens stay readable as the created-order positions they are, so no
traversal in flight has to restart. This does not contradict "the token carries
no filters": filters select the set, the order decides what the position means.

Storage grows one field. IssueFilter.AfterPriority extends the existing
position; the predicate nests the created one rather than restating it, because
the created/id comparison is only reachable at the cursor's own priority.
Flattening it the way the created predicate's leading-bound trick invites looks
equivalent and is not — it re-delivers rows at the cursor's priority created
after it, which the new conformance walk catches against real Dolt.

NO INDEX MIGRATION, by measurement rather than by omission. A composite
(priority, created_at, id) index was tried on Dolt 2.2.0 against the production
predicate, in both the plain ascending and the mixed-direction spelling Dolt's
DDL accepts: the plan is byte-identical in all three cases, keeping the
single-column priority seek and the TopN. It would have bought write
amplification on every insert and every priority update for no measured change.
The sargability guard pins what is achieved — an IndexedTableAccess range on
idx_issues_priority — and records the measurement to redo if Dolt learns to
stream the composite.

Agent-Signature: claude-opus-5
Co-authored-by: CI Bot <ci@beads.test>

* fix(changelog): drop leftover diff3 conflict marker in sort entry

The rebased adopt-PR head left a stray '|||||||' merge-base marker on the first line of the new `sort` CHANGELOG entry (CHANGELOG.md:381), which `git diff --check` flagged as a leftover conflict marker. Remove only the marker line; the resolved entry content is unchanged. Maintainer fixup for PR #5666 adoption review.

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

---------

Co-authored-by: CI Bot <ci@beads.test>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-27 09:21:12 -07:00
Bee
8301974ecd
fix(sweep): purge/prune select candidates by tier — a typed wisp is ephemeral however it was minted (#5995)
* fix(sweep): select purge/prune candidates by tier, not the raw ephemeral flag

A typed wisp minted without the ephemeral flag was invisible to bd purge:
the candidate filter matched ephemeral=1 alone, and the Ephemeral=true
search route only looks at the wisps plane — so legacy typed wisps in the
issues table (858 rows / 7.3 MB in one production DB) survived every sweep
that existed to delete them, while still reporting 'No closed ephemeral
beads to purge'.

IssueFilter gains EphemeralTier: ephemeral-tier is ephemeral=1 OR a
non-empty wisp_type; the durable tier is the complement, so bd prune stops
silently owning rows purge should. The field deliberately does not take
the wisps-plane-only fast path — a tier query merges both planes, because
the rows that motivated it live in the issues table. NoHistory beads
(wisps plane, ephemeral=0, no wisp_type) stay durable-tier (GH#3649).

The list/ready golden filters gain the new field as null.

* fix(create): a wisp_type implies the ephemeral tier at mint

All three create paths (ExecuteCreate, the batch body, and the dolt
store's own createIssue routing) now infer ephemeral from a non-empty
wisp_type, the same way they already infer it from a configured infra
type — so no new mints produce the flag-less typed-wisp shape the sweep
fix has to catch. NoHistory keeps its own retention mode, as before.

* test(dolt): pin the tier boundary on the legacy typed-wisp shape

Three cases: a manufactured issues-plane row with wisp_type but no
ephemeral flag is taken by the ephemeral sweep and left by the durable
one; a NoHistory bead stays durable-tier; and a create carrying only a
wisp_type lands in the wisps plane marked ephemeral. The first and third
were verified red against their halves of the fix reverted.

* test(sweep): conformance tier-boundary cases + the remaining mint sites

Adds two cases to the sweeper conformance kit, wired in all three backends:

- RunSweeperTreatsALegacyTypedWispAsEphemeralTier — the row shape that
  motivated the fix: a closed issues-plane row carrying wisp_type but not
  the ephemeral flag (858 such rows / 7.3 MB survived every purge in one
  production DB). Manufactured with a raw UPDATE through a new optional
  Exec fixture hook, because every current create path now infers the flag.
- RunSweeperLeavesNoHistoryBeadsToTheDurableTier — the other edge: a
  NoHistory bead (wisps plane, ephemeral=0, no wisp_type) is durable-tier
  (GH#3649) and must survive the widened ephemeral sweep. Seeded through
  CreateWisp because plane routing of NoHistory is the create verb's
  concern and the uow kit's CreateIssue calls the domain-level create.

Also carries the wisp_type→ephemeral mint inference to the five remaining
create sites (uow issue_operations/batch_creator/batch_applier,
embeddeddolt create_issue) and slims the dolt-local typed-wisp test to the
mint case now that the sweep half lives in the conformance kit.

Verified: TestSweeperContract green on dolt (91s), uow (87s), and
embeddeddolt with BEADS_TEST_EMBEDDED_DOLT=1 (76s, 13/13 subtests, no
skips).

* test(sweep): dispatch the two new sweeper cases in roleContractCases

The conformance package's own coverage tripwire
(TestRoleContractCasesCoverEveryContractCase) failed in CI: a role contract
case that no roleContractCases row dispatches is invisible to an external
backend running RunRoleContracts. The legacy typed-wisp case still skips
cleanly on a bundle whose SweeperFixture carries no Exec hook.
2026-08-27 05:06:50 -07:00
Stephanie Jarmak
7e825441b4
feat(workapi,storage): opt-in Brief projection for the list and ready pages (#5554)
STORAGE LAYER ONLY, per CONTRIBUTING_PR_GUIDELINES.md. issueops.ListRequest
and issueops.ReadyRequest gain Brief; no CLI flag and no HTTP parameter sets
it yet, so no front door's payload changes. The wiring stacks on top.

WHAT IT DROPS is the free-form text: description, design, acceptance_criteria,
notes, payload and waiters are not selected, and the row comes back carrying
types.Issue.IsLitePartial. #5546 measured a 16,051-issue store where
`bd ready --json` returned 454,021 bytes and notes plus description were 76% of
it, on the call an agent makes to decide what to work on. Measured through
issueops.Reader on 100 rows sized from those per-row ratios: 362,301 bytes
full, 24,001 brief, a 93.4% reduction.

THE PRIMITIVE WAS HALF-BUILT AND UNREACHABLE. #3906 landed
types.IssueFilter.Lite, IssueSelectColumnsLite, HeavyDropList,
ScanIssueLiteFrom and Issue.IsLitePartial, then wired filter.Lite into exactly
one place: SearchIssuesInTx, the UNCOUNTED store-backed search. Every read that
answers with IssueWithCounts, which is every --json route of both commands,
both implementations of issueops.Reader, and both HTTP reads, runs the counts
mega-query instead and ignored the field. A request that set it would have come
back correct, fully hydrated, and with nothing on it to say the projection had
not happened. That silent no-op is what this closes.

THE APPLICATION POINT IS THE COUNTS MEGA-QUERY, and it is one point rather than
four because sqlbuild.SearchCountsSQL and issueops.ScanReadyWorkRowWithCounts
are already the pair every counted read passes through: the store seam's list
(search_counts.go) and ready (ready_work_counts.go), and the unit-of-work
seam's list (issue_search_counts.go) and ready (ready_work_union.go, via
fetchCountsByIDs). sqlbuild.CountsHydration is already the value that carries
hydration opt-outs across that pair on both seams, so Lite is a third field on
it rather than a new channel.

IT CHANGES THE PROJECTION'S SHAPE, which SkipLabels and SkipCounts do not, and
that is why ScanReadyWorkRowWithCounts now takes the whole hydration instead of
a bool: the value that chose the SELECT list is the value that drives the scan,
so the two cannot be given different answers. Substituting empty strings in the
heavy positions would have kept one scan path and was rejected, because the row
would carry blank text with IsLitePartial=false, which is indistinguishable
from a genuinely textless row, the ambiguity ga-clgh and CommentsOmitted
already record.

WHERE IS INDEPENDENT OF SELECT, so this bounds the size of a row and never
which rows match: DescContains, NotesContains and EmptyDesc keep selecting
exactly what they select today, and no sort key, keyset cursor or wisp-merge
dedup reads a dropped column (CompareIssuesBy orders on nine fields, none of
them heavy).

THE CLAIM REFUSES IT, which is not the same call the page makes and is the
sharper case of the rule Limit and Offset already state. A claim does not read
its row through the page's query at all: ExecuteClaimNext refetches the winning
row whole with GetIssueInTx and hydrates its counts itself, so the projection
has nothing to apply to. Accepting the field would answer a MUTATING request
with a fully hydrated row carrying IsLitePartial=false, the caller's one signal
that it did not get what it asked for, reporting that it did. The check lives
in issueops.ValidateClaimNextRequest, which is the shared rule both ready
claimers and BatchCloser's claim already run, so all four backends refuse it on
the same line.

BuildReadyCountFilter CARRIES it, which is the opposite treatment and the
opposite reason. A count reads no field of any row, so the projection cannot
make the number wrong, and the count is not always cheap enough for that to be
the end of it: the unit-of-work seam has no COUNT(*) over the ready predicate
and sizes the set by running the unbounded page and taking its length
(uow/ready_counter.go), so dropping the field there would hydrate every heavy
column of the whole ready set to answer `bd ready --brief`, a larger read than
the page it was asked for. Carrying it also keeps that builder what its doc
says it is: the listing's filter with the PAGE removed and nothing else.

TWO ASYMMETRIES on the page path, both deliberate and both stated in code:

  - Brief IS carried onto the --ready arm (ReadyFilterFromIssueFilter) where
    SkipLabels and SkipCounts are dropped. Those two hide a number the ready
    renderings print; this drops a body no listing prints, so carrying it is
    what makes `bd list --ready` and `bd ready` answer one request one way.
  - types.WorkFilter carries Lite and neither of the other two, so the ready
    paths get readyHydrationFor rather than hydrationFor. Before this, both
    uow ready call sites passed a hardcoded CountsHydration{}, a literal that
    could not carry a filter's answer at all, which is how that path would have
    been missed.

CONFORMANCE at all four registered sites, one Test per case, for the two page
cases and for the claim refusal. Every field the cases assert stripped is
seeded heavy first and the premise is checked, so a backend that never
round-trips one of the six fails loudly instead of turning that clause into one
that cannot fail. Identity is asserted too (ID, Title, Status, IssueType,
Priority), or a body that stripped the row to its id would satisfy every
emptiness clause. IsLitePartial is asserted in both directions.

THE LITE COLUMN LIST IS PINNED BY ORDER, not only by membership. Both lists are
scanned positionally, so two columns of the same SQL type can be transposed
with no membership change at all: the pre-existing set-based parity test stays
green, the scan succeeds, and every row silently carries one column's value in
another's field. TestIssueSelectColumnsLite_IsFullMinusHeavyInOrder derives the
expected list by deleting HeavyDropList from IssueSelectColumns in place, which
makes the lite list a derivation rather than a second hand-maintained copy.

RED BEFORE GREEN, five sabotages, each verified and reverted:

  - deleting the lite branch from CountsHydration.IssueColumns fails both page
    cases with "expected 58 destination arguments in Scan, not 52";
  - accepting Brief without plumbing it to either filter, the silent no-op this
    change exists to close, fails both page cases on all six text fields and on
    IsLitePartial, which is the run that proves the assertions are
    load-bearing;
  - transposing created_by and owner in IssueSelectColumnsLite fails only the
    new order test, on IssueSelectColumnsLite[9] = owner, want created_by,
    while the set-based test stays green, which is the gap it was added for;
  - dropping the claim's refusal fails the claimer contract with "ClaimNext
    with brief: error = <nil>, want ErrValidation"; and
  - clearing Brief in BuildReadyCountFilter fails
    TestBuildReadyCountFilterIsTheUnboundedReadyFilter, which already existed to
    catch a ReadyRequest field the count builder forgets to carry and gains
    Brief in its fixture here.

The recorded ready-filter golden gains "Lite": false in 62 cases because
types.WorkFilter gained the field and the test compares marshaled JSON
byte-for-byte. False is what a request that did not ask for the projection
resolves that field to, so the replay stays exact; the test comment says so.

Gates: go build ./..., go vet ./..., gofmt, internal/storage/... (dolt,
embeddeddolt with BEADS_TEST_EMBEDDED_DOLT=1, uow, issueops, sqlbuild,
domain/db), internal/workapi/..., backend/conformance/..., issueops/...,
make api-check.

Refs: #5546, #3906

Co-authored-by: sjarmak <t@t.co>
2026-08-10 10:45:23 -07:00
Julian Knutsen
ff75b45c91
docs: the ext-api-store documentation tranche — post-#5516 auth sweep, wave doc coherence, role checklist refresh (#5545)
Three beads (ga-uwix0.1, ga-2yaqp.5, ga-2yaqp.6) plus a fable review round.
Docs and spec prose only: all 19 touched .go files are gofmt-normalized,
comment-stripped byte-identical to main. The one exception is deliberate and
reviewed — scripts/check_doc_freshness_test.go gains a data row, because the
delegated gate ruling required it.

ga-uwix0.1 — #5516 gave bd serve optional bearer auth and made it MANDATORY
beyond loopback; fifteen prose sites still said the opposite. The three the
council named are reworded to the stronger true form (the actor is not the
authenticated principal even where a bearer is required; a shared token admits
a client to the WHOLE surface and grants no narrower right). The sweep for a
fourth found eight more in five spellings the audit's grep could not reach,
including claim.go's "any client can claim as any name", release.go's
no-AUTHORIZATION variant, and six memory/settings-plane sites where the true
statement is sharper: a bearer decides WHO may call, never what a caller who
is let in may read. The review round found four more in the CHANGELOG's
UNRELEASED section, which round one had misclassified as released history —
they would have shipped false in the same release as the auth entry.

The serve runbook's "Binding beyond loopback" section was actionably wrong: it
said the flag "prints a warning and changes nothing else", and its refusals
table quoted a string not in the binary. Rewritten against a build, with every
flag, error string, event name and reason value produced by running the
command. It gains the operational trap nobody had written down: /healthz is
auth-exempt and GET /v0/beads/ready is not, so an unauthenticated readiness
probe earns a 401 forever while liveness stays green. The runbook is now IN
scripts/check-doc-freshness.sh, pinned to the four files it is read against.

ga-2yaqp.5 — nine prose defects, every count re-derived rather than trusted;
three of the audit's own numbers had moved again. 38 route rows and 36
capability-bearing ones; thirteen pinned schemas, not twelve or seven; six
missing entries in the no-query-parameter list, not five; twenty-eight role
accessors, not twenty-seven; nineteen patch members, not thirteen. Two prose
"code counts" were counting paragraphs. CodeAlreadyClaimed claimed the holder
is always attached when only one of four producers always attaches it and
releaseIssue never does. MetadataCAS's leaf contradicted its own shipped wire.
The path/operationId inversion is now recorded where a spec author looks.

ga-2yaqp.6 — the role checklist refreshed against what this wave's additions
actually cost, traced to real commits. Step 10 sent people to a name list
#5460 deleted. The "four more edits" claim was stated twice and undercounted
both times: the two freshest wire slices share a nine-file core plus
roles_test.go. The step-with-no-number gained the fact that explains its
instances — write-role decorators wrap, read-role decorators recurse, so the
call lands on the stub, and both real instances are reads. The wave got its
first CHANGELOG entry: six new public operations, not three, and zero new role
accessors in the window.

Review verdict: FIX-REQUIRED then all items addressed. The reviewer
live-falsified the strong auth form and failed to break it, and confirmed
every recount re-derives exact.
2026-08-10 08:05:07 -07:00
Stephanie Jarmak
8ac3e6ea04
feat(workapi): opt-in BriefDeps projection for the issue detail view (#5547)
be-4d36f2 gave the dependents side a shallow shape after hub beads made
`bd show --json <hub>` allocate 5-13 GB marshaling full Issue records. The
dependencies side of the same builder never got it, and still returns the
complete body of every dependency.

Measured on a 16,051-issue store, one `bd show <id> --json` returned 214,456
bytes, of which 193,039 was the dependencies array; a single dependency carried
a 180,975-byte notes field. Reading one issue costs the full text of everything
it depends on.

BriefDeps reuses the shape collectDependents already settled on (id, status,
type, priority, title, dependency_type) and drops the free-form text. It is
opt-in and the default payload is unchanged, so no existing caller loses a
field it reads. That matters here: #4122 objects to default payload changes
and #5078 records what the last one cost.

The reduction runs after the Parent scan, which reads DependencyType and ID off
the full rows, and builds a new slice rather than overwriting the one the source
returned, which a caching source would keep shallow for later callers.

collectDependents now routes through the same shallowDep helper so the two
shapes are identical by construction rather than by coincidence.

Storage layer only, per CONTRIBUTING_PR_GUIDELINES.md; the cmd/bd flag that
reaches this is the follow-up PR.

Refs #5546

Co-authored-by: sjarmak <t@t.co>
2026-08-10 06:51:41 -07:00
Isis Anisoptera
c8dd08c262
fix(human): respond/dismiss text sources, bd list parity, and proxied-server support (#5333)
* fix(cli): one text-source layer for comment, note, and human respond

`bd comment`, `bd note` and `bd comments add` each read their body text a
little differently, and all three applied a SILENT precedence when a caller
gave two sources: positional text plus --stdin or --file resolved to the flag
and dropped the positional half with no message. In every case we could find,
the dropped half was the text the caller meant.

One textSources layer now owns the reading for all of them. Naming two sources
is an ERROR ("cannot combine positional text ... with --stdin") rather than a
precedence question; --file content is passed through verbatim, matching every
other file-input flag (--body-file, --design-file, --reason-file), while stdin
keeps trimming the trailing newline a shell appends; and an explicitly-set-but-
empty text flag counts as a source via cobra's Changed, so `--response ""` gets
"cannot be empty" rather than "no text provided".

`bd human respond` joins them: its response can come from positional args,
--response, --file or --stdin, so --response is no longer a required flag.
`bd human dismiss` takes its reason positionally as well as via --reason, and
both accept trailing free text (`<id> [text...]`) the way `bd comment` does —
a second argument is text, never a second id. The "Response: " prefix and the
shared Dismissed close reason are now formatted ONCE, before the proxied
dispatch, so the two backends cannot shape them differently; the same move
lets the proxied comment entry points take resolved text instead of re-reading
the flags themselves.

`human stats` classifies dismissals by that shared Dismissed prefix instead of
a case-insensitive substring search for "dismiss", so the writer and the
classifier cannot drift. Beads closed earlier with a lowercase or mid-string
"dismiss" move from the Dismissed count to Responded; CHANGELOG carries the
note.

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

* fix(human): bring `human list`/`stats` to bd list parity via IncludeAllTypes

`bd human list` built its own two-field filter: a label match plus whatever
--status the caller typed, unvalidated. So it showed closed beads by default
where `bd list` hides them, answered a typo'd status with a silent empty list
instead of an error, and — because it never went through the shared builder —
could not be told what a default listing is SUPPOSED to hide.

It goes through workapi.BuildListFilter now, which gets it the done/frozen
status exclusions, the pinned default, status validation against built-in and
custom names, comma-separated sets, and "all". `human stats` counts the same
universe (--status=all) through the same path, and the proxied side calls
openAndPrepare rather than hand-building a second filter, so the command
cannot mean one thing in direct mode and another behind the proxy.

What it must NOT inherit is the type suppression: a `human` label is an
explicit request for a person's attention, and this command is the only place
a person sees it, so gates, wisps, infra beads and templates all show. That is
the new issueops.ListRequest.IncludeAllTypes — the union of IncludeTemplates,
IncludeGates, IncludeInfra AND IncludeEphemeral. Both the type exclusions and
the PLANE decision now live in one applyTypeSuppressions that the flag skips
whole, so it decides the ephemeral plane too rather than lifting three type
knobs and leaving `bd human list` blind to human-labeled wisps. A suppression
added there in future is lifted here without touching this command.

Two pinned fixes fall out of parsing the status selector ONCE instead of
comparing the raw string in three places:

  * --status=all no longer forces Pinned=false. "all" promises every status;
    the string comparison never matched it, so the one selector that hides
    nothing kept hiding pinned beads. The golden case status_all_keyword is
    re-recorded (Pinned false -> null) and TestPinnedDefaultBySelector owns
    the rule now.
  * --status=pinned,closed no longer excludes the pinned beads it asks for —
    the same comparison missed every multi-status set.

--ready is deliberately unaffected: it forces status open and otherwise
ignores the selector, so an "all" the query never applies must not have a
pinned side effect either.

BEHAVIOR CHANGE, called out in CHANGELOG: scripts using --status=all as a way
to list everything EXCEPT pinned beads will see pinned beads appear. Add
--no-pinned to keep the old result.

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

* fix(human): let proxied respond/dismiss answer wisps, and stop the phantom label warning

Two gaps in the proxied twins of `bd human respond`/`dismiss`, both of which
`bd human list` showing every bead type now makes reachable:

WISPS. The pair resolved through proxiedRequireIssue and then wrote the
comment and the close against the DURABLE tables. A human-labeled wisp is a
bead a person can see in `bd human list` — so it has to be one they can also
answer. Resolution goes through workapi.GetIssueOrWisp and the write side
branches: AddCommentToWisp/CloseWisp for the ephemeral plane, unchanged calls
for the durable one, still inside the single RunTx the proxied write
convention asks for.

THE ADVISORY WARNING FIRED ON A FAILED LOAD. The missing-'human'-label warning
read labels with the error discarded, so a label load that FAILED was
indistinguishable from a bead with no human label, and the user was told the
label was missing when nothing had been checked. The result now carries
labelsKnown, and a failed load simply warns nothing.

NOT salvaged: the post-commit close-hook firing this branch originally carried.
It was written when each proxied call site hand-wired its own hooks; main has
since moved firing onto the unit-of-work plumbing (uow.NewNotifyingProvider,
bd-opisf), which buffers during the transaction and drains after Commit. The
proxied human close already fires its hooks — a hand-wired call here would
fire each one twice. The reason is recorded on closeHumanProxied so the next
reader does not re-add it.

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

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-10 05:36:11 -07:00
Julian Knutsen
6775f60f67
Publish revision on the detail read: the token a guarded write is composed from (#5535)
Every `expected_version` on this surface is composed from a token some response
carried, and until now every response that carried one was a WRITE. A client
that wanted to read a row, decide from what it said, and write it back under a
guard had to precede its first guarded write with a write it did not want to
make — or guard on nothing, which is the lost update the whole family exists to
refuse. Five places in the document said "no READ on this surface publishes a
revision yet" and named the member a read would have to agree with. This is that
member.

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

GET /v0/beads/issues/{id} PUBLISHES IT; GET /v0/beads/issues DOES NOT, and the
reason is not payload. Measured against a 20,482-row production export the
member is 28 bytes on a 1449-byte median row — under 2%, and the list rows are
already fat enough that a token would disappear into them. The reason is that
`types.IssueWithCounts` is ALSO THE INTERCHANGE ROW: `exportIssueRecord` embeds
it in both `bd export` and the auto-export that flushes a git-tracked
`issues.jsonl`, and the token is re-minted by every write, so publishing it on
that element would put a per-write-random value into a file whose whole value is
that it diffs when something meant something. That is precisely the loss
`types.Issue.RowVersion`'s `json:"-"` is there to prevent, and a wire member
cannot opt out of it — the list element and the export element are one pinned Go
struct. `types.IssueDetails` has neither problem: nothing interchanges it, and
`workapi.BuildIssueDetails` is its ONE production construction site against
IssueWithCounts's SIX, which is the second half of the argument. (Six
field-populating non-test literals: export.go, export_auto.go, search.go,
claim_next.go, ready_work_counts.go and uow/ready_claimer.go. The `[]*T{claimed}`
spellings in ready.go and ready_proxied_server.go are slice literals wrapping a
role-built element, not independent places to forget a field, and they are not
counted.) A token field on a struct built in six places is silently 0 wherever a
site forgets it, and 0 is a LEGAL token (the migration-0054 backfill), so
nothing — no test, no client — can tell a forgotten one from a legacy row.

So the projection moved onto the canonical type behind ONE DOOR. types.Revision
is set by types.NewIssueDetails and nowhere else, because a struct literal with
an unset token publishes a wrong answer that looks exactly like a right one.

THE DOOR IS WRITTEN INTO THE DOCUMENT, not just into this description. A later
revision that wants the token on the list rows needs a list element that is NOT
the interchange element, and the listing's own prose now says so — together with
the rule a client needs meanwhile: model the absent member as ABSENT, never as
0, because 0 is a real token and a client that defaulted would compose guards
matching exactly the rows it is most dangerous to be wrong about.

THIS DELETES A PARITY DIVERGENCE RATHER THAN ADDING ONE. `bd show --json` has
published this token for as long as guarded writes have existed, through a
CLI-only wrapper, and `readsParityAllowlist` waived the difference with the note
"if the token is ever needed over HTTP, extend that surface and delete this
entry". The wrapper is gone, both front doors read the member off the one detail
seam, and the allowlist is now EMPTY — kept declared, because an empty allowlist
is a stronger statement than no allowlist.

The wire council's outstanding fix rides along, because it is the same member
family: `ApplyItemResult.revision` and both apply-item `expected_version`
members gained the DECODE-AS-64-BIT clause every other revision-bearing member
already carried. The batch spelling is where it bites hardest — a token
corrupted by an IEEE-754-double parser refuses the WHOLE plan rather than one
write.

Evidence. Four mutations, each watched to go red in the right place and only
there: the constructor stopping projecting reddens all three legs; the seam
regressing to a struct literal reddens the workapi pin ALONE and leaves the
httpapi case green, which is why both exist; `omitempty` reddens exactly the
legacy-zero arms; and adding the field to `types.IssueWithCounts` reddens the
new list case while leaving `TestRowVersionNeverSerialized` GREEN — the separate
unset field carries none of the forbidden spellings — and reddens
`TestWireTagBijection` only while the document has not caught up. That measured
pair is written into the new case's own comment, because it is why the case is
not redundant with either gate.

Real Dolt through a real `bd serve`: read the token, guard a patch with it, watch
it land; watch a write move it; watch the read and the write agree on the new
one; watch the stale guard 409 with `param: expected_version`; re-read and watch
the retry land. The same loop on `close`, and the ephemeral fallback — where the
token is a different column on a different table and the failure mode is a zero
rather than an absence.

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

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

Co-authored-by: Review Sim <ci@beads.test>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-10 00:27:49 -07:00
Julian Knutsen
a72a15220b
Refuse kv.* point reads on the settings role and stop printing them (#5493)
* Refuse kv.* point reads on the settings role and stop printing them

The `bd kv` keys and the `bd remember` memories nested under them are user
data stored as config rows. They ride in the settings table without being
settings, and only the ENUMERATION was filtered: a caller naming an exact
key still got the value back from GetSetting. That is not a smaller hole
than the enumeration was. `bd remember` derives its key from the content it
stores, so the keys are guessable, and the walk-around is one request to
GET /v0/beads/config/kv.memory.<slug> — a surface with no authentication
whose redaction decides on the key NAME while a memory's secret is in the
VALUE.

The point read now answers a `kv.` key exactly as it answers a key nothing
ever stored: the echoed key, an empty value, a nil error. Indistinguishable
from absence on purpose — this role has no ErrNotFound to give, and an
error of any kind would confirm the guessed key to the caller. The row is
not touched, and no read reaches the store at all.

The refusal lives in internal/workapi beside FilterSettingsEnumeration,
where both WorkspaceConfig bodies already reach for the enumeration rule,
so the three legs inherit one decision. Both filters now decide with
workapi.KeyIsOnTheKVPlane, which is the single statement of where the plane
boundary runs.

`bd config show` gets the same rule (bd-klko9). Its database section reads
GetAllConfig raw rather than through the role, so it inherited neither
filter, and it prints values in FULL because it is the operator's
provenance view — every stored memory went into every terminal and pasted
bug report that ran the command. Nothing replaces the view; `bd kv list`
and `bd memories` are the surfaces that own those rows.

The writes are deliberately untouched: SetSetting and UnsetSetting still
take a verbatim `kv.` key, which keeps the escape hatch for a wedged
memory, and a write discloses nothing.

RunWorkspaceConfigPointReadRefusesTheKVPlane pins it on all three legs. It
reads the config table out of band around the refusal, because "the row is
there and the read refuses it" has to be a different fact from "there is no
row", and it asserts a settings key still reads back so a role that
answered "" to everything cannot pass. Reverting either half of the
production refusal turns it red on dolt, embeddeddolt and uow.

bd-rfwtv, bd-klko9

* test(memory): move the proxied leg onto the new settings-plane contract

The proxied memory journey asserted that `bd config get kv.memory.<key>`
returns the memory content, with a comment calling it "visible via bd
config get". That is exactly the behaviour this branch removes, so the
case was pinning the old contract from a shard that does not run locally
-- which is why it stayed green until CI reached it.

It now asserts the new one: the point read answers as an unset key does,
and the content does not appear in the output. The rest of the journey is
untouched and still proves the memory is readable through the surfaces
that own it -- `bd memories` lists it, `bd recall` returns it
byte-for-byte -- so this is the proxied leg of the same firewall the role
contract pins, not a weakened assertion.

Also records in the CHANGELOG what the change does NOT buy. `bd serve`
has no authentication and serves every memory in full through
/v0/beads/memories by design, so this is plane hygiene -- keeping user
data out of the routes that get republished into agent transcripts -- and
not a confidentiality boundary against anyone who can reach the port.

---------

Co-authored-by: Review Sim <ci@beads.test>
2026-08-09 11:06:51 -07:00
Julian Knutsen
3b8e85bae3
Add issueops.Releaser: give a claim back, optionally only a named holder's (#5482)
* Add issueops.Releaser: give a claim back, optionally only a named holder's

Claiming has had its own role since Claimer; releasing has never had one.
`bd unclaim` reaches the raw seam directly, and everything that isn't the
CLI has had to spell the release as a patch — assignee to empty, status to
open, started_at to null — which puts the transition's definition in the
caller three fields at a time and still leaves the lease row behind. A
release is one act with a known post-state, and the lease it drops is the
part a patch cannot express at all.

It is its own role rather than a method on Claimer for the reason
Bootstrapper and InitVerifier are two: a caller entitled to give its own
work back is very often not entitled to take new work, and a surface
carrying both hands it a capability it should not be able to reach.

THE SHAPE MIRRORS THE RAW SEAM, and the two places it does not are both
refusals rather than permissions. UnclaimIssueInTx and
UnclaimIssueIfAssigneeInTx refuse an unheld row and a status the release
transition is not defined over with UNTYPED strings — "issue X is not
assigned" and, for the second, "no matching row", which explains nothing
and no caller can classify. The role reads the row first and names them:
ErrNotClaimed and ErrNotReleasable. Which requests are refused is
unchanged; the raw calls still run their own checks underneath.

ErrNotReleasable is wider than "closed" and the leaf says so out loud: the
release UPDATE is pinned to status open or in_progress, so an issue parked
in `blocked` while still holding a claim is refused. That is a limitation
of the transition, not a policy, and it is now visible instead of arriving
as "no matching row".

A RELEASE IS NOT IDEMPOTENT and this keeps it that way. An unheld row is
ErrNotClaimed with or without Force, not a Changed-false no-op — the raw
rule, and the one a reaper can errors.Is in a line it writes knowingly.
ExpectedAssignee is the compare-and-set: a match REPLACES the ownership
fence, exactly as UpdateRequest.ExpectedAssignee does for a transfer, so a
supervisor can free a named agent's claim without Force and without being
able to clobber a claim that has since moved. Force may not accompany it —
the two answer one question and disagree — and a non-nil pointer to "" is
ErrValidation rather than "expected unassigned", because releasing a row
nobody holds describes no release.

ErrNotOwner MOVES to issueops and internal/storage aliases it forward. A
refusal the public role raises has to be classifiable by a caller that
cannot import an internal package; a Go alias preserves identity in both
directions, so every existing errors.Is site keeps matching the same value.

All three legs share one body (internal/storage/issueops.ReleaseIssueInTx),
so this is one reading plus two wrapper checks rather than three backends
agreeing — and the wrapper check earned its keep again, in the same place
MetadataCAS's did. An EPHEMERAL release writes a row and versions nothing;
the unit-of-work leg's commit message is what commits its SQL transaction
as well as what versions it, so composing the message from the durable
table set rolled the write back and the wisp came out still claimed. Green
on both stores, red on the unit of work, exactly as the engdocs predicted.
The domain reach now answers Wrote and the store legs take Tables.

Eleven contract cases on all three legs. The post-state is read RAW, cell
by cell, because the whole reason to state it on the role was that a caller
should not have to reconstruct it — including the lease row, whose survival
is the failure no role-answer assertion can see. The attribution case
forces a release by someone who is NOT the holder, the only arrangement in
which stamping the holder is distinguishable from stamping the actor, and
counts entries per actor because created_at is second-granularity and an
ORDER BY would decide it on a coin toss.

The contract does NOT carry a case for a false ReleaseResult.Changed, and
says so: nothing returns it false, so the case could not fail. What can
fail is the decorator's use of it, which internal/storage/hook_releaser_test
drives with the answer the role reserves the right to give.

FACADE ONLY: no wire, spec or httpapi change, and no bd command re-pointed.
The wire half follows in the conditional-update / release wire slice per
the program's council gating.

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

* Delete the two release pre-checks a mutation proved could not fail

Written as defence in depth, measured as dead weight. ErrNotOwner and
ErrAssigneeMismatch already come back from UnclaimIssueInTx and
UnclaimIssueIfAssigneeInTx typed, wrapped and in this same order, so
removing both copies left the whole eleven-case contract green on the
server-backed leg — the mutation-equivalence verdict that says a branch
exists to look reassuring rather than to hold anything.

What stays is the pair the raw seam answers with a bare string: an unheld
row ("issue %s is not assigned") and a status the release transition is not
defined over ("no matching row"). Those are the refusals this body is FOR,
and each one goes red when it is skipped.

The header now says which refusals this function owns and which it leaves
to the calls below, so the absence reads as a decision rather than as a
check somebody forgot.

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

* Lint: one spelling of the holder, and drop two parameters nothing varies

golangci-lint's unparam found releaserSeedClaimed's holder and
releaserRowVersion's table taking one value at every call site. Both are now
gone, and the holder is one package constant rather than nine copies of the
same literal — which is worth more than the lint: half these cases are ABOUT
the difference between the holder and the caller, and two spellings of "the
holder" is how such a case comes to assert the wrong one.

Plus two British spellings misspell caught.

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

* Review: say why Changed is asymmetric with Claimer's, and three prose fixes

Doc only; no behaviour changes and none intended.

THE RULING ON ReleaseResult.Changed, written where it belongs. Keeping the
unheld-row refusal was defended here as "the rule the raw seam already
has", which is an appeal to precedent rather than a reason. The reason is a
fact about the two POST-STATES. Claimer can afford an idempotent answer
because a claim's post-state IDENTIFIES THE CLAIMANT: a re-claim finds
assignee == Actor and StatusInProgress, the claim's own signature surviving
on the row, so the role can tell "you already did this" from "somebody else
holds it". A release leaves an ANONYMOUS post-state — assignee cleared,
status open, started_at gone — which is the same row whoever emptied it and
whether or not it was ever full. An idempotent release would answer Changed
false identically for "I already released this", "a reaper beat me to it"
and "nothing ever claimed it", with nothing left on the row to tell them
apart. Those three want different things from a caller, so the role refuses
and lets the caller pick. ClaimResult.Changed is now named at the
comparison rather than merely gestured at.

ExpectedAssignee compares BYTE FOR BYTE, now said out loud: " agent-a" is
not agent-a and refuses. The validator trims only far enough to tell a
blank expectation from a real one and never writes the trimmed form back,
and the no-mutation promise makes that permanent — so a padded expectation
loses every time rather than intermittently, which is the failure worth
warning about.

And the deleted-pre-checks note now states the CONSEQUENCE rather than the
shortcut: one leg was sufficient evidence BECAUSE all three legs run this
function and it reaches the same two raw entry points, so there is no
second implementation in which a deleted pre-check could still have been
load-bearing. "A mutation verdict is only true of the body you mutated" is
answered by there being one body. Where the legs DO differ is in what they
version — hence ReleaseWrite's two facts and the wisp case on all three.

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

---------

Co-authored-by: Review Sim <ci@beads.test>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-09 07:48:56 -07:00
Julian Knutsen
2c3a75d78c
Add DeleteRequest.ExpectedVersion: a compare-and-delete on the named row (#5481)
* Add DeleteRequest.ExpectedVersion: a compare-and-delete on the named row

`bd delete` is the one irreversible verb with no way to say "only if this
is still the row I looked at". Every other guarded write has one —
Lifecycle's Update, Close and Reopen all take an ExpectedVersion over the
same row_lock token — and the operation that most needs it is the one
where being wrong cannot be undone. A caller that reads a row, decides it
is finished with it, and deletes it has a window in which somebody else
reopened, reassigned or restarted the work; today the delete lands anyway.

The token is the ordinary one: server-minted, opaque, equality-only, nil
to disable, and read inside the deleting transaction so the pair is a
compare-and-delete rather than a read followed by a hopeful write.

TWO DECISIONS ARE WORTH THE REVIEW.

It requires a SINGLE-ID request, and a non-nil version beside more than
one distinct id is ErrValidation before anything is read. A row version
is per-row and the space is not shared, so one number checked against a
batch would pass a whole list of never-written rows by coincidence —
every one of them holds 0 — and fail forever for any list whose rows have
diverged. A guard that passes by coincidence and a guard nobody can
satisfy are the same defect from two sides. The shape a batch would need
is a token per ITEM, which BatchCloser.Items is, and this role is a list
of ids rather than a list of items; BatchCloseItem carries no version for
the same reason. Duplicates collapse first, so `bd delete a a` with a
token is one row and is legal.

It OUTRANKS the dependents guard and neither Force nor Cascade bypasses
it. A mismatch says the caller's whole view is stale, so reporting the
dependents refusal first would ask it to choose --cascade or --force over
information that has already moved; and force bypasses policy, never a
precondition, exactly as CloseRequest.Force does. It still ranks below
the existence probe: a request that named no row has nothing to be stale
about.

Two bodies, as ever. The store legs call the same CheckVersionInTx the
update and close guards use, on the transaction they delete in. The
unit-of-work leg compares the row its own existence probe already
loaded — the probe now keeps rows rather than a set of ids — which is
what updatePreconditionsHold does for the same token on the update path,
and avoids a second read of the same rows in the same unit of work.

Four contract cases on all three legs, written as a falsifiable pair: the
satisfied case takes the row's REAL token straight out of row_lock, on
both planes, so a body that refused every versioned delete reddens; the
stale case is the refusal, under DryRun too, with the rows counted raw
and the token asserted unmoved. The ranking case keeps a live outside
dependent on every arm, so "force did not bypass" is distinguishable from
"force was not needed", and ends on a matching-token force release so the
three refusals cannot be satisfied by a body that refuses unconditionally.
The arity case uses a token that MATCHES the first id, which is the only
arrangement that catches a body checking the first row and deleting the
list, and pairs it with the repeated-mention collapse so the rule cannot
be read as "expected-version deletes take one element".

FACADE ONLY. No wire, spec or httpapi change: the delete handler reads an
explicit member allowlist, so a new leaf field is invisible to clients
until the wire half follows in the conditional-update / release wire slice
per the program's council gating.

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

* Review: pin existence-outranks-version, and say what the second SELECT buys

Three review items, one of which was a real hole.

THE HOLE: the leaf promises the version precondition ranks BELOW the
existence probe — "a request that named no row has nothing to be stale
about" — and nothing watched it. A second block on RefusesAnAbsentID does,
with a single absent id carrying a version.

It asserts the TYPE and not the sentinel, which is the whole point.
errors.Is(err, ErrNotFound) is satisfied by the WRONG order too: the store
legs run the guard through CheckVersionInTx, which answers a bare wrapped
ErrNotFound of its own for a row that is not there, so a flipped order
looks identical to a reader of the sentinel. Only *NotFoundError — which
nothing but the existence probe mints, and which carries the id — tells
them apart. The unit-of-work leg cannot answer at all: its comparison reads
the row the probe loaded, so a flipped order is a nil dereference.

Watched: moving the guard above the probe in the store body reddens it.

The other two are prose. workapi/delete.go cited `--expect-version`, a flag
that does not exist — the wire half is deferred — and now states the request
shape instead. And delete_role.go now says that CheckVersionInTx re-reads a
row the existence probe already returned, that what the second SELECT buys
is ONE definition of the guard shared with the update and close paths, and
that the unit-of-work leg answers the same trade the other way because the
shared function is not reachable from it — so the difference reads as a
consequence of where each leg sits rather than as drift.

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

---------

Co-authored-by: Review Sim <ci@beads.test>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-09 07:17:54 -07:00
Julian Knutsen
9a2c918b0e
Admit the ephemeral plane from a list request, on the facade and on the wire (#5476)
* feat(reader): admit the ephemeral plane from a list request

`issueops.Reader.Ready` has had an ephemeral gate since it was written;
`List` has not. The wisp plane was reachable from a list request only as
a SIDE EFFECT of `IncludeInfra`, which also drops the infra-type
exclusions, or by naming an infra type, which routes to that plane
ALONE. A caller that wants the ephemeral rows of ordinary types — a
message bead, say — could ask for them on the ready query and not on the
listing, and the wire said so in prose: listIssues published no
`include_ephemeral`, and the document called the asymmetry out.

ListRequest.IncludeEphemeral closes it, with the same semantics
ReadyRequest.IncludeEphemeral already has.

  false (zero value)  durable rows only — today's listing, unchanged
  true                the wisp plane merged IN ADDITION; the answer is a
                      superset of the false answer under the same
                      filters, and never ephemeral-only
  WispType            a predicate on the wisp_type COLUMN, which BOTH
                      tables carry, so it selects no plane: it narrows
                      whatever was admitted. WispType alone answers with
                      nothing, since no durable row carries a
                      classification; WispType + IncludeEphemeral is
                      lawful and composes as an ordinary AND
  order               ONE order across both planes, by SortBy, as if
                      they were a single table — not durable rows
                      followed by ephemeral ones. A Limit truncates the
                      merged order, and the keyset position is applied
                      to BOTH legs, so a cursored walk over the merge
                      drops no row and repeats none. The non-snapshot
                      caveat is the one every multi-page walk already
                      has; the ephemeral plane only turns over faster
  --ready             CARRIED, not dropped. The ready query has an
                      ephemeral gate of its own, so
                      ReadyFilterFromIssueFilter now reads the plane bit
                      off the list filter. That also carries
                      IncludeInfra's plane half, which the projection
                      used to drop silently — `bd list --ready
                      --include-infra` now answers with the wisps `bd
                      count --include-infra` already counts

It is a PLANE knob and not a TYPE knob, which is the whole difference
from the three fields beside it: templates, gates and infra types stay
hidden by their own predicates. IncludeInfra remains strictly wider.

The wire gets `include_ephemeral` on listIssues, spec-first. There is no
capability-token change: it is an ordinary optional query parameter, so
an older server answers it with 400 `unknown_parameter` — the designed
skew signal, whose recovery is to degrade rather than retry.

Conformance runs on all three legs (server-backed store, embedded store,
unit of work) and covers admission, the merged order, every page bound
across the interleaving, a cursored walk across the plane boundary, and
the WispType interaction. The two seams arrange the merge differently —
one merge-sorts two independently ordered legs in Go and trims, the
other ORDERs a SQL UNION ALL — so the bounded and cursored arms are a
genuine two-body case rather than one body twice.

* fix(reader): correct the flag's reach, and settle the merge seam it lands on

Review follow-up. Three of these are documentation being wrong about the
code; one is the code itself.

THE MOTIVATING EXAMPLE WAS FALSE. `message` is one of the DEFAULT INFRA
TYPES (agent, role, message), so "the ephemeral rows of ordinary types —
a message bead, say" named the one row this flag cannot reach: the
infra-type exclusion is a TYPE predicate and survives the plane knob, as
the golden already recorded and nothing asserted. `bd ready` cannot
deliver it either — ReadyWorkExcludeTypes appends the infra set
unconditionally. The field doc, the operation description and the
parameter text now say that ephemeral agent/role/message rows need
IncludeInfra, and what the flag alone reaches is the ephemeral rows of
the types a listing already shows.

The contract case is what makes it more than a corrected sentence. The
fixture's only wisp was a task, which comes back under EITHER knob, so a
body that wired the plane flag to IncludeInfra's branch answered every
row correctly. An infra-typed wisp is hidden twice over — once by the
plane, once by the type — and is the only row that can tell the two
apart. Three rows now pin it: absent under IncludeEphemeral, present
under IncludeInfra, present under both. Wiring the flag into the
type branch fails it.

TWO MORE DOC CORRECTIONS on the same field. It admits the wisps TABLE,
which holds no-history rows (ephemeral = 0) alongside true ephemerals —
stated, rather than left as "the ephemeral plane". And it is NOT
identical to ReadyRequest.IncludeEphemeral: ready reads both planes
either way and adds a per-ROW ephemeral predicate when unset, where this
selects which TABLES are read. The difference is observable on exactly
those no-history rows, which a DEFAULT ready answer already contains and
a default listing does not.

The ready projection's predicate is negative, on a field whose zero
value means admit, so it fires for a filter that merely never set
SkipWisps rather than for one that asked. Every caller is handed a
BuildListFilter result, which decides that field for every request, so
"unset" is unreachable today — named at the site so the next hand-built
filter does not walk into it.

THE SEAM DISAGREEMENT, which is the code change. A cross-plane duplicate
id was tolerated by the per-table seam (collapse to the canonical wisp,
answer) and HARD-ERRORED by the union seam, and this flag routes every
wisp-inclusive read onto the union. Two implementations of one role
answering a page and an error is a divergence, not a design, and leaving
it silent while making it reachable is worse than either behavior.

The union now resolves it the way its sibling does, at all four sites,
and the strict flag is gone rather than left as a footgun. Three things
say that is the right verdict and not merely the convenient one: the
per-table seam has said so since be-iabdi ("hard-erroring breaks every
lookup city-wide"); `bd doctor` detects the state with a query of its
own, so answering blinds no detector; and its fix deletes the stale
ISSUES copy, which is exactly the row the union now drops. Its own check
text names the hard failure as the damage — "stale issues-table copies
break every lookup for the affected IDs". The four tests that pinned the
error now pin the wisp-canonical answer; inverting the preference fails
all four.

Preferring the wisp needs a second pass: the outer ORDER BY can place
either copy first, so which leg produced a row is known in full only
after the scan.

Last, a stale comment: issueops/count.go claimed SearchIssuesInTx was
the corruption detector. It has not been one since be-iabdi. The count
trusts the disjoint-table invariant and no read enforces it, so a
dual-resident id is counted twice and listed once; doctor is the
detector and the repair.

---------

Co-authored-by: Review Sim <ci@beads.test>
2026-08-09 05:06:36 -07:00
Julian Knutsen
e29abaea37
Converge Offset and MaxRows on all three legs, and fix the panic and the breaker hole under them (#5435)
Offset and MaxRows were mirror-image splits: the unit-of-work seam honored
Offset and refused MaxRows; the two store legs did the opposite. Three contract
cases absorbed that with an "either HONORED or REFUSED with a typed
*ErrUnsupported" disjunction.

A contract that asserts a capability is either honored or refused is not pinning
semantics — it is ratifying a split. All three are gone, along with
assertReaderUnsupported. Converging upward rather than uow-matches-server is the
owner's one ratified exception, because the server refusing MaxRows was a
capability gap rather than a semantics choice.

Offset now runs in the shared page epilogue on every leg rather than in whichever
seam could render it: the skip must happen in the caller's display order, which
is not SQL-expressible for --sort id, and a row the database skips is a row the
query matched.

Two bugs fixed under it.

The panic: domain/db rendered LIMIT 18446744073709551615 OFFSET k for an
unbounded query, and Dolt sized a buffer from limit+offset and returned a
recovered makeslice panic instead of rows. The contract case had been shaped
around it, bounding every request, with a comment calling it a storage-seam bug
that predates the role. It now drives the unbounded shape.

The breaker hole, found by review: proxied bd list --watch with an offset and a
cap counted the cap against post-skip rows while the page route counted
pre-skip, so the same flags produced opposite verdicts — L=10, k=2, M=3 over 5
rows returned a page on one route and ErrTooManyRows on the other. Newly
reachable since 3b2385922 removed the proxied --max-rows rejection ahead of the
watch dispatch, and it falsified the comment claiming no caller combines an
offset with a cap.

MaxRows semantics are now ratified and documented: the cap counts the rows the
query TOUCHED (offset+limit), not the rows the caller receives. A skipped row is
still a matched row. Review reported the Limit+Offset == MaxRows boundary as an
off-by-one; measured under those semantics the code was already correct and the
doc was wrong, so the fix was the doc plus pinning the behaviour.

A seventh cannot-fail test was caught mid-slice: an unreachable "under a
defensive cap" branch in searchWindowFor absorbed the exact regression the new
MaxRows-behind-offset arm exists to catch, and the mutation returned
INCONCLUSIVE. Removed.

Equivalence of the epilogue skip to a SQL OFFSET was checked rather than
assumed. One narrow uncovered exception stands: under --sort title, SQL
collation and Go byte-compare can disagree on non-ASCII and then pick different
skip sets. Conformance seeds ASCII.
2026-08-08 11:37:09 -07:00
Julian Knutsen
4e8b017fd4
Put the memory plane behind memoryops, conformance-tested at three backends (#5387)
The memory commands get the treatment the sixteen issue commands got in #5378:
a role interface in a leaf package, conformance-tested at all three backends,
with the CLI routes and the HTTP handlers as thin callers over one
implementation.

memoryops is its own namespace rather than an addition to issueops. The two
planes share a config table and nothing else; a memory whose key shadows a
settings name is still a memory, and that separation is now the role's,
pinned by its contract, rather than a filter each caller reapplies.

Closes an unauthenticated disclosure found on the way: memory content was
served in cleartext on GET /v0/beads/config, and reachable through two more
doors — `bd config show` and `bd info --json`, the latter republished into
agent transcripts by MCP get_schema_info. Enumeration is now filtered at the
shared seam (workapi.FilterSettingsEnumeration); `bd config show` is left
alone deliberately, since an operator asks for it by name.

Two wire contracts were settled after the review council, recorded in full on
the PR: the search parameter is spelled `search` rather than `q`, because
issues:query already publishes `q` as a boolean expression and one surface
must not spell two questions one name; and getMemory keeps its 404, because
the status reports the distinction the front door already reports and
`bd recall` exits 1 on a miss where `bd config get` exits 0.
2026-08-07 03:57:04 -07:00
CI Bot
76e3b16fd7 Merge branch 'facade/wave-3' into facade/wave-4
# Conflicts:
#	.golangci.yml
#	cmd/bd/dep.go
#	internal/httpapi/stats.go
2026-08-06 21:39:05 +00:00
CI Bot
650b0cd2a9 Bound a filter-expressible query page IN ORDER, like bd list already does
BuildListFilter pushes SortBy into the SQL filter; BuildQueryPlan did not. So
for a filter-expressible expression the database bounded the page in STORAGE
order and the display sort ran afterwards in Go, which makes "which N rows are
in the page" a property of whatever order the engine happened to return.

The two bodies then disagreed. The store body over-fetches one row as a
has-more probe and FinishPage sorted that probe INTO the page before cutting;
the unit-of-work body trims to Limit natively and never sees it. Same
expression, same --sort, same --limit, different rows — the exact failure
FinishPage's own comment cites as the reason it exists.

Pushed down, the bound and the order are one decision the engine makes: the
page is the first Limit rows in the requested order on every backend, and the
probe row is genuinely last, so cutting removes precisely it.

RunQuerierSortBoundsThePageInOrder pins it. The fixture is built so storage
order and sort order DISAGREE — four matches, limit two, and the two rows that
should win carry the worst priorities so the default engine order puts them
outside the three rows an over-fetch sees. Verified by mutation: without the
push-down the store leg returns [b y] where [a b] is correct.

It sorts by `title`, not `id`: sqlbuild routes `id` to a GO-SIDE sort
(natural id ordering has no SQL spelling), so no push-down can apply there and
both bodies bound in storage order alike. A first draft of this case used
`id` and passed against the unfixed code for exactly that reason.
2026-08-06 21:29:15 +00:00
CI Bot
67d38d2620 Trim this series' comments toward the repo's own density
Ten agents over 216 files, one directory-balanced group each, working to a
rubric that named what to cut (duplication narration, restatement of the next
line, the governing rule echoed in every command file, throat-clearing) and
what to keep (traps, invariants, security, tracker ids, behaviour changes, and
the "why a naive simplification destroys this assertion" rationale).

Net 1,523 lines. Density against this repo's own per-directory norm on main:

  cmd/bd              33.6% -> 27.3%   (main 10.7%)
  internal/storage    26.1% -> 23.1%   (main 14.1%)
  backend/conformance 34.0% -> 29.6%   (main 22.8%)
  internal/httpapi    30.9% -> 27.8%   (main 30.6%, now below)
  overall             34.7% -> 31.6%

Every agent landed at 18-25% rather than the 30% asked for, and every one gave
the same reason independently: what remained was on the keep list. Ten separate
judgements agreeing is the most useful result here — the prose is dense, but it
is mostly load-bearing, and the shortfall is the honest answer rather than a
failure to try.

TWO REVERTS, both to protect something worth more than the lines.

issueops/ is back to its pre-trim state, giving up 610 lines. The conformance
contracts cite the leaf docs BY LINE — "pins treewalker.go:52-66" — 155 times.
Trimming the cited files silently repointed those at whatever text moved into
those numbers, across agent boundaries so no agent could see it. A semantic
remapper recovered 141 of them, but 23 needed judgement and several landed on
struct fields. The leaf docs are the spec the contracts are written against;
they are the one place in this change where dense prose IS the deliverable, and
keeping them stable is worth more than the 610 lines. tree_walker_contract.go
and version_reconciler_contract.go went back for the same reason: an agent had
deleted a paragraph containing a citation, so positional restoration could not
align them.

After the reverts, exactly 5 citations point into a still-trimmed file and 2 of
those are weak — both in cmd/bd/config_guard_test.go, which this series never
touched and whose citations were already wrong on main (init.go:361 pointed at
a closing brace; the guard it names is at init.go:1499).

VERIFICATION. A guard strips every comment and all whitespace from each of the
193 modified files at HEAD and in the worktree and requires the two to be
byte-identical, so a code change cannot hide in a comment diff. It handles `//`
inside string and raw-string literals, and was tested against a deliberate code
change before being trusted. gofmt clean, go build, go vet, golangci-lint 0
issues, and the two AST-based tests that PARSE trimmed files — the timed
provider binding pin over claim.go and the serve database-source gate over
serve.go — both pass.

One real defect found while trimming: checkDatabaseSource's doc block ran into
`// sourceRoles is ...` with no blank line, so godoc attached thirty-one lines
of the wrong prose to func sourceRoles and left checkDatabaseSource
undocumented. Fixed by separating them.
2026-08-06 08:06:59 +00:00
CI Bot
eee1a14b00 Delete the duplication narration git history already holds
Fifteen paragraphs of the form "this file used to hold a second copy of <cmd>:
it parsed the flags again, opened a unit of work...". The fact that a second
implementation existed explains nothing about the code that is there now, and
the commit that removed it says so in more detail than a doc comment should.

Reviewed individually rather than pattern-matched. A first pass keyed on
phrases like "used to" and "this slice" flagged 130 paragraphs and would
have taken out design rationale with them — it cut bootstrapper.go's "WHY ONLY
THIS SLICE OF bd init IS A ROLE" because "THIS SLICE" matched a pattern
meant for programme slices. That pass was reverted. Of the 69 paragraphs a
tightened pass surfaced, these 15 are the ones carrying no live information;
the other 54 explain an invariant, a trap, or a behaviour change a user sees,
and stay.
2026-08-06 06:59:33 +00:00
CI Bot
27ffb42e1f feat(init): put bd init's identity seam behind Bootstrapper and InitVerifier (bd-zl3u8)
`bd init` had two implementations of what a workspace's identity IS. The direct
route read issue_prefix out of the config plane at init.go:1358 and _project_id
four hundred lines later, decided adopt-vs-write with two helper predicates, and
wrote both keys by name. The proxied route called domain.BootstrapUseCase, which
held its own list of which keys an identity is made of, wrote them
unconditionally, and folded the Dolt remote into the same call. The two agreed on
the key names and disagreed on the rule, and no test compared them.

ONLY THE IDENTITY SEAM IS A ROLE. Everything else init does — creating .beads/,
writing metadata.json and config.yaml, initializing git, installing hooks,
starting a Dolt server — CREATES the substrate or the workspace around it, and a
role is reached through an accessor ON a store, so it cannot be what makes the
store exist. init.go alone is 3,060 lines; this commit touches the part that
happens inside the database.

TWO ROLES, AGAINST THE VersionReconciler PRECEDENT. That one is a read and a
write on one role because they are two shapes of one question, and every word of
that is true here too. The test that separates them is different: can one caller
be entitled to the READ and not the WRITE? Here yes, and not hypothetically —
`bd init --team-server` adopts a bts-provisioned identity and is forbidden to
write one, and a gateway credential may be read-only. Those paths now hold an
InitVerifier and never obtain a Bootstrapper, which the type system checks;
with one role they would hold the writer and the suppression would stay where it
is today, in three should* predicates on the CLI.

Q8 ANSWERED IN THE ROLE. Bootstrap over an already-identified substrate is
ErrAlreadyIdentified, carried by an *AlreadyIdentifiedError naming what was
found, decided from the same read the write would have followed inside ONE
transaction. Either marker is enough: a substrate several rigs share carries a
prefix one of them chose, and overwriting it renames every id the others are
about to mint. The guard now sits below both front doors instead of in front of
one, so gateway and adopt paths inherit it, and re-identifying is something
somebody asks for rather than something init does twice.

THE ROLE OWNS THE IDENTITY AND NOTHING ELSE. BootstrapProject wrote six values;
BootstrapRequest carries two. The fingerprints, the synced-at marker and the
recorded binary version are refreshed on EVERY init, adopt or not — a fresh clone
of an already-identified database needs its own fingerprints precisely because it
bootstrapped nothing — so a refusable one-time write would mean either a refusal
that stops recording them or a write that is no longer one-time. bd_version has a
second reason: it is VersionReconciler's key. The Dolt remote left too; it is
where the database syncs to, not what it is, and putting them in one call is what
let a remote that could not be created fail a bootstrap that had already
succeeded. domain.BootstrapUseCase is DELETED and domain.ConfigUseCase gains
SetMetadata, the write half of the GetMetadata it already published, so the
unit-of-work body can read, refuse and write in one transaction.

THE DEFECT. Proxied `bd init` against a database another rig had already
identified rewrote both markers with its own derived values. It verifies and
adopts now, printing the direct route's existing line, with the role's refusal as
the backstop. The direct route's two identity reads also became one snapshot, so
the prefix it adopts and the project id it reconciles against can no longer come
from either side of a concurrent write; shouldConsultInitProjectID still gates
whether the id is USED, so which identities init adopts is unchanged.

CONFORMANCE. backend/conformance/bootstrapper_contract.go holds twelve cases —
both roles in one file, because every promise on either is a statement about the
other — run at all three implementations with ZERO PARKS and zero divergences.
They deliberately do not re-test the decision: the validator's and the refusal's
whole tables are pinned without a database in internal/workapi/bootstrap_test.go.
What only a real backend can show is asserted instead: that the identity is there
for the NEXT caller (a new transaction on the unit-of-work backend), that a
refusal and a validation failure leave the markers EXACTLY as they were, that the
verifier reports an unreadable identity as an error rather than as an empty one,
and that a bootstrap costs at most one version-control entry. Two independent
bodies plus an engine check, not three votes: dolt and embeddeddolt share
internal/storage/issueops.BootstrapInTx and VerifyIdentityInTx and differ only in
how they reach a transaction. The bodies live there rather than in an importable
store<role> package because the read and the write it qualifies must see one
snapshot, which storage.DoltStorage cannot express — so there is no constructor
for a depguard entry to deny.

NO HTTP OPERATION, and that is a decision. A server can only serve a database it
is already bound to, and binding it required the identity this role writes, so
the only caller that could reach such an endpoint would be asking a running
server to identify a workspace that is by construction already identified — which
is the refusal. Bootstrapping over an unauthenticated surface is a different risk
class from reading one. The read half already has an endpoint:
ContextResponse.project_id on GET /v0/beads/context is InitVerifier's answer, on
the wire, today. Recorded in both leaf docs and in the checklist.

USER-VISIBLE, for the wave's changelog pass: proxied init adopts instead of
overwriting on a shared database; `bd init` no longer heals a substrate carrying
a prefix and no project id, which is Q8 as written; an explicit BEADS_DIR outside
the repo now gets a project id written from its own metadata.json instead of
being left half-identified. Reasoning and the alternatives are in
/data/tmp/sd-server/AMBIGUITIES.md as A-ini-0..7.

A-ini-0 IS A FALSE PREMISE IN THE BRIEF, not a finding about the code: bd-zl3u8,
bd-jtp1h and bd-yby99 do not exist in the workspace at BEADS_DIR. Verified by two
bd binaries failing to open it and by a direct SQL read of all 5,603 issues.
Everything else the brief asserted about the code checked out, so the spec used
was the brief plus Q8 plus A2.

Verified: build, vet, gofmt clean; golangci-lint 0 issues (its unparam check is
what found resolveInitIssuePrefix's now-dead `write` return, removed here);
TestBootstrapperContract 12/12 at dolt, embeddeddolt and uow; internal/workapi,
internal/storage, internal/telemetry, internal/jira, issueops, the root layering
pins and the whole internal/storage/domain and internal/storage/uow packages
green; internal/httpapi green and `make api-check` clean with no spec or
generated diff; TestInit* and TestResolveInit*/TestApplyInitGateway* and
TestCorpusGolden and TestDoctor* green under BEADS_TEST_EMBEDDED_DOLT=1;
TestProxiedServerExternalCreate, TestProxiedServerPing and TestProxiedServerUpdate
green under BEADS_TEST_PROXIED_SERVER=1, each of which runs
`bd init --proxied-server` in its harness; TestProxiedLookup green.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-06 03:01:33 +00:00
CI Bot
cf0a42cdae feat(delete): put bd delete behind the Deleter role and converge both routes (bd-x82so)
THE TWO ROUTES DISAGREED ABOUT WHAT --force MEANS on a destructive command.
On a local database `--force` deletes the named beads and orphans their
dependents; on a team server it deleted the whole dependent subtree, `--cascade`
was REFUSED outright ("not supported in proxied-server mode (delete always
cascades)") and Cascade was hardcoded true at both call sites. So there was no
way to delete one bead on a team server without taking everything under it, and
asking for the safer behaviour was an error.

Q1 ANSWERED IN THE ROLE. issueops.Deleter has one method, reached through
store.Deleter() and the provider's own accessor, and the three modes are request
fields: no flags refuses over a dependent the request did not name, Force
orphans it, Cascade deletes the closure. The guard is workapi's and the body's,
below every front door, for the reason Sweeper's require-a-filter gate is: a
second front door that inherited the capability without the guard would orphan a
workspace's graph by omission — which is exactly what this commit's HTTP
operation would otherwise have been.

IT IS A DIFFERENT ROLE FROM Sweeper, not a mode of it. Sweeper erases a set the
caller DESCRIBED; this erases rows the caller NAMED. That is what decides where
each one's safety lives: a description can be accidentally too wide, so Sweeper
carries a require-a-filter refusal; a list of ids cannot be, so this one's guard
is about the graph.

THE DEFECT. The direct route's batch path deleted the rows in one transaction
and then rewrote `[deleted:ID]` into the neighbours' text afterwards, discarding
every update error. A failure in the window left a workspace whose beads were
gone and whose descriptions still cited them by id. The existence probe, the
guard, the cascade expansion, the deletion and the rewrite are now one
transaction. WHAT THAT COSTS is written into the leaf beside the promise: the
transaction is as large as the deletion plus its neighbourhood, so a batch with
a very large neighbourhood fails whole. It is NOT Sweeper's trade (bd-hysee) —
the delete itself was already one transaction on every route — and the part that
is new is named rather than measured, which is recorded for sign-off.

TWO MORE DEFECTS the single call site removed. The one-id path held its own
transaction that removed each edge by hand, so it never reported labels, events
or orphans; and `domain.DeleteIssuesParams.EnforceCascadePolicy` and `.Force`
were declared, documented in fifteen lines describing exactly these three modes,
and READ BY NOTHING. They are deleted; the policy lives in the role now.

THE CONTRACT IS WHAT WAS DELETED, not what was reported.
backend/conformance/deleter_contract.go holds eleven cases, each citing the leaf
doc, run at all three backends with ZERO PARKS and zero divergences. Every case
that acts asserts row counts through QueryScalar rather than trusting the result
the delete reported about itself. They are TWO INDEPENDENT BODIES plus an engine
check: dolt and embeddeddolt share internal/storage/issueops.DeleteInTx and
differ only in how they reach a transaction, and the unit-of-work provider
reaches the same questions through the domain use cases. It does NOT duplicate
backend/conformance/audit_issue-lifecycle.go, which stays the right home for
`DeleteIssues` at the STORAGE seam: that suite's Factory hands back a bare
storage.DoltStorage, so the unit-of-work backend — where the guard did not exist
at all before this commit — can never run a case placed there.

`bd serve` gains POST /v0/beads/issues:delete, spec first. The dependents guard,
the all-or-nothing id resolution and the reference rewrite are the role's, so
the handler is argument validation and a projection. `cascade` and `force`
default false, which is the guarded mode; DeleteIssuesResult is not
x-go-type-pinned for the reason SweepResult is not, and a reflection test keeps
the projection honest. No page envelope, so nothing to pin in pinning.go.

USER-VISIBLE, and the CHANGELOG says so loudly: a team-server script relying on
the implicit cascade starts leaving orphans; `bd delete <one-id>` without
--force now refuses over an outside dependent, converging the direct route's
three paths onto the answer two of them already gave; the proxied `--json`
result gains `orphaned_issues`. Reasoning and the alternatives are in
/data/tmp/sd-server/AMBIGUITIES.md as A-del-1..6.

Verified: build, vet, gofmt clean; golangci-lint 0 issues; make api-check
(regenerate-and-diff plus the httpapi suite) green; TestDeleterContract 11/11 at
dolt, embeddeddolt and uow; the internal/workapi delete unit tests; the
internal/storage, internal/telemetry and root layering pins;
TestConformance/Audit/issue-lifecycle and the dolt TestDeleteIssues* family
(this commit refactors DeleteIssuesInTx's guard); TestEmbeddedDelete,
TestEmbeddedDeleteJSONDependencyErrorContract, TestBurnWisps,
TestWispGCProtectsActiveWisps and TestCLI_WispGCExcludeType under
BEADS_TEST_EMBEDDED_DOLT=1; TestProxiedServerDelete{,ForceOrphans,Wisp,
Concurrent}, TestProxiedServerMolBurn and TestProxiedServerWispGC under
BEADS_TEST_PROXIED_SERVER=1; and TestProxiedLookup*.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-06 02:59:08 +00:00
CI Bot
d10a388340 feat(list): put bd list behind Reader.List and the new BlockingAnnotator role (bd-5k21g)
STAGE TWO OF TWO. Stage 1 (aa10a725e) added MaxRows and SkipCounts to
ListRequest and flipped no routes; this is the flip, plus the one role the
decoration needed.

TWO PARTS, and the role first because the flip needs it.

THE ROLE. `issueops.BlockingAnnotator` answers the decoration a listing prints
beside each row — `(parent: X, blocked by: Y, blocks: Z)` — for the ids of a
page that has already been chosen. It is its own role rather than EdgeReader
growth (Q12 asked and answered two), and the distance between them is larger
than it looks: EdgeReader returns STORED ROWS of every type with targets
spelled as stored, no status consulted, and a per-anchor Missing flag from an
existence probe; this one returns a DERIVED summary of two types with closed
blockers dropped, the inbound direction included, and NO existence probe at
all. It is not Reader growth either — it has no order of its own, nothing it
returns depends on how the page was chosen, and a ListRequest field would have
implied the annotation was part of the query.

THERE IS NO MISSING FLAG, and that is a decision the leaf states rather than an
omission: an id that names nothing and an id with no live blocking edges
decorate identically, so a probe would be a read whose answer no caller can
use. One conformance case asserts that ABSENCE of a distinction.

A BLOCKER THIS DATABASE HOLDS NO ROW FOR COUNTS AS OPEN — an `external:`
reference, a foreign-repository id, a row whose issue was deleted. An
unreadable status is not `closed`, and a listing that hid a blocker it could
not resolve would report work as unblocked on the strength of a row it never
found. Both implementations already did this; it now has a sentence and a case.

THE ORDER WITHIN EACH LIST IS NOW PINNED, ascending with repeats collapsed, and
this is the commit's ONE user-visible change. Both lists are joined into one
line of output, so the query's natural order was user-visible bytes that could
move between runs. It affects only rows with two or more live blockers, and it
is recorded as A-blk-2.

TWO BODIES, NOT THREE. dolt and embeddeddolt share
storage/issueops.ExecuteBlockingAnnotation inside their own read transaction;
the unit-of-work provider is the genuinely separate one — it reads BOTH
dependency tiers for every id and merges, where the store side partitions the
ids by plane, and it resolves statuses only for the ids a row mentioned.
FinishBlockingAnnotation is what makes the SHAPE of the answer one decision
rather than two. Seventeen cases, three wirings, ZERO PARKS.

THE HTTP HALF. GET /v0/beads/dependencies/blocking, spec first, `make api-gen`
after. `IssueBlocking` is x-go-type-pinned to the role package the way `Cycle`
and `CycleMember` are, and BOTH the schema and the envelope's Items are pinned
in internal/httpapi/pinning.go — the v2.6.0 allOf trap was checked (the
generated type is a bare alias) and bd-5o3gt did not become two. The size bound
is maxDependencyAnchors, SHARED with the stored-edge read rather than given a
constant of its own: the two operations are asked about the same page of ids,
and two numbers would let a client ask one about a page the other refuses.
`dependencies.blocking` joins the capability vocabulary; `checkDatabaseSource`
grows a required role, which is the edit that reaches code this commit did not
write.

THE FLIP, one mode at a time and named as such in the code. FIRST `--json`:
the role's List runs the same LoadStoreListConfig, the same BuildListFilter and
the same workapi.FinishPage the branch ran longhand, so the page is unchanged
bytes and ErrTooManyRows still reaches handleMaxRowsError for exit 2. SECOND
every text rendering, with SkipCounts set — stage 1 added that field for this
arrival, and without it the flip would trade a plain scan for three aggregate
joins on the most-run command in the tree. THIRD the decoration.

WHAT STAYS OFF THE ROLE is --watch and the hierarchical --parent tree, the two
modes that consume the FILTER as a value. The bead also named --deps and
--format, and its stated reason — "reach no epilogue on either route" — is
false for both: they run FinishPage and printTruncationHint today. What is
genuinely off-role in those two is the WHOLE-GRAPH dependency-record load they
perform, which is neither a page nor the blocking decoration; their page comes
from the role like every other mode's. Recorded as A-blk-3 with the reading
this commit proceeded under, which is also the reading stage 1's own message
states ("stage 2 moves bd list's TEXT path onto the role").

The proxied route loses `runListProxiedReady`: --ready is ListRequest.ReadyFlag
and picking the ready query from it is the role's job on both routes. Two
functions differing only in which use-case method they called is the drift this
replaces.

PROVABLY INERT AT THE CLI, measured rather than argued: 31 `bd list` / `bd
children` invocations — every output mode, both cap knobs, --ready, --parent,
--format, --deps — run against a binary built from integration/facade-wave-3
and one built from this commit, over ONE shared workspace, differ on exactly
the two multi-blocker lines A-blk-2 predicts and nothing else in 687 lines. A
base-against-base run isolates the one other moving line as the
once-per-period install tip.

The forbidigo exception list did NOT shrink, and the count in
issueops/reader.go's claim is unchanged. cmd/bd/list.go and
list_proxied_server.go were never on it; cmd/bd/list_show_filter_modes.go still
is, because the tree walk, the watch loop, the proxied builder call and `bd
show --current` all still name the type. Said in the config rather than implied
by silence.

Verified: build, vet, gofmt clean; golangci-lint 0 issues; the seventeen new
cases at dolt, embeddeddolt (BEADS_TEST_EMBEDDED_DOLT=1) and uow, all green
with no skips; internal/httpapi and make api-check; internal/storage,
internal/telemetry, internal/jira, internal/workapi/..., issueops and the root
layering pins; the embedded `bd list`/`bd children`/max-rows CLI suites,
TestProxiedServerList under BEADS_TEST_PROXIED_SERVER=1 (58 subtests including
tree_parent, the three format modes, ready pagination and the three max-rows
refusals), TestProxiedLookup*, and the protocol corpus package.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-06 02:56:57 +00:00
CI Bot
519fb1479b feat(issueops): put bd purge and bd prune behind the Sweeper role (bd-pn231)
`bd purge` selected closed wisps in one transaction and deleted them in
another. A bead closed, unpinned or cited in the window between the two was
judged on one state and acted on in a different one — the TOCTOU the bead
names — and the proxied twin held a second copy of the whole flow: its own
candidate filter, its own glob match, its own closed_at recheck, its own
reference scan and 190 lines of output kept character-identical to the direct
route's by hand.

PURGE AND PRUNE ARE ONE CAPABILITY, which the design left open and the code
answers plainly: both routes already ran ONE function with a `purgeScope`
struct choosing the tier. So issueops.Sweeper has ONE method, reached through
store.Sweeper() and the provider's own accessor, and SweepRequest.Tier selects
the plane — `ephemeral` is purge, `durable` is prune, and the two are disjoint
by construction. What genuinely differed became request fields rather than a
second role: the require-a-filter refusal keys on Tier, and the citation
protection is ASKED FOR (ProtectReferenced) instead of being inferred from a
command name, which is what the shared body did (`scope.cmdName == "prune"`).

Q9 ANSWERED IN THE ROLE. The require-a-filter gate is
workapi.ValidateSweepRequest, below every front door: a durable sweep with
neither a cutoff nor an id pattern is ErrValidation. It is a safety invariant,
not presentation — without it a second front door is one handler away from an
unguarded mass delete, which is exactly what this commit's HTTP operation would
otherwise have been. The CLI keeps its friendly message, and says in place that
it is there for the WORDING while the guard is the role's; the contract case is
what proves the guard survives that branch being deleted.

THE DEFECT, AND ITS PRICE. The whole sweep is now one transaction, so the set
the result describes IS the set it deleted. That gives up the server-backed
store's batched wisp deletion (200 per transaction, added for Dolt's 10s write
timeout after bd-2ehd and ff-tqm): a sweep too large now fails WHOLE. That is
the better failure — the partial one it replaces reported a deleted count of
ZERO while having deleted rows — and the other two backends already worked this
way. It is written down as a promise WITH its cost, and recorded for sign-off.

TWO MORE DEFECTS the single call site removed. `--dry-run` passed force=false
to the delete where the real run passed force=true, so a preview could FAIL
over dependents the sweep would have orphaned — and the CLI answered that
failure with zeros. And `filepath.Match`'s error was discarded on both routes,
so `--pattern '['` printed "No closed beads to prune" and exited 0; it is now
ErrValidation quoting the pattern.

THE CONTRACT IS WHAT WAS DELETED, not what was reported.
backend/conformance/sweeper_contract.go holds ten cases, each citing the leaf
doc, run at all three backends with ZERO PARKS and zero divergences. Every case
that acts asserts row counts through QueryScalar rather than trusting the
result the sweep reported about itself, which on a destructive operation is the
assertion that matters; every case scopes itself with an id pattern, because a
sweep is asked of a whole TIER and an unscoped one would clear the next case's
seeds. They are TWO INDEPENDENT BODIES plus an engine check: dolt and
embeddeddolt share internal/storage/issueops.SweepInTx and differ only in how
they reach a transaction, and the unit-of-work provider reaches the same four
questions through the domain use cases.

THE HTTP OPERATION, spec first (per bd-jtp1h's A2 scope decision):
POST /v0/beads/issues:sweep, capability `issues.sweep` — the first DESTRUCTIVE
operation on a surface that was reads plus one claim. It is a collection-level
custom method with a body rather than DELETE with a query string, because a
dropped query parameter widens what is erased where an unknown body member is
refused by name. The handler decodes six members and calls the role; it does
not implement the safety gate, the tier vocabulary or the glob, all of which
are the role's ErrValidation reaching the wire as a 400 through failSweepErr.
No component carries allOf and none is x-go-type-pinned — there is no canonical
Go struct whose JSON encoding is this body, since the CLI publishes these
numbers under `purged_count`/`pruned_count` — so the projection is tested
instead. `bd serve --help` grew a DESTRUCTIVE OPERATIONS section and the
--allow-non-loopback warning now says peers can bulk-delete closed beads.

`bd gc` keeps the closed-candidate recheck by calling the SAME pure function
the role calls (workapi.FilterSweepCandidates), so the two cannot drift; the
reference matcher and its 10K-body budget moved to internal/workapi with the
scan. cmd/bd/purge.go and purge_proxied_server.go LEFT the forbidigo exception
list, which is how a role commit proves its front doors reached the role.

USER-VISIBLE, for the wave's changelog pass: the version-control label for a
sweep is now `bd: sweep <n> <tier> bead(s)` on both routes, where proxied wrote
`bd: prune <n> bead(s)` and direct wrote `bd: delete <n> issue(s)` — an HTTP
sweep is not `bd prune`, so the label names the operation and the tier from
every door; a malformed `--pattern` now exits non-zero; `--dry-run` no longer
refuses over dependents the real sweep orphans; and `bd serve` gains a
bulk-delete endpoint. Reasoning and the alternatives are in
/data/tmp/sd-server/AMBIGUITIES.md as A-swp-1..9.

Verified: build, vet, gofmt clean; golangci-lint 0 issues; make api-check
(regenerate-and-diff plus the httpapi suite) green; TestSweeperContract 10/10 at
dolt, embeddeddolt and uow; the internal/workapi, internal/storage and
internal/telemetry suites; TestEmbeddedPurge, TestEmbeddedPurgeConcurrent,
TestEmbeddedPrune, TestPrune_protectsBeadCitedByCustomStatusBead and
TestEmbeddedGC under BEADS_TEST_EMBEDDED_DOLT=1; TestProxiedServerPrune under
BEADS_TEST_PROXIED_SERVER=1; TestProxiedLookup*; and the root layering pins.
The protocol corpus has no purge/prune case to account for.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-05 16:40:26 +00:00
CI Bot
aa10a725e5 feat(list): put bd list's row cap and counts hydration on ListRequest (bd-b34o7)
STAGE ONE OF TWO. Fields, not methods, and no route flips — those are stage 2
(bd-5k21g). `issueops.ListRequest` gains MaxRows, MaxRowsSource and SkipCounts,
each with a conformance contract running at all three backends and zero parks.

MAXROWS IS THE EXACT INVERSE OF OFFSET, which is why it needed no new shape.
Offset is honored by the unit-of-work body — it renders OFFSET — and refused by
the store-backed one with a typed *ErrUnsupported. The cap points the other way:
the store search path enforces it after the scan (EnforceMaxRowsCap), and the
unit-of-work query path (internal/storage/domain/db) reads no cap at all, so a
request carrying one would come back as the FULL uncapped answer with nothing on
it to say so — a caller that set a circuit breaker handed exactly the runaway
query it was guarding against. It refuses instead, naming the operation and the
backend. `bd list --max-rows --proxied-server` has always refused one layer up
in the CLI for that reason; this is the same refusal for the callers that are
not the CLI. RunReaderListMaxRowsIsHonoredOrRefused mirrors
RunReaderOffsetIsHonoredOrRefused, including the never-silently-ignored clause,
and asserts the complement too: a cap the result set FITS inside must still come
back as an ordinary page, or a body that refused every cap out of hand would
pass.

MAXROWSSOURCE is the third field and the bead named two. It is attribution
only — it decides no answer — but `handleMaxRowsError` falls back to
"BEADS_MAX_ROWS" when it is empty, so a request that carried the number without
the source would make stage 2's route flip start telling operators to raise the
wrong knob. The contract asserts it comes back on the cap error.

SKIPCOUNTS is the SkipLabels precedent one column over: the three cardinality
joins are dropped and DependencyCount/DependentCount/CommentCount come back
zero, to be read as unknown rather than as none. It has to land WITH MaxRows —
stage 2 moves `bd list`'s TEXT path onto the role, and that path calls
SearchIssues today and projects no counts at all, so arriving on a counted page
without a way to opt out is a straight perf regression. The expensive member is
the reverse-blocker aggregate, which joins on a COALESCE key the pure-Go
analyzer cannot auto-index — the known embedded sore point, and the reason the
knob is worth having at all.

The contract's second half is the load-bearing one: NOTHING ELSE MOVES. Same
rows, same order, same has-more, same Parent — asserted by running the identical
request both ways rather than against a written-out expectation. Parent is the
tripwire: it rides the same mega-query and is not a cardinality, so an
implementation that made an aggregate join inner, or suppressed the parent join
too, would answer a strict subset and still look like it had "skipped the
counts".

WHAT THE SQL DOES. sqlbuild.SearchCountsSQL's two trailing hydration bools
become one CountsHydration value, so a path cannot pick up one opt-out and drop
the other, and both stores plus the unit-of-work repository read the pair
through one helper. A suppressed aggregate is projected as a constant IN PLACE
rather than removed: the scan reads the six extra columns positionally, so the
shape is invariant. Ready work passes the zero value at every call site —
types.WorkFilter carries neither knob, which is what "SkipLabels and SkipCounts
are not carried onto the ReadyFlag arm" means, now stated where a caller reads
it. MaxRows IS carried there; reader_ready_scope.go already claimed so, and this
is the commit that makes the claim true, since until now the field existed only
on the filter.

ONE HAND-ROLL DELETED. `bd list` built the filter through the shared builder and
then reached in and stamped filter.MaxRows/MaxRowsSource onto it — the
"build it, then change it" half-step this programme exists to make unreachable,
and the reason the cap was invisible to every implementation of Reader.List. The
cap is resolved in gatherListInput onto the request, BuildListFilter is now the
only writer of those two filter fields, and the proxied refusal reads the
already-resolved value (rejectResolvedMaxRowsUnderProxiedServer) so a malformed
BEADS_MAX_ROWS still warns exactly once.

PROVABLY INERT AT THE CLI, measured rather than argued: 22 `bd list` / `bd
children` invocations — every output mode, both max-rows knobs, the malformed
and negative cases — run against a binary built from integration/facade-wave-2
and one built from this commit, over ONE shared workspace so both read identical
data, differ on exactly one line of 617. `bd list --max-rows -1 --status bogus`
now reports the malformed flag instead of the invalid status; both exit 1, it
needs two bad arguments to reach, and it is recorded as A-lst1-3.

NO OPENAPI OPERATION AND NO NEW QUERY PARAMETER, deliberately, recorded as
A-lst1-1. `bd list`'s operation (GET /v0/beads/issues) already exists and is
already on the role, and neither field can be published on it yet: `bd serve`
always builds a provider-backed server, which REFUSES max_rows, so the parameter
would be one the reference server can never honor; and skip_counts would set
three unconditional integers on a PINNED response component to zero, leaving a
client unable to tell "no dependencies" from "not computed" — the failure
comments_omitted exists to prevent on the detail view. `make api-check`
regenerates nothing.

Verified: build, vet, gofmt clean; golangci-lint 0 issues; the two new cases at
dolt, embeddeddolt (BEADS_TEST_EMBEDDED_DOLT=1) and uow, plus the whole Reader
contract at all three; the builder golden (35 recorded cases plus two new ones
for the new fields) and the counts-SQL shape test; internal/httpapi and
make api-check; internal/storage/{issueops,domain/...}, internal/workapi,
internal/types, internal/telemetry, the root package; the embedded
`bd list`/`bd children`/max-rows CLI suites, TestProxiedServerList under
BEADS_TEST_PROXIED_SERVER=1 (including reject_max_rows_flag,
reject_max_rows_env and allow_max_rows_zero), TestProxiedLookup*, and the
protocol corpus package.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-05 16:36:31 +00:00
CI Bot
671c7801d2 feat(query): put bd query behind the Querier role and stop it dropping matches (bd-pohmh)
`bd query "type=bug OR label=urgent"` has been answering with a prefix of its
answer and calling it complete. The expression language has OR, NOT and
parentheses, which no storage filter expresses, so both routes fetched a WINDOW
of candidate rows — max(3*limit, 100) — and applied the expression to those in
memory. A match past row 100 was absent from the page and unreported by
has-more. The same six lines of arithmetic were written twice, once per route,
and both copies were wrong in the same way.

THE ROLE. issueops.Querier, reached through store.Querier() and the provider's
own accessor. One method over a request whose predicate is a SENTENCE rather
than a set of fields, which is what makes it a role instead of a mode of
Reader: a ListRequest is a conjunction — every field narrows — and no
arrangement of its twelve callers' fields expresses a disjunction. It is
equally not a raw query passthrough; the language names no table, no join and
no column outside a closed vocabulary, which is why a contract can promise
anything about it at all.

THE FIX, which Q3 approved as user-visible. A predicate query's filter now
carries NO row limit: the predicate sees every candidate row, the page is the
first Limit MATCHES of the complete matching set, and has-more is exact. The
decision has one home, internal/workapi.BuildQueryPlan, which both bodies
execute. The cost is stated rather than hidden — a broad OR over a large
workspace now reads every row its base filters admit — and CHANGELOG.md says so
in the same words.

WHAT PINS THE FIX, at three levels, because the contract alone cannot see it.
TestBuildQueryPlanLeavesAPredicateQueryUNBOUNDED asserts the arithmetic in
microseconds. TestAPredicateQueryFindsAMatchBeyondTheOldWindow seeds 101 rows at
ONE backend and reads back the match at row 101 — verified to discriminate:
with the old window temporarily reinstated it returns zero rows. The portable
contract asserts the PROMISE the window broke (a page is a prefix, has-more is
exact) and, confirmed by the same experiment, does NOT discriminate the old
window at its small scale; the contract's header says so rather than implying
coverage it does not have.

THE CONTRACT. backend/conformance/querier_contract.go holds nine cases, each
citing the leaf doc by line, run at all three backends with ZERO parks. TWO
independent bodies plus an engine check: dolt and embeddeddolt share
internal/workapi/storequerier, and the unit-of-work provider is genuinely
separate — it is the only leg on which the Offset case takes its HONORED branch,
since that seam renders OFFSET where the store body refuses uniformly.

TWO SMALLER USER-VISIBLE CHANGES ride along, both filed in AMBIGUITIES.md
(Q22, Q23) for the owner's batch. `--offset` with an OR/NOT expression is no
longer refused: the offset skips MATCHES, which is only meaningful now that
every match is seen, so an error became an answer. `--limit -1` is now
ErrValidation instead of an undocumented second spelling of unlimited. The
`--offset` + `--sort` refusal survives and moved INWARD — the role makes it, for
every caller, because the order is applied to the rows the query bounded and
each page of an offset walk would be sorted for itself — so its wording changed
with its address, as did the wording of a malformed expression on both routes.

A DEFECT FOUND AND NOT FIXED, recorded as A-qry-1 rather than papered over: an
UNLIMITED request carrying an Offset renders SQL the Dolt engine answers with a
recovered panic (makeslice: cap out of range, out of topRowsIter). It predates
this role — `bd query --offset N --limit 0 --proxied-server` built the same
filter — and it is a storage-seam bug, so the contract case asks its question at
a bounded limit and says why at the case site.

THE HTTP OPERATION, spec first (per bd-jtp1h's A2 scope decision):
GET /v0/beads/issues:query, capability `issues.query`, answering a new QueryPage
{items, has_more}. It publishes no cursor and no `offset`: a predicate query's
matching set is assembled outside the database, so there is no keyset position
to encode, and an offset is honored by one database source and refused by the
other, which is not a difference to put on a wire. QueryPage carries no allOf
and its Items are pinned in pinning.go beside ReadyPage's and IssuesPage's — the
edit wave 2 missed once (bd-8ri3m). Adding a second sort enum made oapi-codegen
disambiguate the FIRST one, renaming the generated ListReadyWorkParamsSort
constants (Hybrid -> ListReadyWorkParamsSortHybrid); nothing outside the
generated file named them. httpapi.Config's roles source grows a required eighth
member, and a Config complete under the previous release is now refused at
Listen rather than nil-dereferencing on the first issues:query request.

WHAT ELSE CONVERGED. Both output modes read ONE query — the counted one --json
always used — so a predicate can no longer be applied to two different row sets
depending on the flag (A-qry-1's neighbour, Q24). The direct route prints the
truncation hint for the first time, not by new choice but because it finally has
an honest has-more to print.

Incidental: internal/storage/role_accessor_decorator_test.go's four
near-identical "the four read roles" paragraphs — one appended by each wave-2
slice — are collapsed into the one accurate paragraph the table needs. Same
defect as bd-8ri3m, comments only.

Verified: build, vet, gofmt clean; golangci-lint 0 issues; make api-check green;
TestQuerierContract 9/9 at dolt, embeddeddolt and uow;
TestAPredicateQueryFindsAMatchBeyondTheOldWindow; the internal/httpapi package
suite; internal/workapi, internal/storage, internal/telemetry, internal/query
and the root package; TestEmbeddedQuery under BEADS_TEST_EMBEDDED_DOLT=1 and
TestProxiedServerQuery under BEADS_TEST_PROXIED_SERVER=1; TestProxiedLookup*.
The protocol corpus drives no `bd query` invocation and is untouched.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-05 16:36:05 +00:00
CI Bot
75b2374890 feat(issueops): put the startup version reconciler behind the VersionReconciler role (bd-gkmft)
The version markers had two implementations of one rule. The direct route read
bd_version and bd_version_max out of the metadata plane in
cmd/bd/version_tracking.go, compared them with doctor.CompareVersions and wrote
them back; the proxied route opened a unit of work and called a ReconcileVersion
method on the config use case, which held its own copy of the same comparison,
the same two downgrade guards and the same high-water rule. The two agreed, but
nothing made them agree and no test compared them. Both now ask for a role, and
the difference between the routes is which accessor answers.

THE ROLE BELONGS TO NO COMMAND, and it is the only one in this programme that
does not. It fires from PersistentPreRun on EVERY startup, on both routes,
before the command the user typed has run — which is exactly why it went
unnoticed: `bd version` prints two strings, opens no store and reaches none of
this, so the state machinery was hiding behind a command that does not use it.

THAT ORIGIN IS A CONSTRAINT ON THE PROMISES, not a piece of history, and the
leaf doc says so where a reader will meet it. A role that runs before every
command pays for itself on every command, so it does two point reads on the path
that changes nothing, loads no configuration, takes no lock, repairs nothing —
and, the clause that matters most, it NEVER refuses the command in front of it.
A downgrade is an OUTCOME with a nil error, because an older binary is allowed
to use a workspace a newer one has opened; a genuine failure is an error the
CALLER logs and walks past, which both front doors do at debug level. A role
whose callers must ignore its errors has to say so where the promise is made
rather than leave each caller to decide.

TWO METHODS, ONE ROLE. RecordedVersion and ReconcileVersion are two shapes of
one question — the write's promise IS a statement about what a later read
returns — which is what the governing rule permits a role to be born with, and
WorkspaceConfig set the precedent. It is not padding: the direct front door
needs the READ alone. autoMigrateOnVersionBump probes a read-only store first so
an already-current workspace never pays for the writable open, and before this
commit that probe read the metadata key by hand — the "CLI knows the storage
key" shape this programme exists to remove, on the hottest path in the codebase.

WHY IT IS NOT WorkspaceConfig WITH TWO MORE KEYS. Two planes, two lifetimes. A
workspace setting is durable and travels with the database; these two markers
are dolt-ignored, do not survive a clone and are deliberately different per
machine. Publishing them through the settings plane would put a value that
cannot be shared behind an interface whose whole promise is that its values are.

ONE DECISION, THREE SUBSTRATES. workapi.PlanVersionReconcile is the pure planner
every implementation decides through; domain.ConfigUseCase LOSES ReconcileVersion
and gains SetLocalMetadata, the write half of the GetLocalMetadata it already
published, so the unit-of-work body can read, plan and write in ONE transaction.
Deleting the use-case method is what makes the rule single-sourced rather than
duplicated under a role.

CONFORMANCE. backend/conformance/version_reconciler_contract.go holds nine cases
run at all three implementations with ZERO parks and zero divergences. They
deliberately do NOT re-test the decision: the planner's whole table — upgrade,
no-op, both refusals, the catch-up to the mark, the dotted comparison in which
1.2.0 and 1.2.0-rc1 are equal — is pinned without a database in
internal/workapi/versionreconcile_test.go, and repeating it here would be
testing one pure function three times over three sql-servers. What only a real
backend can show is asserted instead: that a recorded marker is there for the
next caller (a new transaction on the unit-of-work backend), that a refusal and
a validation failure write NOTHING, that reconciliation adds no history entry at
all, and that a reconciliation which CANNOT COMPLETE reports an error and leaves
both markers standing. Two independent bodies plus an engine check, not three
votes: dolt and embeddeddolt share internal/workapi/storeversionreconciler.

The fixture carries one hook the frozen roleFixtureKit cannot supply, built at
each wiring site the way CycleDetectorFixture.Exec is: the two states that
matter most — a recorded version BELOW the high-water mark, and its catch-up —
are states the role can never produce, so they are seeded past it.

THIS IS THE FIRST COVERAGE THE DIRECT ROUTE'S RECONCILIATION HAS EVER HAD. Its
round-trip tests (MigratesVersion, AlreadyMigrated, RefusesDowngrade,
TracksMaxVersion) were deleted with the SQLite backend and never replaced; the
note recording that is still in cmd/bd/version_tracking_test.go. The seven
subtests of the deleted use-case method go with it, replaced by the exhaustive
planner table plus nine cases at three backends.

NO HTTP OPERATION, and that is a decision rather than an omission — recorded in
the leaf doc and as A-ver-2 for the owner. The markers are clone-local: they
describe the machine holding the database, so a remote client reading them
learns something it cannot compare against anything it holds. The one version
fact a client CAN act on, the serving binary's release, is already published as
ContextResponse.bd_version, which the document already names as the only field a
client may compare as a version. A write endpoint is worse: reconciliation is an
effect of a PROCESS STARTING, and a client asking a server to record the
client's version would be asking it to lie about which binary holds the
database. If the owner wants a read-only GET /v0/beads/version, the role, the
accessor and both bodies are already here.

NO USER-VISIBLE CHANGE. Every outcome is identical; only three debug lines
moved. One accidental behaviour became deliberate: a binary whose Version string
is empty used to be handled by the downgrade guard on a populated workspace and
by an equality short-circuit on an empty one, and is now an explicit
ErrValidation that writes nothing either way.

ENFORCEMENT. storeversionreconciler joins the cmd-bd-role-constructors deny
list. The version path never named types.IssueFilter, so there is no forbidigo
exception to remove. engdocs/ADDING_AN_ISSUEOPS_ROLE.md gains the two things
this role taught the checklist: a role may honestly have NO HTTP surface, and a
contract case may need a fixture hook for a state the role cannot produce.

Verified: build, vet, gofmt clean; golangci-lint 0 issues;
TestVersionReconcilerContract green at dolt (9/9), embeddeddolt (9/9) and uow
(9/9); the planner unit tests, both decorator enumerations, the root layering
pins, internal/jira and the internal/storage/domain/db config suite green;
internal/httpapi green and `make api-check` clean with no spec or generated
diff; TestReconcileVersionPersistsAcrossUOW green; TestProxiedLookup green;
`-run 'TestTrackBdVersion|TestAutoMigrateOnVersionBump|TestGetVersionsSince|TestMaybeShowUpgradeNotification|TestInitDoltMetadata'`
green under BEADS_TEST_EMBEDDED_DOLT and TestProxiedServerContext /
TestProxiedServerInfo green under BEADS_TEST_PROXIED_SERVER; TestCorpusGolden
green, so no command's JSON moved.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-05 16:35:01 +00:00
CI Bot
b1b253f35b feat(ready): put bd ready's published total behind the ReadyCounter role (bd-s10oa)
`bd ready --limit 100` prints "showing 100 of 412", and the 412 came from
nowhere in particular. The direct route computed it inline: unwrap past the
storage decorators, type-assert to storage.ReadyWorkCounter, and fall back to
an unbounded ready query when the assertion missed — twice, once in the --json
branch and once in the text one, with two different fallbacks. The proxied
route could not compute it at all and published no `total` key, so the same
script read a number under one workspace topology and nothing under another.

THE ROLE. issueops.ReadyCounter, reached through store.ReadyCounter() and the
provider's own accessor. It answers a question neither neighbour can: Reader
answers with a PAGE and its verdict is has-more ("did the limit hide
anything"), where this is "how many" — strictly larger, and already published
output, so collapsing the two would change what a shipped surface says. Counter
answers a predicate over one table, and the ready predicate is blocker-aware:
it reads the dependency graph and the wisp tier, which no CountRequest can
describe. Counter's own doc already said the count of ready work would be its
own role for that reason.

It takes issueops.ReadyRequest VERBATIM, the precedent ClaimNextRequest set, so
a listing, a claim and a count ask ONE question of ONE set. Limit and Offset are
ErrValidation for the reason a claim refuses them: a cardinality has no page, so
a limit would answer "how many of the first N" and an offset would subtract the
rows it skipped from the size of a set that still holds them.

THE CONTRACT IS AN IDENTITY, not a resemblance:

	CountReady(r).Total == len(Reader.Ready(r with Limit=0).Items)

at every implementation. backend/conformance/ready_counter_contract.go holds
seven cases, each citing the leaf doc by line, run at all three backends with
ZERO parks. They are TWO independent bodies plus an engine check: dolt and
embeddeddolt share internal/workapi/storereadycounter (one indexed COUNT(*) per
plane minus their overlap), and the unit-of-work provider is genuinely separate
code that runs the unbounded ready query and takes its length — which is why
the wisp-tier case is written the way it is, since that is where a COUNT and
the page it sizes are assembled by different arithmetic.

A DEFECT THIS FOUND, and it is not the count's. `bd ready`'s directory-label
default (GH#541) never reached the ReadyClaimer role. claimNextRequest re-ran
the gatherer's own emptiness test against in.filter — and the gatherer had
already written the default INTO that filter, so the test saw a non-empty label
set and skipped. The branch could never fire. In a directory with
`directory.labels` configured, `bd ready --claim` therefore claimed from the
WHOLE ready front while `bd ready` beside it listed only the configured scope:
exactly the "hand an agent work the listing never offered it" that
ReadyClaimer's contract exists to forbid. The gatherer now RECORDS its decision
(readyInput.dirLabels) and both roles read it, so there is one answer instead of
two derivations of it. Caught by writing the count's own test for the same
line, and pinned by cmd/bd/ready_role_request_test.go.

WHAT ELSE CONVERGED. Both routes and both output modes now ask one question
through one accessor: the direct route's two inline epilogues become one call,
and the proxied route's `pagination.total` exists for the first time. The
"showing X of N" text a human reads and the total a script parses are the same
number by construction. cmd/bd no longer names storage.ReadyWorkCounter at all
— the capability is required by the store body's PARAMETER TYPE, so a backend
that cannot size the ready set fails to compile instead of falling back to a
mega-query at runtime.

THE HTTP OPERATION, spec first (per bd-jtp1h's A2 scope decision):
GET /v0/beads/ready:count, capability `ready.count`, answering
`ReadyCount {total}`. It publishes no `limit` and no `sort`: a cardinality has
no page and no order, and the handler sends the listing's own sort default so
the request stays the listing's request rather than one that resembles it. The
filter vocabulary is decoded by ONE function shared with GET /v0/beads/ready
(readyFilters), so the two operations cannot admit different parameters — which
is what the identity rests on over the wire.
`TestCountReadyAndListReadyAdmitTheSameFilters` compares the two predicates
built from one query string. No component here carries allOf and none is
x-go-type-pinned: the pinned seven are canonical Go structs whose JSON encoding
IS the contract, and there is no canonical struct for this number — the CLI
publishes it inside its own stdout envelope, which is not a wire type — so
pinning would weld the body to a CLI presentation type rather than prevent a
drift. The generated output was read to confirm it (a struct with `Total
int64`, not an alias), which is the v2.6.0 trap this document warns about.

httpapi.Config's ROLES database source grows a REQUIRED third member. That is
the sharp edge for the next role commit and is now written down in
engdocs/ADDING_AN_ISSUEOPS_ROLE.md as step 13: a Config carrying the old pair
would bind and then nil-dereference on the first request that reached the new
handler, so Listen refuses it with the same message a half-set pair gets.

USER-VISIBLE, for the wave's changelog pass: proxied `bd ready --json --limit N`
now publishes `pagination.total`; `bd ready --claim` now honours the
directory-label scope on both routes.

Verified: build, vet, gofmt clean; golangci-lint 0 issues; make api-check
(regenerate-and-diff plus the httpapi suite) green; TestReadyCounterContract
7/7 at dolt, embeddeddolt and uow; the httpapi package suite; the direct-route
`bd ready` suites under BEADS_TEST_EMBEDDED_DOLT=1 and the proxied ones under
BEADS_TEST_PROXIED_SERVER=1, including the pagination envelope that now asserts
the total; TestProxiedLookup*; and the ready protocol-corpus tests, which are
byte-identical.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-05 09:47:24 +00:00
CI Bot
c1c283e5ce feat(issueops): put bd status behind the StatsReporter role (bd-4ze25)
`bd status` (and its `bd stats` alias) had two implementations of the same
command. The direct route asked the store for statistics and, under
--assigned, built an assignee filter, ran a ready-work query and folded
five status counts itself; status_proxied_server.go did all four again
through a unit of work. Both now build an issueops request and ask for the
role, and the difference between the two routes is which accessor answers.

THE ROLE. Its numbers are DEPENDENCY-AWARE — the blocked count reads the
denormalized transitive is_blocked flag and readiness is derived from it —
so no predicate over the issues table describes them and this is its own
role rather than a sixth Counter dimension, which is what issueops/
counter.go already said it would be. Stats and AssigneeStats are born
together because they answer the same question of two sets; they are two
METHODS rather than one with an Assignee field because the assignee answer
fills four fields of the same struct by different definitions, and a
request whose optional string silently changed what a number meant is the
shape this programme exists to remove.

WHAT THE LEAF DOC NOW SAYS OUT LOUD, none of it written down anywhere
before: BlockedIssues counts the graph, not the "blocked" status;
ReadyIssues is arithmetic and NOT the cardinality of `bd ready`;
PinnedIssues overlaps every status bucket so the buckets do not sum to
Total; the workspace-wide answer excludes the wisp tier while the
assignee-scoped one merges it; --no-blocked is a HINT whose only report is
BlockedIssues being nil; and EpicsEligibleForClosure and AverageLeadTime
are structurally always zero, which is why `bd status`'s "Extended:"
branch has never once printed.

CONFORMANCE. backend/conformance/stats_reporter_contract.go holds thirteen
cases, each citing the leaf doc by line, run at all three implementations
with ZERO parks and zero divergences. Unusually for this suite they are
THREE genuine votes: the two stores share the role body (storestats) but
dolt/queries.go, embeddeddolt/statistics.go and domain/db/issue.go each
spell the blocked count and the ready subtraction themselves. Every
workspace-wide case asserts a before/after DELTA — a summary takes no
predicate, so there is no IDFilter to scope it with the way the Counter
contract scopes its cases.

HTTP. GET /v0/beads/stats is added to the Tier-1 document FIRST and the
types generated from it: a `Statistics` schema x-go-type-pinned to
types.Statistics (checked: the pin survives, and the schema is now in the
JSON-tag bijection test), a StatsResponse envelope mirroring the CLI's
--json shape minus `recent_activity`, which no shipped path populates. The
handler calls the same role both CLI routes call. `blocked_count_skipped`
is DERIVED from the answer, never echoed from the request, because the
hint is a hint. httpapi.Config's roles source grows a third field and
requires it with the other two: a source that answers some operations and
faults on others is not a source.

ENFORCEMENT. cmd/bd/status.go and status_proxied_server.go no longer name
types.IssueFilter or types.WorkFilter, so `status` LEAVES the forbidigo
exception list (63 -> 61 of 388 files). The role-constructor depguard list
gains storestats.

TWO USER-VISIBLE CHANGES, both improvements and both small: `bd status
--assigned` reports the underlying failure instead of the bare "failed to
get assigned statistics", identically on both routes; and the proxied
--no-blocked warning now fires from the ANSWER rather than from the route,
so a backend that gains a fast path stops printing it with no edit.

Verified: build, vet, gofmt clean; golangci-lint 0 issues; make api-check
clean (no codegen drift, whole httpapi package green);
TestStatsReporterContract 13/13 at dolt, embeddeddolt and uow;
TestEmbeddedStatus and TestProxiedServerStatus green with their gates set;
TestProxiedLookup green; TestCorpusGolden green.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-05 09:27:16 +00:00