beads/internal/httpapi/gate_fields_test.go
Julian Knutsen 3862b03ff5
feat(http): gate await members on create and update over bd serve (#7589)
* feat(issueops): gate members on create and update, one bounds validator

The library half of serving gate await fields. Every local leg already
stores await_type, await_id, timeout and waiters on create, and await_id
on update; this adds the two missing pieces.

- IssuePatch.Waiters: a whole-value replacement of the waiter list (nil
  or empty clears, stored as []), mapped by UpdateFields and by the
  unit-of-work updateSpec, deep-copied by CloneUpdateRequest, and
  classified as a non-coordination signal on the dolt leg. Duplicates are
  stored as given; dedup stays the CLI's.
- ValidateGateFields / ValidateGatePatch with *issueops.GateFieldError
  {Field, Detail} wrapping ErrValidation, mirroring ReclaimFieldError so a
  front door can name the member. The rules are the columns' only:
  await_type <= 32 characters, await_id <= 255 characters, the JSON
  waiter list <= one TEXT column (65535 bytes), and timeout >= 0. No
  await_type allowlist, no gate-type-only rule, no timer-needs-timeout
  rule. Run from ValidatePublicCreateRequest (every create shape on every
  backend) and ValidateUpdateRequest (await_id, waiters).
- Conformance: LifecycleCreate WritesTheGateMembers / BoundsTheGateMembers,
  LifecycleUpdate PatchesTheGateMembers / BoundsTheGateMembers and
  BatchApply CarriesTheGateMembers, each bound asserted from both sides,
  wired on the dolt, embedded and uow legs and parked on the http leg on
  the live refusal rows until the wire slices land.
- httpclient: IssuePatch.Waiters is refused before the dial on both patch
  documents under a new W-IssuePatch.Waiters row (refuse-not-drop), until
  the wire publishes it.

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

* feat(httpapi): publish the gate members on create and update

The wire half of serving gate await fields, over the library slice.

- createIssue and the issues:batchApply create item publish await_type,
  await_id, timeout (nanoseconds, the encoding Issue.timeout reads back)
  and waiters, behind the new behavior token issues.create.gates (one token
  for both create shapes, the issues.create.defaultPriority precedent).
- updateIssue's patch and the batchApply update item's patch publish
  await_id and waiters (whole-value replacement; [] clears), behind
  issues.update.gates. await_type and timeout are not patch members: no
  local update route changes them. Neither is nullable; null is refused
  naming the member, as on title.
- The handlers only decode and project (createGateMembers,
  patchGateMembers). The wire is no stricter than the library: every bound
  is the role's *issueops.GateFieldError (await_type <= 32, await_id <=
  255, the JSON waiter list <= one TEXT column, timeout >= 0), mapped to the
  existing 400 invalid_argument with param naming the member at its level
  (await_type, patch.waiters, items[i].create.timeout,
  items[i].update.patch.await_id). The spec mirrors exactly that:
  maxLength 32/255 and minimum 0, and no minLength/maxLength/maxItems on
  waiters. Blank and duplicate waiters and any await_type reach the role
  untouched.
