feat(http): list/show counts/dep tree/ping over http, the advertised external-dependency policy, one-lookup not-found (S6b/S6c/S6d) (#7471)

* feat(http): serve list/show counts/dep tree/ping, close+reopen under a session, one-lookup not-found (S6b/S6c/S6d)

S6c. The external-dependency decorator rebuilt its role views from the
legacy DoltStorage seam (storereader over itself, IsBlocked,
GetDependencyTree, ClaimReadyIssue), which a remote store only partly
serves: `bd list`/`bd children` refused on the SearchIssuesWithCounts stub,
`bd show --json` printed zero counts, the default `bd dep tree` refused,
`bd ready --claim` and `bd close` of an externally blocked issue reached
unsupported paths. For a storage.RemoteBackendStore each view now passes the
inner role through and lays the policy over it in role terms
(externaldeps/remote_roles.go): ready reads and the ready claim exclude the
workspace-wide blocked set over a widened window; per-issue checks (claim,
close, batch close, list annotations, tree leaves) read only the named
issues' edges through EdgeReader instead of every edge in the workspace. A
server advertising policy.external_dependencies (MC's does) gets a plain
passthrough. `bd ping` uses a new storage.Pinger, which the http store
answers with its authenticated context read.

S6d. A store reporting storage.CallerAttributionLimitedStore (http) cannot
carry a Provenance label or a patch's closed_by_session. The library still
refuses both; the CLI omits them where nothing is lost: `bd reopen`'s fixed
"bd: reopen <id>" label (the server labels the same entry), and the
closed_by_session of `bd update -s closed` (attribution only, usually the
ambient CLAUDE_SESSION_ID; an explicit --session prints a notice; `bd close`
still records it). See cmd/bd/remote_backend.go.

S6b. utils.ExactIDLookupStore: the resolver stops at exact lookups for a
store with no substring search, so a missing prefixed id is a not-found
(beadserrors.ErrNotFound, "no issue found matching") after one getIssue.
The general resolver no longer repeats an identical normalized probe. The
http SearchIssueIDs answers D11's partial-id refusal, which now unwraps to
ErrNotFound. Contributor auto-routing for a remote workspace reads local
config only, so the not-found fallback pays no settings round trip.
`bd update <absent> --claim` (gc's hook claim) answers a gc-classifiable
not-found in at most two requests.

Served e2e (backend/http/e2e_remote_roles_test.go): every gc list shape and
`bd children` against embedded, `show --json` count parity, default dep
tree parity, external blocking still enforced, close/reopen under
CLAUDE_SESSION_ID, missing-id request counts, absent-id claim against the
current server and the MC handshake mask, policy passthrough under the MC
mask, ping.

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

* test(externaldeps): role-level remote reader and claimer cases

bd ready and bd update --claim reach the policy through the legacy seam and
the lifecycle guard, so the remote Reader.Ready exclusion and the remote
Claimer guard (what bd serve and library callers reach) are pinned at the
role level with a fake remote store.

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

* feat(http): bd serve advertises policy.external_dependencies; clients pass through

bd serve composes every ready, claim, claim-next, close, blocking and tree
role through the external-dependency policy, but never said so. Every
client therefore ran the policy a second time, with the CLIENT machine's
external-project config, and claim-next became a non-atomic read-then-claim
loop on the client.

The server now advertises the token exactly when the roles it serves were
composed through the policy: httpapi.Config.ExternalDependencyPolicy, which
bd serve derives from its actual chain (externaldeps.Applied for the store
arm, externaldeps.AppliedToProvider for the provider arm). A server handed
raw roles still withholds it, so the token stays truthful.

Against a server that advertises it, every remote role view hands the
request to the server's own role untouched: no client validation, no edge
reads, claim-next is the server's one atomic call, and the ready count is
the server's countReadyWork (new remoteReadyCounter). The client-side
policy remains only for servers that do not advertise the token.

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

* fix(create): default created_by to the request's actor in the create role

created_by was stamped in two front doors and never in the library: the
CLI (creationActorStamp, with a remote-workspace special case) and the
three httpapi create handlers. A library caller of Lifecycle.Create or
BatchCreator with an empty CreatedBy stored "" locally and the actor over
http.

PreparePublicCreateRequest, which every create shape prepares through
(Lifecycle.Create, BatchCreator items, batch-apply create items), now
defaults an empty CreatedBy to request.Actor; an explicit value is kept.
The handlers no longer stamp, `bd create` and the state event create pass
only the actor, and creationActorStamp/isRemoteBackendWorkspace are gone.

The CLI sites that still create through the raw CreateIssue seam (swarm,
todo, gate, the create form) keep stamping currentActor(): that seam is
shared with import, where defaulting would re-attribute imported rows, and
the http store refuses it anyway, so the remote special case was never
reachable there.

Conformance: the lifecycle-create, batch-creator and batch-apply contracts
now pin created_by == actor for an item that names none, on every leg.

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

* fix(httpclient): GetIssue answers a miss with storage.ErrNotFound, like the local stores

The http store's raw GetIssue answered a missing id with (nil, nil), where
DoltStore and the embedded store return a wrapped storage.ErrNotFound. A
caller written against the backend contract read the http miss as a hit:
`bd create --graph` refused every explicit-id plan over http (patched in
cmd/bd on feat/http-mc-corpus; that workaround is reverted there).

GetIssue now returns the miss (and the empty id) as storage.ErrNotFound,
spelled as issueops.GetIssueInTx spells it. GetLabels, which reads through
GetIssue, keeps the local read's "no labels" answer for a missing id; the
`bd list --parent` walk reads the typed miss as "parent issue not found".

The served bridge test now holds the local reference store and the http
store to the same miss: ErrNotFound with the same text.

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

* test(createbatchequiv): re-record the apply golden for the created_by default

c2866ea7fe made the create role default an empty CreatedBy to the
request's actor, so every create item of the apply scenario's batch
(actor "apply-writer") now stores created_by "apply-writer" instead of "".
TestCreateBatchFastPathsMatchPerRow_*/apply compared the stored rows to a
digest recorded before that change and failed on exactly the three tables
the column reaches: issues and wisps (the row) and events (the update
event's old-value snapshot). Fast and per-row bodies still agree; the
batch-apply conformance contract pins the same value.

Bisected with bazel: passes at be92efe40f's integ twin 696f7acc8e, fails
from the created_by commit on. Only apply.json's three digests move.

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

* style: gofmt ledger.go and the externaldeps remote-roles test

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

* fix(cmd/bd): bd create reads routing settings local-only on a remote backend too

determineAutoRoutedRepoPath skipped a remote backend's settings document
(routing targets are local paths that one shared document cannot name for
every client), but getRoutingConfigValue, which `bd create` and
migrate-personal read routing.* and contributor.* through, still asked it.
The same workspace could route a create one way and a lookup another, and
every create paid a settings round trip per key.

Both now go through routingSettingsStore: nil for a remote backend, so
routing comes from config.yaml / the environment only there, and a local
store is still consulted. A unit test holds both reads to the rule with a
store that counts settings reads.

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

* fix(cmd/bd): say so when update -s closed drops an ambient CLAUDE_SESSION_ID

Over http `bd update -s closed` cannot carry closed_by_session, so the CLI
drops it rather than refusing the close. An explicit --session printed a
notice; the ambient CLAUDE_SESSION_ID every agent under Claude Code exports
was dropped without a word, a silent data difference from a local backend
(the served corpus's mc-update-meta-status-closed). The drop is now named
on stderr in both cases, once per command, pointing at `bd close`, whose
wire operation records the session. The served e2e asserts the notice.

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

* test(backend/http): hold bd list --limit 2 to each side's own unlimited order

TestE2E_ListWithGCFiltersMatchesEmbedded compared the --limit 2 rows of
the served and embedded workspaces as sets. The seed has four P2 rows, so
the limit cuts a priority tie whose created_at order differs between two
workspaces seeded seconds apart: a test-only flake, the order itself being
total. Each side's two rows must now be, in order, the first two of that
same side's --limit 0 listing; the unlimited listings are still compared
across sides by the shape loop.

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

* test: unit-tier pins for the created_by default, the policy token and the GetIssue miss

Three review mutations were caught only by a heavier tier (the uow
conformance legs, the served httpclient tier) or by one package's test
alone. Each now has a unit test where its rule lives:

- issueops: PreparePublicCreateRequest defaults an empty CreatedBy to the
  actor and keeps an explicit one, without mutating the caller's request.
- externaldeps: the policy layer AppliedToProvider finds becomes the
  handshake's policy.external_dependencies through httpapi.Listen, the
  composition bd serve performs, and a raw provider's handshake lacks it.
- httpclient (no embedded engine): GetIssue over the real wire client
  against a stub server answers a 404 not_found, and the empty id without
  dialing, as storage.ErrNotFound spelled like the local stores.

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

* docs(changelog): S6b/c/d entries match the code

The S6 entry still said `bd create` suppresses created_by on a remote
workspace and that the external-dependency policy runs client-side. Since
S6b/c/d, created_by defaults to the actor in the library on every backend,
and every bd serve composed through the policy advertises
policy.external_dependencies, so clients pass those operations through;
the client-side policy (now in role terms) runs only against a server that
does not advertise it.

New entries: the advertised policy token, bd ping over http, the created_by
library default, closed_by_session dropped by an http `bd update -s closed`
(with a notice, typed or ambient), reopen without a Provenance label over
http, local-only routing.* / contributor.* on a remote backend, GetIssue's
miss as storage.ErrNotFound, and list/children/show counts/dep tree over
http.

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

* fix(externaldeps): keep S6's list --ready, --claim-next refusal and lost-race error on the S6c composition

The re-adopted S6 head (#7288) carries the review fixup's remote role
composition; S6c replaces it with its own (rolesAreRemote, the widened
ready window, the policy passthrough). Two behaviours S6 shipped and its
reviews pinned would otherwise go:

- bd close --claim-next against a server that does not apply the policy
  is refused whole, before anything is read or closed, with "the served
  batch close cannot carry a next claim, so nothing was closed; close
  without --claim-next, then run `bd ready --claim`". S6c passed the batch
  to the http closer, whose W-CloseBatchRequest.ClaimNext refusal drops the
  remedy, so TestE2E_BDOverHTTP's two refuseClaimNext steps went red. A
  request invalid on every backend is still ErrValidation first, and a
  server that applies the policy still gets the request untouched.
- remoteReadyClaimer.ClaimNext reports a page on which every candidate was
  lost to another actor as "claim ready: lost N races ...", not as the
  empty answer that means there is no work.

- `bd list --ready` (List with ReadyFlag) is answered by the policy
  store's own reader over the served ready reads, as S6 does. S6c passed
  it to the served listing, which cannot carry ReadyFlag (httpclient
  ledger row E-ListRequest.ReadyFlag), so it exited 1 over http with or
  without external refs; TestE2E_BDOverHTTP and
  TestServedRolesKeepTheExternalDependencyPolicy were red on it.
  TestRemoteReaderAnswersAReadyListingWithoutTheWireFlag pins it, with the
  fake's served List refusing ReadyFlag as the wire does.

S6's composition tests now run against S6c as remote_roles_composition_test.go.
Their fake serves Ready the way a server does (the S6 composition read
ready work through the legacy policy reader instead), and two call logs
gain that Ready. TestRemoteBatchCloserRefusesANextClaim,
TestRemoteBatchCloserValidatesANextClaimFirst and
TestRemoteReadyClaimerReportsLostRaces were red on S6c before this change.

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

* fix(externaldeps): unassigned claim-next and fail-closed close reads

Review fixes for the S6c composition against a server that does not
advertise policy.external_dependencies: the two majors of review
attempt 1, plus the minors on the same code.

- ReadyClaimer: the composed claim-next reads only open, unassigned
  ready rows (Unassigned=true, Assignee cleared), the candidates the
  local ClaimReadyIssueInTx selects. A row another actor holds, or one
  already assigned to the caller, is no longer taken or counted as a
  lost race. Each pass reads 25 candidates past the blocked rows, as
  httpclient's composed claim does, and a full window lost end to end
  is read once more: claimed rows leave the unassigned set. Only a
  claim that tried candidates and won none is an error.
- BatchCloser: an externally blocked item travels to the server only
  when its status read finds it closed or not found (liveRefusal). Any
  other read error is that item's outcome, so a transient or auth
  failure no longer forwards a refused close to a server that will not
  refuse it.
- TreeWalker: a failed capability probe renders the external leaves
  over the walked tree instead of failing a walk the server already
  answered. appendTreeExternalReferences skips an id the tree holds,
  so an enforcing server's own leaves are not doubled.
- remoteEdges names each anchor once and skips an empty one, which the
  http EdgeReader refuses with ErrValidation.

The composition fakes now honor Unassigned/Assignee as
workapi.BuildReadyFilter does, model a rival claim landing first and a
failing GetIssue, and refuse an empty edge anchor as httpclient does.
New: TestRemoteReadyClaimerTakesOnlyUnassignedWork,
TestRemoteReadyClaimerWalksAContendedFront,
TestRemoteBatchCloserAnswersAFailedReadWithIt,
TestRemoteEdgesNamesEachAnchorOnce, and the probe-failure cases of
TestRemoteTreeWalkerAddsExternalLeaves. Each is red with its fix
reverted.

From review attempt 2, three nearby cleanups:

- TestServedRolesKeepTheExternalDependencyPolicy seeds open rows held
  by another actor and by the claimant ahead of the free work, then
  claims with and without an assignee filter. The unassigned-only claim
  is now pinned over a real served server, not only through the fakes:
  red with the pre-fixup remote_roles.go, with filter.Unassigned
  dropped, and (the filtered claim) with an explicit assignee honored.
- The capabilities description in openapi.v0.yaml (and the regenerated
  types.gen.go comment) no longer calls the whole list build-level:
  policy.external_dependencies depends on how the server composed its
  roles, as the paragraph above it says.
- createbatchequiv's golden note names
  issueops.PreparePublicCreateRequest instead of a commit id that is
  not on this branch.

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

* test(backend/http): count a not_found read as reaching the remote in #7469's credential doors

main's #7469 added TestExplicitCredentialIgnoresTheEnvPlaintextGrant. Its
OpenWith and Open doors read bd-1 from plaintextRemote, which answers
every issue read not_found, and the granted leg needs that read to return
a nil error. That held while the http client answered a miss with
(nil, nil). This branch's "fix(httpclient): GetIssue answers a miss with
storage.ErrNotFound, like the local stores" makes the same read return
storage.ErrNotFound. So on main plus this branch both doors fail at
per_open_credential_test.go:392 ("with Target.AllowInsecureCredential:
not found: issue bd-1") under plain go test. The merge is textually
clean, so only a build of the merge shows it.

The two store doors now count storage.ErrNotFound as success, since that
answer came off the wire. The assertions are unchanged. The refused leg
still needs the "refusing to send a credential" error and no request on
the transport. The granted leg still needs exactly one request carrying
"Bearer explicit-token": a granted read that never reaches the wire still
fails at :408.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Julian Knutsen 2026-10-10 18:11:56 +00:00 • committed by GitHub
commit c4e667cb14
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
70 changed files with 3537 additions and 957 deletions

View file

@ -155,18 +155,33 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
`BEADS_HTTP_TOKEN_COMMAND=host[:port]=<command>`, then the credentials
file, then none); both variables take only that host-scoped form, and a
bare value is refused, since it would be sent to whatever server the
workspace's `http_target.json` names. The external-dependency policy
decorator (`internal/storage/externaldeps`) still wraps an http store, and
stands down only when the server's handshake advertises
`policy.external_dependencies` (that server has already applied the policy
before answering); against any other server it applies the policy
client-side, around the http store's own served roles. Externally blocked
issues drop out of `bd ready`'s page, total, and count (the v0 wire cannot
express an id exclusion) and out of `bd ready --claim`, `bd close` refuses
them without `--force`, and `bd dep tree` shows their external leaves.
workspace's `http_target.json` names.
`bd create` sends no `created_by` on any backend: the
create role defaults it to the request's actor (see *Changed*). The
external-dependency policy decorator (`internal/storage/externaldeps`)
still wraps an http store, and passes every ready, claim, claim-next,
close, blocking and tree request through untouched when the server's
handshake advertises `policy.external_dependencies`, which every `bd
serve` composed through the policy now does (see below). Only against a
server that does not advertise it (an older `bd serve`, or one handed raw
roles) does the client apply the policy itself, in role terms: ready reads
and the ready claim exclude the workspace-wide externally blocked set over
a widened window, and per-issue checks (claim, close, batch close, list
annotations, tree leaves) read only the named issues' edges.
`bd close --claim-next` refuses over http before anything closes, since
the wire's batch close cannot carry the claim; its error says to close
without it and then run `bd ready --claim`.
- `bd serve` advertises the conditional behavior token
`policy.external_dependencies` exactly when the roles or provider it
serves were composed through the external-dependency policy
(`httpapi.Config.ExternalDependencyPolicy`, which `bd serve` derives with
`externaldeps.Applied` / `externaldeps.AppliedToProvider`); a server handed
raw roles withholds it. A client that sees it hands claim-next to the
server as one atomic call and takes the ready count from the server,
instead of judging external dependencies a second time against the CLIENT
machine's project config.
- `bd ping` works on an http workspace (a new `storage.Pinger`, which the
http store answers with its authenticated context read).
- The public `backend/http` package (`bdhttp`) is the out-of-tree door onto
this backend for an embedder that links beads as a library rather than
running `cmd/bd`: `Register(Options)` adds `"http"` to the registry and
@ -179,6 +194,40 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Changed
- **`created_by` defaults to the actor in the library, for every create
shape and every backend.** `PreparePublicCreateRequest`, which
`Lifecycle.Create`, `BatchCreator` items and batch-apply create items all
prepare through, now sets an empty `Issue.CreatedBy` to the request's
`Actor`; an explicit value is kept. The CLI (`bd create`, the state event
create) and the three `bd serve` create handlers no longer stamp it
themselves. A library caller that left `CreatedBy` empty used to store
`""` locally and the actor over http; both now store the actor. The raw
`CreateIssue` seam is unchanged: import keeps the creator its rows carry,
and `bd swarm`, `bd todo`, `bd gate` and the create form still stamp
`currentActor()` there.
- **On an http workspace, `bd update -s closed` does not record
`closed_by_session`.** The update wire cannot carry it, so the CLI drops
it rather than refusing the close; the status change, its close-policy
guards and every other field in the same update still apply. A one-line
notice on stderr names the drop, both for an explicit `--session` and for
the ambient `CLAUDE_SESSION_ID` every agent under Claude Code exports, so
it is never silent. `bd close` (and `bd close --session`) still records
the session over http: its wire operation carries it. Local backends are
unchanged.
- **On an http workspace, `bd reopen` sends no Provenance label.** The
CLI's label is the fixed `bd: reopen <id>`, which the wire cannot carry;
the server records its own reopen entry for the same issue and actor, so
the reopen no longer refuses. Local backends still record the label.
- **Routing settings are local-only on a remote backend.** For an http
workspace, `routing.mode`, `routing.contributor`, `routing.default`,
`routing.maintainer`, `contributor.auto_route` and
`contributor.planning_repo` come from local config (`config.yaml` or the
environment) only; the server's shared settings document is not read for
them, because routing targets are local filesystem paths that one shared
document cannot name for every client. `bd create`'s routing decision, `bd
migrate-personal` and the missing-id lookup fallback all read the same
local-only answer, and none pays a settings round trip for it. Local
backends still fall back to the database values.
- Every `bd` invocation used to start two git subprocesses before doing any
work: `git rev-parse` to locate the repository and `git config user.name`
to resolve the actor. On Linux the repository is now located in-process
@ -369,6 +418,22 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
rollout) still stores P0, with no error on either side.
Out-of-tree storage backends must now honor `DefaultPriority`; see the
BREAKING (out-of-tree storage backends) entry under `### Changed`.
- **The http store's `GetIssue` answers a miss with `storage.ErrNotFound`,
like the local stores.** It used to answer a missing (or empty) id with
`(nil, nil)`, which every caller written against the backend contract
read as a hit: `bd create --graph` refused every plan naming an explicit
id over http. The miss is now `not found: issue <id>`, wrapping
`storage.ErrNotFound` exactly as `issueops.GetIssueInTx` does; the empty
id never dials.
- **`bd list`, `bd children`, `bd show --json` counts, the default `bd dep
tree`, `bd ready --claim` and `bd close` work on an http workspace.** The
external-dependency decorator rebuilt its views from storage seams the
http store only partly serves, so `bd list`/`bd children` refused, `bd
show --json` printed zero dependency and comment counts without an error,
and the default dep tree refused; each view now passes the server's own
role through (see *Added*). A missing id is a plain not-found after one
`getIssue`, instead of a partial-id search refusal, and `bd update
<absent> --claim` answers a not-found gc classifies.
- **PRs based on `hotfix/**` branches now run full CI, not just
cross-version historical smokes and triage labeling.** `pr.yml`,
`pr-risk.yml`, `conformance.yml`, `cross-version-smoke.yml` and

View file

@ -223,6 +223,19 @@ reference as a leaf, and while it is unsatisfied the issue stays out of
`--force`. A server that advertises enforcing that policy itself is trusted
to do so instead.
Three CLI-level differences are worth knowing up front:
- IDs resolve exactly: an abbreviated id is not expanded (the wire has no
substring search), and a missing id is reported as not found after one
lookup.
- `bd update -s closed` does not record `closed_by_session` (from `--session`
or `CLAUDE_SESSION_ID`), because the wire's update cannot carry it; the
close itself happens as usual. `bd close` does record the session. `bd
reopen`'s history entry carries the server's own label.
- Contributor auto-routing (`routing.*` settings) is read from local
`config.yaml` / environment only, never from the server's settings: its
targets are local paths.
`bd connect` writes two things on success: `.beads/metadata.json` gets
`"backend": "http"`, and a per-user, never-git-tracked sidecar
(`.beads/http_target.json`) records the server URL and pinned project id. It

View file

@ -171,6 +171,12 @@ func RunBatchApplyAppliesEveryItemInDeclarationOrder(t *testing.T, ctx context.C
if got := batchApplyColumn(t, ctx, fixture, "status", blocked); got == string(types.StatusClosed) {
t.Errorf("%s was closed by a request that only asked to close %s", blocked, blocker)
}
// Neither create item names a creator, so each defaults to the request's actor.
for _, id := range []string{blocked, blocker} {
if got := batchApplyColumn(t, ctx, fixture, "created_by", id); got != "apply-writer" {
t.Errorf("%s created_by = %q, want the request's actor %q", id, got, "apply-writer")
}
}
}
// RunBatchApplyBindsEachNamedKeyToItsMintedID pins ApplyBatchResult.Keys: it is

View file

@ -97,6 +97,14 @@ func RunBatchCreatorCreatesEveryItemAsOneAct(t *testing.T, ctx context.Context,
}
seen[issue.ID] = true
assertBatchCreatorRowCount(t, ctx, fixture, "issues", issue.ID, 1)
// No item names a creator, so each defaults to the batch's actor.
var createdBy string
if err := fixture.QueryScalar(ctx, "SELECT COALESCE(created_by, '') FROM issues WHERE id = ?", []any{issue.ID}, &createdBy); err != nil {
t.Fatalf("read created_by for %s: %v", issue.ID, err)
}
if createdBy != request.Actor || issue.CreatedBy != request.Actor {
t.Errorf("item %d created_by = %q (result %q), want the request's actor %q", i, createdBy, issue.CreatedBy, request.Actor)
}
}
if labels := result.Issues[0].Labels; len(labels) != 1 || labels[0] != "alpha" {
t.Errorf("result issue 0 labels = %v, want [alpha]: the snapshot is promised hydrated with labels", labels)

View file

@ -490,6 +490,12 @@ func RunLifecycleCreateWritesEveryScalarField(t *testing.T, ctx context.Context,
t.Errorf("%s created_at = %v after a create that named none, want a stamp between %v and %v — a bare non-empty check would accept the zero time",
stamped, autoStamp, lower, upper)
}
// And no created_by: the request's actor is the creator (CreateRequest.Issue),
// stamped by the role itself, so a library caller and every front door store
// the same value for the same request.
if got := lifecycleCreateRow(t, ctx, fixture, stamped).CreatedBy; got != "writer" {
t.Errorf("%s created_by = %q after a create that named none, want the request's actor %q", stamped, got, "writer")
}
want := []lifecycleCreateMember{
{"title", "created title"},

View file

@ -32,6 +32,7 @@ go_test(
srcs = [
"attach_test.go",
"e2e_cli_test.go",
"e2e_remote_roles_test.go",
"open_test.go",
"per_open_credential_test.go",
"register_test.go",

View file

@ -0,0 +1,700 @@
//go:build cgo
// Served e2e for S6b/S6c/S6d (written fresh for OSS beads). Every case drives
// the real `bd` binary over the wire and, where the answer is a listing or a
// count, against an embedded workspace seeded the same way — parity, not just
// "it exited 0".
package bdhttp_test
import (
"bytes"
"encoding/json"
"io"
"net"
"net/http"
"net/http/httputil"
"net/url"
"os"
"path/filepath"
"slices"
"sort"
"strconv"
"strings"
"sync"
"testing"
)
// remoteRolesFixture is one workspace seeded through the CLI, whichever
// backend it selects. Titles identify rows across the two workspaces, whose
// minted ids differ.
type remoteRolesFixture struct {
t *testing.T
bin string
dir string
ids map[string]string // title -> id
}
func (f *remoteRolesFixture) run(env []string, args ...string) bdResult {
f.t.Helper()
return runBD(f.t, f.bin, f.dir, env, args...)
}
func (f *remoteRolesFixture) mustRun(env []string, args ...string) bdResult {
f.t.Helper()
r := f.run(env, args...)
if r.code != 0 {
f.t.Fatalf("bd %s failed (exit %d): stdout=%s stderr=%s", strings.Join(args, " "), r.code, r.stdout, r.stderr)
}
return r
}
func (f *remoteRolesFixture) create(title string, args ...string) string {
f.t.Helper()
r := f.mustRun(nil, append([]string{"create", title, "--json"}, args...)...)
id := firstJSONField(f.t, r.stdout, "id")
if id == "" {
f.t.Fatalf("bd create %q --json produced no id: %s", title, r.stdout)
}
f.ids[title] = id
return id
}
// seed builds the same graph in either workspace:
//
// epic "parent"
// ├─ "child-a" task, label gc:a, assignee alice, in_progress, meta k=v
// ├─ "child-b" bug, label gc:b
// ├─ "child-c" task, closed
// └─ "child-x" task, blocked by external:other:cap (unresolvable project)
// "loner" task, priority 3, a comment, depends on child-b
// "tmpl" task, template
func (f *remoteRolesFixture) seed() {
f.t.Helper()
parent := f.create("parent", "-t", "epic")
a := f.create("child-a", "-t", "task", "-l", "gc:a", "-a", "alice")
b := f.create("child-b", "-t", "bug", "-l", "gc:b")
c := f.create("child-c", "-t", "task")
x := f.create("child-x", "-t", "task", "-p", "0")
loner := f.create("loner", "-t", "task", "-p", "3")
f.create("tmpl", "-t", "task")
for _, child := range []string{a, b, c, x} {
f.mustRun(nil, "dep", "add", child, parent, "--type", "parent-child")
}
f.mustRun(nil, "dep", "add", x, "external:other:cap")
f.mustRun(nil, "dep", "add", loner, b)
f.mustRun(nil, "update", a, "-s", "in_progress", "--set-metadata", "k=v")
f.mustRun(nil, "close", c, "--reason", "done")
f.mustRun(nil, "comments", "add", loner, "a comment")
f.mustRun(nil, "update", f.ids["tmpl"], "--set-metadata", "kind=template")
}
func (f *remoteRolesFixture) titlesOf(out string) []string {
f.t.Helper()
titles := f.orderedTitlesOf(out)
sort.Strings(titles)
return titles
}
// orderedTitlesOf is titlesOf in the listing's own order.
func (f *remoteRolesFixture) orderedTitlesOf(out string) []string {
f.t.Helper()
rows := jsonRows(f.t, out)
titles := make([]string, 0, len(rows))
for _, row := range rows {
if title, ok := row["title"].(string); ok {
titles = append(titles, title)
}
}
return titles
}
// jsonRows parses a listing: a bare array, or the object envelope
// (`--skip-labels` adds a meta block) whose "issues" member holds it.
func jsonRows(t *testing.T, out string) []map[string]any {
t.Helper()
trimmed := []byte(strings.TrimSpace(out))
var rows []map[string]any
if err := json.Unmarshal(trimmed, &rows); err == nil {
return rows
}
var envelope map[string]json.RawMessage
if err := json.Unmarshal(trimmed, &envelope); err != nil {
t.Fatalf("parse JSON listing: %v\n%s", err, out)
}
for _, key := range []string{"issues", "data", "items"} {
if raw, ok := envelope[key]; ok {
if err := json.Unmarshal(raw, &rows); err != nil {
t.Fatalf("parse JSON listing member %q: %v\n%s", key, err, out)
}
return rows
}
}
t.Fatalf("JSON listing has no row array: %s", out)
return nil
}
// expand replaces {title} placeholders with this workspace's id for that title.
func (f *remoteRolesFixture) expand(args []string) []string {
out := make([]string, len(args))
for i, arg := range args {
for title, id := range f.ids {
arg = strings.ReplaceAll(arg, "{"+title+"}", id)
}
out[i] = arg
}
return out
}
func newEmbeddedFixture(t *testing.T, bin string) *remoteRolesFixture {
t.Helper()
f := &remoteRolesFixture{t: t, bin: bin, dir: t.TempDir(), ids: map[string]string{}}
f.mustRun(nil, "init", "--prefix", "e2e", "--quiet")
return f
}
func newHTTPFixture(t *testing.T, bin, addr string) *remoteRolesFixture {
t.Helper()
f := &remoteRolesFixture{t: t, bin: bin, dir: t.TempDir(), ids: map[string]string{}}
f.mustRun(nil, "connect", "http://"+addr, "--expect-project-id", e2eProjectID, "--json")
return f
}
// requestCounter is a loopback reverse proxy in front of the in-process
// server that counts the requests a command makes, by path.
type requestCounter struct {
mu sync.Mutex
paths []string
}
func (c *requestCounter) reset() {
c.mu.Lock()
defer c.mu.Unlock()
c.paths = nil
}
func (c *requestCounter) snapshot() []string {
c.mu.Lock()
defer c.mu.Unlock()
return append([]string(nil), c.paths...)
}
func startCountingProxy(t *testing.T, upstream string) (string, *requestCounter) {
t.Helper()
return startMaskingProxy(t, upstream, nil)
}
// mcServerCapabilities is the capability list the MC production server
// (bd-enterprise 5464806e97) advertises, read off its handshake on
// 2026-10-09 (mc-http-switch DESIGN.md A3). It notably includes
// policy.external_dependencies and lacks every newer token.
var mcServerCapabilities = []string{
"config.get", "config.list", "config.set", "config.unset",
"dependencies.add", "dependencies.blocking", "dependencies.count", "dependencies.cycles",
"dependencies.list", "dependencies.remove", "dependencies.tree",
"events.list", "events.watch",
"issues.addComment", "issues.batchApply", "issues.batchClose", "issues.batchCreate",
"issues.casMetadata", "issues.claim", "issues.claimNext", "issues.close", "issues.count",
"issues.create", "issues.delete", "issues.get", "issues.list", "issues.list.sort",
"issues.query", "issues.related", "issues.release", "issues.reopen", "issues.sweep", "issues.update",
"memories.forget", "memories.get", "memories.list", "memories.remember",
"policy.external_dependencies", "project.enforce", "ready.count", "ready.list", "stats.get",
}
// mcContextMask rewrites the handshake into the MC server's shape: no
// wire_revision member and exactly its capability list.
func mcContextMask(body map[string]any) {
delete(body, "wire_revision")
caps := make([]any, len(mcServerCapabilities))
for i, c := range mcServerCapabilities {
caps[i] = c
}
body["capabilities"] = caps
}
// startMaskingProxy is startCountingProxy that also rewrites every handshake
// (GET /v0/beads/context) body through mask, when one is given.
func startMaskingProxy(t *testing.T, upstream string, mask func(map[string]any)) (string, *requestCounter) {
t.Helper()
target, err := url.Parse("http://" + upstream)
if err != nil {
t.Fatal(err)
}
counter := &requestCounter{}
proxy := httputil.NewSingleHostReverseProxy(target)
if mask != nil {
proxy.ModifyResponse = func(resp *http.Response) error {
if resp.Request.URL.Path != "/v0/beads/context" || resp.StatusCode != http.StatusOK {
return nil
}
raw, err := io.ReadAll(resp.Body)
_ = resp.Body.Close()
if err != nil {
return err
}
var body map[string]any
if err := json.Unmarshal(raw, &body); err != nil {
return err
}
mask(body)
if raw, err = json.Marshal(body); err != nil {
return err
}
resp.Body = io.NopCloser(bytes.NewReader(raw))
resp.ContentLength = int64(len(raw))
resp.Header.Set("Content-Length", strconv.Itoa(len(raw)))
return nil
}
}
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
srv := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
counter.mu.Lock()
counter.paths = append(counter.paths, r.Method+" "+r.URL.Path)
counter.mu.Unlock()
proxy.ServeHTTP(w, r)
})}
go func() { _ = srv.Serve(ln) }()
t.Cleanup(func() { _ = srv.Close() })
return ln.Addr().String(), counter
}
// TestE2E_ListWithGCFiltersMatchesEmbedded is S6c's list case: `bd list` used
// to refuse over http (the external-deps decorator rebuilt the reader from the
// stubbed SearchIssuesWithCounts). Every list shape gc's BdStore emits, plus
// `bd children`, must answer the same rows as an embedded workspace.
func TestE2E_ListWithGCFiltersMatchesEmbedded(t *testing.T) {
skipUnlessEmbeddedDolt(t)
bin := buildBD(t)
remote := newHTTPFixture(t, bin, startE2EServer(t))
local := newEmbeddedFixture(t, bin)
remote.seed()
local.seed()
base := []string{"list", "--json", "--include-infra", "--include-gates"}
shapes := [][]string{
append(append([]string{}, base...), "--limit", "50"),
append(append([]string{}, base...), "--limit", "0"),
append(append([]string{}, base...), "--limit", "50", "--all"),
append(append([]string{}, base...), "--limit", "50", "--label=gc:a"),
append(append([]string{}, base...), "--limit", "50", "--assignee=alice"),
append(append([]string{}, base...), "--limit", "50", "--status=in_progress"),
append(append([]string{}, base...), "--limit", "50", "--status=closed", "--all"),
append(append([]string{}, base...), "--limit", "50", "--type=bug"),
append(append([]string{}, base...), "--limit", "50", "--parent", "{parent}"),
append(append([]string{}, base...), "--limit", "50", "--parent", "{parent}", "--all"),
append(append([]string{}, base...), "--limit", "50", "--metadata-field", "k=v"),
append(append([]string{}, base...), "--limit", "50", "--metadata-field", "k=v", "--status=in_progress", "--assignee=alice", "--label=gc:a", "--type=task", "--parent", "{parent}"),
append(append([]string{}, base...), "--limit", "50", "--include-templates"),
append(append([]string{}, base...), "--limit", "50", "--skip-labels"),
append(append([]string{}, base...), "--limit", "50", "--created-before", "2999-01-01T00:00:00Z"),
{"list", "--json"},
{"children", "{parent}", "--json"},
}
for _, shape := range shapes {
name := strings.Join(shape, " ")
r := remote.run(nil, remote.expand(shape)...)
if r.code != 0 {
t.Errorf("http: bd %s failed (exit %d): stderr=%s", name, r.code, r.stderr)
continue
}
l := local.mustRun(nil, local.expand(shape)...)
got, want := remote.titlesOf(r.stdout), local.titlesOf(l.stdout)
if strings.Join(got, ",") != strings.Join(want, ",") {
t.Errorf("bd %s: http rows %v, embedded rows %v", name, got, want)
}
}
// A limit that cuts the listing. The seed holds four P2 rows, so --limit 2
// cuts a priority tie whose created_at order differs between two
// workspaces seeded seconds apart: the limited rows are not compared
// across sides. Each side's rows must instead be, in order, a prefix of
// that SAME side's unlimited listing, and both sides return two rows.
limited := append(append([]string{}, base...), "--limit", "2")
unlimited := append(append([]string{}, base...), "--limit", "0")
for _, f := range []*remoteRolesFixture{remote, local} {
cut := f.orderedTitlesOf(f.mustRun(nil, limited...).stdout)
all := f.orderedTitlesOf(f.mustRun(nil, unlimited...).stdout)
if len(cut) != 2 || len(all) < 2 || !slices.Equal(cut, all[:2]) {
t.Errorf("bd %s on %s: rows %v are not the first two of its --limit 0 listing %v", strings.Join(limited, " "), f.dir, cut, all)
}
}
}
// TestE2E_ShowJSONCountsMatchEmbedded is S6c's count case: over http the
// decorator's store-backed reader hydrated `bd show --json`'s counts from
// stubbed reads and printed zeros without an error.
func TestE2E_ShowJSONCountsMatchEmbedded(t *testing.T) {
skipUnlessEmbeddedDolt(t)
bin := buildBD(t)
remote := newHTTPFixture(t, bin, startE2EServer(t))
local := newEmbeddedFixture(t, bin)
remote.seed()
local.seed()
type counts struct{ deps, dependents, comments float64 }
read := func(f *remoteRolesFixture, title string) counts {
r := f.mustRun(nil, "show", f.ids[title], "--json")
var rows []map[string]any
if err := json.Unmarshal([]byte(strings.TrimSpace(r.stdout)), &rows); err != nil || len(rows) != 1 {
t.Fatalf("parse bd show --json for %s: %v\n%s", title, err, r.stdout)
}
num := func(k string) float64 { v, _ := rows[0][k].(float64); return v }
return counts{num("dependency_count"), num("dependent_count"), num("comment_count")}
}
nonZero := false
for _, title := range []string{"parent", "child-b", "child-x", "loner"} {
got, want := read(remote, title), read(local, title)
if got != want {
t.Errorf("bd show %s --json counts: http %+v, embedded %+v", title, got, want)
}
if want != (counts{}) {
nonZero = true
}
}
if !nonZero {
t.Fatal("fixture produced no non-zero count; the parity check proves nothing")
}
}
// TestE2E_DefaultDepTreeOverHTTP is S6c's tree case: the default (down) `bd
// dep tree` used to refuse (GetDependencyTree). It must render the same nodes
// as embedded, including the synthetic external leaf the client-side policy
// hangs off a node with an external dependency.
func TestE2E_DefaultDepTreeOverHTTP(t *testing.T) {
skipUnlessEmbeddedDolt(t)
bin := buildBD(t)
remote := newHTTPFixture(t, bin, startE2EServer(t))
local := newEmbeddedFixture(t, bin)
remote.seed()
local.seed()
for _, title := range []string{"child-x", "loner"} {
r := remote.run(nil, "dep", "tree", remote.ids[title])
if r.code != 0 {
t.Fatalf("http: bd dep tree %s failed (exit %d): stderr=%s", title, r.code, r.stderr)
}
l := local.mustRun(nil, "dep", "tree", local.ids[title])
normalize := func(out string, f *remoteRolesFixture) string {
for t, id := range f.ids {
out = strings.ReplaceAll(out, id, "<"+t+">")
}
return out
}
if got, want := normalize(r.stdout, remote), normalize(l.stdout, local); got != want {
t.Errorf("bd dep tree %s:\nhttp:\n%s\nembedded:\n%s", title, got, want)
}
}
tree := remote.mustRun(nil, "dep", "tree", remote.ids["child-x"])
if !strings.Contains(tree.stdout, "cap (external)") {
t.Errorf("http dep tree of child-x lacks the external leaf: %s", tree.stdout)
}
if !strings.Contains(tree.stdout, remote.ids["parent"]) {
t.Errorf("http dep tree of child-x lacks its parent: %s", tree.stdout)
}
}
// TestE2E_ExternalDependencyBlockingStillEnforced pins that the passthrough
// kept the client-side policy against a server that does not advertise
// policy.external_dependencies: the externally blocked child-x (priority 0,
// so it sorts first) never reaches ready, a direct claim, an unforced close,
// or `bd ready --claim`; `bd list` still marks it blocked.
func TestE2E_ExternalDependencyBlockingStillEnforced(t *testing.T) {
skipUnlessEmbeddedDolt(t)
bin := buildBD(t)
f := newHTTPFixture(t, bin, startE2EServer(t))
f.seed()
x := f.ids["child-x"]
ready := f.mustRun(nil, "ready", "--json")
if jsonIDSet(t, ready.stdout)[x] {
t.Errorf("bd ready listed the externally blocked %s: %s", x, ready.stdout)
}
readyOne := f.mustRun(nil, "ready", "--json", "--limit", "1")
if ids := jsonIDSet(t, readyOne.stdout); len(ids) != 1 || ids[x] {
t.Errorf("bd ready --limit 1 = %v; want exactly one row and not %s (the widened window must still fill the page)", ids, x)
}
if r := f.run(nil, "update", x, "--claim", "--json"); r.code == 0 || !strings.Contains(r.stderr, "external:other:cap") {
t.Errorf("bd update --claim of the externally blocked %s: exit %d, stderr=%s; want a refusal naming the blocker", x, r.code, r.stderr)
}
if r := f.run(nil, "close", x, "--json"); r.code == 0 || !strings.Contains(r.stderr, "external:other:cap") {
t.Errorf("bd close of the externally blocked %s: exit %d, stderr=%s; want a refusal naming the blocker", x, r.code, r.stderr)
}
if r := f.run([]string{"CLAUDE_SESSION_ID=sess-x"}, "update", x, "-s", "closed", "--json"); r.code == 0 || !strings.Contains(r.stderr, "external:other:cap") {
t.Errorf("bd update -s closed of the externally blocked %s: exit %d, stderr=%s; want a refusal naming the blocker", x, r.code, r.stderr)
}
claimed := f.mustRun(nil, "ready", "--claim", "--json")
if id := firstJSONField(t, claimed.stdout, "id"); id == "" || id == x {
t.Errorf("bd ready --claim claimed %q; want an unblocked issue, never %s: %s", id, x, claimed.stdout)
}
list := f.mustRun(nil, "list", "--json", "--limit", "50")
for _, row := range jsonRows(t, list.stdout) {
if row["id"] == x && row["status"] == "closed" {
t.Errorf("child-x was closed despite the refusals: %v", row)
}
}
if r := f.run(nil, "show", x, "--json"); r.code != 0 {
t.Fatalf("bd show %s failed: %s", x, r.stderr)
}
if r := f.mustRun(nil, "close", x, "--force", "--json"); r.code != 0 {
t.Fatalf("bd close --force %s failed: %s", x, r.stderr)
}
}
// TestE2E_CloseAndReopenUnderClaudeSession is S6d: under Claude Code every bd
// process carries CLAUDE_SESSION_ID, and over http `bd update -s closed`
// refused (closed_by_session has no wire member) while `bd reopen` always
// refused (its fixed Provenance label has none either). Both must work, the
// dropped session must be named on stderr (typed or ambient, never silent),
// and `bd close` must still record the session its wire operation does carry.
func TestE2E_CloseAndReopenUnderClaudeSession(t *testing.T) {
skipUnlessEmbeddedDolt(t)
bin := buildBD(t)
f := newHTTPFixture(t, bin, startE2EServer(t))
session := []string{"CLAUDE_SESSION_ID=sess-s6d"}
id := f.create("closable", "-t", "task")
status := func() map[string]any {
r := f.mustRun(nil, "show", id, "--json")
var rows []map[string]any
if err := json.Unmarshal([]byte(strings.TrimSpace(r.stdout)), &rows); err != nil || len(rows) != 1 {
t.Fatalf("parse bd show: %v\n%s", err, r.stdout)
}
return rows[0]
}
// The MC hot shape: metadata and status in one update, session ambient.
ambient := f.mustRun(session, "update", id, "--set-metadata", "phase=done", "--status", "closed", "--json")
if !strings.Contains(ambient.stderr, "CLAUDE_SESSION_ID is not recorded") {
t.Errorf("the ambient session was dropped without a notice: stderr=%s", ambient.stderr)
}
if row := status(); row["status"] != "closed" {
t.Fatalf("after update -s closed under CLAUDE_SESSION_ID: %v", row)
}
reopen := f.mustRun(session, "reopen", id, "--json")
if !strings.Contains(reopen.stdout, id) {
t.Errorf("bd reopen --json did not report %s: %s", id, reopen.stdout)
}
if row := status(); row["status"] != "open" {
t.Fatalf("after reopen: %v", row)
}
// An explicit --session is honored too, and says it was not recorded.
explicit := f.mustRun(nil, "update", id, "-s", "closed", "--session", "typed-session", "--json")
if !strings.Contains(explicit.stderr, "--session is not recorded") {
t.Errorf("explicit --session over http gave no notice: stderr=%s", explicit.stderr)
}
if row := status(); row["status"] != "closed" {
t.Fatalf("after update -s closed --session: %v", row)
}
f.mustRun(nil, "reopen", id, "--reason", "again", "--json")
// bd close carries the session on its own wire member.
f.mustRun(session, "close", id, "--json")
row := status()
if row["status"] != "closed" || row["closed_by_session"] != "sess-s6d" {
t.Errorf("after bd close under CLAUDE_SESSION_ID: status=%v closed_by_session=%v; want closed/sess-s6d", row["status"], row["closed_by_session"])
}
f.mustRun(session, "reopen", id, "--json")
if row := status(); row["status"] != "open" {
t.Errorf("after the second reopen: %v", row)
}
}
// TestE2E_ShowMissingIDIsNotFoundInOneLookup is S6b: `bd show <missing>`
// made five round trips and then reported "SearchIssueIDs not supported". It
// must classify as not found — the same exit and stdout as embedded — after a
// single issue lookup.
func TestE2E_ShowMissingIDIsNotFoundInOneLookup(t *testing.T) {
skipUnlessEmbeddedDolt(t)
bin := buildBD(t)
proxyAddr, counter := startCountingProxy(t, startE2EServer(t))
remote := newHTTPFixture(t, bin, proxyAddr)
local := newEmbeddedFixture(t, bin)
remote.create("present")
for _, missing := range []string{"e2e-nope", "nope"} {
counter.reset()
r := remote.run(nil, "show", missing, "--json")
paths := counter.snapshot()
l := local.run(nil, "show", missing, "--json")
if r.code != l.code || r.code == 0 {
t.Errorf("bd show %s: http exit %d, embedded exit %d; want the same non-zero not-found exit", missing, r.code, l.code)
}
if strings.TrimSpace(r.stdout) != strings.TrimSpace(l.stdout) {
t.Errorf("bd show %s --json stdout differs:\nhttp: %s\nembedded: %s", missing, r.stdout, l.stdout)
}
if !strings.Contains(r.stderr, "Issue "+missing+" not found") || strings.Contains(r.stderr, "not supported") {
t.Errorf("bd show %s over http is not classified as not found: stderr=%s", missing, r.stderr)
}
lookups := 0
for _, p := range paths {
if strings.HasPrefix(p, "GET /v0/beads/issues/") {
lookups++
}
}
// A prefixed id is one exact lookup and nothing else: no prefix
// vocabulary, no repeated probe, no settings read for contributor
// auto-routing (a remote workspace configures that locally). A bare
// hash also reads the prefix vocabulary once (behind the handshake
// that read's capability check) and tries its prefixed spelling.
wantLookups, maxTotal := 1, 1
if !strings.Contains(missing, "-") {
wantLookups, maxTotal = 2, 4
}
if lookups != wantLookups {
t.Errorf("bd show %s made %d issue lookups, want %d: %v", missing, lookups, wantLookups, paths)
}
if len(paths) > maxTotal {
t.Errorf("bd show %s made %d requests in all, want at most %d: %v", missing, len(paths), maxTotal, paths)
}
}
// A present id still resolves, abbreviation-free.
if r := remote.run(nil, "show", remote.ids["present"], "--json"); r.code != 0 {
t.Errorf("bd show of a present id failed over http: %s", r.stderr)
}
}
// TestE2E_PingOverHTTP: `bd ping` ran a one-row SearchIssues, which the http
// backend refuses; it now reads the authenticated server context.
func TestE2E_PingOverHTTP(t *testing.T) {
skipUnlessEmbeddedDolt(t)
bin := buildBD(t)
proxyAddr, counter := startCountingProxy(t, startE2EServer(t))
f := newHTTPFixture(t, bin, proxyAddr)
counter.reset()
r := f.mustRun(nil, "ping", "--json")
if status := firstJSONField(t, r.stdout, "status"); status != "ok" {
t.Errorf("bd ping --json status = %q: %s", status, r.stdout)
}
sawContext := false
for _, p := range counter.snapshot() {
if p == "GET /v0/beads/context" {
sawContext = true
}
}
if !sawContext {
t.Errorf("bd ping made no context request: %v", counter.snapshot())
}
// A dead server is a failed ping, not a stale success.
sidecar := filepath.Join(f.dir, ".beads", "http_target.json")
data, err := os.ReadFile(sidecar)
if err != nil {
t.Fatal(err)
}
dead := strings.ReplaceAll(string(data), proxyAddr, "127.0.0.1:1")
if err := os.WriteFile(sidecar, []byte(dead), 0o600); err != nil {
t.Fatal(err)
}
if r := f.run(nil, "ping", "--json"); r.code == 0 {
t.Errorf("bd ping against a dead server exited 0: %s", r.stdout)
}
}
// TestE2E_ClaimOfAbsentIDIsGCNotFound is S24-T: gc's hook claims through
// `bd update <id> --claim --json` on the work store and, on a not-found,
// escalates to its own wisp store (gascity BdStore.Claim -> isBdNotFound).
// Over http an absent id must therefore answer a not-found gc's matcher
// accepts — never a refusal — in at most two round trips, against both the
// current server and the MC server's handshake shape.
func TestE2E_ClaimOfAbsentIDIsGCNotFound(t *testing.T) {
skipUnlessEmbeddedDolt(t)
bin := buildBD(t)
addr := startE2EServer(t)
for _, tc := range []struct {
name string
mask func(map[string]any)
}{
{"current server", nil},
{"MC server mask", mcContextMask},
} {
t.Run(tc.name, func(t *testing.T) {
proxyAddr, counter := startMaskingProxy(t, addr, tc.mask)
f := newHTTPFixture(t, bin, proxyAddr)
present := f.create("claimable")
counter.reset()
r := f.run([]string{"BEADS_ACTOR=gc-hook"}, "update", "e2e-absent9", "--claim", "--json")
paths := counter.snapshot()
if r.code == 0 {
t.Fatalf("bd update <absent> --claim exited 0: %s", r.stdout)
}
// gascity internal/beads/bdstore.go isBdNotFound, verbatim. The
// error gc classifies carries stderr (and stdout's --json
// envelope when stderr is empty), so stderr must match alone.
isBdNotFound := func(msg string) bool {
msg = strings.ToLower(msg)
return strings.Contains(msg, "not found") ||
strings.Contains(msg, "no issue found") ||
strings.Contains(msg, "no issues found")
}
if !isBdNotFound(r.stderr) || (r.stdout != "" && !isBdNotFound(r.stdout)) {
t.Errorf("absent-id claim is not a gc not-found: stdout=%s stderr=%s", r.stdout, r.stderr)
}
for _, bad := range []string{"not supported", "already claimed", "already assigned"} {
if strings.Contains(strings.ToLower(r.stderr+r.stdout), bad) {
t.Errorf("absent-id claim output mentions %q: stdout=%s stderr=%s", bad, r.stdout, r.stderr)
}
}
if len(paths) > 2 {
t.Errorf("absent-id claim made %d requests, want at most 2: %v", len(paths), paths)
}
// A present id still claims through the same shape.
ok := f.run([]string{"BEADS_ACTOR=gc-hook"}, "update", present, "--claim", "--json")
if ok.code != 0 || firstJSONField(t, ok.stdout, "assignee") != "gc-hook" {
t.Errorf("claim of a present id: exit %d stdout=%s stderr=%s", ok.code, ok.stdout, ok.stderr)
}
})
}
}
// TestE2E_AdvertisedExternalPolicyIsPassedThrough is the other half of the
// design 3.6 rule, against the MC server's handshake shape: a server that
// advertises policy.external_dependencies has applied it, so the client reads
// no dependency edges for it on list, ready, claim, show or close.
func TestE2E_AdvertisedExternalPolicyIsPassedThrough(t *testing.T) {
skipUnlessEmbeddedDolt(t)
bin := buildBD(t)
proxyAddr, counter := startMaskingProxy(t, startE2EServer(t), mcContextMask)
f := newHTTPFixture(t, bin, proxyAddr)
id := f.create("plain")
other := f.create("other")
f.mustRun(nil, "dep", "add", id, "external:other:cap")
counter.reset()
f.mustRun(nil, "list", "--json", "--limit", "50")
f.mustRun(nil, "ready", "--json", "--limit", "10")
f.mustRun(nil, "show", id, "--json")
f.mustRun(nil, "update", other, "--claim", "--json")
// claim-next is the server's ONE atomic operation, not a client-side
// read-then-claim loop.
f.mustRun(nil, "ready", "--claim", "--json")
var claimNexts, byID int
for _, p := range counter.snapshot() {
switch {
case p == "POST /v0/beads/issues:claimNext":
claimNexts++
case strings.HasPrefix(p, "POST /v0/beads/issues/") && strings.HasSuffix(p, ":claim"):
byID++
}
}
if claimNexts != 1 || byID != 0 {
t.Errorf("claimNext requests = %d, by-id claims = %d; want one atomic claim-next and no by-id claim: %v", claimNexts, byID, counter.snapshot())
}
f.mustRun(nil, "close", other, "--json")
for _, p := range counter.snapshot() {
if strings.HasPrefix(p, "GET /v0/beads/dependencies") {
t.Errorf("client-side policy ran against a server advertising policy.external_dependencies: %s in %v", p, counter.snapshot())
break
}
}
}

View file

@ -6,6 +6,7 @@ package bdhttp_test
import (
"context"
"errors"
"io"
"net/http"
"net/http/httptest"
@ -18,6 +19,7 @@ import (
"github.com/steveyegge/beads/backend"
bdhttp "github.com/steveyegge/beads/backend/http"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/storage/backends"
)
@ -333,7 +335,10 @@ func TestExplicitCredentialIgnoresTheEnvPlaintextGrant(t *testing.T) {
doors := []struct {
name string
// call drives one request through the door with a fresh explicit
// credential and returns that request's error.
// credential and returns that request's error. plaintextRemote
// answers the issue read not_found, which GetIssue reports as
// storage.ErrNotFound; that request reached the remote, so the
// store doors count it as success.
call func(t *testing.T, target bdhttp.Target, client *http.Client) error
}{
{"OpenWith", func(t *testing.T, target bdhttp.Target, client *http.Client) error {
@ -352,7 +357,9 @@ func TestExplicitCredentialIgnoresTheEnvPlaintextGrant(t *testing.T) {
t.Fatalf("OpenWith: %v", err)
}
t.Cleanup(func() { _ = store.Close() })
_, err = store.GetIssue(ctx, "bd-1")
if _, err = store.GetIssue(ctx, "bd-1"); errors.Is(err, storage.ErrNotFound) {
return nil
}
return err
}},
{"Open", func(t *testing.T, target bdhttp.Target, client *http.Client) error {
@ -363,7 +370,9 @@ func TestExplicitCredentialIgnoresTheEnvPlaintextGrant(t *testing.T) {
t.Fatalf("Open: %v", err)
}
t.Cleanup(func() { _ = store.Close() })
_, err = store.GetIssue(ctx, "bd-1")
if _, err = store.GetIssue(ctx, "bd-1"); errors.Is(err, storage.ErrNotFound) {
return nil
}
return err
}},
{"Handshake", func(t *testing.T, target bdhttp.Target, client *http.Client) error {

View file

@ -278,6 +278,7 @@ go_library(
"recompute_blocked_proxied_server.go",
"relate.go",
"relate_proxied_server.go",
"remote_backend.go",
"remote_migrate_gate.go",
"rename.go",
"rename_prefix.go",
@ -1083,6 +1084,7 @@ go_test(
"root_context_lifecycle_test.go",
"routed_test.go",
"routing_notice_test.go",
"routing_read_remote_test.go",
"routing_read_test.go",
"rules_test.go",
"sandbox_test.go",

View file

@ -523,7 +523,6 @@ var createCmd = &cobra.Command{
Ephemeral: wisp,
NoHistory: noHistory,
StorageClass: storageClass,
CreatedBy: getActorWithGit(),
Owner: getOwner(),
Labels: labels,
MolType: molType,

View file

@ -66,12 +66,12 @@ func getHierarchicalChildren(ctx context.Context, store storage.DoltStorage, dbP
parentIssue, err = s.GetIssue(ctx, parentID)
return err
})
if errors.Is(err, storage.ErrNotFound) || (err == nil && parentIssue == nil) {
return nil, fmt.Errorf("parent issue '%s' not found", parentID)
}
if err != nil {
return nil, fmt.Errorf("error checking parent issue: %v", err)
}
if parentIssue == nil {
return nil, fmt.Errorf("parent issue '%s' not found", parentID)
}
// Use recursive search to find all descendants using the same logic as --parent filter.
// The parent itself is NOT included in the result set — only actual children and

View file

@ -22,7 +22,8 @@ var pingCmd = &cobra.Command{
Steps:
1. Resolve the .beads workspace
2. Open the store (embedded or server)
3. Run a trivial query (issue count)
3. Run a trivial query (one issue row; a remote backend reads its
authenticated server context instead)
4. Report timing
Exit 0 on success, exit 1 on failure.
@ -60,8 +61,14 @@ Examples:
}
storeMs := time.Since(start).Milliseconds()
filter := types.IssueFilter{Limit: 1}
_, err := st.SearchIssues(rootCtx, "", filter)
// A store with its own liveness check (a remote backend's handshake
// read) answers through it; every other store runs the one-row query.
var err error
if pinger, ok := storage.UnwrapStore(st).(storage.Pinger); ok {
err = pinger.Ping(rootCtx)
} else {
_, err = st.SearchIssues(rootCtx, "", types.IssueFilter{Limit: 1})
}
if err != nil {
return pingFail(start, fmt.Sprintf("query failed: %v", err))
}

61
cmd/bd/remote_backend.go Normal file
View file

@ -0,0 +1,61 @@
package main
import (
"github.com/steveyegge/beads/internal/storage"
)
// THE ATTRIBUTION OMISSIONS (S6d).
//
// A store that reports storage.CallerAttributionLimitedStore (today the http
// backend) refuses two caller-authored members its wire cannot carry, and
// would otherwise refuse two everyday commands outright. The CLI omits them
// for such a store only where the omission loses nothing a reader relies on:
//
// - `bd reopen`'s Provenance. The CLI's label is the fixed "bd: reopen <id>",
// fully derivable from the operation and the id; the server records its
// own reopen entry for the same issue and the same actor. Nothing is lost.
//
// - `bd update -s closed`'s closed_by_session. It is attribution only: no
// bd or gc behavior (ready, close guards, claims) reads it, and the status
// change, its close-policy guards and the atomicity with every other field
// in the same update are all kept. It is also usually AMBIENT — every agent
// under Claude Code exports CLAUDE_SESSION_ID — so refusing the close
// would break the command for an input the caller never typed. The close
// still happens, and a one-line notice on stderr says the session was not
// recorded — for an explicit --session and for the ambient
// CLAUDE_SESSION_ID alike, so the omission is never silent — pointing at
// `bd close`, whose wire operation does carry the session.
//
// No capability token is spent on either: the wire publishes neither member,
// so there is nothing to negotiate yet. When a wire revision publishes one,
// the store's CallerAttributionLimited answer becomes the handshake check and
// these call sites need no change.
// storeCarriesCallerAttribution reports whether s can record the caller's own
// history label and closed_by_session.
func storeCarriesCallerAttribution(s storage.DoltStorage) bool {
if s == nil {
return true
}
limited, ok := storage.UnwrapStore(s).(storage.CallerAttributionLimitedStore)
return !ok || !limited.CallerAttributionLimited()
}
// reopenProvenance is `bd reopen`'s history label for store, or "" (the
// backend's own label) where the store cannot carry one.
func reopenProvenance(store storage.DoltStorage, id string) string {
if !storeCarriesCallerAttribution(store) {
return ""
}
return "bd: reopen " + id
}
// storeIsRemoteBackend reports whether s is a pure network client of a remote
// bd serve (storage.RemoteBackendStore), seen through the decorator chain.
func storeIsRemoteBackend(s storage.DoltStorage) bool {
if s == nil {
return false
}
remote, ok := storage.UnwrapStore(s).(storage.RemoteBackendStore)
return ok && remote.IsRemoteBackendStore()
}

View file

@ -109,8 +109,9 @@ another actor won the race, so retrying the same guard is pointless).`,
ExpectedVersion: ifRevision,
// Names the issue for the reason `bd close`'s does, and keeps
// the entry identical across backends: the proxied route
// already writes "bd: reopen <ids>".
Provenance: "bd: reopen " + fullID,
// already writes "bd: reopen <ids>". A remote store labels the
// entry itself (remote_backend.go).
Provenance: reopenProvenance(issueStore, fullID),
})
if err != nil {
// Only a guarded reopen reports through the conditional-write

View file

@ -95,10 +95,28 @@ func resolveAndGetIssueWithRoutingAccess(ctx context.Context, localStore storage
return nil, err
}
// idResolverFor is the store id resolution should ask. A backend that can only
// look ids up exactly (utils.ExactIDLookupStore, the http backend) sits under
// the decorator chain, which does not forward that capability, so the
// resolver is handed the backend itself: resolution is a pure read, and the
// decorators (hooks, the external-dependency policy, telemetry) decide
// nothing about it. Every other store is resolved through s unchanged.
func idResolverFor(s storage.DoltStorage) utils.PartialIDResolverStore {
if s == nil {
return s
}
if raw := storage.UnwrapStore(s); raw != nil {
if exact, ok := raw.(utils.ExactIDLookupStore); ok && exact.ExactIDLookupOnly() {
return raw
}
}
return s
}
// resolveAndGetFromStore resolves a partial ID and gets the issue from a specific store.
func resolveAndGetFromStore(ctx context.Context, s storage.DoltStorage, id string, routed bool) (*RoutedResult, error) {
// First, resolve the partial ID
resolvedID, err := utils.ResolvePartialID(ctx, s, id)
resolvedID, err := utils.ResolvePartialID(ctx, idResolverFor(s), id)
if err != nil {
return nil, err
}
@ -123,7 +141,7 @@ func resolveAndGetFromStore(ctx context.Context, s storage.DoltStorage, id strin
// happens to be a leading-prefix abbreviation of some issue's hash) is
// reported as "not found" rather than silently resolved.
func resolveAndGetFromStoreExact(ctx context.Context, s storage.DoltStorage, id string, routed bool) (*RoutedResult, error) {
resolvedID, err := utils.ResolvePartialIDExact(ctx, s, id)
resolvedID, err := utils.ResolvePartialIDExact(ctx, idResolverFor(s), id)
if err != nil {
return nil, err
}

View file

@ -31,12 +31,30 @@ func resolveRoutingConfigValue(key string, dbValues map[string]string) string {
return strings.TrimSpace(dbValues[key])
}
// routingSettingsStore is the store whose settings document may supply the
// routing.* and contributor.* keys, or nil when none may.
//
// A remote backend's settings are one document shared by every client of the
// server, and the routing targets are LOCAL filesystem paths, which such a
// document cannot name for every machine reading it. Contributor routing for a
// remote workspace is therefore configured locally (config.yaml / env) only:
// `bd create`'s routing decision and the lookup fallback a missing id takes
// read the same local-only answer, and neither pays a settings round trip to
// learn it (S6b).
func routingSettingsStore(store storage.DoltStorage) storage.DoltStorage {
if store == nil || storeIsRemoteBackend(store) {
return nil
}
return store
}
func getRoutingConfigValue(ctx context.Context, store storage.DoltStorage, key string) string {
if src := config.GetValueSource(key); src != config.SourceDefault {
if value := strings.TrimSpace(config.GetString(key)); value != "" {
return value
}
}
store = routingSettingsStore(store)
if store == nil {
return ""
}
@ -50,7 +68,8 @@ func getRoutingConfigValue(ctx context.Context, store storage.DoltStorage, key s
func determineAutoRoutedRepoPath(ctx context.Context, store storage.DoltStorage) (string, routing.RoutingRule) {
var dbValues map[string]string
if store != nil {
// Local-only for a remote backend: see routingSettingsStore.
if store = routingSettingsStore(store); store != nil {
all, allErr := store.GetAllConfig(ctx)
if allErr != nil {
debug.Logf("DEBUG: failed to read config from store: %v\n", allErr)

View file

@ -0,0 +1,62 @@
package main
import (
"context"
"testing"
"github.com/steveyegge/beads/internal/storage"
)
// routingSettingsFake answers the two settings reads routing makes and counts
// them. The embedded DoltStorage is nil: any other call panics, so the test
// says so if routing starts reading something else.
type routingSettingsFake struct {
storage.DoltStorage
remote bool
reads int
}
func (f *routingSettingsFake) IsRemoteBackendStore() bool { return f.remote }
func (f *routingSettingsFake) GetConfig(_ context.Context, key string) (string, error) {
f.reads++
if key == "routing.mode" {
return "auto", nil
}
return "", nil
}
func (f *routingSettingsFake) GetAllConfig(context.Context) (map[string]string, error) {
f.reads++
return map[string]string{"routing.mode": "auto"}, nil
}
// TestRoutingSettingsAreLocalOnlyOnARemoteBackend pins one rule for both
// routing reads: `bd create`'s per-key getRoutingConfigValue and the lookup
// fallback's determineAutoRoutedRepoPath. On a remote backend neither reads
// the server's shared settings document (routing targets are local paths), so
// create and lookup cannot route differently for the same workspace. A local
// store is still consulted.
func TestRoutingSettingsAreLocalOnlyOnARemoteBackend(t *testing.T) {
initConfigForTest(t)
t.Setenv("BEADS_ROUTING_MODE", "")
t.Setenv("BD_ROUTING_MODE", "")
ctx := context.Background()
remote := &routingSettingsFake{remote: true}
if got := getRoutingConfigValue(ctx, remote, "routing.mode"); got != "" {
t.Errorf("getRoutingConfigValue(remote, routing.mode) = %q, want \"\" (local config only)", got)
}
_, _ = determineAutoRoutedRepoPath(ctx, remote)
if remote.reads != 0 {
t.Errorf("a remote backend's settings were read %d times for routing, want 0", remote.reads)
}
local := &routingSettingsFake{}
if got := getRoutingConfigValue(ctx, local, "routing.mode"); got != "auto" {
t.Errorf("getRoutingConfigValue(local, routing.mode) = %q, want the store's \"auto\"", got)
}
if local.reads != 1 {
t.Errorf("a local store's settings were read %d times, want 1", local.reads)
}
}

View file

@ -17,6 +17,7 @@ import (
"github.com/steveyegge/beads/internal/storage/backends"
"github.com/steveyegge/beads/internal/storage/contextinfo"
"github.com/steveyegge/beads/internal/storage/domain"
"github.com/steveyegge/beads/internal/storage/externaldeps"
"github.com/steveyegge/beads/internal/storage/uow"
"github.com/steveyegge/beads/issueops"
"github.com/steveyegge/beads/memoryops"
@ -343,9 +344,13 @@ func runServe() error {
// extraction, this flag and the maintenance ticker cannot disagree
// about whether this workspace journals.
EventsJournalEnabled: journalEnabled,
Workspace: info,
SchemaVersion: JSONSchemaVersion,
Mode: serveResolvedMode(info, db),
// The roles above come from the storage chain, which interposes
// the external-dependency policy (wireStorageDecorators); the
// handshake advertises it only if that layer is really there.
ExternalDependencyPolicy: externaldeps.Applied(store),
Workspace: info,
SchemaVersion: JSONSchemaVersion,
Mode: serveResolvedMode(info, db),
})
}
@ -419,10 +424,11 @@ func runServe() error {
// is still the workspace's answer and still has to be handed in — the
// provider knows how to READ the journal, not whether this workspace has
// one.
EventsJournalEnabled: eventsjournal.EnabledFor(info.BeadsDir),
Workspace: info,
SchemaVersion: JSONSchemaVersion,
Mode: serveResolvedMode(info, db),
EventsJournalEnabled: eventsjournal.EnabledFor(info.BeadsDir),
ExternalDependencyPolicy: externaldeps.AppliedToProvider(provider),
Workspace: info,
SchemaVersion: JSONSchemaVersion,
Mode: serveResolvedMode(info, db),
})
}

View file

@ -175,6 +175,10 @@ func assertServedCapabilities(t *testing.T, body map[string]any) {
if len(want) == 0 {
t.Fatal("this build derives no capabilities; the assertion below would pass against a server that advertises nothing")
}
// Every bd serve topology composes its roles through the external-dependency
// policy, so every one advertises the conditional policy token too.
want = append(want, httpapi.CapExternalDependencies)
slices.Sort(want)
if !slices.Equal(got, want) {
t.Errorf("capabilities = %v, want %v", got, want)
}

View file

@ -9,6 +9,7 @@ import (
"net/http"
"os"
"path/filepath"
"slices"
"strings"
"sync/atomic"
"testing"
@ -17,6 +18,7 @@ import (
"github.com/steveyegge/beads/internal/beads"
"github.com/steveyegge/beads/internal/configfile"
"github.com/steveyegge/beads/internal/git"
"github.com/steveyegge/beads/internal/httpapi"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/storage/backends"
"github.com/steveyegge/beads/internal/storage/embeddeddolt"
@ -91,6 +93,15 @@ func TestServeAnswersFromARegisteredBackendStore(t *testing.T) {
}
})
// The store arm serves roles from the storage chain, which interposes the
// external-dependency policy, so a client must be told not to run it again.
t.Run("the handshake advertises the external-dependency policy", func(t *testing.T) {
caps, _ := getJSON(t, base+"/v0/beads/context")["capabilities"].([]any)
if !slices.Contains(caps, any(httpapi.CapExternalDependencies)) {
t.Errorf("capabilities = %v, want %q: bd serve applies the policy on this arm", caps, httpapi.CapExternalDependencies)
}
})
// GET /v0/beads/context is the one endpoint automation is told to trust for
// this server's identity, and it was reporting backend="dolt",
// dolt_mode="embedded", database="beads" here — a full, confident

View file

@ -233,7 +233,6 @@ func runSetState(ctx context.Context, issueID, dimension, newValue, reason strin
Status: types.StatusClosed,
Priority: 4,
IssueType: types.TypeEvent,
CreatedBy: getActorWithGit(),
Ephemeral: details.Ephemeral,
NoHistory: details.NoHistory,
},

View file

@ -145,6 +145,10 @@ pointless).`,
// was given without an explicit --status, to flip status=deferred back
// to open (matches the help text's "show in bd ready immediately").
var clearDeferStatus bool
// explicitSession: --session was typed (rather than inherited from
// CLAUDE_SESSION_ID), so omitting it on a store that cannot carry it
// is said out loud (remote_backend.go).
var explicitSession bool
if cmd.Flags().Changed("status") {
status, _ := cmd.Flags().GetString("status")
@ -167,6 +171,7 @@ pointless).`,
// If status is being set to closed, include session if provided
if status == "closed" {
session, _ := cmd.Flags().GetString("session")
explicitSession = session != ""
if session == "" {
session = os.Getenv("CLAUDE_SESSION_ID")
}
@ -438,6 +443,7 @@ pointless).`,
updatedIssues := []*types.Issue{}
var firstUpdatedID string // Track first successful update for last-touched
var warnedSessionOmitted bool
var failures []updateIDFailure
recordFailure := func(id, reason string) {
failures = append(failures, updateIDFailure{ID: id, Error: reason})
@ -534,6 +540,19 @@ pointless).`,
// earlier transaction) silently erased concurrent writers' keys —
// both processes exited 0, one process's committed write vanished.
patch := basePatch
// S6d: a store whose wire cannot carry closed_by_session still
// closes; the session is attribution only (remote_backend.go).
if patch.ClosedBySession.Set && !storeCarriesCallerAttribution(issueStore) {
patch.ClosedBySession = issueops.Field[string]{}
if !warnedSessionOmitted {
warnedSessionOmitted = true
if explicitSession {
fmt.Fprintf(os.Stderr, "%s --session is not recorded: this backend's update cannot carry closed_by_session (bd close --session records it)\n", ui.RenderWarn("!"))
} else {
fmt.Fprintf(os.Stderr, "%s CLAUDE_SESSION_ID is not recorded as closed_by_session: this backend's update cannot carry it (bd close records it)\n", ui.RenderWarn("!"))
}
}
}
// GH#3233: --defer="" restores ready visibility only if the issue
// was actually deferred. Other statuses (blocked, in_progress, …)
// shouldn't be clobbered just because defer_until was stale.

View file

@ -126,13 +126,13 @@ Role-request fields on the served writes that the v0 wire publishes no member fo
| W-IssuePatch.ParentID | retired | — | a parent re-hang through update used to refuse | RETIRED with W-IssuePatch.Status (ga-7i6by). It is ONE call rather than a remove-then-add pair, which is the whole reason the member exists: the two-call spelling leaves the issue parentless if the second call fails, and dependencies:add/remove — still the general write side of the graph over this wire — cannot express the atomic replacement. The empty string removes every parent-child edge, so it travels like `assignee`'s empty string rather than being skipped. The graph refusals it earns are the server's and arrive typed: a cycle through the issue's own descendant as the PLAIN dependency_cycle, and an existing edge of another type as dependency_exists | D8 refuse-not-drop | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the in-repo divergence ledger, engdocs/design/http-divergence-ledger.md, for the discipline |
| W-CreateBatchRequest.Provenance | refuse | `CreateBatchRequest.Provenance` | labeling a batch create's history entry refuses | batchCreateIssues publishes actor and items only, and the server writes its own label; see W-UpdateRequest.Provenance. It is the one Provenance whose ABSENCE is visible in shipped history — the surface this role serves has always named its source file in the entry (`bd: create 3 issue(s) from plan.md`) | D8 row 14 refuse-not-drop | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the in-repo divergence ledger, engdocs/design/http-divergence-ledger.md, for the discipline |
| W-CreateBatchRequest.ForceIDPrefix | refuse | `CreateBatchRequest.ForceIDPrefix` `--force` | permitting explicit ids outside the workspace's configured prefix refuses | the wire publishes no such member — and could not honor one, since it publishes no explicit id for the flag to permit (W-BatchCreateItem.Issue). Dropping it would answer a request about WHERE ids may be written with a batch whose ids the server chose | D8 row 14 refuse-not-drop | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the in-repo divergence ledger, engdocs/design/http-divergence-ledger.md, for the discipline |
| W-BatchCreateItem.Issue | refuse | `BatchCreateItem.Issue` | an item whose Issue populates any member outside the wire's eight refuses, naming the member | apigen.BatchCreateItem carries title, description, design, acceptance_criteria, priority, issue_type, assignee and labels and nothing else, while the role accepts far more of a types.Issue: an explicit id, the wisp flags, metadata, the storage class, every timestamp, the gate/molecule/event fields. ONE row rather than one per member because the reason is one reason — the wire's item vocabulary — and forty rows repeating it would say nothing a reader does not learn here. Exhaustiveness is held by REFLECTION instead: the client's carried and role-ignored tables are checked against types.Issue field by field, so a member added upstream is refused the day it lands rather than dropped until someone notices. The members the role ITSELF ignores on a create (ContentHash, RowVersion, lease, compaction, routing overrides, hydration flags) are not in this population and are not refused: a local create drops them too. Nor is a CreatedBy that names the request's actor: the server stamps every item's created_by from the actor (W-CreateRequest.Issue), so that value arrives as written and only a CreatedBy naming someone else refuses | D8 row 14 refuse-not-drop | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the in-repo divergence ledger, engdocs/design/http-divergence-ledger.md, for the discipline |
| W-BatchCreateItem.Issue | refuse | `BatchCreateItem.Issue` | an item whose Issue populates any member outside the wire's eight refuses, naming the member | apigen.BatchCreateItem carries title, description, design, acceptance_criteria, priority, issue_type, assignee and labels and nothing else, while the role accepts far more of a types.Issue: an explicit id, the wisp flags, metadata, the storage class, every timestamp, the gate/molecule/event fields. ONE row rather than one per member because the reason is one reason — the wire's item vocabulary — and forty rows repeating it would say nothing a reader does not learn here. Exhaustiveness is held by REFLECTION instead: the client's carried and role-ignored tables are checked against types.Issue field by field, so a member added upstream is refused the day it lands rather than dropped until someone notices. The members the role ITSELF ignores on a create (ContentHash, RowVersion, lease, compaction, routing overrides, hydration flags) are not in this population and are not refused: a local create drops them too. Nor is a CreatedBy that names the request's actor: the server's create role defaults every item's created_by to the actor (W-CreateRequest.Issue), so that value arrives as written and only a CreatedBy naming someone else refuses | D8 row 14 refuse-not-drop | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the in-repo divergence ledger, engdocs/design/http-divergence-ledger.md, for the discipline |
| W-CreateDependency.Reverse | refuse | `CreateDependency.Reverse` | an edge written from the target back to the new issue refuses ON A BATCH CREATE | BatchCreateDependency carries target_id and type only; dropping Reverse would write the edge in the OPPOSITE direction from the one asked for, which is a different graph. createIssue's CreateIssueDependency DOES publish it, and the single-create path sends it (internal/httpapi/spec BatchCreateDependency) | D8 row 14 refuse-not-drop | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the in-repo divergence ledger, engdocs/design/http-divergence-ledger.md, for the discipline |
| W-CreateDependency.Metadata | refuse | `CreateDependency.Metadata` | typed edge metadata refuses ON A BATCH CREATE | BatchCreateDependency publishes no metadata member, and a waits-for gate whose metadata was dropped is a readiness rule that silently does not hold. createIssue's edge publishes it, and the single-create path sends it verbatim (internal/httpapi/spec BatchCreateDependency) | D8 row 14 refuse-not-drop | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the in-repo divergence ledger, engdocs/design/http-divergence-ledger.md, for the discipline |
| W-CreateDependency.ThreadID | refuse | `CreateDependency.ThreadID` | associating an edge with a discussion thread refuses | neither BatchCreateDependency nor CreateIssueDependency publishes a thread member (internal/httpapi/spec BatchCreateDependency) | D8 row 14 refuse-not-drop | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the in-repo divergence ledger, engdocs/design/http-divergence-ledger.md, for the discipline |
| W-CreateRequest.IDPrefix | refuse | `CreateRequest.IDPrefix` | overriding the prefix an explicit, unforced id is checked against refuses | createIssue publishes no `id_prefix`, and the omission is the SERVER's decision rather than a gap (internal/httpapi/create.go): the field exists because a workspace's own config.yaml prefix wins over the database's and only a local front door can read that file, so a remote caller's config.yaml describes a workspace this server does not serve. Publishing it would let a caller override the served workspace's prefix rule from outside it. Dropping it instead would check the id against the SERVER's prefix while the caller believed it was checked against theirs — the same request, two different answers to 'may this workspace mint this id'. It refuses only where it would ACT: the role reads the override for nothing but an explicit id it was not told to force, so a create that mints its id, or sets ForceIDPrefix, is the same request with or without it and is sent without it. That matters because `bd create` sends the workspace's prefix on EVERY create, so an unconditional refusal would refuse every create in a workspace whose config.yaml names one | D8 row 16 refuse-not-drop | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the in-repo divergence ledger, engdocs/design/http-divergence-ledger.md, for the discipline |
| W-CreateRequest.Issue | refuse | `CreateRequest.Issue` | a create whose Issue populates any member outside the wire's twenty refuses, naming the member | createIssue publishes the whole create VOCABULARY — id, title, description, design, acceptance_criteria, notes, status, issue_type, priority, assignee, owner, estimated_minutes, external_ref, due_at, defer_until, sender, metadata, labels, ephemeral, no_history — and deliberately not the rest of a types.Issue: the creation time (created_at), because a caller-supplied creation time makes the row disagree with the journal entry that records it and re-dating history is what an import is for; and spec_id, await_*, mol_type, wisp_type, work_type, storage_class, source_*, pinned, is_template and the event quartet, which this surface publishes on no operation, read or write. ONE row rather than one per member for W-BatchCreateItem.Issue's reason — the reason is one reason — and exhaustiveness is held by the same REFLECTION over types.Issue, sharing the role-ignored table with the batch so the two operations cannot disagree about what the ROLE drops. Issue.Comments and Issue.Dependencies are not in this population: the role itself refuses them, so a local create fails too and this is validation rather than divergence. created_by is published on no create shape either, but every one of them STAMPS it from the request's actor (internal/httpapi's create.go, batch_create.go and batch_apply.go) — the local front doors' own rule, since the role copies the member rather than stamping it. So a CreatedBy that names the actor, which is what every CLI create sends, arrives as written, and only one naming someone else refuses: the stamp would silently replace it. A server that predates the stamp stores an empty created_by for that one member | D8 row 16 refuse-not-drop | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the in-repo divergence ledger, engdocs/design/http-divergence-ledger.md, for the discipline |
| W-CreateItem.Issue | refuse | `CreateItem.Issue` | a create ITEM whose Issue populates any member outside the wire's twenty refuses, naming the member | ApplyCreateItem publishes exactly createIssue's create vocabulary — id, title, description, design, acceptance_criteria, notes, status, issue_type, priority, assignee, owner, estimated_minutes, external_ref, due_at, defer_until, sender, metadata, labels, ephemeral, no_history — and deliberately not the rest of a types.Issue, for the reasons W-CreateRequest.Issue gives in full. It is a row of its OWN rather than a citation of that one because the operations are different: a caller auditing why their PLAN refuses must not be sent to a row about a single create, and the two can diverge the day either vocabulary moves. The partition itself is SHARED — one carried table, one role-ignored table, held against types.Issue by the same reflection — so they cannot disagree about what the wire carries or about what the role drops. Issue.Comments and Issue.Dependencies are not in this population and are refused as validation on both sides: edges in this role are ITEMS, so a create item has nowhere to put one at all. Nor is a CreatedBy that names the request's actor: the server stamps every create item's created_by from the actor (W-CreateRequest.Issue), so that value arrives as written and only a CreatedBy naming someone else refuses | D8 refuse-not-drop | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the in-repo divergence ledger, engdocs/design/http-divergence-ledger.md, for the discipline |
| W-CreateRequest.Issue | refuse | `CreateRequest.Issue` | a create whose Issue populates any member outside the wire's twenty refuses, naming the member | createIssue publishes the whole create VOCABULARY — id, title, description, design, acceptance_criteria, notes, status, issue_type, priority, assignee, owner, estimated_minutes, external_ref, due_at, defer_until, sender, metadata, labels, ephemeral, no_history — and deliberately not the rest of a types.Issue: the creation time (created_at), because a caller-supplied creation time makes the row disagree with the journal entry that records it and re-dating history is what an import is for; and spec_id, await_*, mol_type, wisp_type, work_type, storage_class, source_*, pinned, is_template and the event quartet, which this surface publishes on no operation, read or write. ONE row rather than one per member for W-BatchCreateItem.Issue's reason — the reason is one reason — and exhaustiveness is held by the same REFLECTION over types.Issue, sharing the role-ignored table with the batch so the two operations cannot disagree about what the ROLE drops. Issue.Comments and Issue.Dependencies are not in this population: the role itself refuses them, so a local create fails too and this is validation rather than divergence. created_by is published on no create shape either, but the create role behind every one of them defaults an empty created_by to the request's actor (issueops.PreparePublicCreateRequest), the same rule a local create gets. So an empty CreatedBy and one that names the actor both arrive as the actor, and only one naming someone else refuses: the default would silently replace it. A server older than either stamp (handler or role) stores an empty created_by for that one member | D8 row 16 refuse-not-drop | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the in-repo divergence ledger, engdocs/design/http-divergence-ledger.md, for the discipline |
| W-CreateItem.Issue | refuse | `CreateItem.Issue` | a create ITEM whose Issue populates any member outside the wire's twenty refuses, naming the member | ApplyCreateItem publishes exactly createIssue's create vocabulary — id, title, description, design, acceptance_criteria, notes, status, issue_type, priority, assignee, owner, estimated_minutes, external_ref, due_at, defer_until, sender, metadata, labels, ephemeral, no_history — and deliberately not the rest of a types.Issue, for the reasons W-CreateRequest.Issue gives in full. It is a row of its OWN rather than a citation of that one because the operations are different: a caller auditing why their PLAN refuses must not be sent to a row about a single create, and the two can diverge the day either vocabulary moves. The partition itself is SHARED — one carried table, one role-ignored table, held against types.Issue by the same reflection — so they cannot disagree about what the wire carries or about what the role drops. Issue.Comments and Issue.Dependencies are not in this population and are refused as validation on both sides: edges in this role are ITEMS, so a create item has nowhere to put one at all. Nor is a CreatedBy that names the request's actor: the server's create role defaults every create item's created_by to the actor (W-CreateRequest.Issue), so that value arrives as written and only a CreatedBy naming someone else refuses | D8 refuse-not-drop | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the in-repo divergence ledger, engdocs/design/http-divergence-ledger.md, for the discipline |
| W-ApplyPatch.ParentID | refuse | `IssuePatch.ParentID` | a parent re-hang inside an update ITEM refuses, where the same member serves on updateIssue | ApplyPatchBody deliberately publishes no parent_id, and the absence is this operation's ONE-EDGE-ONE-SPELLING rule rather than a gap: a parent is a dep_add item of type parent-child, so the ORDER of every edge in a plan stays total and there is exactly one place an edge is written. The single patch has no ordering to express and publishes the member directly (W-IssuePatch.ParentID, retired by client wave ga-7i6by), which is why the same Go field is carried by one document and refused by the other. Refusing is not a loss of capability, only of spelling: a plan re-hangs a parent with a dep_add item, which is the atomic replacement in the position the caller declared it | D8 refuse-not-drop | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the in-repo divergence ledger, engdocs/design/http-divergence-ledger.md, for the discipline |
| W-DepAddItem.HasSpawner | retired | `DepAddItem.HasSpawner` | a waits-for edge ITEM that names its spawner used to refuse | RETIRED by issues.batchApply.depAddLineage (S5). ApplyDepAddItem now publishes `has_spawner` — the write this row said only the role could make, metadata's spawner_id stamped from the resolved target — gated on the capability rather than dropped: a caller on a server that has not advertised the token refuses locally before the dial (BatchApplier.refuseUnservedDepAddLineage), and a caller on a server that has sends the member exactly as given. The flag is sent, and gated, on a waits-for edge only, the one type the role reads it on. Off a waits-for edge it is the role's no-op, so the client drops it there without loss — the stored row is the same either way — rather than refusing a request the flag cannot change, or sending an older server a member it answers with a 400 | D8 refuse-not-drop (RETIRED) | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the in-repo divergence ledger, engdocs/design/http-divergence-ledger.md, for the discipline |
| W-DepAddItem.ThreadID | retired | `DepAddItem.ThreadID` | associating an edge ITEM with a discussion thread used to refuse | RETIRED with W-DepAddItem.HasSpawner (S5, issues.batchApply.depAddLineage). ApplyDepAddItem now publishes `thread_id` as a plain column on the stored edge, gated by the same capability and the same pre-dial refusal rather than dropped — a caller naming a thread on an unadvertising server is refused before the dial, never silently stored with no thread | D8 refuse-not-drop (RETIRED) | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the in-repo divergence ledger, engdocs/design/http-divergence-ledger.md, for the discipline |
@ -152,13 +152,13 @@ Whole commands, and the flag modes of served commands, that dispatch onto method
| F-ready-gated | refuse | `--gated` | `bd ready --gated` refuses | it dispatches onto a filtered SearchIssues shape the bridge cannot express, plus GetDependents | D7 | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the in-repo divergence ledger, engdocs/design/http-divergence-ledger.md, for the discipline |
| F-show-thread | refuse | `--thread` | `bd show --thread` refuses | showMessageThread renders each reply's sender, recipient, body and timestamp off GetDependentsWithMetadata, but that read was flipped onto getIssue's include_dependents parameter, which carries the collectDependents SHALLOW projection (id/status/type/priority/title + edge type only, be-4d36f2). Those fields come back zeroed over http and zero-timestamp replies sort ahead of the root — a silent-wrong degrade the refuse-over-degrade doctrine forbids. Retires with a full-dependent wire shape, a server-side ask | D7 | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the in-repo divergence ledger, engdocs/design/http-divergence-ledger.md, for the discipline |
| F-show-refs | refuse | `--refs` | `bd show --refs` refuses | showIssueRefs's --json marshals the full GetDependentsWithMetadata rows, but the wire answers the same collectDependents shallow projection, so created_at/assignee/description come back zeroed and the JSON differs from a local workspace. The text render consumes only the shallow fields, but the flag cannot be split from its --json mode, so the whole flag refuses rather than serve a divergent JSON silently | D7 | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the in-repo divergence ledger, engdocs/design/http-divergence-ledger.md, for the discipline |
| F-show-children | refuse | `--children` | `bd show --children` refuses | showIssueChildren's --json marshals the full GetDependentsWithMetadata rows, the same collectDependents shallow projection as --refs, so created_at/assignee/description come back zeroed over http; `bd children` refuses as a whole command for the same reason | D7 | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the in-repo divergence ledger, engdocs/design/http-divergence-ledger.md, for the discipline |
| F-show-children | refuse | `--children` | `bd show --children` refuses | showIssueChildren's --json marshals the full GetDependentsWithMetadata rows, the same collectDependents shallow projection as --refs, so created_at/assignee/description come back zeroed over http. `bd children` is NOT this flag: it is a `bd list --parent` listing, served through the reader role (S6c) | D7 | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the in-repo divergence ledger, engdocs/design/http-divergence-ledger.md, for the discipline |
| F-mol-ready | refuse | — | `bd mol ready` refuses | it is the same runMolReadyGatedCore body as `bd ready --gated` | D7 | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the in-repo divergence ledger, engdocs/design/http-divergence-ledger.md, for the discipline |
| F-blocked | refuse | — | `bd blocked` refuses | it is raw GetBlockedIssues, which is on the unsupported allowlist | D7 | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the in-repo divergence ledger, engdocs/design/http-divergence-ledger.md, for the discipline |
| F-count | retired | — | RETIRED — `bd count` is SERVED whole | it said the command refuses because "issueops.Counter has no wire operation; a counts operation is a filed upstream ask", and that ask was DELIVERED: upstream #5508 published countIssues, client wave ga-icks1 wired the Counter accessor, and `count` moved from httpRefusedCommands into httpServedCommands. D8 row 20 and docs/reference/http-workspaces.md have said so since; this row was the last place that did not. Every flag the command publishes reaches a wire member — the whole predicate, the six instant bounds, the three emptiness checks, --include-infra, and the five --by-* flags as the one group_by parameter — so there is no refused mode left to name either. HOW IT ROTTED IS THE PART WORTH KEEPING. Its pin was TestClassifiedRefusedCommandsRefuseBeforeTheOSSPreRun, which walks httpRefusedCommands and drives every entry. The moment `count` left that table the pin stopped covering this row — it stayed LIVE BY NAME, so the well-formedness gate that resolves PinnedBy to a real test kept passing, and DEAD BY COVERAGE, so nothing anywhere asserted the row's claim. A ledger row can be false for a whole wave under a green pin, which is what TestFRowsAgreeWithTheCommandClassification now makes impossible | D7 (RETIRED), D8 row 20 | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the in-repo divergence ledger, engdocs/design/http-divergence-ledger.md, for the discipline |
| F-serve | refuse | — | `bd serve` refuses against an http workspace | the OSS classifier would happily serve it from the opened store, and a bd serve re-serving a remote bd serve is a proxy chain nobody designed: run serve where the database is | D7 | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the in-repo divergence ledger, engdocs/design/http-divergence-ledger.md, for the discipline |
| F-close | refuse | — | `bd close` is SERVED whole — single id and several ids — over issues:batchClose; it refuses against a DOWN-LEVEL server that does not advertise issues.batchClose, and --claim-next refuses against every server, before anything closes | the CLI's close front door routes every id, single-id included, through BatchCloser.CloseBatch, and Lifecycle.Close has zero CLI callers at tip. The wire now carries issues:batchClose, so a CloseBatchRequest of any size is one wire call and one server-side transaction; nothing is composed or refused where the capability is present. THE NEXT CLAIM IS THE EXCEPTION. batchCloseIssues has no member to carry it, so the client refuses a ClaimNext on both legs, after the claim's own validation and before the dial (W-CloseBatchRequest.ClaimNext). Closing and then claiming would split the role's one transaction in two, and a claim that failed after the closes committed could not report them, because the role answers with an error or with outcomes, never both. On the CLI's chain the external-dependency decorator (design 3.6) refuses first unless the server advertises wire.CapExternalDependencies, and its refusal says nothing closed and names the commands that do the same work: close without --claim-next, then `bd ready --claim` (internal/storage/externaldeps/remote_roles.go). Against a server too old to advertise issues.batchClose, servesBatchClose() reads the handshake snapshot and routes around the batch dial entirely, so no Preflight runs and no wire.ErrCapabilityAbsent is raised: the down-level leg's refuseUnservedCloseShape raises the STORE's own *ErrHTTPUnsupported (batchcloser.go), which names the refused shape and the server, and cmd/bd prints it against each id the batch carried. The single-item, no-ClaimNext shape still composes onto closeIssue in that down-level leg (see L18); the shapes that cannot compose refuse there. The item cap is L-close-cap | D8 row 17 (resolved, Wire), D9 L18, D9 L-close-cap | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the in-repo divergence ledger, engdocs/design/http-divergence-ledger.md, for the discipline |
| F-partial-id | refuse | — | partial-id resolution refuses with its own taxonomy text | SearchIssueIDs has no wire operation, and the client cannot tell a partial id from a full id that does not exist — so the refusal text covers both outcomes rather than falling through to a raw search error | D11 | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the in-repo divergence ledger, engdocs/design/http-divergence-ledger.md, for the discipline |
| F-partial-id | refuse | — | partial-id resolution refuses with its own taxonomy text | SearchIssueIDs has no wire operation, and the client cannot tell a partial id from a full id that does not exist — so the refusal text covers both outcomes rather than falling through to a raw search error, and it unwraps to ErrNotFound. The store also reports utils.ExactIDLookupStore, so the CLI's routed lookups (show, update, close, reopen, ...) stop at the exact getIssue and answer a plain not-found after that one round trip, never reaching the search (S6b) | D11 | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the in-repo divergence ledger, engdocs/design/http-divergence-ledger.md, for the discipline |
## Ready-request fields

View file

@ -1050,9 +1050,9 @@ type ContextResponse struct {
// OPTIONAL, and absent means only that this server does not disclose its filesystem layout — never that it has no workspace. A client MUST NOT require it, MUST NOT treat absence as an error, and has no use for the value beyond display: it is a path on the SERVER's filesystem, which the client cannot open. Identify the workspace by `project_id` and `database`, which are required.
BeadsDir *string `json:"beads_dir,omitempty"`
// Capabilities The tokens this server advertises: the OPERATIONS it implements, derived from its route table, and the server-wide BEHAVIORS it enforces. v0's operation vocabulary is `ready.list`, `ready.count`, `issues.list`, `issues.query`, `issues.count`, `issues.get`, `issues.related`, `issues.create`, `issues.addComment`, `issues.batchClose`, `issues.claim`, `issues.claimNext`, `issues.release`, `issues.close`, `issues.reopen`, `issues.update`, `issues.sweep`, `issues.delete`, `issues.batchGet`, `issues.reclaim`, `issues.batchCreate`, `issues.batchApply`, `stats.get`, `config.list`, `config.get`, `config.set`, `config.unset`, `dependencies.cycles`, `dependencies.list`, `dependencies.count`, `dependencies.blocking`, `dependencies.tree`, `dependencies.add`, `dependencies.remove`, `memories.list`, `memories.get`, `memories.remember`, `memories.forget`, `events.list`, `events.watch`, `issues.casMetadata`; the behavior tokens are `project.enforce`, which announces that a `Bd-Project-Id` stamp for the wrong workspace is refused here rather than silently ignored, `issues.batchApplyLarge`, which announces that `POST /v0/beads/issues:batchApply` accepts the RAISED envelope — up to 1000 items (`ApplyBatchRequest.items.maxItems`), a 16 MiB body, and (for a request over 100 items) a run budget that EXTENDS to an operator-configured ceiling (`bd serve --large-apply-ceiling`, 5 minutes by default) — rather than the original 100-item, 4 MiB bound. The ceiling is a flat whole-run budget, not a value scaled by item count: a 101-item request and a 1000-item request both get the same extended budget. A request at or under 100 items is unaffected either way and keeps the server's ordinary deadline exactly as before. A client that checks for this token before sending a plan over 100 items learns whether THIS server accepts it without paying for a round trip an older server would refuse anyway, and `issues.list.sort`, which announces that `GET /v0/beads/issues` accepts the `sort` query parameter (two closed, pageable total orders — see that parameter) rather than silently answering `unknown_parameter`, and `issues.count.scope`, which announces that `GET /v0/beads/issues:count` accepts `parent`, `no_parent`, `exclude_type`, and `exclude_status` (see those parameters) rather than silently answering `unknown_parameter` for all four, `issues.sweep.wispsPlane`, which announces that `POST /v0/beads/issues:sweep` accepts the `wisps-plane` value of `tier` rather than silently answering `invalid_value`, `issues.sweep.liveDependents`, which announces that the same operation accepts `protect_live_dependents` and answers `skipped.live_dependent` rather than silently answering `unknown_parameter`, `issues.sweep.limit`, which announces that it accepts `limit` and answers `remaining` rather than silently answering `unknown_parameter`, and `issues.batchApply.depAddLineage`, which announces that a `dep_add` item on `POST /v0/beads/issues:batchApply` accepts `has_spawner` and `thread_id` (see `ApplyDepAddItem`) rather than a `400` naming the member unknown, and `issues.update.allowTemplate`, which announces that `PATCH /v0/beads/issues/{id}` accepts `allow_template` (see `UpdateIssueRequest`) rather than a `400` naming the member unknown, and `issues.create.defaultPriority`, which announces that a create (`POST /v0/beads/issues`, `issues:batchCreate` and `issues:batchApply` create items) with no `priority` member stores the default P2 rather than P0. The list grows additively, and an operation never appears here unless it is fully implemented. This is how a client checks for an operation or a behavior — never the version string.
// Capabilities The tokens this server advertises: the OPERATIONS it implements, derived from its route table, and the server-wide BEHAVIORS it enforces. v0's operation vocabulary is `ready.list`, `ready.count`, `issues.list`, `issues.query`, `issues.count`, `issues.get`, `issues.related`, `issues.create`, `issues.addComment`, `issues.batchClose`, `issues.claim`, `issues.claimNext`, `issues.release`, `issues.close`, `issues.reopen`, `issues.update`, `issues.sweep`, `issues.delete`, `issues.batchGet`, `issues.reclaim`, `issues.batchCreate`, `issues.batchApply`, `stats.get`, `config.list`, `config.get`, `config.set`, `config.unset`, `dependencies.cycles`, `dependencies.list`, `dependencies.count`, `dependencies.blocking`, `dependencies.tree`, `dependencies.add`, `dependencies.remove`, `memories.list`, `memories.get`, `memories.remember`, `memories.forget`, `events.list`, `events.watch`, `issues.casMetadata`; the behavior tokens are `project.enforce`, which announces that a `Bd-Project-Id` stamp for the wrong workspace is refused here rather than silently ignored, `issues.batchApplyLarge`, which announces that `POST /v0/beads/issues:batchApply` accepts the RAISED envelope — up to 1000 items (`ApplyBatchRequest.items.maxItems`), a 16 MiB body, and (for a request over 100 items) a run budget that EXTENDS to an operator-configured ceiling (`bd serve --large-apply-ceiling`, 5 minutes by default) — rather than the original 100-item, 4 MiB bound. The ceiling is a flat whole-run budget, not a value scaled by item count: a 101-item request and a 1000-item request both get the same extended budget. A request at or under 100 items is unaffected either way and keeps the server's ordinary deadline exactly as before. A client that checks for this token before sending a plan over 100 items learns whether THIS server accepts it without paying for a round trip an older server would refuse anyway, and `issues.list.sort`, which announces that `GET /v0/beads/issues` accepts the `sort` query parameter (two closed, pageable total orders — see that parameter) rather than silently answering `unknown_parameter`, and `issues.count.scope`, which announces that `GET /v0/beads/issues:count` accepts `parent`, `no_parent`, `exclude_type`, and `exclude_status` (see those parameters) rather than silently answering `unknown_parameter` for all four, `issues.sweep.wispsPlane`, which announces that `POST /v0/beads/issues:sweep` accepts the `wisps-plane` value of `tier` rather than silently answering `invalid_value`, `issues.sweep.liveDependents`, which announces that the same operation accepts `protect_live_dependents` and answers `skipped.live_dependent` rather than silently answering `unknown_parameter`, `issues.sweep.limit`, which announces that it accepts `limit` and answers `remaining` rather than silently answering `unknown_parameter`, and `issues.batchApply.depAddLineage`, which announces that a `dep_add` item on `POST /v0/beads/issues:batchApply` accepts `has_spawner` and `thread_id` (see `ApplyDepAddItem`) rather than a `400` naming the member unknown, and `issues.update.allowTemplate`, which announces that `PATCH /v0/beads/issues/{id}` accepts `allow_template` (see `UpdateIssueRequest`) rather than a `400` naming the member unknown, and `issues.create.defaultPriority`, which announces that a create (`POST /v0/beads/issues`, `issues:batchCreate` and `issues:batchApply` create items) with no `priority` member stores the default P2 rather than P0. One behavior token is CONDITIONAL rather than build-level: `policy.external_dependencies` announces that this server's ready, claim, claim-next, close, blocking and dependency-tree operations already apply bd's external-dependency policy (an issue blocked by an unsatisfied `external:<project>:<capability>` dependency is neither ready, claimable nor closable without force). A server advertises it only when it enforces that policy; a client that sees it must not apply the policy again, and a client that does not see it applies the policy itself. The list grows additively, and an operation never appears here unless it is fully implemented. This is how a client checks for an operation or a behavior — never the version string.
//
// THIS LIST IS BUILD-LEVEL, NOT WORKSPACE-LEVEL. It says which operations this binary serves, and for every entry but two that is the whole answer. `events.list` and `events.watch` are the exceptions: the durable events journal is a per-workspace setting that is OFF by default, so a server that advertises them may still refuse every request to both with 409 `events_journal_disabled` — correctly, because the operations exist and the workspace has no journal. A consumer of either MUST treat the capability as "this server speaks it" and the 409 as "not on this workspace", and must not read the capability as a promise that records will arrive.
// THIS LIST IS BUILD-LEVEL, NOT WORKSPACE-LEVEL, apart from the conditional `policy.external_dependencies` above, which depends on how this server composed its roles rather than on the build. It says which operations this binary serves, and for every entry but two that is the whole answer. `events.list` and `events.watch` are the exceptions: the durable events journal is a per-workspace setting that is OFF by default, so a server that advertises them may still refuse every request to both with 409 `events_journal_disabled` — correctly, because the operations exist and the workspace has no journal. A consumer of either MUST treat the capability as "this server speaks it" and the 409 as "not on this workspace", and must not read the capability as a promise that records will arrive.
Capabilities []string `json:"capabilities"`
// Database Logical database name (not a host or a DSN).

View file

@ -213,14 +213,7 @@ func (s *Server) applyBatchRequest(w http.ResponseWriter, r *http.Request) (issu
if res != nil {
return refuse(res)
}
// created_by is stamped from the actor on every create item, createIssue's
// rule (create.go): the item publishes no created_by and the role copies the
// issue's rather than stamping one.
for _, item := range items {
if item.Create != nil {
item.Create.Issue.CreatedBy = actor
}
}
// No created_by stamp: the role defaults each create item's to the actor.
return issueops.ApplyBatchRequest{
Actor: actor,
Items: items,

View file

@ -144,10 +144,11 @@ func TestApplyBatchForwardsEveryLevelOfTheDocumentedBody(t *testing.T) {
if create.Issue.Priority != 1 {
t.Errorf("create.priority = %d, want 1", create.Issue.Priority)
}
// created_by is stamped from the trimmed actor, createIssue's rule: the
// role copies the issue's and never stamps one itself.
if create.Issue.CreatedBy != "alice" {
t.Errorf("create.created_by = %q, want the actor %q", create.Issue.CreatedBy, "alice")
// created_by is not the handler's to stamp: the item reaches the role
// without one, and the role defaults it to the request's actor
// (backend/conformance's batch-apply contract pins that half).
if create.Issue.CreatedBy != "" {
t.Errorf("create.created_by = %q, want it left to the role", create.Issue.CreatedBy)
}
if create.Issue.EstimatedMinutes == nil || *create.Issue.EstimatedMinutes != 30 {
t.Errorf("create.estimated_minutes = %v, want 30", create.Issue.EstimatedMinutes)

View file

@ -101,13 +101,7 @@ func (s *Server) batchCreateRequest(w http.ResponseWriter, r *http.Request) (iss
if !ok {
return issueops.CreateBatchRequest{}, false
}
// created_by is stamped from the actor on every item, createIssue's rule
// (create.go): the item publishes no created_by and the role copies the
// issue's rather than stamping one, so without this a batch-created issue
// would store none where `bd create --file` stores its actor.
for _, item := range items {
item.Issue.CreatedBy = actor
}
// No created_by stamp: the role defaults each item's to the actor.
return issueops.CreateBatchRequest{Actor: actor, Items: items}, true
}

View file

@ -85,11 +85,12 @@ func TestBatchCreatePassesTheRequestToTheRoleAndAnswersWithWhatItCreated(t *test
if got.Items[1].Issue.Priority != 0 || got.Items[1].Issue.Description != "body" {
t.Errorf("item 1 = %+v, want the wire's description and no priority", *got.Items[1].Issue)
}
// created_by is stamped from the actor on EVERY item, createIssue's rule:
// the role copies the issue's and never stamps one itself.
// created_by is not the handler's to stamp: every item reaches the role
// without one, and the role defaults it to the request's actor
// (backend/conformance's batch-creator contract pins that half).
for i, item := range got.Items {
if item.Issue.CreatedBy != "alice" {
t.Errorf("item %d created_by = %q, want the actor %q", i, item.Issue.CreatedBy, "alice")
if item.Issue.CreatedBy != "" {
t.Errorf("item %d created_by = %q, want it left to the role", i, item.Issue.CreatedBy)
}
}
// No provenance: the file name a CLI batch spells has no analogue here, so

View file

@ -202,18 +202,9 @@ func (s *Server) createIssueRequest(w http.ResponseWriter, r *http.Request) (iss
Sender: derefString(wire.Sender),
Ephemeral: derefBool(wire.Ephemeral),
NoHistory: derefBool(wire.NoHistory),
// CreatedBy is stamped from the caller-asserted actor, matching the
// local front door's semantics (cmd/bd/create.go sets issue.CreatedBy
// from getActorWithGit() before calling the same role): the role
// itself never stamps it, copying whatever the caller already put on
// types.Issue (internal/storage/issueops/public_create.go's
// publicCreateIssue). The wire's `actor` member is the caller-asserted
// identity this request carries — provenance for the audit trail, not
// authenticated identity, exactly as this file's own doc comment
// states above — so it is the one value this server has to make that
// stamp from. batch_create.go and batch_apply.go make the same
// stamp, so no create shape stores an empty created_by.
CreatedBy: actor,
// No CreatedBy: the wire publishes none, and the role defaults it to
// the request's actor (issueops.PreparePublicCreateRequest), the same
// rule every front door and library caller gets.
}
if wire.Priority != nil {
issue.Priority = *wire.Priority

View file

@ -190,17 +190,15 @@ func TestCreateForwardsEveryDocumentedMember(t *testing.T) {
t.Errorf("the handler put edges or comments on the issue (%d/%d); they belong to the request's own members",
len(issue.Dependencies), len(issue.Comments))
}
// created_at is unpublished, so a fresh row must reach the role with it
// zero and take the implementation's own value. created_by IS stamped by
// this handler, from the same trimmed actor identity asserted above —
// matching the local front door's semantics (cmd/bd/create.go sets
// issue.CreatedBy from getActorWithGit() before calling the same role,
// because the role itself never stamps it).
// created_at and created_by are unpublished, so a fresh row reaches the
// role with both zero: the implementation stamps created_at, and the role
// defaults created_by to the request's actor (the lifecycle-create
// contract in backend/conformance pins that half), as for every caller.
if !issue.CreatedAt.IsZero() {
t.Errorf("the handler set created_at (%v); it is not published on this operation", issue.CreatedAt)
}
if issue.CreatedBy != "alice" {
t.Errorf("created_by = %q, want the actor %q", issue.CreatedBy, "alice")
if issue.CreatedBy != "" {
t.Errorf("created_by = %q, want it left to the role", issue.CreatedBy)
}
if len(req.Dependencies) != 2 {

View file

@ -182,6 +182,28 @@ const CapIssuesUpdateAllowTemplate = "issues.update.allowTemplate"
// send the default explicitly rather than omit the member.
const CapIssuesCreateDefaultPriority = "issues.create.defaultPriority"
// CapExternalDependencies is the CONDITIONAL behavior capability announcing
// that this server's ready, claim, claim-next, close, blocking-annotation and
// dependency-tree operations already apply bd's external-dependency policy
// (an issue blocked by an unsatisfied `external:<project>:<capability>`
// dependency is not ready, not claimable and not closable without force). A
// client that sees it must pass those operations through untouched: running
// the policy again on the client would judge it against the CLIENT machine's
// project configuration and would turn the server's atomic claim-next into a
// read-then-claim loop.
//
// It is not in behaviorCapabilities because it is not a property of the
// build: the policy is a decorator the serving process composes its roles or
// provider through. Listen advertises it exactly when Config says the roles it
// was handed were composed that way (Config.ExternalDependencyPolicy), so the
// token is never advertised by a server that does not enforce the policy.
const CapExternalDependencies = "policy.external_dependencies"
// conditionalCapabilities are the behavior tokens a server advertises only
// when its configuration says the behavior is in force. Capabilities() never
// lists them; advertisedCapabilities adds each one whose condition holds.
var conditionalCapabilities = []string{CapExternalDependencies}
// customMethodTarget splits the custom method off the segment the router
// matched, and reports the row that claims it.
//
@ -963,3 +985,14 @@ func Capabilities() []string {
slices.Sort(out)
return out
}
// advertisedCapabilities is what this server's handshake publishes: the
// build-level Capabilities() plus each conditional token cfg puts in force.
func advertisedCapabilities(cfg Config) []string {
out := Capabilities()
if cfg.ExternalDependencyPolicy {
out = append(out, CapExternalDependencies)
slices.Sort(out)
}
return out
}

View file

@ -390,6 +390,18 @@ type Config struct {
// a server without this flag would answer "you are caught up" to a consumer
// polling a workspace that will never emit a record.
EventsJournalEnabled bool
// ExternalDependencyPolicy reports that every ready, claim, claim-next,
// close, blocking-annotation and tree role this server answers from — the
// Provider's, or the individual role fields' — was composed through bd's
// external-dependency policy (internal/storage/externaldeps). It makes the
// handshake advertise CapExternalDependencies, which tells a client to
// pass those operations through without applying the policy itself.
//
// Set it only from the composition actually handed in (cmd/bd's serve
// derives it with externaldeps.Applied / externaldeps.AppliedToProvider):
// a server that advertises the token without enforcing the policy makes
// every client skip it.
ExternalDependencyPolicy bool
// Workspace is the startup snapshot GET /v0/beads/context answers from.
// Only the allowlisted fields are ever serialized — see contextResponse,
// which names the whole set and the reasons for the exclusions.
@ -671,7 +683,7 @@ func Listen(cfg Config) (*Server, error) {
log: log.New(cfg.Stderr, "bd serve: ", log.LstdFlags|log.LUTC),
stdout: cfg.Stdout,
ctxBody: contextResponse(cfg.Workspace, cfg.SchemaVersion, Capabilities()),
ctxBody: contextResponse(cfg.Workspace, cfg.SchemaVersion, advertisedCapabilities(cfg)),
hosts: newHostPolicy(ip, cfg.AllowedHosts),
auth: cfg.Auth,
idPrefix: prefix,

View file

@ -650,6 +650,37 @@ func TestCapabilitiesAdvertiseEveryImplementedOperation(t *testing.T) {
}
}
// TestExternalDependencyPolicyIsAdvertisedOnlyWhenEnforced pins the one
// conditional token: policy.external_dependencies rides the handshake exactly
// when Config says the roles were composed through the policy, and the rest of
// the list is unchanged either way.
func TestExternalDependencyPolicyIsAdvertisedOnlyWhenEnforced(t *testing.T) {
read := func(cfg Config) []string {
ts := newTestServer(t, cfg)
caps, _ := decodeBody(t, ts.get(t, "/v0/beads/context"))["capabilities"].([]any)
var got []string
for _, c := range caps {
got = append(got, c.(string))
}
return got
}
without := read(Config{})
if slices.Contains(without, "policy.external_dependencies") {
t.Errorf("a server not composed through the policy advertises it: %v", without)
}
with := read(Config{ExternalDependencyPolicy: true})
if !slices.Contains(with, "policy.external_dependencies") {
t.Errorf("a server composed through the policy does not advertise it: %v", with)
}
if !slices.IsSorted(with) {
t.Errorf("capabilities = %v, want them sorted", with)
}
rest := slices.DeleteFunc(slices.Clone(with), func(c string) bool { return c == "policy.external_dependencies" })
if !slices.Equal(rest, without) {
t.Errorf("the policy flag changed other tokens: with=%v without=%v", with, without)
}
}
// THE `implemented` GATE IS NOT PINNED HERE, and saying so is the point.
//
// A loop asserting that no unimplemented row is advertised was written, run

View file

@ -8146,22 +8146,34 @@ components:
`issues.create.defaultPriority`, which announces that a create
(`POST /v0/beads/issues`, `issues:batchCreate` and
`issues:batchApply` create items) with no `priority` member stores
the default P2 rather than P0. The
the default P2 rather than P0. One behavior token is
CONDITIONAL rather than build-level: `policy.external_dependencies`
announces that this server's ready, claim, claim-next, close,
blocking and dependency-tree operations already apply bd's
external-dependency policy (an issue blocked by an unsatisfied
`external:<project>:<capability>` dependency is neither ready,
claimable nor closable without force). A server advertises it
only when it enforces that policy; a client that sees it must not
apply the policy again, and a client that does not see it applies
the policy itself. The
list grows additively, and an operation never appears here unless
it is fully implemented. This is how a client checks for an
operation or a behavior — never the version string.
THIS LIST IS BUILD-LEVEL, NOT WORKSPACE-LEVEL. It says which
operations this binary serves, and for every entry but two that is
the whole answer. `events.list` and `events.watch` are the
exceptions: the durable events journal is a per-workspace setting
that is OFF by default, so a server that advertises them may still
refuse every request to both with 409 `events_journal_disabled` —
correctly, because the operations exist and the workspace has no
journal. A consumer of either MUST treat the capability as "this
server speaks it" and the 409 as "not on this workspace", and must
not read the capability as a promise that records will arrive.
THIS LIST IS BUILD-LEVEL, NOT WORKSPACE-LEVEL, apart from the
conditional `policy.external_dependencies` above, which depends on
how this server composed its roles rather than on the build. It
says which operations this binary serves, and for every entry but
two that is the whole answer. `events.list` and `events.watch` are
the exceptions: the durable events journal is a per-workspace
setting that is OFF by default, so a server that advertises them
may still refuse every request to both with 409
`events_journal_disabled` — correctly, because the operations exist
and the workspace has no journal. A consumer of either MUST treat
the capability as "this server speaks it" and the 409 as "not on
this workspace", and must not read the capability as a promise that
records will arrive.
items:
type: string
wire_revision:

View file

@ -490,6 +490,15 @@ func TestSpecCapabilityVocabularyMatchesTheRouteTable(t *testing.T) {
for _, token := range Capabilities() {
served[token] = true
}
// The conditional tokens are documented in the same paragraph. Their
// snake_case segment is outside capabilityToken's shape, so each is looked
// for verbatim.
for _, token := range conditionalCapabilities {
served[token] = true
if strings.Contains(desc, "`"+token+"`") {
documented[token] = true
}
}
if missing := diff(served, documented); len(missing) > 0 {
t.Errorf("this build serves capabilities the document does not enumerate: %v\n"+

View file

@ -109,6 +109,7 @@ go_test(
"divergence_citation_gate_test.go",
"divergence_test.go",
"expected_revision_contract_test.go",
"getissue_miss_test.go",
"helpers_test.go",
"insecure_credential_guard_test.go",
"lifecycle_create_test.go",

View file

@ -46,8 +46,8 @@ const maxBatchCreateItems = 100
// an Owner from git config (W-BatchCreateItem.Issue), so it still refuses
// over this wire.
// - CreatedBy: apigen.BatchCreateItem has no member for it either, but the
// batch server stamps every item's created_by from the request's actor
// (internal/httpapi/batch_create.go), as single create does. A CreatedBy
// server's create role defaults every item's created_by to the request's
// actor (issueops.PreparePublicCreateRequest), as single create does. A CreatedBy
// naming the actor is therefore carried BY the actor
// (actorStampedCreateMember below), and any other value is refused rather
// than silently replaced by the stamp.
@ -92,10 +92,10 @@ var roleIgnoredCreateIssueMembers = map[string]string{
// server writes from the request's actor rather than reads from the body, and
// already holds the value that stamp will write.
//
// CreatedBy is the one such member: every create shape stamps created_by from
// the actor (internal/httpapi's create.go, batch_create.go and batch_apply.go).
// It is neither carried nor role-ignored — a local create stores whatever the
// issue names — so it is carried BY THE ACTOR: a CreatedBy that names the actor,
// CreatedBy is the one such member: every create shape's role defaults an empty
// created_by to the actor (issueops.PreparePublicCreateRequest), on the server
// as locally. It is neither carried nor role-ignored — a local create keeps
// whatever explicit value the issue names — so it is carried BY THE ACTOR: a CreatedBy that names the actor,
// which is what `bd create`, `bd create --file` and the graph apply send,
// arrives as written, and any other value would be silently replaced by the
// stamp and is refused.

View file

@ -5,6 +5,7 @@ package httpclient
import (
"context"
"errors"
"fmt"
"net/http"
"net/url"
@ -146,13 +147,13 @@ func (s *Store) readyBridgePage(ctx context.Context, op string, filter types.Wor
// GetIssue serves getIssue. It is the `bd list --parent` walk's
// parent-existence probe and the molecule loader's read half.
//
// A MISS IS (nil, nil), NOT AN ERROR. That is the raw method's own contract and
// the walk depends on it: getHierarchicalChildren reads a nil result as "parent
// issue not found" and prints that, where an error would print the transport's
// vocabulary instead.
// A MISS IS storage.ErrNotFound (issueops.ErrNotFound), wrapped exactly as the local stores wrap it
// (issueops.GetIssueInTx: "not found: issue <id>"), so a caller written against
// the backend contract — `errors.Is(err, storage.ErrNotFound)` — reads an http
// miss the same as a local one. The empty id is a miss too, as it is locally.
func (s *Store) GetIssue(ctx context.Context, id string) (*types.Issue, error) {
if id == "" {
return nil, nil
return nil, issueNotFound(id)
}
path, err := wire.IssuePath(id)
if err != nil {
@ -170,7 +171,7 @@ func (s *Store) GetIssue(ctx context.Context, id string) (*types.Issue, error) {
IssueID: id,
}, &details)
if errors.Is(err, issueops.ErrNotFound) {
return nil, nil
return nil, issueNotFound(id)
}
if err != nil {
return nil, err
@ -195,3 +196,8 @@ func (s *Store) GetIssue(ctx context.Context, id string) (*types.Issue, error) {
issue.RowVersion = version
return &issue, nil
}
// issueNotFound is the raw GetIssue miss, spelled as the local stores spell it.
func issueNotFound(id string) error {
return fmt.Errorf("%w: issue %s", issueops.ErrNotFound, id)
}

View file

@ -281,7 +281,6 @@ var legitimatelyUnsupported = map[string]string{
"GetNextChildID": "raw read: id allocation is a server-side act",
"GetStaleIssues": "raw read: no staleness operation",
"GetStatisticsNoBlocked": "raw read: getStats has no blocked-suppression variant",
"SearchIssueIDs": "raw read: no partial-id search operation (D11)",
"SearchIssueSummaries": "raw read: no summary-projection search operation; SearchIssues (role: Searcher) hydrates full issues, and the wire publishes no narrower searchIssues projection for list-shaped rendering to drop onto",
"SearchIssuesWithCounts": "raw read: no counts-bearing search operation",

View file

@ -36,8 +36,8 @@ import (
// getIssueDetails is the shared dial behind the three include-bearing reads: GET
// the issue-detail path with the caller's query and decode types.IssueDetails,
// exactly as bridge.go's GetIssue does. A 404 is (nil, nil) rather than an
// error, so each read maps its own empty answer onto it.
// as bridge.go's GetIssue does. A 404 is (nil, nil) rather than an error here,
// unlike GetIssue's miss, so each read maps its own empty answer onto it.
func (s *Store) getIssueDetails(ctx context.Context, id string, query url.Values) (*types.IssueDetails, error) {
if id == "" {
return nil, nil
@ -73,7 +73,11 @@ func (s *Store) getIssueDetails(ctx context.Context, id string, query url.Values
// second dial here would be a second copy of that correction.
func (s *Store) GetLabels(ctx context.Context, id string) ([]string, error) {
issue, err := s.GetIssue(ctx, id)
if err != nil || issue == nil {
if errors.Is(err, issueops.ErrNotFound) {
// The local read answers a nonexistent id with no labels, not an error.
return nil, nil
}
if err != nil {
return nil, err
}
return issue.Labels, nil

View file

@ -752,7 +752,7 @@ func writeSideRows() []Row {
Why: "apigen.BatchCreateItem carries title, description, design, acceptance_criteria, priority, issue_type, assignee and labels and nothing else, while the role accepts far more of a types.Issue: an explicit id, the wisp flags, metadata, the storage class, every timestamp, the gate/molecule/event fields. " +
"ONE row rather than one per member because the reason is one reason — the wire's item vocabulary — and forty rows repeating it would say nothing a reader does not learn here. Exhaustiveness is held by REFLECTION instead: the client's carried and role-ignored tables are checked against types.Issue field by field, so a member added upstream is refused the day it lands rather than dropped until someone notices. " +
"The members the role ITSELF ignores on a create (ContentHash, RowVersion, lease, compaction, routing overrides, hydration flags) are not in this population and are not refused: a local create drops them too. " +
"Nor is a CreatedBy that names the request's actor: the server stamps every item's created_by from the actor (W-CreateRequest.Issue), so that value arrives as written and only a CreatedBy naming someone else refuses",
"Nor is a CreatedBy that names the request's actor: the server's create role defaults every item's created_by to the actor (W-CreateRequest.Issue), so that value arrives as written and only a CreatedBy naming someone else refuses",
SpecRow: "D8 row 14 refuse-not-drop",
PinnedBy: batchCreatePin,
},
@ -787,7 +787,7 @@ func writeSideRows() []Row {
Why: "createIssue publishes the whole create VOCABULARY — id, title, description, design, acceptance_criteria, notes, status, issue_type, priority, assignee, owner, estimated_minutes, external_ref, due_at, defer_until, sender, metadata, labels, ephemeral, no_history — and deliberately not the rest of a types.Issue: the creation time (created_at), because a caller-supplied creation time makes the row disagree with the journal entry that records it and re-dating history is what an import is for; and spec_id, await_*, mol_type, wisp_type, work_type, storage_class, source_*, pinned, is_template and the event quartet, which this surface publishes on no operation, read or write. " +
"ONE row rather than one per member for W-BatchCreateItem.Issue's reason — the reason is one reason — and exhaustiveness is held by the same REFLECTION over types.Issue, sharing the role-ignored table with the batch so the two operations cannot disagree about what the ROLE drops. " +
"Issue.Comments and Issue.Dependencies are not in this population: the role itself refuses them, so a local create fails too and this is validation rather than divergence. " +
"created_by is published on no create shape either, but every one of them STAMPS it from the request's actor (internal/httpapi's create.go, batch_create.go and batch_apply.go) — the local front doors' own rule, since the role copies the member rather than stamping it. So a CreatedBy that names the actor, which is what every CLI create sends, arrives as written, and only one naming someone else refuses: the stamp would silently replace it. A server that predates the stamp stores an empty created_by for that one member",
"created_by is published on no create shape either, but the create role behind every one of them defaults an empty created_by to the request's actor (issueops.PreparePublicCreateRequest), the same rule a local create gets. So an empty CreatedBy and one that names the actor both arrive as the actor, and only one naming someone else refuses: the default would silently replace it. A server older than either stamp (handler or role) stores an empty created_by for that one member",
SpecRow: "D8 row 16 refuse-not-drop",
PinnedBy: createPin,
},
@ -823,7 +823,7 @@ func writeSideRows() []Row {
Why: "ApplyCreateItem publishes exactly createIssue's create vocabulary — id, title, description, design, acceptance_criteria, notes, status, issue_type, priority, assignee, owner, estimated_minutes, external_ref, due_at, defer_until, sender, metadata, labels, ephemeral, no_history — and deliberately not the rest of a types.Issue, for the reasons W-CreateRequest.Issue gives in full. " +
"It is a row of its OWN rather than a citation of that one because the operations are different: a caller auditing why their PLAN refuses must not be sent to a row about a single create, and the two can diverge the day either vocabulary moves. The partition itself is SHARED — one carried table, one role-ignored table, held against types.Issue by the same reflection — so they cannot disagree about what the wire carries or about what the role drops. " +
"Issue.Comments and Issue.Dependencies are not in this population and are refused as validation on both sides: edges in this role are ITEMS, so a create item has nowhere to put one at all. " +
"Nor is a CreatedBy that names the request's actor: the server stamps every create item's created_by from the actor (W-CreateRequest.Issue), so that value arrives as written and only a CreatedBy naming someone else refuses",
"Nor is a CreatedBy that names the request's actor: the server's create role defaults every create item's created_by to the actor (W-CreateRequest.Issue), so that value arrives as written and only a CreatedBy naming someone else refuses",
SpecRow: "D8 refuse-not-drop",
PinnedBy: applyPin,
},
@ -1081,7 +1081,7 @@ func commandRows() []Row {
row("F-show-refs", "show", "--refs", "`bd show --refs` refuses",
"showIssueRefs's --json marshals the full GetDependentsWithMetadata rows, but the wire answers the same collectDependents shallow projection, so created_at/assignee/description come back zeroed and the JSON differs from a local workspace. The text render consumes only the shallow fields, but the flag cannot be split from its --json mode, so the whole flag refuses rather than serve a divergent JSON silently"),
row("F-show-children", "show", "--children", "`bd show --children` refuses",
"showIssueChildren's --json marshals the full GetDependentsWithMetadata rows, the same collectDependents shallow projection as --refs, so created_at/assignee/description come back zeroed over http; `bd children` refuses as a whole command for the same reason"),
"showIssueChildren's --json marshals the full GetDependentsWithMetadata rows, the same collectDependents shallow projection as --refs, so created_at/assignee/description come back zeroed over http. `bd children` is NOT this flag: it is a `bd list --parent` listing, served through the reader role (S6c)"),
row("F-mol-ready", "mol ready", "", "`bd mol ready` refuses",
"it is the same runMolReadyGatedCore body as `bd ready --gated`"),
row("F-blocked", "blocked", "", "`bd blocked` refuses",
@ -1115,8 +1115,9 @@ func commandRows() []Row {
},
{
ID: "F-partial-id", Kind: KindRefuse,
What: "partial-id resolution refuses with its own taxonomy text",
Why: "SearchIssueIDs has no wire operation, and the client cannot tell a partial id from a full id that does not exist — so the refusal text covers both outcomes rather than falling through to a raw search error",
What: "partial-id resolution refuses with its own taxonomy text",
Why: "SearchIssueIDs has no wire operation, and the client cannot tell a partial id from a full id that does not exist — so the refusal text covers both outcomes rather than falling through to a raw search error, and it unwraps to ErrNotFound. " +
"The store also reports utils.ExactIDLookupStore, so the CLI's routed lookups (show, update, close, reopen, ...) stop at the exact getIssue and answer a plain not-found after that one round trip, never reaching the search (S6b)",
SpecRow: "D11",
PinnedBy: pinnedByS3Conformance,
},

View file

@ -0,0 +1,72 @@
package httpclient
import (
"encoding/json"
"errors"
"io"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"sync/atomic"
"testing"
"github.com/steveyegge/beads/internal/httpclient/wire"
"github.com/steveyegge/beads/internal/storage"
)
// TestGetIssueMissIsErrNotFound is the unit-tier pin of the raw GetIssue miss,
// over the real wire client against a stub server (no embedded engine): the
// server's 404 not_found, and the empty id that never dials, must both come
// back as storage.ErrNotFound with a nil issue, spelled as the local stores
// spell it. A (nil, nil) miss reads as a hit to every caller written against
// the backend contract: `bd create --graph` refused every explicit-id plan.
func TestGetIssueMissIsErrNotFound(t *testing.T) {
var gets atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case r.URL.Path == wire.PathContext:
ctx := v0Context("proj-miss")
ctx.Capabilities = []string{"issues.get"}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(ctx)
case strings.HasPrefix(r.URL.Path, wire.PathIssues+"/"):
gets.Add(1)
w.Header().Set("Content-Type", "application/problem+json; charset=utf-8")
w.WriteHeader(http.StatusNotFound)
_, _ = io.WriteString(w, `{"status":404,"code":"not_found","title":"not found"}`)
default:
http.NotFound(w, r)
}
}))
t.Cleanup(srv.Close)
base, err := url.Parse(srv.URL)
if err != nil {
t.Fatal(err)
}
client, err := wire.New(base, nil, wire.Options{HTTPClient: srv.Client()})
if err != nil {
t.Fatal(err)
}
store := New(Target{BaseURL: base}, client, nil)
issue, err := store.GetIssue(t.Context(), "bd-absent")
if issue != nil || !errors.Is(err, storage.ErrNotFound) {
t.Fatalf("GetIssue(absent) = (%v, %v), want (nil, storage.ErrNotFound)", issue, err)
}
if want := "not found: issue bd-absent"; err.Error() != want {
t.Errorf("GetIssue(absent) error = %q, want the local stores' %q", err, want)
}
if got := gets.Load(); got != 1 {
t.Errorf("getIssue requests = %d, want 1", got)
}
issue, err = store.GetIssue(t.Context(), "")
if issue != nil || !errors.Is(err, storage.ErrNotFound) {
t.Fatalf("GetIssue(\"\") = (%v, %v), want (nil, storage.ErrNotFound)", issue, err)
}
if got := gets.Load(); got != 1 {
t.Errorf("the empty id dialed: getIssue requests = %d, want still 1", got)
}
}

View file

@ -15,6 +15,7 @@ import (
"github.com/steveyegge/beads/internal/httpapi/apigen"
"github.com/steveyegge/beads/internal/httpclient/encode"
"github.com/steveyegge/beads/internal/httpclient/wire"
"github.com/steveyegge/beads/internal/storage"
storageops "github.com/steveyegge/beads/internal/storage/issueops"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/issueops"
@ -40,8 +41,8 @@ var _ issueops.Lifecycle = (*httpLifecycle)(nil)
// dropping: IDPrefix where it would act on an explicit, unforced id, which the
// server publishes no member for on purpose (W-CreateRequest.IDPrefix), and
// every member of the issue outside the wire's twenty (W-CreateRequest.Issue)
// — save a CreatedBy that names the actor, which the server stamps from the
// actor itself. A create that reported success having silently dropped the
// — save a CreatedBy that names the actor, which the server's create role
// defaults to on its own (issueops.PreparePublicCreateRequest). A create that reported success having silently dropped the
// storage class, the molecule type or the creation time is a row the caller
// believes they wrote and did not.
//
@ -442,6 +443,10 @@ func (l *httpLifecycle) applyTemplateGuardForServer(ctx context.Context, req iss
return req, nil
}
before, err := l.store.GetIssue(ctx, req.IssueID)
if errors.Is(err, storage.ErrNotFound) {
// GetIssue answers a miss with ErrNotFound, like the local stores.
return req, nil
}
if err != nil {
return req, err
}

View file

@ -50,7 +50,13 @@ func (e *PartialIDSearchError) Error() string {
"check the id or use a local workspace", e.Input, e.ServerURL)
}
func (e *PartialIDSearchError) Unwrap() []error { return []error{e.Unsup, ErrPartialIDSearch} }
// Unwrap also names issueops.ErrNotFound: the one thing the client does know
// is that no row has exactly this id, and a caller classifying the outcome
// (bd show's "Issue X not found", the routed-lookup fallbacks) must read it as
// a miss rather than as a backend fault (S6b).
func (e *PartialIDSearchError) Unwrap() []error {
return []error{e.Unsup, ErrPartialIDSearch, issueops.ErrNotFound}
}
func (s *Store) partialIDSearch(op, input string) error {
e := &PartialIDSearchError{Input: input, ServerURL: s.target.String()}
@ -60,6 +66,20 @@ func (s *Store) partialIDSearch(op, input string) error {
return e
}
// SearchIssueIDs is the resolver's substring id search, which has no wire
// operation: it answers D11's partial-id refusal (a not-found, see
// PartialIDSearchError.Unwrap) without dialing, rather than the generic stub's
// bare "not supported".
func (s *Store) SearchIssueIDs(_ context.Context, query string, _ types.IssueFilter) ([]string, error) {
return nil, s.partialIDSearch("SearchIssueIDs", query)
}
// ExactIDLookupOnly satisfies utils.ExactIDLookupStore: with no substring
// search on the wire, the resolver stops at its exact lookups, so a missing
// id is a not-found after one getIssue instead of a prefix-vocabulary read,
// a repeated probe and a refused search.
func (s *Store) ExactIDLookupOnly() bool { return true }
// SearchIssues serves the two shapes the v0 wire can express and refuses every
// other one.
//

View file

@ -417,9 +417,10 @@ func TestTheReadyBridgeEnforcesMaxRowsClientSide(t *testing.T) {
}
// TestTheParentExistenceProbeCrossesTheWire is the raw GetIssue the walk runs
// before it descends: a miss is (nil, nil), because getHierarchicalChildren
// reads a nil result as "parent issue not found" and an error would print the
// transport's vocabulary in its place.
// before it descends, and the explicit-id probe `bd create --graph` runs. A
// miss is storage.ErrNotFound on EVERY leg — the local reference store and the
// http store alike — so a caller written against the backend contract never
// needs a second, http-only branch for (nil, nil).
func TestTheParentExistenceProbeCrossesTheWire(t *testing.T) {
e := newServedEnv(t, "prb")
ctx := t.Context()
@ -432,8 +433,28 @@ func TestTheParentExistenceProbeCrossesTheWire(t *testing.T) {
if err != nil || got == nil || got.ID != "prb-1" {
t.Fatalf("GetIssue on a hit = (%v, %v)", got, err)
}
if got, err = e.subject.GetIssue(ctx, "prb-nope"); err != nil || got != nil {
t.Errorf("GetIssue on a miss = (%v, %v), want (nil, nil)", got, err)
legs := []struct {
name string
store interface {
GetIssue(context.Context, string) (*types.Issue, error)
}
}{
{"local", e.reference},
{"http", e.subject},
}
for _, leg := range legs {
for _, id := range []string{"prb-nope", ""} {
got, err := leg.store.GetIssue(ctx, id)
if !errors.Is(err, issueops.ErrNotFound) || got != nil {
t.Errorf("%s GetIssue(%q) on a miss = (%v, %v), want (nil, storage.ErrNotFound)", leg.name, id, got, err)
}
}
}
// The http miss reads exactly as the local one does.
_, local := e.reference.GetIssue(ctx, "prb-nope")
_, remote := e.subject.GetIssue(ctx, "prb-nope")
if local == nil || remote == nil || local.Error() != remote.Error() {
t.Errorf("miss text: local %q, http %q; want the same", local, remote)
}
}

View file

@ -27,10 +27,11 @@ import (
//
// This pins the fix at the layer design 3.6 actually gates on: the decorator
// must still apply client-side enforcement whenever the server's handshake
// does not advertise wire.CapExternalDependencies. Today's OSS httpapi never
// advertises it (confirmed below), so this also exercises the http backend's
// GetAllDependencyRecords fallback (loadBlockingState's compatibility path)
// against a real served server, end to end.
// does not advertise wire.CapExternalDependencies. This harness serves raw
// roles, not roles composed through the policy, so its httpapi truthfully
// withholds the token (confirmed below) — the shape of an older bd serve — and
// this also exercises the http backend's GetAllDependencyRecords fallback
// (loadBlockingState's compatibility path) against a real served server.
func TestServedReadyExcludesUnsatisfiedExternalDependencyWithoutServerCapability(t *testing.T) {
env := newServedEnv(t, "hixd")
ctx := t.Context()
@ -206,8 +207,9 @@ func TestServedReadyCountExcludesAnExternallyBlockedIssuePastTheDefaultPage(t *t
// them over legacy methods that store refuses, which failed `bd list`,
// `bd show`, `bd dep tree`, `bd ready --claim` and `bd close` even for an issue
// nothing blocks. And each still holds the externally blocked issue out of
// ready work, claims and closes. The served handler here binds its roles to
// the raw reference store, which knows nothing of the policy, so every
// ready work, claims and closes, while the composed claim-next takes only the
// unassigned work a local one would. The served handler here binds its roles
// to the raw reference store, which knows nothing of the policy, so every
// exclusion below is the client's.
func TestServedRolesKeepTheExternalDependencyPolicy(t *testing.T) {
env := newServedEnv(t, "hixr")
@ -304,13 +306,49 @@ func TestServedRolesKeepTheExternalDependencyPolicy(t *testing.T) {
if _, err := claimer.Claim(ctx, issueops.ClaimRequest{Actor: "worker", IssueID: blockedID}); !errors.Is(err, storage.ErrCloseBlocked) {
t.Errorf("Claim %s over http = %v, want ErrCloseBlocked", blockedID, err)
}
// Open rows already held sort ahead of the free work, one by another actor
// and one by the claimant. A local claim-next (ClaimReadyIssueInTx) takes
// neither, with or without an assignee filter, so the composed claim must
// not either. A second free issue gives the filtered claim something to
// take once freeID is gone.
rivalID, mineID, laterID := env.prefix+"-rival", env.prefix+"-mine", env.prefix+"-later"
for _, seed := range []*types.Issue{
{ID: rivalID, Title: "held by another actor", Status: types.StatusOpen, Priority: 0, IssueType: types.TypeTask, Assignee: "rival"},
{ID: mineID, Title: "held by the claimant", Status: types.StatusOpen, Priority: 0, IssueType: types.TypeTask, Assignee: "worker"},
{ID: laterID, Title: "not blocked by anything either", Status: types.StatusOpen, Priority: 3, IssueType: types.TypeTask},
} {
if err := env.createIssue(ctx, seed, "tester"); err != nil {
t.Fatalf("seed %s: %v", seed.ID, err)
}
}
readyClaimer, err := decorated.ReadyClaimer()
if err != nil {
t.Fatalf("ReadyClaimer: %v", err)
}
next, err := readyClaimer.ClaimNext(ctx, issueops.ClaimNextRequest{Actor: "worker"})
if err != nil || next.Claimed == nil || next.Claimed.ID != freeID {
t.Fatalf("ClaimNext over http = %+v, %v; want %s", next.Claimed, err, freeID)
for _, claim := range []struct {
filter issueops.ReadyRequest
want string
}{
{want: freeID},
{filter: issueops.ReadyRequest{Assignee: "worker"}, want: laterID},
} {
next, err := readyClaimer.ClaimNext(ctx, issueops.ClaimNextRequest{Actor: "worker", Filter: claim.filter})
var got string
if next.Claimed != nil && next.Claimed.Issue != nil {
got = next.Claimed.ID
}
if err != nil || got != claim.want {
t.Errorf("ClaimNext over http with assignee %q claimed %q, %v; want %s", claim.filter.Assignee, got, err, claim.want)
}
}
for id, holder := range map[string]string{rivalID: "rival", mineID: "worker"} {
issue, err := env.getIssue(ctx, id)
if err != nil || issue == nil {
t.Fatalf("read %s back: %v, %v", id, issue, err)
}
if issue.Status != types.StatusOpen || issue.Assignee != holder {
t.Errorf("after the claims %s is %s and held by %q, want open and still held by %q", id, issue.Status, issue.Assignee, holder)
}
}
closer, err := decorated.BatchCloser()

View file

@ -2,6 +2,16 @@
// to OSS beads under the MIT license.
package httpclient
import (
"context"
"fmt"
"net/http"
"github.com/steveyegge/beads/internal/httpapi/apigen"
"github.com/steveyegge/beads/internal/httpclient/wire"
"github.com/steveyegge/beads/internal/storage"
)
// ServerContext reports the three facts design D7's refusal taxonomy needs to
// name the server: the URL it speaks to, the release it is running, and the
// capability tokens it advertises.
@ -27,3 +37,34 @@ func (s *Store) ServerContext() (serverURL, bdVersion string, capabilities []str
}
return serverURL, snap.BdVersion, append([]string(nil), snap.Capabilities...)
}
// Ping satisfies storage.Pinger: one authenticated round trip to the server.
//
// The first call in a process IS the handshake (identity-checked against the
// workspace's pin, and cached for every later dispatch). Once a handshake is
// cached, a later Ping re-reads the context uncached, so it never reports a
// live server from a stale answer.
func (s *Store) Ping(ctx context.Context) error {
if s == nil || s.wire == nil {
return fmt.Errorf("http backend: no transport to ping")
}
if s.cachedSnapshot() == nil {
_, err := s.snapshot(ctx)
return err
}
var out apigen.ContextResponse
return s.wire.Do(ctx, wire.Request{Op: wire.OpGetContext, Method: http.MethodGet, Path: wire.PathContext}, &out)
}
var _ storage.Pinger = (*Store)(nil)
// CallerAttributionLimited satisfies storage.CallerAttributionLimitedStore:
// the v0 wire publishes no provenance member on updateIssue or reopenIssue
// (the server writes its own history label) and no closed_by_session member
// on either patch document (W-UpdateRequest.Provenance,
// W-ReopenRequest.Provenance, W-IssuePatch.ClosedBySession). It is
// unconditional because the gap is in the wire shape; a wire revision that
// publishes either member would turn this into a handshake capability check.
func (s *Store) CallerAttributionLimited() bool { return true }
var _ storage.CallerAttributionLimitedStore = (*Store)(nil)

View file

@ -75,13 +75,11 @@ type Store struct {
// interfaces here would assert a maintenance contract no OSS caller checks.
var _ storage.DoltStorage = (*Store)(nil)
// IsRemoteBackendStore satisfies storage.RemoteBackendStore. cmd/bd's storage
// chain wraps this store in the external-dependency policy decorator like any
// other. The decorator reads this marker only to build its roles on this
// store's served roles rather than on the legacy methods it refuses
// (internal/storage/externaldeps/remote_roles.go). It decides whether to stand
// down through ServerEnforcesExternalDependencyPolicy below, never through
// this marker.
// IsRemoteBackendStore satisfies storage.RemoteBackendStore. The
// external-dependency policy decorator reads it to compose its role views over
// this store's own roles (its legacy method seam is mostly stubs); it decides
// whether to stand down through ServerEnforcesExternalDependencyPolicy below,
// never through this marker.
func (s *Store) IsRemoteBackendStore() bool { return true }
var _ storage.RemoteBackendStore = (*Store)(nil)

View file

@ -637,11 +637,6 @@ func (unsupportedDoltStorage) RunInTransaction(_ context.Context, _ string, _ fu
return
}
func (unsupportedDoltStorage) SearchIssueIDs(_ context.Context, _ string, _ types.IssueFilter) (_ []string, err error) {
err = errUnsupported("SearchIssueIDs")
return
}
func (unsupportedDoltStorage) SearchIssueSummaries(_ context.Context, _ string, _ types.IssueFilter) (_ []*types.IssueSummary, err error) {
err = errUnsupported("SearchIssueSummaries")
return
@ -737,4 +732,4 @@ func (unsupportedDoltStorage) VersionReconciler() (_ issueops.VersionReconciler,
return
}
// NOTE: partial shell (144 of 200 methods generated; 56 left to this package's hand-written set).
// NOTE: partial shell (143 of 200 methods generated; 57 left to this package's hand-written set).

View file

@ -237,18 +237,18 @@ const CapIssuesCreateDefaultPriority = "issues.create.defaultPriority"
//
// It is not in behaviorCapabilities because it is not a property of the build:
// httpapi advertises it only when the serving process composed its roles
// through the policy layer, so httpapi.Capabilities() — the build-level list
// the parity gate compares against — never contains it.
// through the policy layer (httpapi.Config.ExternalDependencyPolicy, which
// `bd serve` sets from its actual composition), so httpapi.Capabilities() —
// the build-level list the parity gate compares against — never contains it.
//
// Consumed since S6 (design 3.6): the externaldeps decorator
// (internal/storage/externaldeps) wraps the http store the same as any local
// backend (cmd/bd/storage_chain.go wires it unconditionally), and consults
// The externaldeps decorator (internal/storage/externaldeps) wraps the http
// store the same as any local backend (cmd/bd/storage_chain.go), and consults
// storage.ExternalDependencyPolicyProber — which httpclient.Store implements
// by checking for this token in the handshake — before deciding whether to
// also enforce the policy client-side. A server that advertises this token
// has already applied the policy itself, so the decorator's own check is
// redundant there. A server that does NOT advertise it gets the ordinary
// client-side enforcement: the policy is never silently skipped merely
// by checking for this token in the handshake. Against a server that
// advertises it, every policy-bearing role is the http store's own, passed
// through untouched (claim-next stays the server's atomic operation). Only a
// server that does NOT advertise it — an older bd serve, or another server —
// gets client-side enforcement: the policy is never silently skipped merely
// because the store is remote.
const CapExternalDependencies = "policy.external_dependencies"

View file

@ -141,6 +141,9 @@ func TestTheProjectIdentityVocabularyMatchesTheServer(t *testing.T) {
if CapProjectEnforce != httpapi.CapProjectEnforce {
t.Errorf("CapProjectEnforce = %q, server says %q", CapProjectEnforce, httpapi.CapProjectEnforce)
}
if CapExternalDependencies != httpapi.CapExternalDependencies {
t.Errorf("CapExternalDependencies = %q, server says %q", CapExternalDependencies, httpapi.CapExternalDependencies)
}
if CapListSort != httpapi.CapIssuesListSort {
t.Errorf("CapListSort = %q, server says %q", CapListSort, httpapi.CapIssuesListSort)
}

View file

@ -89,7 +89,11 @@ func largeScenarios() []scenario {
// recorded from the code BEFORE the batch-create fast paths existed
// (ebe3b6bcb), so the check holds the current code — fast and per-row
// bodies alike, including changes the fast-path switch does not gate — to
// what that code stored.
// what that code stored. One deliberate behavior change since: the create
// role defaults an empty created_by to the request's actor
// (issueops.PreparePublicCreateRequest), so apply.json's issues, wisps and
// events digests were re-recorded with every apply-created row carrying
// created_by "apply-writer"; nothing else moved.
const GoldenDirEnv = "CREATEBATCHEQUIV_GOLDEN_DIR"
// Run seeds fresh databases, applies each scenario's batch through the fast

View file

@ -18,7 +18,7 @@
},
"events": {
"rows": 41,
"sha256": "6738a7e74b5164d19d450390efbeaee6471136b69dcf2a560c5f418c00545e6d"
"sha256": "a71a76f0f3defdc3dd0d3b09b0ed4389e347ccc22627b920eabff6a96aedda35"
},
"events_ids": {
"rows": 1,
@ -30,7 +30,7 @@
},
"issues": {
"rows": 15,
"sha256": "4715873ec097361b74eef201b3411b1fd13f55e5c039be17e5bc636d39dd3412"
"sha256": "e7a2327078561be42b4fdde38f49a24a68a0048fd95c5e780c750b2c9eb8a4de"
},
"issues_updated_at": {
"rows": 4,
@ -54,7 +54,7 @@
},
"wisps": {
"rows": 1,
"sha256": "d0f049baac21bd46b8cc71703d63921387cf94e236cbd235eb384794d484df13"
"sha256": "8a16dda5af1f107f9584b37bbcc0ed4556383e78821378dd75b1b1b47bd50311"
}
},
"skipped": [

View file

@ -29,13 +29,16 @@ go_library(
go_test(
name = "externaldeps_test",
srcs = [
"advertise_test.go",
"decorator_test.go",
"ready_wake_test.go",
"remote_roles_composition_test.go",
"remote_roles_test.go",
"uow_decorator_test.go",
],
embed = [":externaldeps"],
deps = [
"//internal/httpapi",
"//internal/storage",
"//internal/storage/domain",
"//internal/storage/issueops",

View file

@ -0,0 +1,82 @@
package externaldeps
import (
"bytes"
"context"
"encoding/json"
"net/http"
"slices"
"testing"
"time"
"github.com/steveyegge/beads/internal/httpapi"
"github.com/steveyegge/beads/internal/storage/uow"
)
// TestPolicyLayerIsAdvertisedOnTheHandshake closes the loop between this
// package and the server's handshake, the composition `bd serve` performs
// (cmd/bd/serve.go): the policy layer found by AppliedToProvider becomes
// httpapi.Config.ExternalDependencyPolicy, and the handshake must then publish
// httpapi.CapExternalDependencies. A client reads that token to stand its own
// policy down (remote_roles.go), so a server composed through the policy that
// never says so makes every client apply the policy a second time, with the
// CLIENT machine's project config; one that says so without the layer makes
// every client skip it.
func TestPolicyLayerIsAdvertisedOnTheHandshake(t *testing.T) {
plain := &fakeUOWProvider{}
for _, tc := range []struct {
name string
provider uow.UnitOfWorkProvider
advertise bool
}{
{"composed through the policy", WrapUOWProvider(plain, nil, nil), true},
{"raw provider", plain, false},
} {
t.Run(tc.name, func(t *testing.T) {
caps := handshakeCapabilities(t, httpapi.Config{
Provider: tc.provider,
ExternalDependencyPolicy: AppliedToProvider(tc.provider),
})
if got := slices.Contains(caps, httpapi.CapExternalDependencies); got != tc.advertise {
t.Fatalf("handshake advertises %s = %v, want %v: %v", httpapi.CapExternalDependencies, got, tc.advertise, caps)
}
})
}
}
func handshakeCapabilities(t *testing.T, cfg httpapi.Config) []string {
t.Helper()
cfg.Addr = "127.0.0.1:0"
cfg.Stdout, cfg.Stderr = &bytes.Buffer{}, &bytes.Buffer{}
srv, err := httpapi.Listen(cfg)
if err != nil {
t.Fatalf("Listen: %v", err)
}
ctx, cancel := context.WithCancel(context.Background())
done := make(chan error, 1)
go func() { done <- srv.Serve(ctx) }()
t.Cleanup(func() {
cancel()
select {
case <-done:
case <-time.After(30 * time.Second):
t.Error("Serve did not return after shutdown")
}
})
client := &http.Client{Timeout: 20 * time.Second}
resp, err := client.Get("http://" + srv.Addr() + "/v0/beads/context")
if err != nil {
t.Fatalf("GET /v0/beads/context: %v", err)
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusOK {
t.Fatalf("GET /v0/beads/context: status %d", resp.StatusCode)
}
var body struct {
Capabilities []string `json:"capabilities"`
}
if err := json.NewDecoder(resp.Body).Decode(&body); err != nil {
t.Fatalf("decode the handshake: %v", err)
}
return body.Capabilities
}

View file

@ -10,11 +10,15 @@ import (
)
// BatchCloser preserves external policy on bd close, including its next claim.
// Over a store that serves its roles, remoteBatchCloser refuses the next claim
// instead.
// Over a remote store, remoteBatchCloser refuses the next claim unless the
// server applies the policy itself.
func (s *Store) BatchCloser() (issueops.BatchCloser, error) {
if s.servesRoles() {
return &remoteBatchCloser{policy: s}, nil
if s.rolesAreRemote() {
inner, err := s.inner.BatchCloser()
if err != nil {
return nil, err
}
return &remoteBatchCloser{inner: inner, policy: s}, nil
}
return &batchCloser{policy: s}, nil
}
@ -31,20 +35,31 @@ func (c *batchCloser) CloseBatch(ctx context.Context, request issueops.CloseBatc
}
}
var policy storage.BatchClosePolicy
if !request.Force || request.ClaimNext != nil {
switch {
case request.ClaimNext != nil:
// The claim-after-close picks among every ready issue, so it needs the
// workspace-wide blocker set.
state, err := c.policy.loadBlockingState(ctx)
if err != nil {
return issueops.CloseBatchResult{}, err
}
blockers := state.refsByIssue
if request.ClaimNext == nil {
// Only a claim reads blockers beyond the batch. Scoping the rest
// keeps an unrelated blocked issue from demanding policy support
// of a backend that lacks it.
blockers = make(map[string][]string, len(request.Items))
for _, item := range request.Items {
blockers[item.IssueID] = state.refsByIssue[item.IssueID]
}
policy = storage.NewBatchClosePolicy(state.refsByIssue)
case !request.Force:
// Only a claim reads blockers beyond the batch. Scoping the rest
// keeps an unrelated blocked issue from demanding policy support
// of a backend that lacks it — and on a remote store reads only the
// batch's own edges rather than every edge in the workspace.
ids := make([]string, 0, len(request.Items))
for _, item := range request.Items {
ids = append(ids, item.IssueID)
}
refs, err := c.policy.externalBlockersFor(ctx, ids)
if err != nil {
return issueops.CloseBatchResult{}, err
}
blockers := make(map[string][]string, len(request.Items))
for _, item := range request.Items {
blockers[item.IssueID] = refs[item.IssueID]
}
policy = storage.NewBatchClosePolicy(blockers)
}

View file

@ -41,6 +41,24 @@ func New(inner storage.DoltStorage, locateProject ProjectLocator, openProject St
// Unwrap exposes the decorated store to storage.UnwrapStore.
func (s *Store) Unwrap() storage.DoltStorage { return s.inner }
// Applied reports whether store's decorator chain includes this policy layer,
// so the roles it hands out apply the external-dependency policy. bd serve
// reads it to decide whether its handshake may advertise
// policy.external_dependencies (httpapi.Config.ExternalDependencyPolicy).
func Applied(store storage.DoltStorage) bool {
for store != nil {
if _, ok := store.(*Store); ok {
return true
}
u, ok := store.(storage.Unwrapper)
if !ok {
return false
}
store = u.Unwrap()
}
return false
}
// IssueLifecycle preserves the external close policy for public lifecycle
// operations. Returning the inner lifecycle directly would promote around the
// decorator when bd close or bd update uses the lifecycle seam.
@ -92,11 +110,13 @@ func (s *Store) guardExternalClose(ctx context.Context, id string, force bool) e
if force {
return nil
}
state, err := s.loadBlockingState(ctx)
// externalBlockersFor reads only this issue's edges on a remote store
// rather than every edge in the workspace.
refs, err := s.externalBlockersFor(ctx, []string{id})
if err != nil {
return err
}
if blockers := state.refsByIssue[id]; len(blockers) > 0 {
if blockers := refs[id]; len(blockers) > 0 {
return publicops.NewCloseBlockedError(id, blockers)
}
return nil
@ -470,13 +490,24 @@ func (s *Store) CountReadyWork(ctx context.Context, filter types.WorkFilter) (in
// telemetry.InstrumentedStorage.WrapReadyCounter exists for, and why the
// documented storage.ReadyCounter.CountReady span still appears for text-mode
// `bd ready` in the cmd/bd chain (hooks -> externaldeps -> telemetry -> store).
//
// A remote store answers with its own counter (the server's count operation)
// whenever its server applies the policy itself; remoteReadyCounter decides
// per call, since the handshake is read lazily.
func (s *Store) ReadyCounter() (publicops.ReadyCounter, error) {
counter, err := storereadycounter.New(s)
if err != nil {
return nil, err
}
if wrapper, ok := s.inner.(readyCounterWrapper); ok {
return wrapper.WrapReadyCounter(counter), nil
counter = wrapper.WrapReadyCounter(counter)
}
if s.rolesAreRemote() {
inner, err := s.inner.ReadyCounter()
if err != nil {
return nil, err
}
return &remoteReadyCounter{inner: inner, fallback: counter, policy: s}, nil
}
return counter, nil
}

View file

@ -374,7 +374,7 @@ func TestGetReadyWorkFailsClosedForUnconfiguredProject(t *testing.T) {
// mutation coverage. Nothing else in the suite exercises enforced==true: see
// internal/httpclient/served_external_dependency_policy_test.go, which
// documents exercising only enforced==false against a real served server
// (OSS httpapi never advertises the capability).
// (its harness serves raw roles, so it withholds the capability).
//
// configured=false on the foreign-project locator reproduces the fail-closed
// path from TestGetReadyWorkFailsClosedForUnconfiguredProject: if the

View file

@ -9,42 +9,98 @@ import (
storageissueops "github.com/steveyegge/beads/internal/storage/issueops"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/internal/workapi"
"github.com/steveyegge/beads/internal/workapi/storereader"
"github.com/steveyegge/beads/issueops"
)
// Remote role composition.
// THE REMOTE COMPOSITION.
//
// The base accessors (role_accessors.go, batch_closer.go) rebuild each role
// over this store's legacy methods, which a SQL store implements in full. A
// remote store does not: httpclient.Store serves its roles over the wire and
// refuses most of the legacy methods those builds call (SearchIssuesWithCounts,
// IsBlocked, GetDependencyRecordsForIssues, GetDependencyTree,
// ClaimReadyIssue, BatchCloserWithPolicy), so the base accessors would fail
// `bd list`, `bd dep tree`, `bd ready --claim` and a policed close even in a
// workspace with no external dependency at all. Over such a store each
// accessor starts from the inner store's own role instead and layers the
// policy around it, before or after the served call.
// A remote backend (storage.RemoteBackendStore: today the HTTP client of a
// `bd serve`) serves its ROLES natively and only a slice of the legacy
// storage.DoltStorage method seam. The local role views in role_accessors.go
// are built from that seam — storereader over this decorator, IsBlocked,
// GetDependencyTree, ClaimReadyIssue — so over a remote store they reached the
// generated ErrUnsupported stubs: `bd list` and `bd children` refused
// (SearchIssuesWithCounts), `bd show --json` hydrated its counts from stubbed
// reads and printed zeros, and the default `bd dep tree` refused
// (GetDependencyTree).
//
// storage.RemoteBackendStore chooses that composition and nothing else.
// Whether the policy runs is still serverEnforcesPolicy's question (design
// 3.6), asked on every path that loads blocking state.
// So for a remote store each role view is the INNER store's own role, passed
// through, with this decorator's external-dependency policy laid over it in
// role terms. The policy itself is unchanged and is never skipped merely
// because the store is remote (design 3.6):
//
// - a server that advertises wire.CapExternalDependencies (every bd serve
// that composes the policy, which is every bd serve) has applied it
// already, so every view below first asks serverEnforcesPolicy and then
// hands the request to the inner role UNTOUCHED: no client validation, no
// edge reads, and claim-next stays the server's atomic operation;
// - only against a server that does not advertise it (an older bd serve, or
// another implementation) does the policy run here, client-side. Ready reads and the
// ready claim exclude externally blocked sources, which needs the
// workspace-wide blocker set (loadBlockingState). Every per-issue question
// — may this issue be claimed or closed, what blocks these listed rows,
// which external leaves hang off this tree — reads only the edges of the
// issues it names, through the inner EdgeReader, instead of walking every
// edge in the workspace.
// servesRoles reports whether the inner store serves its roles rather than
// building them over its legacy methods.
func (s *Store) servesRoles() bool {
// maxRemoteEdgeAnchors is how many anchors one EdgeReader read names. It is
// the server's own per-request anchor bound (internal/httpapi's
// maxDependencyAnchors); the http client refuses past it rather than chunking.
const maxRemoteEdgeAnchors = 100
// rolesAreRemote reports whether the inner store is a remote backend whose
// roles, not its legacy method seam, are the surface to compose over.
func (s *Store) rolesAreRemote() bool {
remote, ok := storage.UnwrapStore(s.inner).(storage.RemoteBackendStore)
return ok && remote.IsRemoteBackendStore()
}
// servedEdgeAnchors is the most anchors one served edge read names: the wire
// caps listDependencies' issue_id at 100 items, and the client passes a
// request through without chunking it.
const servedEdgeAnchors = 100
// externalBlockersFor answers, for exactly the named issues, which unsatisfied
// external references block each of them. An issue with none is absent from
// the map.
//
// A remote store reads only those issues' edges (one EdgeReader request per
// maxRemoteEdgeAnchors ids); a local store keeps the indexed workspace-wide
// read loadBlockingState already makes, which is cheaper there than a
// per-issue one.
func (s *Store) externalBlockersFor(ctx context.Context, ids []string) (map[string][]string, error) {
if len(ids) == 0 {
return nil, nil
}
if !s.rolesAreRemote() {
state, err := s.loadBlockingState(ctx)
if err != nil {
return nil, err
}
out := make(map[string][]string, len(ids))
for _, id := range ids {
if refs := state.refsByIssue[id]; len(refs) > 0 {
out[id] = refs
}
}
return out, nil
}
enforced, err := s.serverEnforcesPolicy(ctx)
if err != nil || enforced {
return nil, err
}
deps, err := s.remoteEdges(ctx, ids)
if err != nil {
return nil, fmt.Errorf("external dependencies: read blocking edges: %w", err)
}
state, err := s.blockingStateFromRecords(ctx, deps)
if err != nil {
return nil, err
}
return state.refsByIssue, nil
}
// servedEdges reads the stored outgoing edges of ids through the inner store's
// EdgeReader, the served stand-in for GetDependencyRecordsForIssues. A missing
// anchor contributes no edges.
func (s *Store) servedEdges(ctx context.Context, ids []string) (map[string][]*types.Dependency, error) {
// remoteEdges reads the stored outgoing edges of ids through the inner
// EdgeReader, keyed by source id. Each id is named once, and an empty one not
// at all: the http EdgeReader refuses an empty anchor, which would answer a
// batch close's own validation question with an edge-read error.
func (s *Store) remoteEdges(ctx context.Context, ids []string) (map[string][]*types.Dependency, error) {
anchors := make([]string, 0, len(ids))
named := make(map[string]bool, len(ids))
for _, id := range ids {
@ -61,37 +117,257 @@ func (s *Store) servedEdges(ctx context.Context, ids []string) (map[string][]*ty
if err != nil {
return nil, err
}
for start := 0; start < len(anchors); start += servedEdgeAnchors {
end := min(start+servedEdgeAnchors, len(anchors))
result, err := reader.ReadEdges(ctx, issueops.EdgeReadRequest{IDs: anchors[start:end]})
for start := 0; start < len(anchors); start += maxRemoteEdgeAnchors {
end := min(start+maxRemoteEdgeAnchors, len(anchors))
res, err := reader.ReadEdges(ctx, issueops.EdgeReadRequest{IDs: anchors[start:end]})
if err != nil {
return nil, err
}
for _, anchor := range result.Anchors {
deps[anchor.ID] = append(deps[anchor.ID], anchor.Edges...)
for _, anchor := range res.Anchors {
if len(anchor.Edges) > 0 {
deps[anchor.ID] = append(deps[anchor.ID], anchor.Edges...)
}
}
}
return deps, nil
}
// blockingStateFor is loadBlockingState narrowed to ids, for a role that names
// its issues and so needs only their edges.
func (s *Store) blockingStateFor(ctx context.Context, ids []string) (blockingState, error) {
if enforced, err := s.serverEnforcesPolicy(ctx); err != nil || enforced {
return blockingState{}, err
}
deps, err := s.servedEdges(ctx, ids)
// externallyBlockedIDs is the workspace-wide set of issues an unsatisfied
// external reference blocks — what a ready read has to exclude. Empty when the
// server already enforces the policy (loadBlockingState's own probe).
func (s *Store) externallyBlockedIDs(ctx context.Context) (map[string]bool, error) {
state, err := s.loadBlockingState(ctx)
if err != nil {
return blockingState{}, fmt.Errorf("external dependencies: list blocking records: %w", err)
return nil, err
}
return s.blockingStateFromRecords(ctx, deps)
if len(state.refsByIssue) == 0 {
return nil, nil
}
blocked := make(map[string]bool, len(state.refsByIssue))
for id := range state.refsByIssue {
blocked[id] = true
}
return blocked, nil
}
// plainDownTree reports whether req is the walk the policy decorates. Reverse
// walks do not follow a source's dependencies, and the status- or row-bounded
// variants keep the backend's own traversal semantics.
func plainDownTree(req issueops.WalkTreeRequest) bool {
return (req.Direction == "" || req.Direction == issueops.TreeDown) && req.Status == "" && req.MaxRows == 0
// ── Reader ──────────────────────────────────────────────────────────
type remoteReader struct {
inner issueops.Reader
policy *Store
}
// Get is the inner detail read: the policy decides no detail field, and the
// server's view carries the dependency and comment counts the legacy seam
// could not hydrate.
func (r *remoteReader) Get(ctx context.Context, req issueops.GetRequest) (*issueops.IssueDetails, error) {
return r.inner.Get(ctx, req)
}
// List passes an ordinary listing straight through. A ready listing
// (ReadyFlag, `bd list --ready`) is the ready question, which a remote
// listing cannot carry (httpclient ledger row E-ListRequest.ReadyFlag: over
// the wire it is listReadyWork, a different operation). The policy store's
// own reader answers it through the ready reads, which the remote store
// serves and the policy filters, so it is the same answer the CLI gets
// locally; against a server that applies the policy those reads stand down.
func (r *remoteReader) List(ctx context.Context, req issueops.ListRequest) (issueops.IssuePage, error) {
if !req.ReadyFlag {
return r.inner.List(ctx, req)
}
ready, err := storereader.New(r.policy)
if err != nil {
return issueops.IssuePage{}, err
}
return ready.List(ctx, req)
}
// Ready excludes externally blocked sources.
//
// No remote ready read can carry an id exclusion (L12), so the exclusion is
// applied to a widened window instead: from offset 0, Offset+Limit plus one
// row per blocked id. At most that many rows of the window can be dropped,
// so the caller's page is exact whenever enough unblocked rows exist.
func (r *remoteReader) Ready(ctx context.Context, req issueops.ReadyRequest) (issueops.IssuePage, error) {
blocked, err := r.policy.externallyBlockedIDs(ctx)
if err != nil {
return issueops.IssuePage{}, err
}
if len(blocked) == 0 {
return r.inner.Ready(ctx, req)
}
limit := workapi.LimitOr(req.Limit, workapi.DefaultReadyLimit)
widened := req
widened.Offset = 0
widened.Limit = widenedLimit(req.Offset, limit, len(blocked))
page, err := r.inner.Ready(ctx, widened)
if err != nil {
return issueops.IssuePage{}, err
}
return excludeAndPage(page, blocked, req.Offset, limit), nil
}
// widenedLimit is the window a client-side exclusion reads: 0 (unlimited)
// stays unlimited.
func widenedLimit(offset, limit, blocked int) *int {
n := 0
if limit > 0 {
n = offset + limit + blocked
}
return &n
}
// excludeAndPage drops the blocked rows from a widened window, then cuts the
// caller's page out of what remains. HasMore is true when unblocked rows are
// left past the page, or when the window itself was cut short by the server —
// beyond it the rows are unread, so "no more" cannot be claimed.
func excludeAndPage(page issueops.IssuePage, blocked map[string]bool, offset, limit int) issueops.IssuePage {
kept := make([]*issueops.IssueWithCounts, 0, len(page.Items))
for _, row := range page.Items {
if row != nil && row.Issue != nil && blocked[row.ID] {
continue
}
kept = append(kept, row)
}
if offset >= len(kept) {
return issueops.IssuePage{Items: []*issueops.IssueWithCounts{}, HasMore: page.HasMore}
}
kept = kept[offset:]
hasMore := page.HasMore
if limit > 0 && len(kept) > limit {
kept = kept[:limit]
hasMore = true
}
return issueops.IssuePage{Items: kept, HasMore: hasMore}
}
// ── Claimer ─────────────────────────────────────────────────────────
type remoteClaimer struct {
inner issueops.Claimer
policy *Store
}
// Claim refuses a direct claim of externally blocked work before the server's
// atomic claim. Local blocking edges are the server's claim to judge. Against
// a server that applies the policy, externalBlockersFor reads nothing and the
// claim goes through untouched.
func (c *remoteClaimer) Claim(ctx context.Context, req issueops.ClaimRequest) (issueops.ClaimResult, error) {
blockers, err := c.policy.externalBlockersFor(ctx, []string{req.IssueID})
if err != nil {
return issueops.ClaimResult{}, err
}
if refs := blockers[req.IssueID]; len(refs) > 0 {
return issueops.ClaimResult{}, fmt.Errorf("%w: %s is blocked by %v", storage.ErrCloseBlocked, req.IssueID, refs)
}
return c.inner.Claim(ctx, req)
}
// ── ReadyClaimer ────────────────────────────────────────────────────
// remoteClaimPage is how many externally unblocked candidates one pass of
// remoteReadyClaimer reads, matching httpclient's composed ready claim.
const remoteClaimPage = 25
type remoteReadyClaimer struct {
inner issueops.ReadyClaimer
policy *Store
}
// ClaimNext is the server's atomic claim-next, untouched, against a server
// that applies the policy itself, and against any server while nothing is
// externally blocked. Only an older server with externally blocked work
// cannot be told what to skip, so there the choice is made here, among the
// candidates a local claim-next selects (ClaimReadyIssueInTx): read the open,
// unassigned ready rows in the requested order, skip the blocked ones, and
// claim each remaining candidate by id until one is won. A candidate another
// actor took in between is a lost race and the next one is tried. A full
// window lost end to end is read once more: claimed rows leave the unassigned
// set, so the second pass reads the candidates behind them. Only a claim that
// tried candidates and won none is an error.
func (c *remoteReadyClaimer) ClaimNext(ctx context.Context, req issueops.ClaimNextRequest) (issueops.ClaimNextResult, error) {
// externallyBlockedIDs is empty against a server that applies the policy
// (loadBlockingState's probe), so that server's atomic claim answers.
blocked, err := c.policy.externallyBlockedIDs(ctx)
if err != nil {
return issueops.ClaimNextResult{}, err
}
if len(blocked) == 0 {
return c.inner.ClaimNext(ctx, req)
}
if err := storageissueops.ValidateClaimNextRequest(req); err != nil {
return issueops.ClaimNextResult{}, err
}
reader, err := c.policy.inner.IssueReader()
if err != nil {
return issueops.ClaimNextResult{}, err
}
claimer, err := c.policy.inner.IssueClaimer()
if err != nil {
return issueops.ClaimNextResult{}, err
}
// Unassigned whatever assignee the request names, as locally: a row
// another actor holds is never a candidate. Each window holds
// remoteClaimPage candidates past the blocked rows it may also hold.
filter := req.Filter
filter.Unassigned = true
filter.Assignee = ""
filter.Offset = 0
window := remoteClaimPage + len(blocked)
filter.Limit = &window
lost := 0
for range 2 {
page, err := reader.Ready(ctx, filter)
if err != nil {
return issueops.ClaimNextResult{}, err
}
claimed, tried, err := claimFirstCandidate(ctx, claimer, req.Actor, page.Items, blocked)
if err != nil {
return issueops.ClaimNextResult{}, err
}
if claimed != nil {
return issueops.ClaimNextResult{Claimed: claimed}, nil
}
if tried == 0 {
// Nothing unblocked is left to take, whatever an earlier pass lost.
return issueops.ClaimNextResult{}, nil
}
lost += tried
if len(page.Items) < window {
// A short window is the whole front: reading it again would only
// re-read the rows that just refused.
break
}
}
// There was work, and every candidate went to another actor first: an
// empty answer would say there is no work.
return issueops.ClaimNextResult{}, fmt.Errorf("claim ready: lost %d races for externally unblocked ready work; re-run to take the next one", lost)
}
// claimFirstCandidate claims, by id and in order, the first row that is not
// externally blocked and that no other actor takes first. tried counts the
// candidates it attempted, so with nothing claimed it is the races lost.
func claimFirstCandidate(ctx context.Context, claimer issueops.Claimer, actor string, rows []*issueops.IssueWithCounts, blocked map[string]bool) (*issueops.IssueWithCounts, int, error) {
tried := 0
for _, row := range rows {
if row == nil || row.Issue == nil || blocked[row.ID] {
continue
}
tried++
res, err := claimer.Claim(ctx, issueops.ClaimRequest{Actor: actor, IssueID: row.ID})
if isLostClaimRace(err) {
continue
}
if err != nil {
return nil, tried, err
}
claimed := *row
if res.Issue != nil {
claimed.Issue = res.Issue
}
return &claimed, tried, nil
}
return nil, tried, nil
}
// isLostClaimRace classifies the refusals that mean someone else took a
@ -104,186 +380,96 @@ func isLostClaimRace(err error) bool {
errors.Is(err, issueops.ErrNotFound)
}
// remoteReader serves List and Get from the inner store's reader: this store
// overrides no search or detail method, so neither loses any policy. Ready and
// a ready-flagged List go through the policy reader, whose ready listing drops
// externally blocked work.
type remoteReader struct {
served issueops.Reader
policy issueops.Reader
// ── ReadyCounter ────────────────────────────────────────────────────
type remoteReadyCounter struct {
inner issueops.ReadyCounter
fallback issueops.ReadyCounter
policy *Store
}
func (r *remoteReader) Ready(ctx context.Context, req issueops.ReadyRequest) (issueops.IssuePage, error) {
return r.policy.Ready(ctx, req)
}
func (r *remoteReader) List(ctx context.Context, req issueops.ListRequest) (issueops.IssuePage, error) {
if req.ReadyFlag {
return r.policy.List(ctx, req)
}
return r.served.List(ctx, req)
}
func (r *remoteReader) Get(ctx context.Context, req issueops.GetRequest) (*issueops.IssueDetails, error) {
return r.served.Get(ctx, req)
}
// remoteClaimer refuses an externally blocked claim before the served one.
// Local blockers are the served claim's own answer: IsBlocked is a refused
// legacy method on a remote store, and the server checks its own graph.
type remoteClaimer struct {
served issueops.Claimer
policy *Store
}
func (c *remoteClaimer) Claim(ctx context.Context, req issueops.ClaimRequest) (issueops.ClaimResult, error) {
state, err := c.policy.blockingStateFor(ctx, []string{req.IssueID})
// CountReady is the server's count when the server applies the policy. Against
// any other server it is the decorator's externally filtered count.
func (c *remoteReadyCounter) CountReady(ctx context.Context, req issueops.ReadyRequest) (issueops.ReadyCountResult, error) {
enforced, err := c.policy.serverEnforcesPolicy(ctx)
if err != nil {
return issueops.ClaimResult{}, err
return issueops.ReadyCountResult{}, err
}
if refs := state.refsByIssue[req.IssueID]; len(refs) > 0 {
return issueops.ClaimResult{}, fmt.Errorf("%w: %s is blocked by %v", storage.ErrCloseBlocked, req.IssueID, refs)
if enforced {
return c.inner.CountReady(ctx, req)
}
return c.served.Claim(ctx, req)
return c.fallback.CountReady(ctx, req)
}
// remoteClaimPage is how many externally unblocked candidates one pass of
// remoteReadyClaimer reads, matching httpclient's composed ready claim.
const remoteClaimPage = 25
// ── BlockingAnnotator ───────────────────────────────────────────────
// remoteReadyClaimer hands the claim to the served ReadyClaimer when no issue
// in the workspace holds an unsatisfied external ref. Otherwise the served
// claim cannot be told what to skip — the wire's claim-next has no exclusion
// parameter — so it reads the policy's filtered ready page and claims down it
// through the served Claimer, as httpclient's own composition does for an
// older server. The same window applies: a row that gains a blocker between
// the listing and its claim can still be claimed.
//
// A closed holder counts too, as it does in every backend's blocking state.
// It can never be a candidate, so the composed claim takes the same issue the
// served one would. Leaving it out would cost a status read per holder, since
// the wire has no batch form of one.
type remoteReadyClaimer struct{ policy *Store }
func (c *remoteReadyClaimer) ClaimNext(ctx context.Context, req issueops.ClaimNextRequest) (issueops.ClaimNextResult, error) {
if err := storageissueops.ValidateClaimNextRequest(req); err != nil {
return issueops.ClaimNextResult{}, err
}
filter, err := workapi.BuildReadyFilter(req.Filter)
if err != nil {
return issueops.ClaimNextResult{}, err
}
state, err := c.policy.loadBlockingState(ctx)
if err != nil {
return issueops.ClaimNextResult{}, err
}
if len(state.refsByIssue) == 0 {
served, err := c.policy.inner.ReadyClaimer()
if err != nil {
return issueops.ClaimNextResult{}, err
}
return served.ClaimNext(ctx, req)
}
claimer, err := c.policy.inner.IssueClaimer()
if err != nil {
return issueops.ClaimNextResult{}, err
}
// The candidates a local claim-next selects (ClaimReadyIssueInTx): open,
// unassigned, with no row cap on a scan that delivers one row.
filter.Status = types.StatusOpen
filter.Unassigned = true
filter.Assignee = nil
filter.MaxRows = 0
filter.MaxRowsSource = ""
filter.Limit = remoteClaimPage
// A second pass only after a full page was lost: claimed rows leave the
// unassigned set, so it reads the candidates behind them.
var lost int
for range 2 {
rows, err := c.policy.readyWorkWithCounts(ctx, filter, state)
if err != nil {
return issueops.ClaimNextResult{}, err
}
if len(rows) == 0 {
return issueops.ClaimNextResult{}, nil
}
for _, row := range rows {
if row == nil || row.Issue == nil {
continue
}
res, err := claimer.Claim(ctx, issueops.ClaimRequest{Actor: req.Actor, IssueID: row.ID})
switch {
case err == nil:
return issueops.ClaimNextResult{Claimed: &types.IssueWithCounts{
Issue: res.Issue,
DependencyCount: row.DependencyCount,
DependentCount: row.DependentCount,
CommentCount: row.CommentCount,
Parent: row.Parent,
}}, nil
case isLostClaimRace(err):
lost++
default:
return issueops.ClaimNextResult{}, err
}
}
if len(rows) < remoteClaimPage {
break
}
}
return issueops.ClaimNextResult{}, fmt.Errorf("claim ready: lost %d races for externally unblocked ready work; re-run to take the next one", lost)
}
// remoteBlockingAnnotator merges the external blockers the policy resolves
// into the served annotation's BlockedBy.
type remoteBlockingAnnotator struct {
served issueops.BlockingAnnotator
inner issueops.BlockingAnnotator
policy *Store
}
// AnnotateBlocking adds each listed row's unsatisfied external blockers to the
// server's derived answer, reading the edges of those rows only. A server that
// applies the policy has already added them, and its answer is returned as is.
func (a *remoteBlockingAnnotator) AnnotateBlocking(ctx context.Context, req issueops.BlockingRequest) (issueops.BlockingResult, error) {
result, err := a.served.AnnotateBlocking(ctx, req)
if err != nil || len(result.Items) == 0 {
result, err := a.inner.AnnotateBlocking(ctx, req)
if err != nil {
return issueops.BlockingResult{}, err
}
if enforced, err := a.policy.serverEnforcesPolicy(ctx); err != nil || enforced {
return result, err
}
ids := make([]string, 0, len(result.Items))
for _, item := range result.Items {
ids = append(ids, item.ID)
if item.ID != "" {
ids = append(ids, item.ID)
}
}
state, err := a.policy.blockingStateFor(ctx, ids)
blockers, err := a.policy.externalBlockersFor(ctx, ids)
if err != nil {
return issueops.BlockingResult{}, err
}
for i := range result.Items {
for _, ref := range state.refsByIssue[result.Items[i].ID] {
for _, ref := range blockers[result.Items[i].ID] {
result.Items[i].BlockedBy = appendUnique(result.Items[i].BlockedBy, ref)
}
}
return result, nil
}
// remoteTreeWalker adds external leaves to the served down-tree. A leaf the
// server already rendered is kept as it came (appendTreeExternalReferences
// skips an id the tree holds), and like GetDependencyTree the leaves are
// rendered whether or not the server enforces the policy: a leaf is display,
// not enforcement.
// ── TreeWalker ──────────────────────────────────────────────────────
type remoteTreeWalker struct {
served issueops.TreeWalker
inner issueops.TreeWalker
policy *Store
}
// WalkTree is the server's walk. For the plain down-tree request it also hangs
// the synthetic external leaves the local walker shows — unless the server
// enforces the external-dependency policy, whose own walker already does.
//
// The probe only spares the edge reads: a leaf is display, not enforcement,
// and appendTreeExternalReferences skips an id the tree already holds. So a
// probe that fails renders the leaves here rather than failing a walk the
// server has already answered.
func (t *remoteTreeWalker) WalkTree(ctx context.Context, req issueops.WalkTreeRequest) (issueops.TreeResult, error) {
result, err := t.served.WalkTree(ctx, req)
if err != nil || !plainDownTree(req) || len(result.Nodes) == 0 {
result, err := t.inner.WalkTree(ctx, req)
if err != nil || len(result.Nodes) == 0 {
return result, err
}
if (req.Direction != "" && req.Direction != issueops.TreeDown) || req.Status != "" || req.MaxRows != 0 {
return result, nil
}
if enforced, err := t.policy.serverEnforcesPolicy(ctx); err == nil && enforced {
return result, nil
}
ids := make([]string, 0, len(result.Nodes))
for _, node := range result.Nodes {
if node != nil && !isExternalReference(node.ID) {
ids = append(ids, node.ID)
}
}
deps, err := t.policy.servedEdges(ctx, ids)
deps, err := t.policy.remoteEdges(ctx, ids)
if err != nil {
return issueops.TreeResult{}, fmt.Errorf("external dependencies: load tree edges: %w", err)
}
@ -291,94 +477,117 @@ func (t *remoteTreeWalker) WalkTree(ctx context.Context, req issueops.WalkTreeRe
if err != nil {
return issueops.TreeResult{}, err
}
result.Nodes = nodes
return result, nil
return issueops.TreeResult{Nodes: nodes}, nil
}
// remoteBatchCloser refuses each externally blocked, still-open item the way
// the local policy close does, then sends the rest to the served closer as one
// request, so they still close in one server transaction. The external answer
// is read before that request rather than inside it, the same window
// remoteReadyClaimer has.
//
// A batch that also claims the next issue is refused whole, before anything
// closes. The local closer claims inside the closing transaction with the
// policy's exclusions in its filter. A served close has no parameter to carry
// them, and claiming after the close commits would split the role's one
// transaction in two. The refusal does not read the workspace, so the command
// fails the same way whether or not anything in it is externally blocked.
type remoteBatchCloser struct{ policy *Store }
// ── BatchCloser ─────────────────────────────────────────────────────
type remoteBatchCloser struct {
inner issueops.BatchCloser
policy *Store
}
// CloseBatch applies the close policy around the server's batch close. A
// remote store has no policy-snapshot batch closer
// (storage.PolicyBatchCloserSource), so an unforced batch that names an
// externally blocked live issue is split: that item gets the policy refusal as
// its outcome — exactly the outcome the local batch body records — and the
// rest go to the server in one request. A blocked item that is already closed
// or missing still travels, so its idempotent re-close and the server's
// not-found precedence are the server's answer, as they are locally; one whose
// state cannot be read gets that read's error (liveRefusal).
//
// A forced batch has nothing to judge. A ClaimNext batch goes to
// closeAndClaimNext, Force or not. Against a server that applies the policy,
// externalBlockersFor reads nothing and the whole request goes through
// untouched.
func (c *remoteBatchCloser) CloseBatch(ctx context.Context, request issueops.CloseBatchRequest) (issueops.CloseBatchResult, error) {
if request.ClaimNext != nil {
return c.closeAndClaimNext(ctx, request)
}
if request.Force {
// Force waives the policy, so the base closer reaches the served one
// with an empty policy.
return (&batchCloser{policy: c.policy}).CloseBatch(ctx, request)
}
if err := storageissueops.ValidateCloseBatchRequest(request); err != nil {
return issueops.CloseBatchResult{}, err
return c.inner.CloseBatch(ctx, request)
}
ids := make([]string, 0, len(request.Items))
for _, item := range request.Items {
ids = append(ids, item.IssueID)
}
state, err := c.policy.blockingStateFor(ctx, ids)
blockers, err := c.policy.externalBlockersFor(ctx, ids)
if err != nil {
return issueops.CloseBatchResult{}, err
}
served, err := c.policy.inner.BatchCloser()
if err != nil {
return issueops.CloseBatchResult{}, err
if len(blockers) == 0 {
return c.inner.CloseBatch(ctx, request)
}
if len(state.refsByIssue) == 0 {
return served.CloseBatch(ctx, request)
if err := storageissueops.ValidateCloseBatchRequest(request); err != nil {
return issueops.CloseBatchResult{}, err
}
policy := storage.NewBatchClosePolicy(state.refsByIssue)
outcomes := make([]issueops.CloseOutcome, len(request.Items))
forward := request
forward.Items = make([]issueops.BatchCloseItem, 0, len(request.Items))
forward.Items = nil
forwarded := make([]int, 0, len(request.Items))
policy := storage.NewBatchClosePolicy(blockers)
for i, item := range request.Items {
if refusal := policy.CheckClose(item.IssueID, false); refusal != nil {
// As in the local close: only a live target is refused, so an
// idempotent re-close and a not-found keep their own answers.
issue, err := c.policy.inner.GetIssue(ctx, item.IssueID)
if err != nil {
if err := c.liveRefusal(ctx, item.IssueID, refusal); err != nil {
outcomes[i] = issueops.CloseOutcome{IssueID: item.IssueID, Err: err}
continue
}
if issue != nil && issue.Status != types.StatusClosed {
outcomes[i] = issueops.CloseOutcome{IssueID: item.IssueID, Err: refusal}
continue
}
}
forward.Items = append(forward.Items, item)
forwarded = append(forwarded, i)
}
if len(forward.Items) == 0 {
return issueops.CloseBatchResult{Outcomes: outcomes}, nil
}
result, err := served.CloseBatch(ctx, forward)
if err != nil {
return issueops.CloseBatchResult{}, err
}
if len(result.Outcomes) != len(forward.Items) {
return issueops.CloseBatchResult{}, fmt.Errorf("close batch: served closer answered %d outcomes for %d items", len(result.Outcomes), len(forward.Items))
}
for j, outcome := range result.Outcomes {
outcomes[forwarded[j]] = outcome
if len(forward.Items) > 0 {
res, err := c.inner.CloseBatch(ctx, forward)
if err != nil {
return issueops.CloseBatchResult{}, err
}
if len(res.Outcomes) != len(forwarded) {
return issueops.CloseBatchResult{}, fmt.Errorf("close batch: server answered %d outcomes for %d items", len(res.Outcomes), len(forwarded))
}
for j, i := range forwarded {
outcomes[i] = res.Outcomes[j]
}
}
return issueops.CloseBatchResult{Outcomes: outcomes}, nil
}
// liveRefusal is the outcome of an externally blocked item, or nil when the
// item travels to the server. As in the local close only a live issue is
// refused, so an already closed one keeps its idempotent re-close and a
// missing one the server's not-found. Any other failed read is the item's
// outcome: it is neither refused nor closed on a guess.
func (c *remoteBatchCloser) liveRefusal(ctx context.Context, issueID string, refusal error) error {
issue, err := c.policy.inner.GetIssue(ctx, issueID)
switch {
case errors.Is(err, storage.ErrNotFound):
return nil
case err != nil:
return err
case issue != nil && issue.Status != types.StatusClosed:
return refusal
}
return nil
}
var (
_ issueops.BatchCloser = (*remoteBatchCloser)(nil)
_ issueops.Reader = (*remoteReader)(nil)
_ issueops.Claimer = (*remoteClaimer)(nil)
_ issueops.ReadyClaimer = (*remoteReadyClaimer)(nil)
_ issueops.BlockingAnnotator = (*remoteBlockingAnnotator)(nil)
_ issueops.TreeWalker = (*remoteTreeWalker)(nil)
_ issueops.ReadyCounter = (*remoteReadyCounter)(nil)
)
// closeAndClaimNext answers a batch with a next claim. A request that is
// invalid on every backend is still ErrValidation. A server that enforces the
// policy itself gets the request as it came; over the v0 wire its closer
// refuses a next claim too (ledger row W-CloseBatchRequest.ClaimNext).
// invalid on every backend is still ErrValidation. Against a server that does
// not apply the policy the batch is refused whole, before anything is read or
// closed: a served close cannot keep externally blocked work out of its claim,
// and the v0 wire's batch close cannot carry a next claim at all (ledger row
// W-CloseBatchRequest.ClaimNext). A server that applies the policy gets the
// request as it came; over the v0 wire its closer refuses the claim too.
func (c *remoteBatchCloser) closeAndClaimNext(ctx context.Context, request issueops.CloseBatchRequest) (issueops.CloseBatchResult, error) {
if err := storageissueops.ValidateCloseBatchRequest(request); err != nil {
return issueops.CloseBatchResult{}, err
@ -395,18 +604,5 @@ func (c *remoteBatchCloser) closeAndClaimNext(ctx context.Context, request issue
"close with a next claim: the served batch close cannot carry a next claim, so nothing was closed; close without --claim-next, then run `bd ready --claim` (%w)",
&storage.ErrUnsupported{Op: "CloseBatchRequest.ClaimNext", Backend: fmt.Sprintf("%T", storage.UnwrapStore(c.policy.inner))})
}
served, err := c.policy.inner.BatchCloser()
if err != nil {
return issueops.CloseBatchResult{}, err
}
return served.CloseBatch(ctx, request)
return c.inner.CloseBatch(ctx, request)
}
var (
_ issueops.Reader = (*remoteReader)(nil)
_ issueops.Claimer = (*remoteClaimer)(nil)
_ issueops.ReadyClaimer = (*remoteReadyClaimer)(nil)
_ issueops.BlockingAnnotator = (*remoteBlockingAnnotator)(nil)
_ issueops.TreeWalker = (*remoteTreeWalker)(nil)
_ issueops.BatchCloser = (*remoteBatchCloser)(nil)
)

View file

@ -0,0 +1,904 @@
package externaldeps
import (
"context"
"errors"
"fmt"
"slices"
"strings"
"testing"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/types"
publicops "github.com/steveyegge/beads/issueops"
)
// remoteStore models httpclient.Store for remote_roles.go. Each role it hands
// out is served over the embedded fakeStore's rows, the way a server that
// knows nothing of the policy answers it, and each legacy method a base
// accessor builds on is refused, so a composition that reaches one fails the
// test instead of passing on a fake that answers it. Like httpclient.Store it
// cannot express ExcludeIDs and has no BatchCloserWithPolicy.
type remoteStore struct {
*fakeStore
// served logs each served role call, in order.
served []string
// closes logs the item ids of each served batch close.
closes [][]string
// edgeReads logs how many anchors each served edge read named.
edgeReads []int
// scans counts the whole-workspace dependency scans read through it.
scans int
// localBlockers is the served annotation's own BlockedBy, per id.
localBlockers map[string][]string
// claimErr, when set, answers every served Claim.
claimErr error
// takenFirst names the rows a rival actor claims just before a served
// Claim of them lands: that claim is a lost race, and the row leaves the
// unassigned set.
takenFirst map[string]bool
// getErrs, per id, fails the GetIssue read of that id.
getErrs map[string]error
}
var errLegacyRefused = errors.New("remoteStore: legacy method refused")
// wireEdgeAnchorCap is the most anchors the wire's listDependencies accepts.
const wireEdgeAnchorCap = 100
func newRemoteStore(ready ...*types.Issue) *remoteStore {
return &remoteStore{fakeStore: &fakeStore{
ready: ready,
deps: make(map[string][]*types.Dependency),
excludeIDsUnsupported: true,
}}
}
func (r *remoteStore) IsRemoteBackendStore() bool { return true }
func (r *remoteStore) GetIssue(ctx context.Context, id string) (*types.Issue, error) {
if err := r.getErrs[id]; err != nil {
return nil, err
}
return r.fakeStore.GetIssue(ctx, id)
}
// httpclient.Store serves the vocabulary a listing loads before its search.
func (r *remoteStore) GetCustomStatusesDetailed(context.Context) ([]types.CustomStatus, error) {
return nil, nil
}
func (r *remoteStore) GetCustomTypes(context.Context) ([]string, error) { return nil, nil }
func (r *remoteStore) GetInfraTypes(context.Context) map[string]bool { return nil }
func (r *remoteStore) SearchIssuesWithCounts(context.Context, string, types.IssueFilter) ([]*types.IssueWithCounts, error) {
return nil, errLegacyRefused
}
func (r *remoteStore) IsBlocked(context.Context, string) (bool, []string, error) {
return false, nil, errLegacyRefused
}
func (r *remoteStore) GetDependencyRecordsForIssues(context.Context, []string) (map[string][]*types.Dependency, error) {
return nil, errLegacyRefused
}
func (r *remoteStore) GetDependencyTree(context.Context, string, int, bool, bool) ([]*types.TreeNode, error) {
return nil, errLegacyRefused
}
func (r *remoteStore) ClaimReadyIssue(context.Context, types.WorkFilter, string) (*types.Issue, error) {
return nil, errLegacyRefused
}
func (r *remoteStore) GetAllDependencyRecords(ctx context.Context) (map[string][]*types.Dependency, error) {
r.scans++
return r.fakeStore.GetAllDependencyRecords(ctx)
}
func (r *remoteStore) GetExternalBlockingDependencyRecords(ctx context.Context) (map[string][]*types.Dependency, error) {
r.scans++
return r.fakeStore.GetExternalBlockingDependencyRecords(ctx)
}
func (r *remoteStore) IssueReader() (publicops.Reader, error) { return servedReader{r}, nil }
func (r *remoteStore) IssueClaimer() (publicops.Claimer, error) { return servedClaimer{r}, nil }
func (r *remoteStore) ReadyClaimer() (publicops.ReadyClaimer, error) {
return servedReadyClaimer{r}, nil
}
func (r *remoteStore) TreeWalker() (publicops.TreeWalker, error) { return servedWalker{r}, nil }
func (r *remoteStore) EdgeReader() (publicops.EdgeReader, error) { return servedEdgeReader{r}, nil }
func (r *remoteStore) BatchCloser() (publicops.BatchCloser, error) { return servedCloser{r}, nil }
func (r *remoteStore) BlockingAnnotator() (publicops.BlockingAnnotator, error) {
return servedAnnotator{r}, nil
}
type servedReader struct{ s *remoteStore }
// Ready serves the ready rows the way a server that knows nothing of the
// policy does: in order, narrowed by the request's assignee rule (Unassigned
// wins over Assignee, as in workapi.BuildReadyFilter), up to its limit, with
// has_more past it.
func (r servedReader) Ready(_ context.Context, req publicops.ReadyRequest) (publicops.IssuePage, error) {
r.s.served = append(r.s.served, "Ready")
items := make([]*types.IssueWithCounts, 0, len(r.s.ready))
for _, issue := range r.s.ready {
if req.Unassigned {
if issue.Assignee != "" {
continue
}
} else if req.Assignee != "" && issue.Assignee != req.Assignee {
continue
}
items = append(items, &types.IssueWithCounts{Issue: issue})
}
if req.Limit != nil && *req.Limit >= 0 && *req.Limit < len(items) {
return publicops.IssuePage{Items: items[:*req.Limit], HasMore: true}, nil
}
return publicops.IssuePage{Items: items}, nil
}
func (r servedReader) List(_ context.Context, req publicops.ListRequest) (publicops.IssuePage, error) {
if req.ReadyFlag {
// Like httpclient: listIssues cannot carry ReadyFlag (ledger row
// E-ListRequest.ReadyFlag); a ready listing is listReadyWork's question.
return publicops.IssuePage{}, &storage.ErrUnsupported{Op: "ListRequest.ReadyFlag", Backend: "http"}
}
r.s.served = append(r.s.served, "List")
items := make([]*types.IssueWithCounts, 0, len(r.s.ready))
for _, issue := range r.s.ready {
items = append(items, &types.IssueWithCounts{Issue: issue})
}
return publicops.IssuePage{Items: items}, nil
}
func (r servedReader) Get(ctx context.Context, req publicops.GetRequest) (*publicops.IssueDetails, error) {
r.s.served = append(r.s.served, "Get "+req.ID)
issue, err := r.s.GetIssue(ctx, req.ID)
if err != nil {
return nil, err
}
if issue == nil {
return nil, publicops.ErrNotFound
}
return &publicops.IssueDetails{Issue: *issue}, nil
}
type servedClaimer struct{ s *remoteStore }
func (c servedClaimer) Claim(ctx context.Context, req publicops.ClaimRequest) (publicops.ClaimResult, error) {
c.s.served = append(c.s.served, "Claim "+req.IssueID)
if c.s.claimErr != nil {
return publicops.ClaimResult{}, c.s.claimErr
}
if c.s.takenFirst[req.IssueID] {
if err := c.s.ClaimIssue(ctx, req.IssueID, "rival"); err != nil {
return publicops.ClaimResult{}, err
}
}
if err := c.s.ClaimIssue(ctx, req.IssueID, req.Actor); err != nil {
return publicops.ClaimResult{}, err
}
issue, err := c.s.GetIssue(ctx, req.IssueID)
return publicops.ClaimResult{Issue: issue, Changed: true}, err
}
// servedReadyClaimer claims the first unassigned ready row, blind to the
// policy as a claim-next with no exclusion parameter is.
type servedReadyClaimer struct{ s *remoteStore }
func (c servedReadyClaimer) ClaimNext(ctx context.Context, req publicops.ClaimNextRequest) (publicops.ClaimNextResult, error) {
c.s.served = append(c.s.served, "ClaimNext")
for _, issue := range c.s.ready {
if issue.Assignee != "" {
continue
}
if err := c.s.ClaimIssue(ctx, issue.ID, req.Actor); err != nil {
return publicops.ClaimNextResult{}, err
}
return publicops.ClaimNextResult{Claimed: &types.IssueWithCounts{Issue: issue}}, nil
}
return publicops.ClaimNextResult{}, nil
}
type servedAnnotator struct{ s *remoteStore }
func (a servedAnnotator) AnnotateBlocking(_ context.Context, req publicops.BlockingRequest) (publicops.BlockingResult, error) {
a.s.served = append(a.s.served, "AnnotateBlocking")
items := make([]publicops.IssueBlocking, 0, len(req.IDs))
for _, id := range req.IDs {
items = append(items, publicops.IssueBlocking{ID: id, BlockedBy: slices.Clone(a.s.localBlockers[id])})
}
return publicops.BlockingResult{Items: items}, nil
}
type servedWalker struct{ s *remoteStore }
func (w servedWalker) WalkTree(context.Context, publicops.WalkTreeRequest) (publicops.TreeResult, error) {
w.s.served = append(w.s.served, "WalkTree")
return publicops.TreeResult{Nodes: slices.Clone(w.s.tree)}, nil
}
type servedEdgeReader struct{ s *remoteStore }
func (e servedEdgeReader) ReadEdges(_ context.Context, req publicops.EdgeReadRequest) (publicops.EdgeReadResult, error) {
if len(req.IDs) > wireEdgeAnchorCap {
return publicops.EdgeReadResult{}, fmt.Errorf("served ReadEdges: %d anchors, past the wire's %d", len(req.IDs), wireEdgeAnchorCap)
}
if slices.Contains(req.IDs, "") {
// As httpclient's validateAnchors refuses one.
return publicops.EdgeReadResult{}, fmt.Errorf("%w: an anchor id must not be empty", publicops.ErrValidation)
}
e.s.edgeReads = append(e.s.edgeReads, len(req.IDs))
anchors := make([]publicops.AnchorEdges, 0, len(req.IDs))
for _, id := range req.IDs {
anchors = append(anchors, publicops.AnchorEdges{ID: id, Edges: e.s.deps[id]})
}
return publicops.EdgeReadResult{Anchors: anchors}, nil
}
type servedCloser struct{ s *remoteStore }
// errServedClaimNextRefused is the served closer's answer to a next claim.
// httpclient refuses one on every server: the v0 wire's batch close has no
// member to carry it (ledger row W-CloseBatchRequest.ClaimNext).
var errServedClaimNextRefused = &storage.ErrUnsupported{Op: "BatchCloser.CloseBatch", Backend: "http"}
func (c servedCloser) CloseBatch(ctx context.Context, req publicops.CloseBatchRequest) (publicops.CloseBatchResult, error) {
if req.ClaimNext != nil {
c.s.served = append(c.s.served, "CloseBatch ClaimNext")
return publicops.CloseBatchResult{}, errServedClaimNextRefused
}
ids := make([]string, 0, len(req.Items))
outcomes := make([]publicops.CloseOutcome, 0, len(req.Items))
for _, item := range req.Items {
ids = append(ids, item.IssueID)
result, err := c.s.CloseIssueChecked(ctx, item.IssueID, req.Actor, storage.CloseIssueOptions{})
outcomes = append(outcomes, publicops.CloseOutcome{IssueID: item.IssueID, Changed: err == nil && !result.Unchanged, Err: err})
}
c.s.closes = append(c.s.closes, ids)
return publicops.CloseBatchResult{Outcomes: outcomes}, nil
}
const paymentsRef = "external:remote:payments"
func blockOnPayments(raw *remoteStore, ids ...string) {
for _, id := range ids {
raw.deps[id] = []*types.Dependency{externalDep(id, paymentsRef, types.DepBlocks)}
}
}
func closeItems(ids ...string) []publicops.BatchCloseItem {
items := make([]publicops.BatchCloseItem, 0, len(ids))
for _, id := range ids {
items = append(items, publicops.BatchCloseItem{IssueID: id})
}
return items
}
// TestRemoteRolesAnswerWithoutTheLegacyMethods pins the blocker the base
// accessors had over httpclient.Store: built over legacy methods a remote
// store refuses, they failed bd list, bd show, bd dep tree, bd ready --claim
// and bd close in a workspace where nothing had an external dependency.
func TestRemoteRolesAnswerWithoutTheLegacyMethods(t *testing.T) {
a, b := issue("be-a"), issue("be-b")
raw := newRemoteStore(a, b)
raw.tree = []*types.TreeNode{{Issue: *a}}
store := testStore(raw, &fakeStore{}, true)
ctx := t.Context()
reader, err := store.IssueReader()
if err != nil {
t.Fatalf("IssueReader: %v", err)
}
if page, err := reader.List(ctx, publicops.ListRequest{}); err != nil || len(page.Items) != 2 {
t.Fatalf("List = %d items, %v; want 2", len(page.Items), err)
}
if details, err := reader.Get(ctx, publicops.GetRequest{ID: a.ID}); err != nil || details.ID != a.ID {
t.Fatalf("Get = %v, %v; want %s", details, err, a.ID)
}
if page, err := reader.Ready(ctx, publicops.ReadyRequest{}); err != nil || len(page.Items) != 2 {
t.Fatalf("Ready = %d items, %v; want 2", len(page.Items), err)
}
claimer, err := store.IssueClaimer()
if err != nil {
t.Fatalf("IssueClaimer: %v", err)
}
if _, err := claimer.Claim(ctx, publicops.ClaimRequest{Actor: "worker", IssueID: a.ID}); err != nil {
t.Fatalf("Claim: %v", err)
}
readyClaimer, err := store.ReadyClaimer()
if err != nil {
t.Fatalf("ReadyClaimer: %v", err)
}
if next, err := readyClaimer.ClaimNext(ctx, publicops.ClaimNextRequest{Actor: "worker"}); err != nil || next.Claimed == nil || next.Claimed.ID != b.ID {
t.Fatalf("ClaimNext = %+v, %v; want %s", next.Claimed, err, b.ID)
}
annotator, err := store.BlockingAnnotator()
if err != nil {
t.Fatalf("BlockingAnnotator: %v", err)
}
if result, err := annotator.AnnotateBlocking(ctx, publicops.BlockingRequest{IDs: []string{a.ID, b.ID}}); err != nil || len(result.Items) != 2 {
t.Fatalf("AnnotateBlocking = %+v, %v; want 2 items", result.Items, err)
}
walker, err := store.TreeWalker()
if err != nil {
t.Fatalf("TreeWalker: %v", err)
}
if tree, err := walker.WalkTree(ctx, publicops.WalkTreeRequest{RootID: a.ID, MaxDepth: 50}); err != nil || len(tree.Nodes) != 1 {
t.Fatalf("WalkTree = %d nodes, %v; want the served root alone", len(tree.Nodes), err)
}
closer, err := store.BatchCloser()
if err != nil {
t.Fatalf("BatchCloser: %v", err)
}
result, err := closer.CloseBatch(ctx, publicops.CloseBatchRequest{Actor: "worker", Items: closeItems(a.ID, b.ID)})
if err != nil || len(result.Outcomes) != 2 {
t.Fatalf("CloseBatch = %+v, %v; want 2 outcomes", result.Outcomes, err)
}
if want := []string{"List", "Get be-a", "Ready", "Claim be-a", "ClaimNext", "AnnotateBlocking", "WalkTree"}; !slices.Equal(raw.served, want) {
t.Fatalf("served calls = %v, want %v", raw.served, want)
}
if want := [][]string{{a.ID, b.ID}}; !slices.EqualFunc(raw.closes, want, slices.Equal[[]string]) {
t.Fatalf("served closes = %v, want %v", raw.closes, want)
}
}
// TestRemoteReaderPolicesReadyWorkOnly: an externally blocked issue leaves the
// ready listing and stays in a plain one, which claims nothing about
// readiness.
func TestRemoteReaderPolicesReadyWorkOnly(t *testing.T) {
a, b := issue("be-a"), issue("be-b")
raw := newRemoteStore(a, b)
blockOnPayments(raw, a.ID)
reader, err := testStore(raw, &fakeStore{}, true).IssueReader()
if err != nil {
t.Fatalf("IssueReader: %v", err)
}
ready, err := reader.Ready(t.Context(), publicops.ReadyRequest{})
if err != nil {
t.Fatalf("Ready: %v", err)
}
if len(ready.Items) != 1 || ready.Items[0].ID != b.ID {
t.Fatalf("Ready = %d items, want %s alone (%s is externally blocked)", len(ready.Items), b.ID, a.ID)
}
listed, err := reader.List(t.Context(), publicops.ListRequest{})
if err != nil {
t.Fatalf("List: %v", err)
}
if len(listed.Items) != 2 {
t.Fatalf("List = %d items, want both", len(listed.Items))
}
}
// TestRemoteReaderAnswersAReadyListingWithoutTheWireFlag: `bd list --ready`
// is a List with ReadyFlag, which the served listing refuses. Over a remote
// store it is the ready question, answered by the policy store's own reader
// with externally blocked work left out, and never sent to the served List.
func TestRemoteReaderAnswersAReadyListingWithoutTheWireFlag(t *testing.T) {
a, b := issue("be-a"), issue("be-b")
for _, tc := range []struct {
name string
blocked bool
want []string
}{
{name: "no external refs", want: []string{a.ID, b.ID}},
{name: "an externally blocked issue", blocked: true, want: []string{b.ID}},
} {
t.Run(tc.name, func(t *testing.T) {
raw := newRemoteStore(a, b)
if tc.blocked {
blockOnPayments(raw, a.ID)
}
reader, err := testStore(raw, &fakeStore{}, true).IssueReader()
if err != nil {
t.Fatalf("IssueReader: %v", err)
}
listed, err := reader.List(t.Context(), publicops.ListRequest{ReadyFlag: true})
if err != nil {
t.Fatalf("List(ReadyFlag): %v", err)
}
got := make([]string, 0, len(listed.Items))
for _, row := range listed.Items {
got = append(got, row.ID)
}
if !slices.Equal(got, tc.want) {
t.Fatalf("List(ReadyFlag) = %v, want %v", got, tc.want)
}
if slices.Contains(raw.served, "List") {
t.Fatalf("served calls = %v: a ready listing reached the served List", raw.served)
}
})
}
}
func TestRemoteClaimerRefusesExternallyBlockedWork(t *testing.T) {
for _, enforced := range []bool{false, true} {
t.Run(fmt.Sprintf("server enforces %v", enforced), func(t *testing.T) {
a := issue("be-a")
raw := newRemoteStore(a)
raw.enforced = enforced
blockOnPayments(raw, a.ID)
claimer, err := testStore(raw, &fakeStore{}, true).IssueClaimer()
if err != nil {
t.Fatalf("IssueClaimer: %v", err)
}
_, err = claimer.Claim(t.Context(), publicops.ClaimRequest{Actor: "worker", IssueID: a.ID})
if enforced {
// The server already applied the policy, so the claim is its
// to answer.
if err != nil || !slices.Equal(raw.served, []string{"Claim be-a"}) {
t.Fatalf("Claim = %v, served %v; want the served claim", err, raw.served)
}
return
}
if !errors.Is(err, storage.ErrCloseBlocked) || !strings.Contains(err.Error(), paymentsRef) {
t.Fatalf("Claim = %v, want ErrCloseBlocked naming %s", err, paymentsRef)
}
if len(raw.served) != 0 {
t.Fatalf("served calls = %v, want none for a refused claim", raw.served)
}
})
}
}
// TestRemoteReadyClaimerSkipsExternallyBlockedWork: the served claim-next
// cannot be told what to skip, so with anything externally blocked the claim
// walks the policy's ready page through the served Claimer instead. be-a sorts
// first, where the served claim-next would take it.
func TestRemoteReadyClaimerSkipsExternallyBlockedWork(t *testing.T) {
a, b := issue("be-a"), issue("be-b")
raw := newRemoteStore(a, b)
blockOnPayments(raw, a.ID)
claimer, err := testStore(raw, &fakeStore{}, true).ReadyClaimer()
if err != nil {
t.Fatalf("ReadyClaimer: %v", err)
}
next, err := claimer.ClaimNext(t.Context(), publicops.ClaimNextRequest{Actor: "worker"})
if err != nil {
t.Fatalf("ClaimNext: %v", err)
}
if next.Claimed == nil || next.Claimed.ID != b.ID || b.Assignee != "worker" {
t.Fatalf("ClaimNext claimed %+v, want %s for worker", next.Claimed, b.ID)
}
if want := []string{"Ready", "Claim be-b"}; !slices.Equal(raw.served, want) {
t.Fatalf("served calls = %v, want %v", raw.served, want)
}
}
// TestRemoteReadyClaimerReportsLostRaces: a front that had work but lost every
// candidate is an error, not the empty answer that means there is no work.
func TestRemoteReadyClaimerReportsLostRaces(t *testing.T) {
a, b := issue("be-a"), issue("be-b")
raw := newRemoteStore(a, b)
blockOnPayments(raw, a.ID)
raw.claimErr = storage.ErrAlreadyClaimed
claimer, err := testStore(raw, &fakeStore{}, true).ReadyClaimer()
if err != nil {
t.Fatalf("ReadyClaimer: %v", err)
}
next, err := claimer.ClaimNext(t.Context(), publicops.ClaimNextRequest{Actor: "worker"})
if err == nil || !strings.Contains(err.Error(), "lost 1 races") || next.Claimed != nil {
t.Fatalf("ClaimNext = %+v, %v; want a lost-races error", next.Claimed, err)
}
}
// TestRemoteReadyClaimerTakesOnlyUnassignedWork: the composed claim selects
// what a local claim-next selects (ClaimReadyIssueInTx), open and unassigned
// whatever assignee the request names. A row another actor holds, sorted
// first, is not a race to lose, and a request naming the caller does not try
// to re-take the caller's own row.
func TestRemoteReadyClaimerTakesOnlyUnassignedWork(t *testing.T) {
for _, tc := range []struct {
name string
filter publicops.ReadyRequest
}{
{name: "any assignee"},
{name: "the caller as assignee", filter: publicops.ReadyRequest{Assignee: "worker"}},
} {
t.Run(tc.name, func(t *testing.T) {
held, blocked, mine, free := issue("be-held"), issue("be-blocked"), issue("be-mine"), issue("be-free")
held.Assignee, mine.Assignee = "alice", "worker"
raw := newRemoteStore(held, blocked, mine, free)
blockOnPayments(raw, blocked.ID)
claimer, err := testStore(raw, &fakeStore{}, true).ReadyClaimer()
if err != nil {
t.Fatalf("ReadyClaimer: %v", err)
}
next, err := claimer.ClaimNext(t.Context(), publicops.ClaimNextRequest{Actor: "worker", Filter: tc.filter})
if err != nil {
t.Fatalf("ClaimNext: %v", err)
}
if next.Claimed == nil || next.Claimed.ID != free.ID || free.Assignee != "worker" {
t.Fatalf("ClaimNext claimed %+v, want %s for worker", next.Claimed, free.ID)
}
if want := []string{"Ready", "Claim be-free"}; !slices.Equal(raw.served, want) {
t.Fatalf("served calls = %v, want %v", raw.served, want)
}
if held.Assignee != "alice" {
t.Fatalf("be-held assignee = %q, want alice's claim untouched", held.Assignee)
}
})
}
}
// TestRemoteReadyClaimerWalksAContendedFront: candidates a rival takes between
// the read and the claim are passed over, however many lead the front. A full
// window lost end to end is read once more, and the rows the rivals took have
// left it; only when that pass is lost too is it an error, and a second pass
// with nothing left to take is no work.
func TestRemoteReadyClaimerWalksAContendedFront(t *testing.T) {
for _, tc := range []struct {
name string
rivals int // leading candidates a rival takes first
last bool // be-last follows them
lastTaken bool // and a rival takes it first too
wantLast bool
wantErr string
wantReads int
}{
{name: "three lost ahead", rivals: 3, last: true, wantLast: true, wantReads: 1},
{name: "a full window lost", rivals: remoteClaimPage, last: true, wantLast: true, wantReads: 2},
{name: "both passes lost", rivals: remoteClaimPage, last: true, lastTaken: true, wantErr: "lost 26 races", wantReads: 2},
{name: "nothing behind a lost window", rivals: remoteClaimPage, wantReads: 2},
} {
t.Run(tc.name, func(t *testing.T) {
blocked, last := issue("be-blocked"), issue("be-last")
raw := newRemoteStore(blocked)
blockOnPayments(raw, blocked.ID)
raw.takenFirst = make(map[string]bool)
for i := range tc.rivals {
taken := issue(fmt.Sprintf("be-taken-%02d", i))
raw.ready = append(raw.ready, taken)
raw.takenFirst[taken.ID] = true
}
if tc.last {
raw.ready = append(raw.ready, last)
raw.takenFirst[last.ID] = tc.lastTaken
}
claimer, err := testStore(raw, &fakeStore{}, true).ReadyClaimer()
if err != nil {
t.Fatalf("ReadyClaimer: %v", err)
}
next, err := claimer.ClaimNext(t.Context(), publicops.ClaimNextRequest{Actor: "worker"})
switch {
case tc.wantErr != "":
if err == nil || !strings.Contains(err.Error(), tc.wantErr) || next.Claimed != nil {
t.Fatalf("ClaimNext = %+v, %v; want a %q error", next.Claimed, err, tc.wantErr)
}
case err != nil:
t.Fatalf("ClaimNext: %v", err)
case tc.wantLast:
if next.Claimed == nil || next.Claimed.ID != last.ID || last.Assignee != "worker" {
t.Fatalf("ClaimNext claimed %+v, want %s for worker", next.Claimed, last.ID)
}
case next.Claimed != nil:
t.Fatalf("ClaimNext claimed %+v, want no work: rivals took every candidate", next.Claimed)
}
reads := 0
for _, call := range raw.served {
if call == "Ready" {
reads++
}
}
if reads != tc.wantReads {
t.Fatalf("served ready reads = %d, want %d", reads, tc.wantReads)
}
})
}
}
// TestRemoteBlockingAnnotatorMergesExternalBlockers: the served annotation's
// own blockers stay, the external ones join them, and the edges behind them
// are read in chunks the wire accepts.
func TestRemoteBlockingAnnotatorMergesExternalBlockers(t *testing.T) {
issues := make([]*types.Issue, 0, 150)
ids := make([]string, 0, 150)
for i := range 150 {
issues = append(issues, issue(fmt.Sprintf("be-%03d", i)))
ids = append(ids, issues[i].ID)
}
raw := newRemoteStore(issues...)
blockOnPayments(raw, "be-000", "be-149")
raw.localBlockers = map[string][]string{"be-000": {"be-local"}}
annotator, err := testStore(raw, &fakeStore{}, true).BlockingAnnotator()
if err != nil {
t.Fatalf("BlockingAnnotator: %v", err)
}
result, err := annotator.AnnotateBlocking(t.Context(), publicops.BlockingRequest{IDs: ids})
if err != nil {
t.Fatalf("AnnotateBlocking: %v", err)
}
blockedBy := make(map[string][]string, len(result.Items))
for _, item := range result.Items {
blockedBy[item.ID] = item.BlockedBy
}
if want := []string{"be-local", paymentsRef}; !slices.Equal(blockedBy["be-000"], want) {
t.Errorf("be-000 blocked by %v, want %v", blockedBy["be-000"], want)
}
if want := []string{paymentsRef}; !slices.Equal(blockedBy["be-149"], want) {
t.Errorf("be-149 blocked by %v, want %v", blockedBy["be-149"], want)
}
if len(blockedBy["be-001"]) != 0 {
t.Errorf("be-001 blocked by %v, want nothing", blockedBy["be-001"])
}
if want := []int{100, 50}; !slices.Equal(raw.edgeReads, want) {
t.Errorf("served edge reads named %v anchors, want %v", raw.edgeReads, want)
}
}
// TestRemoteEdgesNamesEachAnchorOnce: the edge read behind every per-issue
// policy question names each id once and never an empty one, which the http
// EdgeReader refuses; nothing to name reads nothing.
func TestRemoteEdgesNamesEachAnchorOnce(t *testing.T) {
raw := newRemoteStore(issue("be-a"))
blockOnPayments(raw, "be-a")
store := testStore(raw, &fakeStore{}, true)
deps, err := store.remoteEdges(t.Context(), []string{"be-a", "", "be-a"})
if err != nil {
t.Fatalf("remoteEdges: %v", err)
}
if len(deps["be-a"]) != 1 {
t.Fatalf("be-a edges = %v, want its one edge", deps["be-a"])
}
if _, err := store.remoteEdges(t.Context(), []string{""}); err != nil {
t.Fatalf("remoteEdges of an empty id: %v", err)
}
if want := []int{1}; !slices.Equal(raw.edgeReads, want) {
t.Fatalf("served edge reads named %v anchors, want %v", raw.edgeReads, want)
}
}
// TestRemoteTreeWalkerAddsExternalLeaves: the served down-tree gains the leaf
// its stored edges name, a leaf the server rendered is not repeated, and any
// other walk is the served answer as it came. A policy probe that fails does
// not fail the walk the server answered: its leaves are rendered here.
func TestRemoteTreeWalkerAddsExternalLeaves(t *testing.T) {
root := &types.TreeNode{Issue: *issue("be-a")}
served := &types.TreeNode{Issue: types.Issue{ID: paymentsRef, Title: "served leaf"}, Depth: 1, ParentID: "be-a"}
for _, tc := range []struct {
name string
req publicops.WalkTreeRequest
tree []*types.TreeNode
probeErr error
wantIDs []string
}{
{name: "down walk", req: publicops.WalkTreeRequest{RootID: "be-a", MaxDepth: 50}, tree: []*types.TreeNode{root}, wantIDs: []string{"be-a", paymentsRef}},
{name: "server rendered the leaf", req: publicops.WalkTreeRequest{RootID: "be-a", MaxDepth: 50}, tree: []*types.TreeNode{root, served}, wantIDs: []string{"be-a", paymentsRef}},
{name: "up walk", req: publicops.WalkTreeRequest{RootID: "be-a", MaxDepth: 50, Direction: publicops.TreeUp}, tree: []*types.TreeNode{root}, wantIDs: []string{"be-a"}},
{name: "probe fails", req: publicops.WalkTreeRequest{RootID: "be-a", MaxDepth: 50}, tree: []*types.TreeNode{root}, probeErr: errors.New("probe failed"), wantIDs: []string{"be-a", paymentsRef}},
{name: "probe fails, server rendered the leaf", req: publicops.WalkTreeRequest{RootID: "be-a", MaxDepth: 50}, tree: []*types.TreeNode{root, served}, probeErr: errors.New("probe failed"), wantIDs: []string{"be-a", paymentsRef}},
} {
t.Run(tc.name, func(t *testing.T) {
raw := newRemoteStore()
raw.tree = tc.tree
raw.enforcedErr = tc.probeErr
blockOnPayments(raw, "be-a")
walker, err := testStore(raw, &fakeStore{}, true).TreeWalker()
if err != nil {
t.Fatalf("TreeWalker: %v", err)
}
result, err := walker.WalkTree(t.Context(), tc.req)
if err != nil {
t.Fatalf("WalkTree: %v", err)
}
ids := make([]string, 0, len(result.Nodes))
for _, node := range result.Nodes {
ids = append(ids, node.ID)
}
if !slices.Equal(ids, tc.wantIDs) {
t.Fatalf("tree = %v, want %v", ids, tc.wantIDs)
}
if leaf := result.Nodes[len(result.Nodes)-1]; tc.name == "down walk" || tc.name == "probe fails" {
if leaf.Status != types.StatusOpen || leaf.ParentID != "be-a" || leaf.Depth != 1 || leaf.Title != "○ payments" {
t.Fatalf("leaf = %+v, want the open payments leaf under be-a", leaf)
}
}
})
}
}
// TestRemoteBatchCloserRefusesExternallyBlockedItems: a still-open externally
// blocked item is refused the way the local policy close refuses it and the
// rest close in one served request. An item already closed keeps the served
// answer, Force waives the policy, and a server that enforces the policy gets
// the whole batch.
func TestRemoteBatchCloserRefusesExternallyBlockedItems(t *testing.T) {
for _, tc := range []struct {
name string
force bool
enforced bool
wantRefused bool
}{
{name: "policy", wantRefused: true},
{name: "force", force: true},
{name: "server enforces", enforced: true},
} {
t.Run(tc.name, func(t *testing.T) {
blocked, free, done := issue("be-blocked"), issue("be-free"), issue("be-done")
done.Status = types.StatusClosed
raw := newRemoteStore(blocked, free, done)
raw.enforced = tc.enforced
blockOnPayments(raw, blocked.ID, done.ID)
closer, err := testStore(raw, &fakeStore{}, true).BatchCloser()
if err != nil {
t.Fatalf("BatchCloser: %v", err)
}
request := publicops.CloseBatchRequest{Actor: "worker", Force: tc.force, Items: closeItems(blocked.ID, free.ID, done.ID)}
result, err := closer.CloseBatch(t.Context(), request)
if err != nil {
t.Fatalf("CloseBatch: %v", err)
}
if len(result.Outcomes) != len(request.Items) {
t.Fatalf("CloseBatch answered %d outcomes for %d items", len(result.Outcomes), len(request.Items))
}
for i, outcome := range result.Outcomes {
if outcome.IssueID != request.Items[i].IssueID {
t.Fatalf("outcome %d is %s's, want %s's", i, outcome.IssueID, request.Items[i].IssueID)
}
}
wantServed := []string{blocked.ID, free.ID, done.ID}
if tc.wantRefused {
refusal := result.Outcomes[0].Err
want := "cannot close blocked issue: be-blocked is blocked by [" + paymentsRef + "]"
if !errors.Is(refusal, storage.ErrCloseBlocked) || refusal.Error() != want {
t.Fatalf("be-blocked outcome = %v, want %q", refusal, want)
}
wantServed = []string{free.ID, done.ID}
} else if result.Outcomes[0].Err != nil {
t.Fatalf("be-blocked outcome = %v, want it closed", result.Outcomes[0].Err)
}
if result.Outcomes[1].Err != nil || result.Outcomes[2].Err != nil {
t.Fatalf("be-free, be-done outcomes = %v, %v; want the served answers", result.Outcomes[1].Err, result.Outcomes[2].Err)
}
if want := [][]string{wantServed}; !slices.EqualFunc(raw.closes, want, slices.Equal[[]string]) {
t.Fatalf("served closes = %v, want %v", raw.closes, want)
}
})
}
}
// TestRemoteBatchCloserAnswersAFailedReadWithIt: whether an externally blocked
// item is live is a read, and a read that fails is that item's outcome. Passing
// the item to the server's close instead would close blocked work on a guess.
// A missing item still travels, for the server's own not-found.
func TestRemoteBatchCloserAnswersAFailedReadWithIt(t *testing.T) {
errRead := errors.New("served read failed")
for _, tc := range []struct {
name string
present bool
readErr error
wantErr error
wantServed []string
}{
{name: "failed read", present: true, readErr: errRead, wantErr: errRead, wantServed: []string{"be-free"}},
{name: "missing", readErr: fmt.Errorf("%w: issue be-blocked", storage.ErrNotFound), wantErr: storage.ErrNotFound, wantServed: []string{"be-blocked", "be-free"}},
} {
t.Run(tc.name, func(t *testing.T) {
blocked, free := issue("be-blocked"), issue("be-free")
raw := newRemoteStore(free)
if tc.present {
raw.ready = append(raw.ready, blocked)
}
blockOnPayments(raw, blocked.ID)
raw.getErrs = map[string]error{blocked.ID: tc.readErr}
closer, err := testStore(raw, &fakeStore{}, true).BatchCloser()
if err != nil {
t.Fatalf("BatchCloser: %v", err)
}
result, err := closer.CloseBatch(t.Context(), publicops.CloseBatchRequest{Actor: "worker", Items: closeItems(blocked.ID, free.ID)})
if err != nil {
t.Fatalf("CloseBatch: %v", err)
}
if len(result.Outcomes) != 2 || result.Outcomes[0].IssueID != blocked.ID || !errors.Is(result.Outcomes[0].Err, tc.wantErr) || result.Outcomes[1].Err != nil {
t.Fatalf("outcomes = %+v; want be-blocked answered %v and be-free closed", result.Outcomes, tc.wantErr)
}
if blocked.Status != types.StatusOpen {
t.Fatalf("be-blocked is %s, want it still open", blocked.Status)
}
if want := [][]string{tc.wantServed}; !slices.EqualFunc(raw.closes, want, slices.Equal[[]string]) {
t.Fatalf("served closes = %v, want %v", raw.closes, want)
}
})
}
}
// TestRemoteBatchCloserRefusesANextClaim: the served batch close cannot carry
// a next claim, so a batch with one is refused whole, the same way whether the
// workspace holds an open holder of an external ref, only a closed one, or
// none, and with Force too. The refusal leads with that wire fact, reads
// nothing, closes nothing and names the commands that do the same work. A
// server that enforces the policy itself gets the request as it came, and its
// closer answers.
func TestRemoteBatchCloserRefusesANextClaim(t *testing.T) {
for _, tc := range []struct {
name string
holder types.Status
force bool
enforced bool
wantServed []string
}{
{name: "open holder", holder: types.StatusOpen},
{name: "closed holder", holder: types.StatusClosed},
{name: "no holder"},
{name: "force", holder: types.StatusOpen, force: true},
{name: "server enforces", holder: types.StatusOpen, enforced: true, wantServed: []string{"CloseBatch ClaimNext"}},
} {
t.Run(tc.name, func(t *testing.T) {
free, holder := issue("be-free"), issue("be-holder")
raw := newRemoteStore(free, holder)
raw.enforced = tc.enforced
if tc.holder != "" {
holder.Status = tc.holder
blockOnPayments(raw, holder.ID)
}
closer, err := testStore(raw, &fakeStore{}, true).BatchCloser()
if err != nil {
t.Fatalf("BatchCloser: %v", err)
}
_, err = closer.CloseBatch(t.Context(), publicops.CloseBatchRequest{
Actor: "worker", Force: tc.force, Items: closeItems(free.ID), ClaimNext: &publicops.ReadyRequest{},
})
if tc.enforced {
if !errors.Is(err, errServedClaimNextRefused) {
t.Fatalf("CloseBatch with ClaimNext = %v, want the served closer's answer", err)
}
} else {
var unsupported *storage.ErrUnsupported
if !errors.As(err, &unsupported) || unsupported.Op != "CloseBatchRequest.ClaimNext" {
t.Fatalf("CloseBatch with ClaimNext = %v, want the CloseBatchRequest.ClaimNext refusal", err)
}
if msg := err.Error(); !strings.Contains(msg, "cannot carry a next claim") || !strings.Contains(msg, "nothing was closed") || !strings.Contains(msg, "then run `bd ready --claim`") {
t.Fatalf("refusal %q does not say why, that nothing closed, and what to run instead", msg)
}
}
if !slices.Equal(raw.served, tc.wantServed) {
t.Fatalf("served calls = %v, want %v", raw.served, tc.wantServed)
}
if len(raw.closes) != 0 || len(raw.edgeReads) != 0 || raw.scans != 0 {
t.Fatalf("closes %v, edge reads %v, scans %d; want none", raw.closes, raw.edgeReads, raw.scans)
}
})
}
}
// TestRemoteBatchCloserValidatesANextClaimFirst: a next claim that is invalid
// on every backend is ErrValidation, not the refusal.
func TestRemoteBatchCloserValidatesANextClaimFirst(t *testing.T) {
for name, claim := range map[string]*publicops.ReadyRequest{
"offset": {Offset: 1},
"bad sort": {Sort: "bogus"},
} {
t.Run(name, func(t *testing.T) {
raw := newRemoteStore(issue("be-free"))
closer, err := testStore(raw, &fakeStore{}, true).BatchCloser()
if err != nil {
t.Fatalf("BatchCloser: %v", err)
}
_, err = closer.CloseBatch(t.Context(), publicops.CloseBatchRequest{
Actor: "worker", Items: closeItems("be-free"), ClaimNext: claim,
})
var unsupported *storage.ErrUnsupported
if !errors.Is(err, storage.ErrValidation) || errors.As(err, &unsupported) {
t.Fatalf("CloseBatch with ClaimNext %+v = %v, want ErrValidation", claim, err)
}
})
}
}

View file

@ -3,634 +3,357 @@ package externaldeps
import (
"context"
"errors"
"fmt"
"slices"
"strings"
"testing"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/storage/uow"
"github.com/steveyegge/beads/internal/types"
publicops "github.com/steveyegge/beads/issueops"
"github.com/steveyegge/beads/issueops"
)
// remoteStore models httpclient.Store for remote_roles.go. Each role it hands
// out is served over the embedded fakeStore's rows, the way a server that
// knows nothing of the policy answers it, and each legacy method a base
// accessor builds on is refused, so a composition that reaches one fails the
// test instead of passing on a fake that answers it. Like httpclient.Store it
// cannot express ExcludeIDs and has no BatchCloserWithPolicy.
type remoteStore struct {
func pageOf(hasMore bool, ids ...string) issueops.IssuePage {
items := make([]*issueops.IssueWithCounts, 0, len(ids))
for _, id := range ids {
items = append(items, &issueops.IssueWithCounts{Issue: &types.Issue{ID: id}})
}
return issueops.IssuePage{Items: items, HasMore: hasMore}
}
func idsOf(page issueops.IssuePage) string {
ids := make([]string, 0, len(page.Items))
for _, row := range page.Items {
ids = append(ids, row.ID)
}
return strings.Join(ids, ",")
}
// TestExcludeAndPage pins the client-side half of the remote ready
// exclusion: drop the blocked rows from the widened window, then cut the
// caller's own page, with an honest HasMore.
func TestExcludeAndPage(t *testing.T) {
blocked := map[string]bool{"b1": true, "b2": true}
for _, tc := range []struct {
name string
window issueops.IssuePage
offset int
limit int
wantIDs string
wantHasMore bool
}{
{"blocked rows leave the page full", pageOf(false, "b1", "a", "b2", "c", "d"), 0, 2, "a,c", true},
{"offset counts unblocked rows only", pageOf(false, "a", "b1", "c", "d"), 1, 2, "c,d", false},
{"unlimited keeps every unblocked row", pageOf(false, "a", "b1", "c"), 0, 0, "a,c", false},
{"a server-truncated window keeps HasMore", pageOf(true, "a", "b1"), 0, 5, "a", true},
{"an offset past the end is an empty page", pageOf(false, "a"), 3, 2, "", false},
} {
t.Run(tc.name, func(t *testing.T) {
got := excludeAndPage(tc.window, blocked, tc.offset, tc.limit)
if idsOf(got) != tc.wantIDs || got.HasMore != tc.wantHasMore {
t.Errorf("got %q hasMore=%v, want %q hasMore=%v", idsOf(got), got.HasMore, tc.wantIDs, tc.wantHasMore)
}
if got.Items == nil {
t.Error("an empty page must be an empty slice, not nil")
}
})
}
}
func TestWidenedLimit(t *testing.T) {
if got := *widenedLimit(3, 10, 2); got != 15 {
t.Errorf("widenedLimit(3,10,2) = %d, want 15", got)
}
if got := *widenedLimit(3, 0, 2); got != 0 {
t.Errorf("an unlimited read stays unlimited, got %d", got)
}
}
// remoteFake is a remote backend (storage.RemoteBackendStore) whose legacy
// method seam is the embedded fakeStore's and whose reader role is its own:
// remoteReader must be reached through the decorator's IssueReader, and the
// fake's legacy ready reads are never consulted by it.
type remoteFake struct {
*fakeStore
// served logs each served role call, in order.
served []string
// closes logs the item ids of each served batch close.
closes [][]string
// edgeReads logs how many anchors each served edge read named.
edgeReads []int
// scans counts the whole-workspace dependency scans read through it.
scans int
// localBlockers is the served annotation's own BlockedBy, per id.
localBlockers map[string][]string
// claimErr, when set, answers every served Claim.
claimErr error
reader *recordingReader
}
var errLegacyRefused = errors.New("remoteStore: legacy method refused")
func (r *remoteFake) IsRemoteBackendStore() bool { return true }
// wireEdgeAnchorCap is the most anchors the wire's listDependencies accepts.
const wireEdgeAnchorCap = 100
func (r *remoteFake) IssueReader() (issueops.Reader, error) { return r.reader, nil }
func newRemoteStore(ready ...*types.Issue) *remoteStore {
return &remoteStore{fakeStore: &fakeStore{
ready: ready,
deps: make(map[string][]*types.Dependency),
excludeIDsUnsupported: true,
}}
// recordingReader serves a fixed ready set in order and records the limits it
// was asked for, so the widened window is observable.
type recordingReader struct {
ready []string
limits []int
lists int
}
func (r *remoteStore) IsRemoteBackendStore() bool { return true }
// httpclient.Store serves the vocabulary a listing loads before its search.
func (r *remoteStore) GetCustomStatusesDetailed(context.Context) ([]types.CustomStatus, error) {
return nil, nil
}
func (r *remoteStore) GetCustomTypes(context.Context) ([]string, error) { return nil, nil }
func (r *remoteStore) GetInfraTypes(context.Context) map[string]bool { return nil }
func (r *remoteStore) SearchIssuesWithCounts(context.Context, string, types.IssueFilter) ([]*types.IssueWithCounts, error) {
return nil, errLegacyRefused
}
func (r *remoteStore) IsBlocked(context.Context, string) (bool, []string, error) {
return false, nil, errLegacyRefused
}
func (r *remoteStore) GetDependencyRecordsForIssues(context.Context, []string) (map[string][]*types.Dependency, error) {
return nil, errLegacyRefused
}
func (r *remoteStore) GetDependencyTree(context.Context, string, int, bool, bool) ([]*types.TreeNode, error) {
return nil, errLegacyRefused
}
func (r *remoteStore) ClaimReadyIssue(context.Context, types.WorkFilter, string) (*types.Issue, error) {
return nil, errLegacyRefused
}
func (r *remoteStore) GetAllDependencyRecords(ctx context.Context) (map[string][]*types.Dependency, error) {
r.scans++
return r.fakeStore.GetAllDependencyRecords(ctx)
}
func (r *remoteStore) GetExternalBlockingDependencyRecords(ctx context.Context) (map[string][]*types.Dependency, error) {
r.scans++
return r.fakeStore.GetExternalBlockingDependencyRecords(ctx)
}
func (r *remoteStore) IssueReader() (publicops.Reader, error) { return servedReader{r}, nil }
func (r *remoteStore) IssueClaimer() (publicops.Claimer, error) { return servedClaimer{r}, nil }
func (r *remoteStore) ReadyClaimer() (publicops.ReadyClaimer, error) {
return servedReadyClaimer{r}, nil
}
func (r *remoteStore) TreeWalker() (publicops.TreeWalker, error) { return servedWalker{r}, nil }
func (r *remoteStore) EdgeReader() (publicops.EdgeReader, error) { return servedEdgeReader{r}, nil }
func (r *remoteStore) BatchCloser() (publicops.BatchCloser, error) { return servedCloser{r}, nil }
func (r *remoteStore) BlockingAnnotator() (publicops.BlockingAnnotator, error) {
return servedAnnotator{r}, nil
}
type servedReader struct{ s *remoteStore }
func (r servedReader) Ready(context.Context, publicops.ReadyRequest) (publicops.IssuePage, error) {
return publicops.IssuePage{}, errors.New("served Ready: ready work is the policy reader's to answer")
}
func (r servedReader) List(context.Context, publicops.ListRequest) (publicops.IssuePage, error) {
r.s.served = append(r.s.served, "List")
items := make([]*types.IssueWithCounts, 0, len(r.s.ready))
for _, issue := range r.s.ready {
items = append(items, &types.IssueWithCounts{Issue: issue})
func (r *recordingReader) Ready(_ context.Context, req issueops.ReadyRequest) (issueops.IssuePage, error) {
limit := 0
if req.Limit != nil {
limit = *req.Limit
}
return publicops.IssuePage{Items: items}, nil
r.limits = append(r.limits, limit)
ids := r.ready[req.Offset:]
hasMore := false
if limit > 0 && len(ids) > limit {
ids, hasMore = ids[:limit], true
}
return pageOf(hasMore, ids...), nil
}
func (r servedReader) Get(ctx context.Context, req publicops.GetRequest) (*publicops.IssueDetails, error) {
r.s.served = append(r.s.served, "Get "+req.ID)
issue, err := r.s.GetIssue(ctx, req.ID)
func (r *recordingReader) List(context.Context, issueops.ListRequest) (issueops.IssuePage, error) {
r.lists++
return pageOf(false, r.ready...), nil
}
func (r *recordingReader) Get(context.Context, issueops.GetRequest) (*issueops.IssueDetails, error) {
return nil, issueops.ErrNotFound
}
func newRemotePolicyStore(enforced bool) (*Store, *recordingReader) {
reader := &recordingReader{ready: []string{"be-x", "be-a", "be-b"}}
raw := &remoteFake{
fakeStore: &fakeStore{
enforced: enforced,
deps: map[string][]*types.Dependency{
"be-x": {externalDep("be-x", "external:remote:payments", types.DepBlocks)},
},
},
reader: reader,
}
store := New(raw, func(ProjectName) (string, bool) { return "", false }, nil)
store.warnProject = nil
return store, reader
}
// TestRemoteReaderReadyExcludesExternallyBlocked is the role-level half of
// S6c's ready exclusion (bd ready itself reads through the legacy seam): the
// reader the decorator hands out for a remote store drops the externally
// blocked row from a widened window and still fills the page.
func TestRemoteReaderReadyExcludesExternallyBlocked(t *testing.T) {
store, reader := newRemotePolicyStore(false)
rd, err := store.IssueReader()
if err != nil {
return nil, err
t.Fatal(err)
}
if issue == nil {
return nil, publicops.ErrNotFound
if _, ok := rd.(*remoteReader); !ok {
t.Fatalf("IssueReader over a remote store = %T, want the inner role passed through", rd)
}
one := 1
page, err := rd.Ready(t.Context(), issueops.ReadyRequest{Limit: &one})
if err != nil {
t.Fatal(err)
}
if idsOf(page) != "be-a" || !page.HasMore {
t.Errorf("Ready(limit 1) = %q hasMore=%v, want \"be-a\" with more", idsOf(page), page.HasMore)
}
if len(reader.limits) != 1 || reader.limits[0] != 2 {
t.Errorf("inner ready limits = %v, want one read widened to 2", reader.limits)
}
if _, err := rd.List(t.Context(), issueops.ListRequest{}); err != nil || reader.lists != 1 {
t.Errorf("an ordinary List did not pass through: lists=%d err=%v", reader.lists, err)
}
return &publicops.IssueDetails{Issue: *issue}, nil
}
type servedClaimer struct{ s *remoteStore }
func (c servedClaimer) Claim(ctx context.Context, req publicops.ClaimRequest) (publicops.ClaimResult, error) {
c.s.served = append(c.s.served, "Claim "+req.IssueID)
if c.s.claimErr != nil {
return publicops.ClaimResult{}, c.s.claimErr
// TestRemoteReaderReadyPassesThroughWhenServerEnforces: a server that
// advertises the policy has applied it; the client neither filters nor widens.
func TestRemoteReaderReadyPassesThroughWhenServerEnforces(t *testing.T) {
store, reader := newRemotePolicyStore(true)
rd, err := store.IssueReader()
if err != nil {
t.Fatal(err)
}
if err := c.s.ClaimIssue(ctx, req.IssueID, req.Actor); err != nil {
return publicops.ClaimResult{}, err
two := 2
page, err := rd.Ready(t.Context(), issueops.ReadyRequest{Limit: &two})
if err != nil {
t.Fatal(err)
}
if idsOf(page) != "be-x,be-a" || reader.limits[0] != 2 {
t.Errorf("Ready = %q (limits %v), want the server's page untouched", idsOf(page), reader.limits)
}
issue, err := c.s.GetIssue(ctx, req.IssueID)
return publicops.ClaimResult{Issue: issue, Changed: true}, err
}
// servedReadyClaimer claims the first unassigned ready row, blind to the
// policy as a claim-next with no exclusion parameter is.
type servedReadyClaimer struct{ s *remoteStore }
type recordingClaimer struct{ claimed []string }
func (c servedReadyClaimer) ClaimNext(ctx context.Context, req publicops.ClaimNextRequest) (publicops.ClaimNextResult, error) {
c.s.served = append(c.s.served, "ClaimNext")
for _, issue := range c.s.ready {
if issue.Assignee != "" {
continue
}
if err := c.s.ClaimIssue(ctx, issue.ID, req.Actor); err != nil {
return publicops.ClaimNextResult{}, err
}
return publicops.ClaimNextResult{Claimed: &types.IssueWithCounts{Issue: issue}}, nil
}
return publicops.ClaimNextResult{}, nil
func (c *recordingClaimer) Claim(_ context.Context, req issueops.ClaimRequest) (issueops.ClaimResult, error) {
c.claimed = append(c.claimed, req.IssueID)
return issueops.ClaimResult{Issue: &types.Issue{ID: req.IssueID}, Changed: true}, nil
}
type servedAnnotator struct{ s *remoteStore }
// remoteClaimFake adds the claim and edge roles a remote claim check uses.
type remoteClaimFake struct {
*remoteFake
claimer *recordingClaimer
}
func (a servedAnnotator) AnnotateBlocking(_ context.Context, req publicops.BlockingRequest) (publicops.BlockingResult, error) {
a.s.served = append(a.s.served, "AnnotateBlocking")
items := make([]publicops.IssueBlocking, 0, len(req.IDs))
func (r *remoteClaimFake) IssueClaimer() (issueops.Claimer, error) { return r.claimer, nil }
func (r *remoteClaimFake) EdgeReader() (issueops.EdgeReader, error) { return fakeEdges{r.deps}, nil }
type fakeEdges struct {
deps map[string][]*types.Dependency
}
func (f fakeEdges) ReadEdges(_ context.Context, req issueops.EdgeReadRequest) (issueops.EdgeReadResult, error) {
out := issueops.EdgeReadResult{}
for _, id := range req.IDs {
items = append(items, publicops.IssueBlocking{ID: id, BlockedBy: slices.Clone(a.s.localBlockers[id])})
out.Anchors = append(out.Anchors, issueops.AnchorEdges{ID: id, Edges: f.deps[id]})
}
return publicops.BlockingResult{Items: items}, nil
return out, nil
}
type servedWalker struct{ s *remoteStore }
func (w servedWalker) WalkTree(context.Context, publicops.WalkTreeRequest) (publicops.TreeResult, error) {
w.s.served = append(w.s.served, "WalkTree")
return publicops.TreeResult{Nodes: slices.Clone(w.s.tree)}, nil
}
type servedEdgeReader struct{ s *remoteStore }
func (e servedEdgeReader) ReadEdges(_ context.Context, req publicops.EdgeReadRequest) (publicops.EdgeReadResult, error) {
if len(req.IDs) > wireEdgeAnchorCap {
return publicops.EdgeReadResult{}, fmt.Errorf("served ReadEdges: %d anchors, past the wire's %d", len(req.IDs), wireEdgeAnchorCap)
// TestRemoteClaimerRefusesExternallyBlocked pins the direct-claim guard of
// the remote composition (the CLI's own `update --claim` goes through the
// lifecycle guard instead; this role is what bd serve and library callers
// reach), reading only the claimed issue's edges.
func TestRemoteClaimerRefusesExternallyBlocked(t *testing.T) {
store, _ := newRemotePolicyStore(false)
raw := &remoteClaimFake{remoteFake: store.inner.(*remoteFake), claimer: &recordingClaimer{}}
store = New(raw, func(ProjectName) (string, bool) { return "", false }, nil)
store.warnProject = nil
claimer, err := store.IssueClaimer()
if err != nil {
t.Fatal(err)
}
e.s.edgeReads = append(e.s.edgeReads, len(req.IDs))
anchors := make([]publicops.AnchorEdges, 0, len(req.IDs))
for _, id := range req.IDs {
anchors = append(anchors, publicops.AnchorEdges{ID: id, Edges: e.s.deps[id]})
if _, err := claimer.Claim(t.Context(), issueops.ClaimRequest{Actor: "a", IssueID: "be-x"}); !errors.Is(err, storage.ErrCloseBlocked) {
t.Errorf("claim of the externally blocked be-x: err = %v, want ErrCloseBlocked", err)
}
return publicops.EdgeReadResult{Anchors: anchors}, nil
}
type servedCloser struct{ s *remoteStore }
// errServedClaimNextRefused is the served closer's answer to a next claim.
// httpclient refuses one on every server: the v0 wire's batch close has no
// member to carry it (ledger row W-CloseBatchRequest.ClaimNext).
var errServedClaimNextRefused = &storage.ErrUnsupported{Op: "BatchCloser.CloseBatch", Backend: "http"}
func (c servedCloser) CloseBatch(ctx context.Context, req publicops.CloseBatchRequest) (publicops.CloseBatchResult, error) {
if req.ClaimNext != nil {
c.s.served = append(c.s.served, "CloseBatch ClaimNext")
return publicops.CloseBatchResult{}, errServedClaimNextRefused
if _, err := claimer.Claim(t.Context(), issueops.ClaimRequest{Actor: "a", IssueID: "be-a"}); err != nil {
t.Errorf("claim of the unblocked be-a: %v", err)
}
ids := make([]string, 0, len(req.Items))
outcomes := make([]publicops.CloseOutcome, 0, len(req.Items))
for _, item := range req.Items {
ids = append(ids, item.IssueID)
result, err := c.s.CloseIssueChecked(ctx, item.IssueID, req.Actor, storage.CloseIssueOptions{})
outcomes = append(outcomes, publicops.CloseOutcome{IssueID: item.IssueID, Changed: err == nil && !result.Unchanged, Err: err})
}
c.s.closes = append(c.s.closes, ids)
return publicops.CloseBatchResult{Outcomes: outcomes}, nil
}
const paymentsRef = "external:remote:payments"
func blockOnPayments(raw *remoteStore, ids ...string) {
for _, id := range ids {
raw.deps[id] = []*types.Dependency{externalDep(id, paymentsRef, types.DepBlocks)}
if strings.Join(raw.claimer.claimed, ",") != "be-a" {
t.Errorf("server claims = %v, want only be-a", raw.claimer.claimed)
}
}
func closeItems(ids ...string) []publicops.BatchCloseItem {
items := make([]publicops.BatchCloseItem, 0, len(ids))
for _, id := range ids {
items = append(items, publicops.BatchCloseItem{IssueID: id})
}
return items
// passthroughFake is a remote store whose policy-bearing roles all record
// their calls, and whose edge reader fails the test if read: against a server
// that applies the policy, the client must neither read edges nor run its own
// read-then-claim loop.
type passthroughFake struct {
*remoteFake
claimer *recordingClaimer
claimNexts int
counts int
closes int
edgeReads int
}
// TestRemoteRolesAnswerWithoutTheLegacyMethods pins the blocker the base
// accessors had over httpclient.Store: built over legacy methods a remote
// store refuses, they failed bd list, bd show, bd dep tree, bd ready --claim
// and bd close in a workspace where nothing had an external dependency.
func TestRemoteRolesAnswerWithoutTheLegacyMethods(t *testing.T) {
a, b := issue("be-a"), issue("be-b")
raw := newRemoteStore(a, b)
raw.tree = []*types.TreeNode{{Issue: *a}}
store := testStore(raw, &fakeStore{}, true)
func (p *passthroughFake) IssueClaimer() (issueops.Claimer, error) { return p.claimer, nil }
func (p *passthroughFake) EdgeReader() (issueops.EdgeReader, error) { return countingEdges{p}, nil }
func (p *passthroughFake) ReadyClaimer() (issueops.ReadyClaimer, error) { return p, nil }
func (p *passthroughFake) ReadyCounter() (issueops.ReadyCounter, error) { return p, nil }
func (p *passthroughFake) BatchCloser() (issueops.BatchCloser, error) { return p, nil }
func (p *passthroughFake) ClaimNext(context.Context, issueops.ClaimNextRequest) (issueops.ClaimNextResult, error) {
p.claimNexts++
return issueops.ClaimNextResult{Claimed: &issueops.IssueWithCounts{Issue: &types.Issue{ID: "be-x"}}}, nil
}
func (p *passthroughFake) CountReady(context.Context, issueops.ReadyRequest) (issueops.ReadyCountResult, error) {
p.counts++
return issueops.ReadyCountResult{Total: 3}, nil
}
func (p *passthroughFake) CloseBatch(_ context.Context, req issueops.CloseBatchRequest) (issueops.CloseBatchResult, error) {
p.closes++
return issueops.CloseBatchResult{Outcomes: make([]issueops.CloseOutcome, len(req.Items))}, nil
}
type countingEdges struct{ p *passthroughFake }
func (c countingEdges) ReadEdges(context.Context, issueops.EdgeReadRequest) (issueops.EdgeReadResult, error) {
c.p.edgeReads++
return issueops.EdgeReadResult{}, nil
}
// TestRemoteRolesPassThroughWhenServerEnforces pins the advertised half of
// design 3.6 at the role level: every policy-bearing role over a server that
// advertises policy.external_dependencies is the server's own operation,
// untouched. In particular claim-next is ONE call to the server's atomic
// ClaimNext, even though the client's own view would call be-x blocked.
func TestRemoteRolesPassThroughWhenServerEnforces(t *testing.T) {
base, reader := newRemotePolicyStore(true)
raw := &passthroughFake{remoteFake: base.inner.(*remoteFake), claimer: &recordingClaimer{}}
store := New(raw, func(ProjectName) (string, bool) { return "", false }, nil)
store.warnProject = nil
ctx := t.Context()
reader, err := store.IssueReader()
rc, err := store.ReadyClaimer()
if err != nil {
t.Fatalf("IssueReader: %v", err)
t.Fatal(err)
}
if page, err := reader.List(ctx, publicops.ListRequest{}); err != nil || len(page.Items) != 2 {
t.Fatalf("List = %d items, %v; want 2", len(page.Items), err)
res, err := rc.ClaimNext(ctx, issueops.ClaimNextRequest{Actor: "a"})
if err != nil || res.Claimed == nil || res.Claimed.ID != "be-x" {
t.Errorf("ClaimNext = %+v, %v; want the server's own answer", res, err)
}
if details, err := reader.Get(ctx, publicops.GetRequest{ID: a.ID}); err != nil || details.ID != a.ID {
t.Fatalf("Get = %v, %v; want %s", details, err, a.ID)
}
if page, err := reader.Ready(ctx, publicops.ReadyRequest{}); err != nil || len(page.Items) != 2 {
t.Fatalf("Ready = %d items, %v; want 2", len(page.Items), err)
if raw.claimNexts != 1 || len(reader.limits) != 0 || len(raw.claimer.claimed) != 0 {
t.Errorf("claim-next: server ClaimNext calls=%d, ready reads=%v, by-id claims=%v; want one atomic call and nothing else",
raw.claimNexts, reader.limits, raw.claimer.claimed)
}
claimer, err := store.IssueClaimer()
if err != nil {
t.Fatalf("IssueClaimer: %v", err)
t.Fatal(err)
}
if _, err := claimer.Claim(ctx, publicops.ClaimRequest{Actor: "worker", IssueID: a.ID}); err != nil {
t.Fatalf("Claim: %v", err)
}
readyClaimer, err := store.ReadyClaimer()
if err != nil {
t.Fatalf("ReadyClaimer: %v", err)
}
if next, err := readyClaimer.ClaimNext(ctx, publicops.ClaimNextRequest{Actor: "worker"}); err != nil || next.Claimed == nil || next.Claimed.ID != b.ID {
t.Fatalf("ClaimNext = %+v, %v; want %s", next.Claimed, err, b.ID)
}
annotator, err := store.BlockingAnnotator()
if err != nil {
t.Fatalf("BlockingAnnotator: %v", err)
}
if result, err := annotator.AnnotateBlocking(ctx, publicops.BlockingRequest{IDs: []string{a.ID, b.ID}}); err != nil || len(result.Items) != 2 {
t.Fatalf("AnnotateBlocking = %+v, %v; want 2 items", result.Items, err)
}
walker, err := store.TreeWalker()
if err != nil {
t.Fatalf("TreeWalker: %v", err)
}
if tree, err := walker.WalkTree(ctx, publicops.WalkTreeRequest{RootID: a.ID, MaxDepth: 50}); err != nil || len(tree.Nodes) != 1 {
t.Fatalf("WalkTree = %d nodes, %v; want the served root alone", len(tree.Nodes), err)
if _, err := claimer.Claim(ctx, issueops.ClaimRequest{Actor: "a", IssueID: "be-x"}); err != nil {
t.Errorf("claim of be-x against an enforcing server: %v; want the server to judge it", err)
}
closer, err := store.BatchCloser()
if err != nil {
t.Fatalf("BatchCloser: %v", err)
t.Fatal(err)
}
result, err := closer.CloseBatch(ctx, publicops.CloseBatchRequest{Actor: "worker", Items: closeItems(a.ID, b.ID)})
if err != nil || len(result.Outcomes) != 2 {
t.Fatalf("CloseBatch = %+v, %v; want 2 outcomes", result.Outcomes, err)
if _, err := closer.CloseBatch(ctx, issueops.CloseBatchRequest{Actor: "a", Items: []issueops.BatchCloseItem{{IssueID: "be-x"}}}); err != nil || raw.closes != 1 {
t.Errorf("close of be-x: closes=%d err=%v; want one server batch close", raw.closes, err)
}
if want := []string{"List", "Get be-a", "Claim be-a", "ClaimNext", "AnnotateBlocking", "WalkTree"}; !slices.Equal(raw.served, want) {
t.Fatalf("served calls = %v, want %v", raw.served, want)
}
if want := [][]string{{a.ID, b.ID}}; !slices.EqualFunc(raw.closes, want, slices.Equal[[]string]) {
t.Fatalf("served closes = %v, want %v", raw.closes, want)
}
}
// TestRemoteReaderPolicesReadyWorkOnly: an externally blocked issue leaves the
// ready listing and stays in a plain one, which claims nothing about
// readiness.
func TestRemoteReaderPolicesReadyWorkOnly(t *testing.T) {
a, b := issue("be-a"), issue("be-b")
raw := newRemoteStore(a, b)
blockOnPayments(raw, a.ID)
reader, err := testStore(raw, &fakeStore{}, true).IssueReader()
counter, err := store.ReadyCounter()
if err != nil {
t.Fatalf("IssueReader: %v", err)
t.Fatal(err)
}
if got, err := counter.CountReady(ctx, issueops.ReadyRequest{}); err != nil || got.Total != 3 || raw.counts != 1 {
t.Errorf("CountReady = %+v, %v (server counts %d); want the server's count", got, err, raw.counts)
}
ready, err := reader.Ready(t.Context(), publicops.ReadyRequest{})
if err != nil {
t.Fatalf("Ready: %v", err)
}
if len(ready.Items) != 1 || ready.Items[0].ID != b.ID {
t.Fatalf("Ready = %d items, want %s alone (%s is externally blocked)", len(ready.Items), b.ID, a.ID)
}
listed, err := reader.List(t.Context(), publicops.ListRequest{})
if err != nil {
t.Fatalf("List: %v", err)
}
if len(listed.Items) != 2 {
t.Fatalf("List = %d items, want both", len(listed.Items))
if raw.edgeReads != 0 {
t.Errorf("the client read edges %d times against a server that applies the policy", raw.edgeReads)
}
}
func TestRemoteClaimerRefusesExternallyBlockedWork(t *testing.T) {
for _, enforced := range []bool{false, true} {
t.Run(fmt.Sprintf("server enforces %v", enforced), func(t *testing.T) {
a := issue("be-a")
raw := newRemoteStore(a)
raw.enforced = enforced
blockOnPayments(raw, a.ID)
claimer, err := testStore(raw, &fakeStore{}, true).IssueClaimer()
if err != nil {
t.Fatalf("IssueClaimer: %v", err)
}
_, err = claimer.Claim(t.Context(), publicops.ClaimRequest{Actor: "worker", IssueID: a.ID})
if enforced {
// The server already applied the policy, so the claim is its
// to answer.
if err != nil || !slices.Equal(raw.served, []string{"Claim be-a"}) {
t.Fatalf("Claim = %v, served %v; want the served claim", err, raw.served)
}
return
}
if !errors.Is(err, storage.ErrCloseBlocked) || !strings.Contains(err.Error(), paymentsRef) {
t.Fatalf("Claim = %v, want ErrCloseBlocked naming %s", err, paymentsRef)
}
if len(raw.served) != 0 {
t.Fatalf("served calls = %v, want none for a refused claim", raw.served)
}
})
// TestAppliedFindsThePolicyLayer pins what bd serve reads to decide whether to
// advertise policy.external_dependencies: the decorator anywhere in the chain
// counts, its absence does not.
func TestAppliedFindsThePolicyLayer(t *testing.T) {
raw := &fakeStore{}
if Applied(raw) || Applied(nil) {
t.Error("a chain without the policy layer reports it applied")
}
if !Applied(New(raw, nil, nil)) {
t.Error("the policy decorator itself is not reported applied")
}
if !Applied(storage.NewHookFiringStore(New(raw, nil, nil), nil)) {
t.Error("the policy decorator beneath the hook layer is not found")
}
plain := &fakeUOWProvider{}
if AppliedToProvider(nil) || AppliedToProvider(plain) {
t.Error("a provider chain without the policy layer reports it applied")
}
wrapped := WrapUOWProvider(plain, nil, nil)
if !AppliedToProvider(wrapped) {
t.Error("WrapUOWProvider's layer is not reported applied")
}
if !AppliedToProvider(uow.NewNotifyingProvider(wrapped, uow.Sinks{Hook: noHooks{}})) {
t.Error("the policy layer beneath a notifying provider is not found")
}
}
// TestRemoteReadyClaimerSkipsExternallyBlockedWork: the served claim-next
// cannot be told what to skip, so with anything externally blocked the claim
// walks the policy's ready page through the served Claimer instead. be-a sorts
// first, where the served claim-next would take it.
func TestRemoteReadyClaimerSkipsExternallyBlockedWork(t *testing.T) {
a, b := issue("be-a"), issue("be-b")
raw := newRemoteStore(a, b)
blockOnPayments(raw, a.ID)
claimer, err := testStore(raw, &fakeStore{}, true).ReadyClaimer()
if err != nil {
t.Fatalf("ReadyClaimer: %v", err)
}
type noHooks struct{}
next, err := claimer.ClaimNext(t.Context(), publicops.ClaimNextRequest{Actor: "worker"})
if err != nil {
t.Fatalf("ClaimNext: %v", err)
}
if next.Claimed == nil || next.Claimed.ID != b.ID || b.Assignee != "worker" {
t.Fatalf("ClaimNext claimed %+v, want %s for worker", next.Claimed, b.ID)
}
if want := []string{"Claim be-b"}; !slices.Equal(raw.served, want) {
t.Fatalf("served calls = %v, want %v", raw.served, want)
}
}
// TestRemoteReadyClaimerReportsLostRaces: a front that had work but lost every
// candidate is an error, not the empty answer that means there is no work.
func TestRemoteReadyClaimerReportsLostRaces(t *testing.T) {
a, b := issue("be-a"), issue("be-b")
raw := newRemoteStore(a, b)
blockOnPayments(raw, a.ID)
raw.claimErr = storage.ErrAlreadyClaimed
claimer, err := testStore(raw, &fakeStore{}, true).ReadyClaimer()
if err != nil {
t.Fatalf("ReadyClaimer: %v", err)
}
next, err := claimer.ClaimNext(t.Context(), publicops.ClaimNextRequest{Actor: "worker"})
if err == nil || !strings.Contains(err.Error(), "lost 1 races") || next.Claimed != nil {
t.Fatalf("ClaimNext = %+v, %v; want a lost-races error", next.Claimed, err)
}
}
// TestRemoteBlockingAnnotatorMergesExternalBlockers: the served annotation's
// own blockers stay, the external ones join them, and the edges behind them
// are read in chunks the wire accepts.
func TestRemoteBlockingAnnotatorMergesExternalBlockers(t *testing.T) {
issues := make([]*types.Issue, 0, 150)
ids := make([]string, 0, 150)
for i := range 150 {
issues = append(issues, issue(fmt.Sprintf("be-%03d", i)))
ids = append(ids, issues[i].ID)
}
raw := newRemoteStore(issues...)
blockOnPayments(raw, "be-000", "be-149")
raw.localBlockers = map[string][]string{"be-000": {"be-local"}}
annotator, err := testStore(raw, &fakeStore{}, true).BlockingAnnotator()
if err != nil {
t.Fatalf("BlockingAnnotator: %v", err)
}
result, err := annotator.AnnotateBlocking(t.Context(), publicops.BlockingRequest{IDs: ids})
if err != nil {
t.Fatalf("AnnotateBlocking: %v", err)
}
blockedBy := make(map[string][]string, len(result.Items))
for _, item := range result.Items {
blockedBy[item.ID] = item.BlockedBy
}
if want := []string{"be-local", paymentsRef}; !slices.Equal(blockedBy["be-000"], want) {
t.Errorf("be-000 blocked by %v, want %v", blockedBy["be-000"], want)
}
if want := []string{paymentsRef}; !slices.Equal(blockedBy["be-149"], want) {
t.Errorf("be-149 blocked by %v, want %v", blockedBy["be-149"], want)
}
if len(blockedBy["be-001"]) != 0 {
t.Errorf("be-001 blocked by %v, want nothing", blockedBy["be-001"])
}
if want := []int{100, 50}; !slices.Equal(raw.edgeReads, want) {
t.Errorf("served edge reads named %v anchors, want %v", raw.edgeReads, want)
}
}
// TestRemoteTreeWalkerAddsExternalLeaves: the served down-tree gains the leaf
// its stored edges name, a leaf the server rendered is not repeated, and any
// other walk is the served answer as it came.
func TestRemoteTreeWalkerAddsExternalLeaves(t *testing.T) {
root := &types.TreeNode{Issue: *issue("be-a")}
served := &types.TreeNode{Issue: types.Issue{ID: paymentsRef, Title: "served leaf"}, Depth: 1, ParentID: "be-a"}
for _, tc := range []struct {
name string
req publicops.WalkTreeRequest
tree []*types.TreeNode
wantIDs []string
}{
{name: "down walk", req: publicops.WalkTreeRequest{RootID: "be-a", MaxDepth: 50}, tree: []*types.TreeNode{root}, wantIDs: []string{"be-a", paymentsRef}},
{name: "server rendered the leaf", req: publicops.WalkTreeRequest{RootID: "be-a", MaxDepth: 50}, tree: []*types.TreeNode{root, served}, wantIDs: []string{"be-a", paymentsRef}},
{name: "up walk", req: publicops.WalkTreeRequest{RootID: "be-a", MaxDepth: 50, Direction: publicops.TreeUp}, tree: []*types.TreeNode{root}, wantIDs: []string{"be-a"}},
} {
t.Run(tc.name, func(t *testing.T) {
raw := newRemoteStore()
raw.tree = tc.tree
blockOnPayments(raw, "be-a")
walker, err := testStore(raw, &fakeStore{}, true).TreeWalker()
if err != nil {
t.Fatalf("TreeWalker: %v", err)
}
result, err := walker.WalkTree(t.Context(), tc.req)
if err != nil {
t.Fatalf("WalkTree: %v", err)
}
ids := make([]string, 0, len(result.Nodes))
for _, node := range result.Nodes {
ids = append(ids, node.ID)
}
if !slices.Equal(ids, tc.wantIDs) {
t.Fatalf("tree = %v, want %v", ids, tc.wantIDs)
}
if leaf := result.Nodes[len(result.Nodes)-1]; tc.name == "down walk" {
if leaf.Status != types.StatusOpen || leaf.ParentID != "be-a" || leaf.Depth != 1 || leaf.Title != "○ payments" {
t.Fatalf("leaf = %+v, want the open payments leaf under be-a", leaf)
}
}
})
}
}
// TestRemoteBatchCloserRefusesExternallyBlockedItems: a still-open externally
// blocked item is refused the way the local policy close refuses it and the
// rest close in one served request. An item already closed keeps the served
// answer, Force waives the policy, and a server that enforces the policy gets
// the whole batch.
func TestRemoteBatchCloserRefusesExternallyBlockedItems(t *testing.T) {
for _, tc := range []struct {
name string
force bool
enforced bool
wantRefused bool
}{
{name: "policy", wantRefused: true},
{name: "force", force: true},
{name: "server enforces", enforced: true},
} {
t.Run(tc.name, func(t *testing.T) {
blocked, free, done := issue("be-blocked"), issue("be-free"), issue("be-done")
done.Status = types.StatusClosed
raw := newRemoteStore(blocked, free, done)
raw.enforced = tc.enforced
blockOnPayments(raw, blocked.ID, done.ID)
closer, err := testStore(raw, &fakeStore{}, true).BatchCloser()
if err != nil {
t.Fatalf("BatchCloser: %v", err)
}
request := publicops.CloseBatchRequest{Actor: "worker", Force: tc.force, Items: closeItems(blocked.ID, free.ID, done.ID)}
result, err := closer.CloseBatch(t.Context(), request)
if err != nil {
t.Fatalf("CloseBatch: %v", err)
}
if len(result.Outcomes) != len(request.Items) {
t.Fatalf("CloseBatch answered %d outcomes for %d items", len(result.Outcomes), len(request.Items))
}
for i, outcome := range result.Outcomes {
if outcome.IssueID != request.Items[i].IssueID {
t.Fatalf("outcome %d is %s's, want %s's", i, outcome.IssueID, request.Items[i].IssueID)
}
}
wantServed := []string{blocked.ID, free.ID, done.ID}
if tc.wantRefused {
refusal := result.Outcomes[0].Err
want := "cannot close blocked issue: be-blocked is blocked by [" + paymentsRef + "]"
if !errors.Is(refusal, storage.ErrCloseBlocked) || refusal.Error() != want {
t.Fatalf("be-blocked outcome = %v, want %q", refusal, want)
}
wantServed = []string{free.ID, done.ID}
} else if result.Outcomes[0].Err != nil {
t.Fatalf("be-blocked outcome = %v, want it closed", result.Outcomes[0].Err)
}
if result.Outcomes[1].Err != nil || result.Outcomes[2].Err != nil {
t.Fatalf("be-free, be-done outcomes = %v, %v; want the served answers", result.Outcomes[1].Err, result.Outcomes[2].Err)
}
if want := [][]string{wantServed}; !slices.EqualFunc(raw.closes, want, slices.Equal[[]string]) {
t.Fatalf("served closes = %v, want %v", raw.closes, want)
}
})
}
}
// TestRemoteBatchCloserRefusesANextClaim: the served batch close cannot carry
// a next claim, so a batch with one is refused whole, the same way whether the
// workspace holds an open holder of an external ref, only a closed one, or
// none, and with Force too. The refusal leads with that wire fact, reads
// nothing, closes nothing and names the commands that do the same work. A
// server that enforces the policy itself gets the request as it came, and its
// closer answers.
func TestRemoteBatchCloserRefusesANextClaim(t *testing.T) {
for _, tc := range []struct {
name string
holder types.Status
force bool
enforced bool
wantServed []string
}{
{name: "open holder", holder: types.StatusOpen},
{name: "closed holder", holder: types.StatusClosed},
{name: "no holder"},
{name: "force", holder: types.StatusOpen, force: true},
{name: "server enforces", holder: types.StatusOpen, enforced: true, wantServed: []string{"CloseBatch ClaimNext"}},
} {
t.Run(tc.name, func(t *testing.T) {
free, holder := issue("be-free"), issue("be-holder")
raw := newRemoteStore(free, holder)
raw.enforced = tc.enforced
if tc.holder != "" {
holder.Status = tc.holder
blockOnPayments(raw, holder.ID)
}
closer, err := testStore(raw, &fakeStore{}, true).BatchCloser()
if err != nil {
t.Fatalf("BatchCloser: %v", err)
}
_, err = closer.CloseBatch(t.Context(), publicops.CloseBatchRequest{
Actor: "worker", Force: tc.force, Items: closeItems(free.ID), ClaimNext: &publicops.ReadyRequest{},
})
if tc.enforced {
if !errors.Is(err, errServedClaimNextRefused) {
t.Fatalf("CloseBatch with ClaimNext = %v, want the served closer's answer", err)
}
} else {
var unsupported *storage.ErrUnsupported
if !errors.As(err, &unsupported) || unsupported.Op != "CloseBatchRequest.ClaimNext" {
t.Fatalf("CloseBatch with ClaimNext = %v, want the CloseBatchRequest.ClaimNext refusal", err)
}
if msg := err.Error(); !strings.Contains(msg, "cannot carry a next claim") || !strings.Contains(msg, "nothing was closed") || !strings.Contains(msg, "then run `bd ready --claim`") {
t.Fatalf("refusal %q does not say why, that nothing closed, and what to run instead", msg)
}
}
if !slices.Equal(raw.served, tc.wantServed) {
t.Fatalf("served calls = %v, want %v", raw.served, tc.wantServed)
}
if len(raw.closes) != 0 || len(raw.edgeReads) != 0 || raw.scans != 0 {
t.Fatalf("closes %v, edge reads %v, scans %d; want none", raw.closes, raw.edgeReads, raw.scans)
}
})
}
}
// TestRemoteBatchCloserValidatesANextClaimFirst: a next claim that is invalid
// on every backend is ErrValidation, not the refusal.
func TestRemoteBatchCloserValidatesANextClaimFirst(t *testing.T) {
for name, claim := range map[string]*publicops.ReadyRequest{
"offset": {Offset: 1},
"bad sort": {Sort: "bogus"},
} {
t.Run(name, func(t *testing.T) {
raw := newRemoteStore(issue("be-free"))
closer, err := testStore(raw, &fakeStore{}, true).BatchCloser()
if err != nil {
t.Fatalf("BatchCloser: %v", err)
}
_, err = closer.CloseBatch(t.Context(), publicops.CloseBatchRequest{
Actor: "worker", Items: closeItems("be-free"), ClaimNext: claim,
})
var unsupported *storage.ErrUnsupported
if !errors.Is(err, storage.ErrValidation) || errors.As(err, &unsupported) {
t.Fatalf("CloseBatch with ClaimNext %+v = %v, want ErrValidation", claim, err)
}
})
}
}
func (noHooks) Run(string, *types.Issue) {}

View file

@ -14,18 +14,20 @@ import (
// IssueReader builds the read role on the policy store. In particular, Ready
// and List(ReadyFlag) must call this store's filtered ready methods rather than
// promoted methods on the undecorated store. Over a remote store the served
// reader answers everything else (remote_roles.go).
// promoted methods on the undecorated store.
//
// A remote inner store answers with its own reader instead, with the ready
// exclusion laid over it (remote_roles.go): storereader is built from the
// legacy method seam a remote store only partly serves.
func (s *Store) IssueReader() (issueops.Reader, error) {
policy, err := storereader.New(s)
if err != nil || !s.servesRoles() {
return policy, err
if s.rolesAreRemote() {
inner, err := s.inner.IssueReader()
if err != nil {
return nil, err
}
return &remoteReader{inner: inner, policy: s}, nil
}
served, err := s.inner.IssueReader()
if err != nil {
return nil, err
}
return &remoteReader{served: served, policy: policy}, nil
return storereader.New(s)
}
// IssueClaimer rejects a direct claim of externally blocked work before the
@ -36,8 +38,8 @@ func (s *Store) IssueClaimer() (issueops.Claimer, error) {
if err != nil {
return nil, err
}
if s.servesRoles() {
return &remoteClaimer{served: inner, policy: s}, nil
if s.rolesAreRemote() {
return &remoteClaimer{inner: inner, policy: s}, nil
}
return &issueClaimer{inner: inner, policy: s}, nil
}
@ -61,8 +63,12 @@ func (c *issueClaimer) Claim(ctx context.Context, req issueops.ClaimRequest) (is
// ReadyClaimer keeps external blockers out of the ready-claim selection used
// by HTTP serving. The local compare-and-swap remains inside ClaimReadyIssue.
func (s *Store) ReadyClaimer() (issueops.ReadyClaimer, error) {
if s.servesRoles() {
return &remoteReadyClaimer{policy: s}, nil
if s.rolesAreRemote() {
inner, err := s.inner.ReadyClaimer()
if err != nil {
return nil, err
}
return &remoteReadyClaimer{inner: inner, policy: s}, nil
}
return &readyClaimer{policy: s}, nil
}
@ -103,8 +109,8 @@ func (s *Store) BlockingAnnotator() (issueops.BlockingAnnotator, error) {
if err != nil {
return nil, err
}
if s.servesRoles() {
return &remoteBlockingAnnotator{served: inner, policy: s}, nil
if s.rolesAreRemote() {
return &remoteBlockingAnnotator{inner: inner, policy: s}, nil
}
return &blockingAnnotator{inner: inner, policy: s}, nil
}
@ -139,8 +145,8 @@ func (s *Store) TreeWalker() (issueops.TreeWalker, error) {
if err != nil {
return nil, err
}
if s.servesRoles() {
return &remoteTreeWalker{served: inner, policy: s}, nil
if s.rolesAreRemote() {
return &remoteTreeWalker{inner: inner, policy: s}, nil
}
return &treeWalker{inner: inner, policy: s}, nil
}
@ -151,7 +157,7 @@ type treeWalker struct {
}
func (t *treeWalker) WalkTree(ctx context.Context, req issueops.WalkTreeRequest) (issueops.TreeResult, error) {
if !plainDownTree(req) {
if (req.Direction != "" && req.Direction != issueops.TreeDown) || req.Status != "" || req.MaxRows != 0 {
return t.inner.WalkTree(ctx, req)
}
nodes, err := t.policy.GetDependencyTree(ctx, req.RootID, req.MaxDepth, false, false)

View file

@ -39,6 +39,22 @@ var _ uow.ProviderUnwrapper = (*uowProvider)(nil)
// to HTTP handlers, which must never run workspace hooks.
func (p *uowProvider) Unwrap() uow.UnitOfWorkProvider { return p.UnitOfWorkProvider }
// AppliedToProvider is Applied for the unit-of-work chain: it reports whether
// provider's decorator chain includes WrapUOWProvider's policy layer.
func AppliedToProvider(provider uow.UnitOfWorkProvider) bool {
for provider != nil {
if _, ok := provider.(*uowProvider); ok {
return true
}
u, ok := provider.(uow.ProviderUnwrapper)
if !ok {
return false
}
provider = u.Unwrap()
}
return false
}
// RunNonTx preserves the optional maintenance capability exposed by the
// proxied provider. Wrapping the provider must not make unrelated commands
// such as compact lose access to their pinned connection.

View file

@ -83,6 +83,14 @@ func PreparePublicCreateRequest(request publicops.CreateRequest, context PublicC
if request.DefaultPriority {
issue.Priority = publicops.DefaultCreatePriority
}
// created_by defaults to the request's actor, here and nowhere else: every
// create shape (Lifecycle.Create, BatchCreator items, batch-apply create
// items) prepares through this function, so the CLI, the HTTP handlers and
// a library caller all store the same creator for the same request. An
// explicit CreatedBy is kept.
if issue.CreatedBy == "" {
issue.CreatedBy = request.Actor
}
if issue.ID != "" && !request.ForceIDPrefix {
// The caller's prefix wins when it supplied one; see
// CreateRequest.IDPrefix for why a front door may know better than the

View file

@ -46,6 +46,34 @@ func TestPreparePublicCreateRequestCarriesSourceRepo(t *testing.T) {
}
}
// TestPreparePublicCreateRequestDefaultsCreatedByToTheActor pins the library
// default every create shape shares (Lifecycle.Create, BatchCreator items,
// batch-apply create items): an empty CreatedBy becomes the request's actor,
// and an explicit CreatedBy is kept. Neither the CLI nor an HTTP handler
// stamps it any more, so without this rule a library or wire create stores "".
func TestPreparePublicCreateRequestDefaultsCreatedByToTheActor(t *testing.T) {
for _, tc := range []struct{ name, createdBy, want string }{
{"empty defaults to the actor", "", "actor"},
{"explicit is kept", "someone-else", "someone-else"},
} {
t.Run(tc.name, func(t *testing.T) {
request := publicops.CreateRequest{Actor: "actor", Issue: &publicops.Issue{
ID: "bd-created-by", Title: "title", IssueType: types.TypeTask, Priority: 2, CreatedBy: tc.createdBy,
}}
prepared, err := PreparePublicCreateRequest(request, PublicCreateContext{IssuePrefix: "bd"})
if err != nil {
t.Fatalf("PreparePublicCreateRequest() error = %v", err)
}
if prepared.Issue.CreatedBy != tc.want {
t.Fatalf("prepared CreatedBy = %q, want %q", prepared.Issue.CreatedBy, tc.want)
}
if request.Issue.CreatedBy != tc.createdBy {
t.Fatalf("the caller's request was mutated: CreatedBy = %q, want %q", request.Issue.CreatedBy, tc.createdBy)
}
})
}
}
func TestPublicCreateIssueFieldClassificationIsComplete(t *testing.T) {
accepted := map[string]bool{
"ID": true, "Title": true, "Description": true, "Design": true, "AcceptanceCriteria": true, "Notes": true, "SpecID": true,

View file

@ -1025,16 +1025,45 @@ type ExternalDependencyQueryStore interface {
// RemoteBackendStore is implemented by a DoltStorage that is a pure network
// client of a remote bd serve process (a registered backend whose
// backends.Backend.Remote is true — see internal/storage/backends). It is
// metadata about the store's transport, not a policy decision. Its one in-tree
// consumer is the external-deps decorator, which wraps a remote store like any
// other and reads this marker only to choose how it composes its roles: over a
// remote store it builds each role on the store's own served role instead of
// the legacy methods such a store refuses. Whether the decorator skips its
// client-side enforcement is ExternalDependencyPolicyProber's question.
// metadata about the store's transport, not a policy decision. Such a store
// serves its ROLES natively and only a slice of the legacy DoltStorage
// method seam, so a decorator that builds role views must compose over the
// inner store's roles rather than rebuild them from that seam: the
// external-deps decorator consults it for exactly that (remote_roles.go).
// It never decides whether a policy runs — the decorator asks
// ExternalDependencyPolicyProber whether to skip its client-side enforcement.
type RemoteBackendStore interface {
IsRemoteBackendStore() bool
}
// CallerAttributionLimitedStore is implemented by a DoltStorage whose write
// transport cannot carry two caller-authored attribution members:
//
// - a history entry's Provenance label (UpdateRequest.Provenance,
// ReopenRequest.Provenance), because the serving process labels the
// entries it writes itself;
// - a patch's ClosedBySession, which only the close operation carries.
//
// Its role implementations refuse those members rather than drop them, since a
// library caller may mean them. A front door that knows its own value is
// derivable or advisory — `bd reopen`'s fixed "bd: reopen <id>" label, the
// ambient CLAUDE_SESSION_ID on `bd update -s closed` — omits it for such a
// store instead of failing the write; cmd/bd/remote_backend.go records
// which members it omits and why.
type CallerAttributionLimitedStore interface {
CallerAttributionLimited() bool
}
// Pinger is implemented by a DoltStorage whose cheapest honest liveness check
// is not an issue query. `bd ping` uses it when present and falls back to a
// one-row SearchIssues otherwise. A remote store implements it with its
// authenticated handshake read, which reaches the serving process and checks
// the credential and the workspace pin without touching an issue table its
// legacy method seam may not serve at all.
type Pinger interface {
Ping(ctx context.Context) error
}
// ExternalDependencyPolicyProber is implemented by a DoltStorage that can
// answer whether the remote server it talks to already enforces bd's
// external-dependency policy itself (design 3.6, "External-dependency server

View file

@ -13,6 +13,7 @@ go_library(
importpath = "github.com/steveyegge/beads/internal/utils",
visibility = ["//:__subpackages__"],
deps = [
"//beadserrors",
"//internal/debug",
"//internal/types",
] + select({
@ -29,6 +30,7 @@ go_library(
go_test(
name = "utils_test",
srcs = [
"id_parser_exact_only_test.go",
"id_parser_exact_test.go",
"id_parser_fake_test.go",
"id_parser_prefix_test.go",
@ -44,6 +46,7 @@ go_test(
],
embed = [":utils"],
deps = [
"//beadserrors",
"//internal/storage/dolt",
"//internal/testutil",
"//internal/types",

View file

@ -9,6 +9,7 @@ import (
"sort"
"strings"
"github.com/steveyegge/beads/beadserrors"
"github.com/steveyegge/beads/internal/debug"
"github.com/steveyegge/beads/internal/types"
)
@ -39,6 +40,24 @@ type PartialIDResolverStore interface {
GetConfig(ctx context.Context, key string) (string, error)
}
// ExactIDLookupStore is an optional PartialIDResolverStore capability: a store
// that can look an issue up only by its EXACT id and has no substring id
// search at all (the http backend: the v0 wire publishes none, design D11).
//
// For such a store the resolver stops at the exact lookups. An input already
// shaped like a prefixed id normalizes to itself, so the first exact probe is
// the whole answer and a miss is a not-found after ONE lookup. A bare hash
// still reads the prefix vocabulary to build its prefixed spelling. A miss
// wraps beadserrors.ErrNotFound — never the substring search's refusal, which
// would report a missing id as a backend fault.
//
// The assertion is made on the store the caller passes, so a decorated chain
// must hand over the store that actually implements it (cmd/bd's routed
// resolution unwraps for this).
type ExactIDLookupStore interface {
ExactIDLookupOnly() bool
}
// parseIssueID ensures an issue ID has the configured prefix.
// If the input already has the prefix (e.g., "bd-a3f8e9"), returns it as-is.
// If the input lacks the prefix (e.g., "a3f8e9"), adds the configured prefix.
@ -103,6 +122,10 @@ func resolvePartialID(ctx context.Context, store PartialIDResolverStore, input s
return "", fmt.Errorf("cannot resolve issue ID %q: storage is nil", input)
}
if exact, ok := store.(ExactIDLookupStore); ok && exact.ExactIDLookupOnly() {
return resolveExactIDOnly(ctx, store, input)
}
// Fast path: Use SearchIssues with exact ID filter (GH#942).
// This uses the same query path as "bd list --id", ensuring consistency.
// Previously we used GetIssue which could fail in cases where SearchIssues
@ -161,10 +184,13 @@ func resolvePartialID(ctx context.Context, store PartialIDResolverStore, input s
normalizedID = prefixWithHyphen + input
}
// Try exact match on normalized ID using SearchIssues (GH#942)
normalizedFilter := types.IssueFilter{IDs: []string{normalizedID}}
if issues, err := store.SearchIssues(ctx, "", normalizedFilter); err == nil && len(issues) > 0 {
return issues[0].ID, nil
// Try exact match on normalized ID using SearchIssues (GH#942). An input
// that normalized to itself was already asked exactly that above.
if normalizedID != input {
normalizedFilter := types.IssueFilter{IDs: []string{normalizedID}}
if issues, err := store.SearchIssues(ctx, "", normalizedFilter); err == nil && len(issues) > 0 {
return issues[0].ID, nil
}
}
// If exact match failed, try substring search.
@ -308,6 +334,83 @@ func resolvePartialID(ctx context.Context, store PartialIDResolverStore, input s
return resolved, nil
}
// resolveExactIDOnly is resolvePartialID for an ExactIDLookupStore: the exact
// lookups only, with the same input normalization, and a not-found that says
// why no abbreviation was tried.
func resolveExactIDOnly(ctx context.Context, store PartialIDResolverStore, input string) (string, error) {
issues, err := store.SearchIssues(ctx, "", types.IssueFilter{IDs: []string{input}})
if err != nil {
return "", err
}
if len(issues) > 0 {
return issues[0].ID, nil
}
if !looksLikePrefixedID(input) {
// A bare hash, or a configured prefix without its hyphen: only the
// prefixed spelling can name an issue, and building it needs the
// workspace's prefix vocabulary.
prefix, allowed := exactOnlyPrefixConfig(ctx, store)
if prefix == "" {
prefix = "bd"
}
prefixWithHyphen := prefix
if !strings.HasSuffix(prefix, "-") {
prefixWithHyphen = prefix + "-"
}
knownPrefixes := []string{strings.TrimSuffix(prefix, "-")}
if allowed != "" {
for _, p := range strings.Split(allowed, ",") {
if p = strings.TrimSuffix(strings.TrimSpace(p), "-"); p != "" {
knownPrefixes = append(knownPrefixes, p)
}
}
}
if !strings.HasPrefix(input, prefixWithHyphen) && !hasKnownPrefix(input, knownPrefixes) {
issues, err = store.SearchIssues(ctx, "", types.IssueFilter{IDs: []string{prefixWithHyphen + input}})
if err != nil {
return "", err
}
if len(issues) > 0 {
return issues[0].ID, nil
}
}
}
return "", &exactIDNotFoundError{input: input}
}
// exactIDNotFoundError is resolveExactIDOnly's miss. Its text keeps the general
// resolver's "no issue found matching" lead, which every not-found matcher
// downstream reads (bd's isNotFoundErr, gc's isBdNotFound), and it wraps
// beadserrors.ErrNotFound for errors.Is callers.
type exactIDNotFoundError struct{ input string }
func (e *exactIDNotFoundError) Error() string {
return fmt.Sprintf("no issue found matching %q (this backend resolves exact ids only; partial-id search is not available)", e.input)
}
func (e *exactIDNotFoundError) Unwrap() error { return beadserrors.ErrNotFound }
// exactOnlyPrefixConfig reads issue_prefix and allowed_prefixes, in one
// settings read when the store can enumerate them (a remote store pays a round
// trip per read) and with two point reads otherwise. A failed read is an unset
// key, as it is on the general path.
func exactOnlyPrefixConfig(ctx context.Context, store PartialIDResolverStore) (prefix, allowed string) {
if all, ok := store.(interface {
GetAllConfig(ctx context.Context) (map[string]string, error)
}); ok {
if values, err := all.GetAllConfig(ctx); err == nil {
return values["issue_prefix"], values["allowed_prefixes"]
}
}
if v, err := store.GetConfig(ctx, "issue_prefix"); err == nil {
prefix = v
}
if v, err := store.GetConfig(ctx, "allowed_prefixes"); err == nil {
allowed = v
}
return prefix, allowed
}
// shouldNotifyPartialResolution is the testable predicate behind the
// partial-resolution notice. It takes the quiet flag and the suppression env
// value as parameters so tests can cover every combination, the same shape as

View file

@ -0,0 +1,133 @@
package utils_test
import (
"context"
"errors"
"strings"
"testing"
"github.com/steveyegge/beads/beadserrors"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/internal/utils"
)
// exactOnlyStore is fakeResolverStore as an exact-lookup-only backend (the
// http client's shape, S6b): it counts every call, and its substring search
// fails the test outright, because the resolver must never reach it.
type exactOnlyStore struct {
t *testing.T
inner fakeResolverStore
lookups []string
configs int
allReads int
}
func (s *exactOnlyStore) ExactIDLookupOnly() bool { return true }
func (s *exactOnlyStore) SearchIssues(ctx context.Context, q string, f types.IssueFilter) ([]*types.Issue, error) {
s.lookups = append(s.lookups, strings.Join(f.IDs, ","))
return s.inner.SearchIssues(ctx, q, f)
}
func (s *exactOnlyStore) SearchIssueIDs(context.Context, string, types.IssueFilter) ([]string, error) {
s.t.Error("exact-only resolution reached the substring search")
return nil, errors.New("no substring search")
}
func (s *exactOnlyStore) GetConfig(ctx context.Context, key string) (string, error) {
s.configs++
return s.inner.GetConfig(ctx, key)
}
func (s *exactOnlyStore) GetAllConfig(context.Context) (map[string]string, error) {
s.allReads++
return s.inner.config, nil
}
func TestResolvePartialID_ExactOnlyStore(t *testing.T) {
newStore := func(t *testing.T) *exactOnlyStore {
return &exactOnlyStore{t: t, inner: fakeResolverStore{
issues: []fakeIssue{{id: "mc-abc123"}, {id: "mc-wisp-z9"}},
config: map[string]string{"issue_prefix": "mc"},
}}
}
t.Run("present prefixed id is one lookup", func(t *testing.T) {
s := newStore(t)
got, err := utils.ResolvePartialID(context.Background(), s, "mc-abc123")
if err != nil || got != "mc-abc123" {
t.Fatalf("got %q, %v", got, err)
}
if len(s.lookups) != 1 || s.configs+s.allReads != 0 {
t.Errorf("lookups=%v configs=%d allReads=%d; want one lookup and no settings read", s.lookups, s.configs, s.allReads)
}
})
t.Run("missing prefixed id is a not-found after one lookup", func(t *testing.T) {
s := newStore(t)
_, err := utils.ResolvePartialID(context.Background(), s, "mc-nope")
if !errors.Is(err, beadserrors.ErrNotFound) {
t.Fatalf("err = %v, want ErrNotFound", err)
}
if !strings.HasPrefix(err.Error(), `no issue found matching "mc-nope"`) {
t.Errorf("err text %q lost the not-found lead every matcher reads", err)
}
if len(s.lookups) != 1 || s.configs+s.allReads != 0 {
t.Errorf("lookups=%v configs=%d allReads=%d; want exactly one lookup", s.lookups, s.configs, s.allReads)
}
})
t.Run("bare hash tries its prefixed spelling with one settings read", func(t *testing.T) {
s := newStore(t)
got, err := utils.ResolvePartialID(context.Background(), s, "abc123")
if err != nil || got != "mc-abc123" {
t.Fatalf("got %q, %v", got, err)
}
if strings.Join(s.lookups, " ") != "abc123 mc-abc123" || s.allReads != 1 || s.configs != 0 {
t.Errorf("lookups=%v configs=%d allReads=%d", s.lookups, s.configs, s.allReads)
}
})
t.Run("an abbreviation is not resolved and reads as not found", func(t *testing.T) {
s := newStore(t)
_, err := utils.ResolvePartialID(context.Background(), s, "abc")
if !errors.Is(err, beadserrors.ErrNotFound) {
t.Fatalf("err = %v, want ErrNotFound (no substring search exists)", err)
}
})
t.Run("the exact resolver takes the same path", func(t *testing.T) {
s := newStore(t)
if _, err := utils.ResolvePartialIDExact(context.Background(), s, "mc-nope"); !errors.Is(err, beadserrors.ErrNotFound) {
t.Fatalf("err = %v, want ErrNotFound", err)
}
})
}
// TestResolvePartialID_SkipsTheRepeatedNormalizedProbe pins the general
// path's one-lookup saving: an input that normalizes to itself is not asked
// for a second time.
func TestResolvePartialID_SkipsTheRepeatedNormalizedProbe(t *testing.T) {
s := &countingResolverStore{fakeResolverStore: fakeResolverStore{
issues: []fakeIssue{{id: "mc-abc123"}},
config: map[string]string{"issue_prefix": "mc"},
}}
if _, err := utils.ResolvePartialID(context.Background(), s, "mc-zzz"); err == nil {
t.Fatal("resolved an id that names nothing")
}
if s.exactProbes != 1 {
t.Errorf("exact probes = %d, want 1 (mc-zzz normalizes to itself)", s.exactProbes)
}
}
type countingResolverStore struct {
fakeResolverStore
exactProbes int
}
func (s *countingResolverStore) SearchIssues(ctx context.Context, q string, f types.IssueFilter) ([]*types.Issue, error) {
if len(f.IDs) > 0 {
s.exactProbes++
}
return s.fakeResolverStore.SearchIssues(ctx, q, f)
}

View file

@ -195,7 +195,8 @@ type CreateRequest struct {
// ignores ContentHash, RowVersion, lease state, compaction state, routing
// overrides, hydration flags, and derived fields. Labels are authoritative.
// Issue.Comments and Issue.Dependencies must be empty; supply edges through
// the request's own Dependencies field.
// the request's own Dependencies field. An empty Issue.CreatedBy defaults to
// Actor (the same rule for every create shape, batch items included).
Issue *Issue
// ParentID creates a typed DepParentChild edge. It must not duplicate an
// explicit edge in Dependencies.