- Spec: the four schemas, the capability prose, and the stale sentences
  (createIssue's "await_* publishes on no operation, read or write" and the
  patch's "spec_id and await_id publish nowhere yet"). apigen regenerated
  (from the remote drift test's diff), wireshape golden regenerated:
  additive entries and sides only, wire_revision stays 2.
- Client: the two tokens are mirrored in wire.behaviorCapabilities so the
  vocabulary stays set-equal with the server's. The client still refuses
  every gate member before the dial (the client slice flips that); the write-ledger
  pending sets name the newly published members under their live refusal
  rows, and the W-CreateRequest.Issue / W-IssuePatch.AwaitID /
  W-IssuePatch.Waiters reasons, the served-leg park reasons and the S4b
  waiver now say the server publishes them and this client does not send
  them yet.

Tests: internal/httpapi/gate_fields_test.go pins member mapping on all four
bodies, clear-by-empty on both patches, null and unpublished-member refusal,
GateFieldError -> param at every nesting level, and both tokens advertised.
Mutating the handlers (dropping the mapping, the GateFieldError arms or the
tokens) turns them red.

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

* feat(httpclient): send the gate members behind their tokens

The client half of serving gate await fields, over the wire slice.

- Create: await_type, await_id, timeout (nanoseconds) and waiters join the
  create vocabulary on createIssue and batchApply create items (now
  twenty-four members), sent verbatim when populated. Patch: await_id (by
  presence; "" clears) and waiters (whole-value; nil/empty travels as [])
  are encoded on both updateIssue's and the batchApply update item's patch.
- Token gate before the dial: a create naming any gate member needs
  issues.create.gates, a patch naming one needs issues.update.gates. Without
  the token the request refuses with wire.NewCapabilityError naming it
  (typed ErrUnsupported{Capability}), never a dropped member. batchApply
  checks the whole plan once, so no partial plan is sent. A request naming
  no gate member never reads either token. Store.requireCapabilityBeforeDial
  is the shared helper; requirePersistenceMove now uses it.
- Bounds read back typed: the server's 400 invalid_argument/invalid_value
  whose param names a gate member at any level (await_type, patch.waiters,
  items[i].create.timeout, items[i].update.patch.await_id) is rebuilt as the
  role's *issueops.GateFieldError, the problem kept in the chain (and a batch
  refusal still becomes its *ItemError). Without this the served bounds
  contracts could not pass.
- Ledger: W-IssuePatch.AwaitID RETIRED; the library slice's W-IssuePatch.Waiters row
  deleted (it never shipped outside this branch); W-CreateRequest.Issue and
  W-CreateItem.Issue no longer cover the gate members; new
  W-CreateRequest.Gates (refuse, Capability issues.create.gates) records the
  token-gated late refusal for both create shapes. engdocs ledger
  regenerated from Ledger() (262 rows: 201 refuse, 34 degrade, 27 retired).
- Write-ledger table: the wire slice's pending sets are flipped into carried.
- Served leg: the five gate cases (LifecycleCreate Writes/Bounds,
  LifecycleUpdate Patches/Bounds, BatchApply Carries) are un-parked and run;
  the S4b waiver and served comments now say await_id is sent.

Tests: internal/httpclient/gate_fields_test.go (encode on all four bodies,
clears, old-server refusal per member naming the token with no dial, no
partial batchApply plan, plain requests unaffected on old and new servers,
GateFieldError rebuilt from the problem). Disabling the three pre-dial
checks turns the refusal tests red.

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

* build(bazel): auto-sync BUILD files

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

* docs(issueops): say the gate timeout rule is no column's

The gate validator's doc said its rules were the stored columns' and that
no command line can produce a negative timeout. The widths are the
columns' (VARCHAR(32), VARCHAR(255), TEXT), but timeout_ns is a BIGINT,
so a non-negative timeout is a rule no column enforces; the wire
publishes it as minimum 0. The raw store creates (CreateIssue,
CreateIssues) and import do not run the validator, so bd gate create
--timeout=-5m, a formula step's gate.timeout and a template clone still
store a negative timeout until they move onto the role.

Also say that GateFieldError.Detail is prose whose HTTP copy ends with
the server's own clause, so a caller dispatches on Field, and why a
create omits an empty waiter list while a patch sends [] to clear it.

Comments only; no behaviour change.

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

* test(corpus): gh:run await_id persist refuses by the missing gate token

#7604 (now on main) made bd gate check persist a gh:run gate's discovered
run ID through Lifecycle.Update. Its served test expected the HTTP
client's W-IssuePatch.AwaitID refusal, which persistGateCheckAwaitID
rewords to name await_id. This PR retires that row: the patch carries
await_id behind issues.update.gates. Through the reference proxy, whose
server advertises no gate token, the persist is now refused before the
dial by the capability error ("bd serve at ... does not advertise
capability "issues.update.gates", which updateIssue requires"), so the
merged tree failed the subtest's await_id and updateIssue assertions.

The subtest now expects that refusal: no writes, the error names the
gate, the missing token and the server, no role or store method leaks,
and await_id is untouched. persistGateCheckAwaitID already returns a
capability error as the role raised it (#7604 pins that), so no code
changes. Against a server that advertises the token the persist goes
through: a scratch probe against the in-process server recorded
await_id=4242 and closed the gate.

Also correct the gate.go comment and the CHANGELOG entry that still said
the HTTP client refuses every await_id patch.

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

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: Eddie the Engineer <adopt-pr@gascity.com>
2026-10-16 17:02:27 +00:00

327 lines
13 KiB
Go

package httpapi
import (
"fmt"
"net/http"
"slices"
"strings"
"testing"
"time"
"github.com/steveyegge/beads/issueops"
)
// The pins for the gate members: await_type, await_id,
// timeout and waiters on createIssue and on issues:batchApply's create item
// (issues.create.gates), and await_id and waiters on updateIssue's patch and
// on the batchApply update item's patch (issues.update.gates).
//
// The wire is NOT stricter than the role. The handlers decode and project;
// every bound is the role's *issueops.GateFieldError, answered as the
// existing 400 invalid_argument with `param` naming the member at its own
// nesting level. So these cases inject the role's refusal and assert the
// mapping, and separately prove a value the role would accept (a blank waiter,
// a duplicate, an unknown await_type) reaches it untouched.
// gateFieldErr is the role's refusal for one member, spelled as
// internal/storage/issueops.ValidateGateFields spells it.
func gateFieldErr(field string) error {
return &issueops.GateFieldError{Field: field, Detail: fmt.Sprintf("validation failed: %s is past its bound", field)}
}
func TestCreateForwardsTheGateMembers(t *testing.T) {
lifecycle := &roleLifecycle{createResult: issueops.CreateResult{Issue: createdIssue("bd-g")}}
ts := newCreateServer(t, lifecycle)
// An await_type no allowlist knows, a blank and a repeated waiter: the
// role stores all of them, so the wire must not refuse any.
resp := ts.createIssue(t, `{
"actor": "alice",
"title": "a gate",
"issue_type": "gate",
"await_type": "mail",
"await_id": "run-42",
"timeout": 7200000000000,
"waiters": ["rig/a", "rig/a", ""]
}`)
if resp.StatusCode != http.StatusOK {
t.Fatalf("status = %d, want 200: %s", resp.StatusCode, readAll(t, resp))
}
got := lifecycle.createRequests()
if len(got) != 1 || got[0].Issue == nil {
t.Fatalf("the role was called %d times, want 1 with an issue", len(got))
}
issue := got[0].Issue
if issue.AwaitType != "mail" || issue.AwaitID != "run-42" {
t.Errorf("await_type/await_id = %q/%q, want mail/run-42", issue.AwaitType, issue.AwaitID)
}
if issue.Timeout != 2*time.Hour {
t.Errorf("timeout = %s, want 2h (the member is nanoseconds)", issue.Timeout)
}
if !slices.Equal(issue.Waiters, []string{"rig/a", "rig/a", ""}) {
t.Errorf("waiters = %q, want the list as sent, duplicates and blanks kept", issue.Waiters)
}
t.Run("absent members leave the issue's gate fields zero", func(t *testing.T) {
lifecycle := &roleLifecycle{createResult: issueops.CreateResult{Issue: createdIssue("bd-1")}}
ts := newCreateServer(t, lifecycle)
if resp := ts.createIssue(t, `{"actor":"alice","title":"plain"}`); resp.StatusCode != http.StatusOK {
t.Fatalf("status = %d, want 200: %s", resp.StatusCode, readAll(t, resp))
}
issue := lifecycle.createRequests()[0].Issue
if issue.AwaitType != "" || issue.AwaitID != "" || issue.Timeout != 0 || issue.Waiters != nil {
t.Errorf("gate fields = (%q, %q, %s, %q), want all zero", issue.AwaitType, issue.AwaitID, issue.Timeout, issue.Waiters)
}
})
}
func TestCreateRefusesANullGateMember(t *testing.T) {
for _, member := range []string{"await_type", "await_id", "timeout", "waiters"} {
t.Run(member, func(t *testing.T) {
lifecycle := &roleLifecycle{}
ts := newCreateServer(t, lifecycle)
resp := ts.createIssue(t, fmt.Sprintf(`{"actor":"alice","title":"one","%s":null}`, member))
if resp.StatusCode != http.StatusBadRequest {
t.Fatalf("status = %d, want 400: %s", resp.StatusCode, readAll(t, resp))
}
if body := decodeBody(t, resp); body["param"] != member {
t.Errorf("param = %v, want %q", body["param"], member)
}
if len(lifecycle.createRequests()) != 0 {
t.Error("the role was called for a refused request")
}
})
}
}
// TestCreateNamesTheGateMemberTheRoleRefused: the bound is the role's, and the
// 400 names the member its *GateFieldError is about.
func TestCreateNamesTheGateMemberTheRoleRefused(t *testing.T) {
for _, field := range []string{
issueops.GateFieldAwaitType, issueops.GateFieldAwaitID, issueops.GateFieldTimeout, issueops.GateFieldWaiters,
} {
t.Run(field, func(t *testing.T) {
lifecycle := &roleLifecycle{createErr: fmt.Errorf("create: %w", gateFieldErr(field))}
ts := newCreateServer(t, lifecycle)
resp := ts.createIssue(t, `{"actor":"alice","title":"one","await_type":"timer","await_id":"x","timeout":-1,"waiters":["a"]}`)
if resp.StatusCode != http.StatusBadRequest {
t.Fatalf("status = %d, want 400: %s", resp.StatusCode, readAll(t, resp))
}
body := decodeBody(t, resp)
if body["code"] != string(CodeInvalidArgument) {
t.Errorf("code = %v, want %s", body["code"], CodeInvalidArgument)
}
if body["param"] != field {
t.Errorf("param = %v, want %q", body["param"], field)
}
if detail, _ := body["detail"].(string); !strings.Contains(detail, field) {
t.Errorf("detail = %q, want it to name %s", detail, field)
}
})
}
}
func TestUpdateForwardsTheGateMembers(t *testing.T) {
for _, test := range []struct {
name string
patch string
wantAwaitID issueops.Field[string]
wantWaiters issueops.Field[[]string]
}{
{
name: "both set",
patch: `{"await_id":"bead:bd-9","waiters":["x","x","y"]}`,
wantAwaitID: issueops.Field[string]{Set: true, Value: "bead:bd-9"},
wantWaiters: issueops.Field[[]string]{Set: true, Value: []string{"x", "x", "y"}},
},
{
name: "both cleared",
patch: `{"await_id":"","waiters":[]}`,
wantAwaitID: issueops.Field[string]{Set: true, Value: ""},
wantWaiters: issueops.Field[[]string]{Set: true, Value: []string{}},
},
{
name: "waiters alone",
patch: `{"waiters":["rig/a"]}`,
wantWaiters: issueops.Field[[]string]{Set: true, Value: []string{"rig/a"}},
},
} {
t.Run(test.name, func(t *testing.T) {
lifecycle := &roleLifecycle{updateResult: issueops.UpdateResult{Issue: updatedIssue("bd-1"), Changed: true}}
ts := newUpdateServer(t, lifecycle)
resp := ts.updateIssue(t, updatePath, `{"actor":"alice","patch":`+test.patch+`}`)
if resp.StatusCode != http.StatusOK {
t.Fatalf("status = %d, want 200: %s", resp.StatusCode, readAll(t, resp))
}
got := lifecycle.updateRequests()
if len(got) != 1 {
t.Fatalf("the role was called %d times, want 1", len(got))
}
p := got[0].Patch
if p.AwaitID != test.wantAwaitID {
t.Errorf("await_id = %+v, want %+v", p.AwaitID, test.wantAwaitID)
}
if p.Waiters.Set != test.wantWaiters.Set || !slices.Equal(p.Waiters.Value, test.wantWaiters.Value) {
t.Errorf("waiters = %+v, want %+v", p.Waiters, test.wantWaiters)
}
if p.Title.Set || p.Status.Set || p.Assignee.Set {
t.Errorf("the handler set a member the body did not carry: %+v", p)
}
})
}
}
// TestUpdateRefusesTheGateMembersThePatchDoesNotPublish: no local route can
// change await_type or timeout, so neither patch body publishes them, and a
// null on the two it does publish is refused as on every non-nullable member.
func TestUpdateRefusesTheGateMembersThePatchDoesNotPublish(t *testing.T) {
for _, test := range []struct {
name, patch, wantParam string
}{
{"await_type is unknown", `{"await_type":"timer"}`, "patch.await_type"},
{"timeout is unknown", `{"timeout":5}`, "patch.timeout"},
{"await_id is not nullable", `{"await_id":null}`, "patch.await_id"},
{"waiters is not nullable", `{"waiters":null}`, "patch.waiters"},
} {
t.Run(test.name, func(t *testing.T) {
lifecycle := &roleLifecycle{}
ts := newUpdateServer(t, lifecycle)
resp := ts.updateIssue(t, updatePath, `{"actor":"alice","patch":`+test.patch+`}`)
if resp.StatusCode != http.StatusBadRequest {
t.Fatalf("status = %d, want 400: %s", resp.StatusCode, readAll(t, resp))
}
if body := decodeBody(t, resp); body["param"] != test.wantParam {
t.Errorf("param = %v, want %q", body["param"], test.wantParam)
}
if len(lifecycle.updateRequests()) != 0 {
t.Error("the role was called for a refused request")
}
})
}
}
func TestUpdateNamesTheGateMemberTheRoleRefused(t *testing.T) {
for _, field := range []string{issueops.GateFieldAwaitID, issueops.GateFieldWaiters} {
t.Run(field, func(t *testing.T) {
lifecycle := &roleLifecycle{updateErr: gateFieldErr(field)}
ts := newUpdateServer(t, lifecycle)
resp := ts.updateIssue(t, updatePath, `{"actor":"alice","patch":{"await_id":"x","waiters":["a"]}}`)
if resp.StatusCode != http.StatusBadRequest {
t.Fatalf("status = %d, want 400: %s", resp.StatusCode, readAll(t, resp))
}
body := decodeBody(t, resp)
if body["code"] != string(CodeInvalidArgument) {
t.Errorf("code = %v, want %s", body["code"], CodeInvalidArgument)
}
if want := "patch." + field; body["param"] != want {
t.Errorf("param = %v, want %q", body["param"], want)
}
})
}
}
func TestApplyBatchForwardsTheGateMembers(t *testing.T) {
applier := &roleBatchApplier{}
ts := newApplyBatchServer(t, applier)
resp := ts.claim(t, batchApplyPath, `{"actor":"alice","items":[
{"kind":"create","create":{"title":"a gate","await_type":"gh:run","await_id":"77","timeout":1,"waiters":["w","w"]}},
{"kind":"update","update":{"target":{"id":"bd-1"},"patch":{"await_id":"","waiters":[]}}}
]}`)
if resp.StatusCode != http.StatusOK {
t.Fatalf("status = %d, want 200: %s", resp.StatusCode, readAll(t, resp))
}
got := applier.requests()
if len(got) != 1 || len(got[0].Items) != 2 {
t.Fatalf("the role received %v, want one request of two items", got)
}
create := got[0].Items[0].Create
if create == nil || create.Issue == nil {
t.Fatal("the create item reached the role without an issue")
}
issue := create.Issue
if issue.AwaitType != "gh:run" || issue.AwaitID != "77" || issue.Timeout != time.Nanosecond ||
!slices.Equal(issue.Waiters, []string{"w", "w"}) {
t.Errorf("create gate fields = (%q, %q, %s, %q), want (gh:run, 77, 1ns, [w w])",
issue.AwaitType, issue.AwaitID, issue.Timeout, issue.Waiters)
}
update := got[0].Items[1].Update
if update == nil {
t.Fatal("the update item reached the role empty")
}
if update.Patch.AwaitID != (issueops.Field[string]{Set: true, Value: ""}) {
t.Errorf("update await_id = %+v, want a set clear", update.Patch.AwaitID)
}
if !update.Patch.Waiters.Set || len(update.Patch.Waiters.Value) != 0 {
t.Errorf("update waiters = %+v, want a set clear", update.Patch.Waiters)
}
}
func TestApplyBatchRefusesTheGateShapesTheDocumentRefuses(t *testing.T) {
for _, test := range []struct {
name, item, wantParam string
}{
{"await_type on a patch", `{"kind":"update","update":{"target":{"id":"bd-1"},"patch":{"await_type":"timer"}}}`, "items[0].update.patch.await_type"},
{"timeout on a patch", `{"kind":"update","update":{"target":{"id":"bd-1"},"patch":{"timeout":1}}}`, "items[0].update.patch.timeout"},
{"a null waiters on a patch", `{"kind":"update","update":{"target":{"id":"bd-1"},"patch":{"waiters":null}}}`, "items[0].update.patch.waiters"},
{"a null await_id on a patch", `{"kind":"update","update":{"target":{"id":"bd-1"},"patch":{"await_id":null}}}`, "items[0].update.patch.await_id"},
} {
t.Run(test.name, func(t *testing.T) {
applier := &roleBatchApplier{}
ts := newApplyBatchServer(t, applier)
resp := ts.claim(t, batchApplyPath, `{"actor":"alice","items":[`+test.item+`]}`)
if resp.StatusCode != http.StatusBadRequest {
t.Fatalf("status = %d, want 400: %s", resp.StatusCode, readAll(t, resp))
}
if body := decodeBody(t, resp); body["param"] != test.wantParam {
t.Errorf("param = %v, want %q", body["param"], test.wantParam)
}
if len(applier.requests()) != 0 {
t.Error("the role was called for a refused request")
}
})
}
}
func TestApplyBatchNamesTheGateMemberTheRoleRefused(t *testing.T) {
for _, test := range []struct {
name string
err error
wantParam string
}{
{"a create item's await_type", itemErr(0, issueops.ItemCreate, "g", "", gateFieldErr(issueops.GateFieldAwaitType)), "items[0].create.await_type"},
{"a create item's timeout", itemErr(0, issueops.ItemCreate, "g", "", gateFieldErr(issueops.GateFieldTimeout)), "items[0].create.timeout"},
{"an update item's waiters", itemErr(0, issueops.ItemUpdate, "", "bd-1", gateFieldErr(issueops.GateFieldWaiters)), "items[0].update.patch.waiters"},
{"an update item's await_id", itemErr(0, issueops.ItemUpdate, "", "bd-1", gateFieldErr(issueops.GateFieldAwaitID)), "items[0].update.patch.await_id"},
// A refusal that lost its item still names the member carrying them all.
{"no item", gateFieldErr(issueops.GateFieldWaiters), "items"},
} {
t.Run(test.name, func(t *testing.T) {
applier := &roleBatchApplier{err: test.err}
ts := newApplyBatchServer(t, applier)
resp := ts.claim(t, batchApplyPath, `{"actor":"alice","items":[{"kind":"create","create":{"title":"one"}}]}`)
if resp.StatusCode != http.StatusBadRequest {
t.Fatalf("status = %d, want 400: %s", resp.StatusCode, readAll(t, resp))
}
body := decodeBody(t, resp)
if body["code"] != string(CodeInvalidArgument) {
t.Errorf("code = %v, want %s", body["code"], CodeInvalidArgument)
}
if body["param"] != test.wantParam {
t.Errorf("param = %v, want %q", body["param"], test.wantParam)
}
})
}
}
func TestTheGateTokensAreAdvertised(t *testing.T) {
got := Capabilities()
for _, token := range []string{CapIssuesCreateGates, CapIssuesUpdateGates} {
if !slices.Contains(got, token) {
t.Errorf("Capabilities() = %v, missing %q", got, token)
}
}
if CapIssuesCreateGates != "issues.create.gates" || CapIssuesUpdateGates != "issues.update.gates" {
t.Errorf("tokens = %q, %q; want issues.create.gates, issues.update.gates", CapIssuesCreateGates, CapIssuesUpdateGates)
}
}