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>
This commit is contained in:
Julian Knutsen 2026-10-16 17:02:27 +00:00 • committed by GitHub
commit 3862b03ff5
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
53 changed files with 2282 additions and 98 deletions

View file

@ -9,6 +9,29 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
- `bd serve` publishes the gate members: `await_type`,
`await_id`, `timeout` (nanoseconds) and `waiters` on `POST
/v0/beads/issues` and on `issues:batchApply` create items, behind the new
`issues.create.gates` capability token, and `await_id` and `waiters` (a
whole-value replacement; `[]` clears) on the `patch` of `PATCH
/v0/beads/issues/{id}` and of `issues:batchApply` update items, behind
`issues.update.gates`. Additive; no wire_revision bump. The bounds are the
library role's, the same ones a local create or update now enforces (see
Changed), answered as `400 invalid_argument` with `param` naming the
member.
- `issueops.IssuePatch.Waiters`: a whole-value replacement of a gate's waiter
list (nil or empty clears it, stored as `[]`), on `Lifecycle.Update` and on
`BatchApplier` update items, on every backend. `issueops.GateFieldError`
(`Field`, `Detail`; wraps `ErrValidation`) names the gate member a create or
update refused, as one of the new `issueops.GateFieldAwaitType`,
`GateFieldAwaitID`, `GateFieldTimeout` and `GateFieldWaiters` constants.
- The HTTP client sends the gate members on create, update and
`issues:batchApply` (create and update items) to a server that advertises
`issues.create.gates` / `issues.update.gates`. Against an older server a
request naming any gate member is refused before the dial with a typed
capability error naming the missing token (never sent without the
member); a batchApply plan is checked whole, so no partial plan is sent.
A request naming no gate member is unaffected by either token.
- `GET /v0/beads/dependencies/blocking` accepts `is_blocked`, behind the new
`dependencies.blocking.isBlocked` capability token (additive; no
wire_revision bump), and answers each item's stored, transitive
@ -316,6 +339,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Changed
- **Gate members are bounds-checked in the library, on every local backend.**
`issueops.Lifecycle.Create`, `Lifecycle.Update` and `BatchApplier` (create
and update items) now refuse, with a typed `*issueops.GateFieldError`
wrapping `ErrValidation`: a negative `Timeout` (previously accepted and
stored), an `await_type` over 32 characters, an `await_id` over 255
characters, and a waiter list whose JSON encoding exceeds its TEXT column
(65535 bytes). Creates check all four; an update can change only
`await_id` and `waiters`, so it checks those two. The over-width values
previously failed with a raw Dolt driver error. There is no `await_type` vocabulary, no gate-type-only rule
and no waiter deduplication.
- **Over an http workspace, a bd command answers its repeated reads of a row
or setting from one response.** `bd show <id> --json` makes one request
instead of three, text `bd show` three instead of six, and `bd update`,
@ -536,11 +569,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
`UpdateIssue`, which the HTTP store does not implement, so every open bead
gate with an open target was an error on every sweep; it now goes through
the Lifecycle role's `Update` (a single-key metadata set, `issues.update` on
the wire), as does the gh:run discovery's `await_id` persist. The HTTP
client still refuses the `await_id` patch before the dial, so a gh:run gate
with a workflow-name hint stays that gate's error, now naming the run and
the server that does not accept the `await_id` update rather than a Go
method. The sweep also skips the gates of a persisted proto
the wire), as does the gh:run discovery's `await_id` persist, which the
HTTP client sends to a server that advertises `issues.update.gates` (see
Added). Against an older server it refuses that patch before the dial, so a
gh:run gate with a workflow-name hint stays that gate's error, naming the
missing token and the server rather than a Go method.
The sweep also skips the gates of a persisted proto
(`bd cook --persist`): they are templates that every pour copies, so a
write to one was refused on every sweep and, in a local workspace, a
resolved one (an expired timer, say) was closed in the proto itself. The

View file

@ -11,6 +11,7 @@ go_library(
"audit_molecule_wisp_batch_iter.go",
"audit_search-counts-stats.go",
"batch_apply_contract.go",
"batch_apply_gate_contract.go",
"batch_closer_contract.go",
"batch_creator_contract.go",
"batch_getter_contract.go",
@ -38,7 +39,9 @@ go_library(
"lease_reclaimer_contract.go",
"lifecycle_close_reopen_contract.go",
"lifecycle_create_contract.go",
"lifecycle_create_gate_contract.go",
"lifecycle_update_contract.go",
"lifecycle_update_gate_contract.go",
"memories_contract.go",
"metadata_cas_contract.go",
"molecule_contract.go",

View file

@ -0,0 +1,145 @@
package conformance
import (
"context"
"encoding/json"
"errors"
"slices"
"testing"
"time"
"github.com/steveyegge/beads/internal/types"
publicops "github.com/steveyegge/beads/issueops"
)
// The BatchApplier half of the gate-member clauses; see
// lifecycle_create_gate_contract.go.
// RunBatchApplyCarriesTheGateMembers pins the gate members through
// BatchApplier: a create item stores all four, an update item replaces the
// waiter list of an existing row whole, a clear through an update item stores
// the empty list `[]`, and a create or update item past a bound refuses the
// WHOLE request as ErrValidation naming its member (on its *ItemError for the
// update item), so the earlier item rolls back with it.
func RunBatchApplyCarriesTheGateMembers(t *testing.T, ctx context.Context, fixture BatchApplyFixture) {
t.Helper()
gate := fixture.IssuePrefix + "-bag-gate"
existing := fixture.IssuePrefix + "-bag-existing"
batchApplySeedIssue(t, ctx, fixture, existing, types.StatusOpen)
issue := batchApplyIssue(gate, "a gate made by a plan")
issue.IssueType = types.TypeGate
issue.AwaitType = "timer"
issue.AwaitID = "await-plan"
issue.Timeout = 2 * time.Hour
issue.Waiters = []string{"a", "a", "b"}
batchApplyMust(t, ctx, fixture, publicops.ApplyBatchRequest{
Actor: "apply-writer",
ForceIDPrefix: true,
Items: []publicops.ApplyItem{
batchApplyCreate("gate", issue),
batchApplyUpdate(publicops.Ref{ID: existing}, publicops.IssuePatch{
AwaitID: publicops.Field[string]{Set: true, Value: "bead:" + gate},
Waiters: publicops.Field[[]string]{Set: true, Value: []string{"x", "y"}},
}),
},
})
assertBatchApplyGateColumns(t, ctx, fixture, gate, "timer", "await-plan", 2*time.Hour, []string{"a", "a", "b"})
assertBatchApplyGateColumns(t, ctx, fixture, existing, "", "bead:"+gate, 0, []string{"x", "y"})
// A clear through an update item stores the empty JSON list, not NULL and
// not the JSON null: the column is read raw here because every reader
// above treats the three alike.
batchApplyMust(t, ctx, fixture, publicops.ApplyBatchRequest{
Actor: "apply-writer",
Items: []publicops.ApplyItem{
batchApplyUpdate(publicops.Ref{ID: existing}, publicops.IssuePatch{
AwaitID: publicops.Field[string]{Set: true},
Waiters: publicops.Field[[]string]{Set: true},
}),
},
})
assertBatchApplyGateColumns(t, ctx, fixture, existing, "", "", 0, nil)
var clearedWaiters string
if err := fixture.QueryScalar(ctx, "SELECT COALESCE(waiters, '<NULL>') FROM issues WHERE id = ?", []any{existing}, &clearedWaiters); err != nil {
t.Fatalf("read the waiters column of %s: %v", existing, err)
}
if clearedWaiters != "[]" {
t.Errorf("%s waiters column after a clear = %q, want the stored empty list %q", existing, clearedWaiters, "[]")
}
first := fixture.IssuePrefix + "-bag-rolledback"
refused := batchApplyIssue(fixture.IssuePrefix+"-bag-refused", "past the bound")
refused.AwaitType = gateFieldAtBoundAwaitType + "x"
_, err := fixture.BatchApplier.ApplyBatch(ctx, publicops.ApplyBatchRequest{
Actor: "apply-writer",
ForceIDPrefix: true,
Items: []publicops.ApplyItem{
batchApplyCreate("first", batchApplyIssue(first, "rolls back with the refusal")),
batchApplyCreate("refused", refused),
},
})
assertGateFieldError(t, err, "a create item with await_type past its bound", publicops.GateFieldAwaitType)
assertBatchApplyRowCount(t, ctx, fixture, "issues", first, 0)
// An update item past a bound refuses the same way, named on its own
// item: the earlier create rolls back, and the target keeps its columns.
firstOfUpdate := fixture.IssuePrefix + "-bag-rolledback-upd"
_, err = fixture.BatchApplier.ApplyBatch(ctx, publicops.ApplyBatchRequest{
Actor: "apply-writer",
ForceIDPrefix: true,
Items: []publicops.ApplyItem{
batchApplyCreate("first", batchApplyIssue(firstOfUpdate, "rolls back with the refusal")),
batchApplyUpdate(publicops.Ref{ID: gate}, publicops.IssuePatch{
Title: publicops.Field[string]{Set: true, Value: "must not land"},
AwaitID: publicops.Field[string]{Set: true, Value: gateFieldAtBoundAwaitID + "x"},
}),
},
})
assertGateFieldError(t, err, "an update item with await_id past its bound", publicops.GateFieldAwaitID)
var itemErr *publicops.ItemError
if !errors.As(err, &itemErr) {
t.Fatalf("an update item with await_id past its bound: error = %v, want an *ItemError naming the item", err)
}
if itemErr.Index != 1 || itemErr.Kind != publicops.ItemUpdate {
t.Errorf("ItemError = %#v, want Index 1 and Kind %q", itemErr, publicops.ItemUpdate)
}
assertBatchApplyRowCount(t, ctx, fixture, "issues", firstOfUpdate, 0)
assertBatchApplyGateColumns(t, ctx, fixture, gate, "timer", "await-plan", 2*time.Hour, []string{"a", "a", "b"})
if got := batchApplyColumn(t, ctx, fixture, "title", gate); got != "a gate made by a plan" {
t.Errorf("%s title = %q, want the created title: a refused item writes nothing", gate, got)
}
}
// assertBatchApplyGateColumns reads the four gate columns of one durable row
// raw, so neither side of the comparison comes from the role.
func assertBatchApplyGateColumns(t *testing.T, ctx context.Context, fixture BatchApplyFixture, id, awaitType, awaitID string, timeout time.Duration, waiters []string) {
t.Helper()
var gotType, gotID, gotWaiters string
var gotTimeout int64
if err := fixture.QueryScalar(ctx,
"SELECT COALESCE(await_type, ''), COALESCE(await_id, ''), COALESCE(timeout_ns, 0), COALESCE(waiters, '') FROM issues WHERE id = ?",
[]any{id}, &gotType, &gotID, &gotTimeout, &gotWaiters); err != nil {
t.Fatalf("read the gate columns of %s: %v", id, err)
}
if gotType != awaitType || gotID != awaitID || time.Duration(gotTimeout) != timeout {
t.Errorf("%s gate columns = (%q, %q, %s), want (%q, %q, %s)", id, gotType, gotID, time.Duration(gotTimeout), awaitType, awaitID, timeout)
}
if stored := parseGateWaiters(gotWaiters); !slices.Equal(stored, waiters) {
t.Errorf("%s waiters column = %q (%q), want %q", id, gotWaiters, stored, waiters)
}
}
// parseGateWaiters reads the waiters TEXT column's JSON array, treating the
// empty string, `null` and `[]` as the one empty list they all mean.
func parseGateWaiters(raw string) []string {
if raw == "" || raw == "null" || raw == "[]" {
return nil
}
var out []string
if err := json.Unmarshal([]byte(raw), &out); err != nil {
return []string{"<unparseable: " + err.Error() + ">"}
}
return out
}

View file

@ -0,0 +1,170 @@
package conformance
import (
"context"
"errors"
"fmt"
"strings"
"testing"
"time"
"github.com/steveyegge/beads/internal/types"
publicops "github.com/steveyegge/beads/issueops"
)
// This file and its two siblings (lifecycle_update_gate_contract.go,
// batch_apply_gate_contract.go) hold the gate-member clauses of Lifecycle.Create,
// Lifecycle.Update and BatchApplier: await_type, await_id, timeout and waiters
// on a create, await_id and waiters on a patch, and the one set of bounds every
// route refuses with a *publicops.GateFieldError.
//
// THE BOUNDS ARE THE COLUMNS', and the boundary is asserted from both sides: a
// value AT the bound lands whole, a value one past it is refused naming its
// member and writes nothing. await_type is VARCHAR(32) and await_id
// VARCHAR(255), both counted in characters, so each at-bound value is
// multi-byte — a byte count would refuse it. waiters is a TEXT column holding
// a JSON array, bounded in BYTES. A negative timeout is the one refusal that is
// not a width.
//
// NOTHING ELSE IS A RULE, and two cases say so: a gate member lands on an
// issue of any type (local `bd update --await-id` has always worked on any
// row), and waiters are stored as given, duplicates included (deduplication is
// the CLI's). A backend that grew a stricter rule fails here.
// gateFieldAtBoundAwaitType is a 32-character, 64-byte await_type.
var gateFieldAtBoundAwaitType = strings.Repeat("é", 32)
// gateFieldAtBoundAwaitID is a 255-character, 510-byte await_id.
var gateFieldAtBoundAwaitID = strings.Repeat("é", types.MaxFieldLen)
// gateFieldAtBoundWaiters is one waiter whose JSON array encoding is exactly
// types.MaxTextBytes bytes: the entry plus `["` and `"]`.
func gateFieldAtBoundWaiters() []string {
return []string{strings.Repeat("w", types.MaxTextBytes-4)}
}
// gateFieldOverBoundWaiters encodes to one byte past the TEXT column.
func gateFieldOverBoundWaiters() []string {
return []string{strings.Repeat("w", types.MaxTextBytes-3)}
}
// assertGateFieldError checks err is ErrValidation carried by a
// *publicops.GateFieldError naming field.
func assertGateFieldError(t *testing.T, err error, label, field string) {
t.Helper()
if !errors.Is(err, publicops.ErrValidation) {
t.Fatalf("%s: error = %v, want ErrValidation", label, err)
}
var fieldErr *publicops.GateFieldError
if !errors.As(err, &fieldErr) {
t.Fatalf("%s: error = %v, want a *GateFieldError naming %s", label, err, field)
}
if fieldErr.Field != field {
t.Errorf("%s: GateFieldError.Field = %q, want %q", label, fieldErr.Field, field)
}
}
// gateMembers renders the four gate members off an issue for comparison.
func gateMembers(issue *types.Issue) string {
waiters := issue.Waiters
if len(waiters) == 0 {
waiters = nil
}
return fmt.Sprintf("await_type=%q await_id=%q timeout=%s waiters=%q", issue.AwaitType, issue.AwaitID, issue.Timeout, waiters)
}
func assertGateMembers(t *testing.T, id, label string, issue *types.Issue, awaitType, awaitID string, timeout time.Duration, waiters []string) {
t.Helper()
if issue == nil {
t.Fatalf("%s %s: no issue to read the gate members off", id, label)
}
if len(waiters) == 0 {
waiters = nil
}
want := fmt.Sprintf("await_type=%q await_id=%q timeout=%s waiters=%q", awaitType, awaitID, timeout, waiters)
if got := gateMembers(issue); got != want {
// The at-bound values are long; report sizes rather than the values.
if len(got)+len(want) > 2000 {
t.Errorf("%s %s gate members differ (got %d bytes, want %d bytes; await_type %d/%d runes, await_id %d/%d runes, waiters %d/%d entries)",
id, label, len(got), len(want),
len([]rune(issue.AwaitType)), len([]rune(awaitType)), len([]rune(issue.AwaitID)), len([]rune(awaitID)),
len(issue.Waiters), len(waiters))
return
}
t.Errorf("%s %s gate members = %s, want %s", id, label, got, want)
}
}
// RunLifecycleCreateWritesTheGateMembers pins that Lifecycle.Create stores all
// four gate members (CreateRequest.Issue's "gate" fields) on the row and
// answers them on the result, with the waiter list stored as given, duplicate
// included, and on an issue that is not of the gate type.
func RunLifecycleCreateWritesTheGateMembers(t *testing.T, ctx context.Context, fixture LifecycleCreateFixture) {
t.Helper()
gate := fixture.IssuePrefix + "-lcg-gate"
issue := lifecycleCreateIssue(gate)
issue.IssueType = types.TypeGate
issue.AwaitType = "gh:run"
issue.AwaitID = "12345"
issue.Timeout = 90 * time.Minute
issue.Waiters = []string{"rig/workers/a", "rig/workers/b", "rig/workers/a"}
created, err := fixture.Lifecycle.Create(ctx, publicops.CreateRequest{Actor: "writer", ForceIDPrefix: true, Issue: issue})
if err != nil {
t.Fatalf("create gate %s: %v", gate, err)
}
want := []string{"rig/workers/a", "rig/workers/b", "rig/workers/a"}
assertGateMembers(t, gate, "in the create result", created.Issue, "gh:run", "12345", 90*time.Minute, want)
assertGateMembers(t, gate, "in the stored row", lifecycleCreateRow(t, ctx, fixture, gate), "gh:run", "12345", 90*time.Minute, want)
// Any type carries them: no gate-type-only rule.
task := fixture.IssuePrefix + "-lcg-task"
carrier := lifecycleCreateIssue(task)
carrier.AwaitType = "formula-defined"
carrier.AwaitID = "bead:" + gate
carrier.Waiters = []string{"mail:someone"}
if _, err := fixture.Lifecycle.Create(ctx, publicops.CreateRequest{Actor: "writer", ForceIDPrefix: true, Issue: carrier}); err != nil {
t.Fatalf("create task %s carrying gate members: %v", task, err)
}
assertGateMembers(t, task, "in the stored row", lifecycleCreateRow(t, ctx, fixture, task), "formula-defined", "bead:"+gate, 0, []string{"mail:someone"})
}
// RunLifecycleCreateBoundsTheGateMembers pins the four GateFieldError bounds
// on create from both sides: each at-bound value lands whole, each value one
// past it is refused as ErrValidation naming its member, and the refused
// create leaves no row.
func RunLifecycleCreateBoundsTheGateMembers(t *testing.T, ctx context.Context, fixture LifecycleCreateFixture) {
t.Helper()
atBound := fixture.IssuePrefix + "-lcg-atbound"
issue := lifecycleCreateIssue(atBound)
issue.IssueType = types.TypeGate
issue.AwaitType = gateFieldAtBoundAwaitType
issue.AwaitID = gateFieldAtBoundAwaitID
issue.Timeout = 0
issue.Waiters = gateFieldAtBoundWaiters()
if _, err := fixture.Lifecycle.Create(ctx, publicops.CreateRequest{Actor: "writer", ForceIDPrefix: true, Issue: issue}); err != nil {
t.Fatalf("create %s with every gate member at its bound: %v", atBound, err)
}
assertGateMembers(t, atBound, "in the stored row", lifecycleCreateRow(t, ctx, fixture, atBound),
gateFieldAtBoundAwaitType, gateFieldAtBoundAwaitID, 0, gateFieldAtBoundWaiters())
for _, test := range []struct {
name string
field string
mutate func(*types.Issue)
}{
{"await_type", publicops.GateFieldAwaitType, func(i *types.Issue) { i.AwaitType = gateFieldAtBoundAwaitType + "x" }},
{"await_id", publicops.GateFieldAwaitID, func(i *types.Issue) { i.AwaitID = gateFieldAtBoundAwaitID + "x" }},
{"timeout", publicops.GateFieldTimeout, func(i *types.Issue) { i.Timeout = -time.Nanosecond }},
{"waiters", publicops.GateFieldWaiters, func(i *types.Issue) { i.Waiters = gateFieldOverBoundWaiters() }},
} {
id := fixture.IssuePrefix + "-lcg-over-" + strings.ReplaceAll(test.name, "_", "")
refused := lifecycleCreateIssue(id)
refused.IssueType = types.TypeGate
test.mutate(refused)
_, err := fixture.Lifecycle.Create(ctx, publicops.CreateRequest{Actor: "writer", ForceIDPrefix: true, Issue: refused})
assertGateFieldError(t, err, "create with "+test.name+" past its bound", test.field)
assertLifecycleCreateAbsent(t, ctx, fixture, id, "after the refused "+test.name)
}
}

View file

@ -0,0 +1,133 @@
package conformance
import (
"context"
"testing"
"time"
publicops "github.com/steveyegge/beads/issueops"
)
// The patch half of the gate-member clauses; see lifecycle_create_gate_contract.go.
// RunLifecycleUpdatePatchesTheGateMembers pins IssuePatch.AwaitID and
// IssuePatch.Waiters: a set value lands and is answered on the result, waiters
// is a WHOLE-VALUE replacement stored as given (duplicates kept), a same-value
// patch is a no-op, a clear (empty await_id, nil waiters) empties both, and a
// second clear is a no-op. await_type and timeout are not patch members, so
// they ride through every edit untouched. The row is a task: no gate-type-only
// rule.
func RunLifecycleUpdatePatchesTheGateMembers(t *testing.T, ctx context.Context, fixture LifecycleUpdateFixture) {
t.Helper()
id := fixture.IssuePrefix + "-lug-gate"
seeded := lifecycleUpdateIssue(id)
seeded.AwaitType = "timer"
seeded.AwaitID = "seeded-await"
seeded.Timeout = time.Minute
seeded.Waiters = []string{"seeded"}
seedLifecycleUpdateIssue(t, ctx, fixture, seeded)
patch := publicops.IssuePatch{
AwaitID: publicops.Field[string]{Set: true, Value: "run-42"},
Waiters: publicops.Field[[]string]{Set: true, Value: []string{"w1", "w2", "w1"}},
}
wantWaiters := []string{"w1", "w2", "w1"}
updated, err := fixture.Lifecycle.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: id, Patch: patch})
if err != nil {
t.Fatalf("patch the gate members of %s: %v", id, err)
}
if !updated.Changed {
t.Errorf("patching the gate members of %s reported Changed = false, want a committed edit", id)
}
assertGateMembers(t, id, "in the update result", updated.Issue, "timer", "run-42", time.Minute, wantWaiters)
assertGateMembers(t, id, "in the stored row", lifecycleUpdateRow(t, ctx, fixture, id), "timer", "run-42", time.Minute, wantWaiters)
after := lifecycleUpdateRow(t, ctx, fixture, id)
again, err := fixture.Lifecycle.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: id, Patch: patch})
if err != nil {
t.Fatalf("re-apply the same gate patch to %s: %v", id, err)
}
if again.Changed {
t.Errorf("re-applying the same gate patch to %s reported Changed = true, want false", id)
}
assertLifecycleUpdateRowUnchanged(t, ctx, fixture, id, "after the same-value gate patch", after)
clear := publicops.UpdateRequest{Actor: "writer", IssueID: id, Patch: publicops.IssuePatch{
AwaitID: publicops.Field[string]{Set: true},
Waiters: publicops.Field[[]string]{Set: true},
}}
cleared, err := fixture.Lifecycle.Update(ctx, clear)
if err != nil {
t.Fatalf("clear the gate members of %s: %v", id, err)
}
if !cleared.Changed {
t.Errorf("clearing the gate members of %s reported Changed = false, want a committed edit", id)
}
assertGateMembers(t, id, "in the clear's result", cleared.Issue, "timer", "", time.Minute, nil)
assertGateMembers(t, id, "in the cleared row", lifecycleUpdateRow(t, ctx, fixture, id), "timer", "", time.Minute, nil)
afterClear := lifecycleUpdateRow(t, ctx, fixture, id)
reclear, err := fixture.Lifecycle.Update(ctx, clear)
if err != nil {
t.Fatalf("re-clear the gate members of %s: %v", id, err)
}
if reclear.Changed {
t.Errorf("re-clearing the already-empty gate members of %s reported Changed = true, want false", id)
}
assertLifecycleUpdateRowUnchanged(t, ctx, fixture, id, "after the re-clear", afterClear)
// An explicitly empty list clears exactly as a nil one does.
if _, err := fixture.Lifecycle.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: id, Patch: publicops.IssuePatch{
Waiters: publicops.Field[[]string]{Set: true, Value: []string{"back"}},
}}); err != nil {
t.Fatalf("re-set the waiters of %s: %v", id, err)
}
if _, err := fixture.Lifecycle.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: id, Patch: publicops.IssuePatch{
Waiters: publicops.Field[[]string]{Set: true, Value: []string{}},
}}); err != nil {
t.Fatalf("clear the waiters of %s with an empty list: %v", id, err)
}
assertGateMembers(t, id, "after the empty-list clear", lifecycleUpdateRow(t, ctx, fixture, id), "timer", "", time.Minute, nil)
}
// RunLifecycleUpdateBoundsTheGateMembers pins the patch half of the
// GateFieldError bounds from both sides: at-bound await_id and waiters land
// whole, one past either is refused as ErrValidation naming its member, and
// the refusal writes nothing — not the gate member, and not an ordinary member
// riding in the same patch.
func RunLifecycleUpdateBoundsTheGateMembers(t *testing.T, ctx context.Context, fixture LifecycleUpdateFixture) {
t.Helper()
id := fixture.IssuePrefix + "-lug-bounds"
seedLifecycleUpdateIssue(t, ctx, fixture, lifecycleUpdateIssue(id))
if _, err := fixture.Lifecycle.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: id, Patch: publicops.IssuePatch{
AwaitID: publicops.Field[string]{Set: true, Value: gateFieldAtBoundAwaitID},
Waiters: publicops.Field[[]string]{Set: true, Value: gateFieldAtBoundWaiters()},
}}); err != nil {
t.Fatalf("patch %s with await_id and waiters at their bounds: %v", id, err)
}
assertGateMembers(t, id, "in the stored row", lifecycleUpdateRow(t, ctx, fixture, id), "", gateFieldAtBoundAwaitID, 0, gateFieldAtBoundWaiters())
before := lifecycleUpdateRow(t, ctx, fixture, id)
for _, test := range []struct {
name string
field string
patch publicops.IssuePatch
}{
{"await_id", publicops.GateFieldAwaitID, publicops.IssuePatch{
Title: publicops.Field[string]{Set: true, Value: "must not land"},
AwaitID: publicops.Field[string]{Set: true, Value: gateFieldAtBoundAwaitID + "x"},
}},
{"waiters", publicops.GateFieldWaiters, publicops.IssuePatch{
Title: publicops.Field[string]{Set: true, Value: "must not land"},
Waiters: publicops.Field[[]string]{Set: true, Value: gateFieldOverBoundWaiters()},
}},
} {
_, err := fixture.Lifecycle.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: id, Patch: test.patch})
assertGateFieldError(t, err, "patch with "+test.name+" past its bound", test.field)
assertLifecycleUpdateRowUnchanged(t, ctx, fixture, id, "after the refused "+test.name, before)
assertGateMembers(t, id, "after the refused "+test.name, lifecycleUpdateRow(t, ctx, fixture, id), "", gateFieldAtBoundAwaitID, 0, gateFieldAtBoundWaiters())
}
}

View file

@ -63,6 +63,7 @@ var roleContractCases = []roleContract{
RunBatchApplyCloseItemsAnswerToTheCloseGuards,
RunBatchApplyRefusesADottedChildGatedOnItsOwnParent,
RunBatchApplyAppliesTheDefaultPriority,
RunBatchApplyCarriesTheGateMembers,
),
roleCases("BatchCloser", "BatchCloser()", oncePerRole,
@ -463,6 +464,8 @@ var roleContractCases = []roleContract{
RunLifecycleCreateWritesEveryScalarField,
RunLifecycleCreateEchoesSubSecondTimestamps,
RunLifecycleCreateAppliesTheDefaultPriority,
RunLifecycleCreateWritesTheGateMembers,
RunLifecycleCreateBoundsTheGateMembers,
),
roleCases("LifecycleUpdate", "IssueLifecycle()", oncePerRole,
@ -494,6 +497,8 @@ var roleContractCases = []roleContract{
RunLifecycleUpdateProvenanceLabelsHistory,
RunLifecycleUpdateRefusesATemplate,
RunLifecycleUpdateAllowTemplateEditsATemplate,
RunLifecycleUpdatePatchesTheGateMembers,
RunLifecycleUpdateBoundsTheGateMembers,
),
roleCases("Memories", "Memories()", oncePerRole,

View file

@ -51,9 +51,11 @@ func gateCheckWrites(reqs []string) []string {
}
// TestServedGateCheckOverAwaitTypedGates runs `bd gate check` over HTTP, through
// the reference proxy, against REAL await-typed gates. No wire create accepts
// await_*, so the gates are seeded straight into the served store before it
// listens, and every outcome is read back from that store:
// the reference proxy, against REAL await-typed gates. The reference server
// advertises neither gate token (issues.create.gates, issues.update.gates), so
// no create through it carries await_*: the gates are seeded straight into the
// served store before it listens, and every outcome is read back from that
// store:
//
// - --dry-run writes nothing;
// - an expired timer closes, a pending one stays open;
@ -61,8 +63,10 @@ func gateCheckWrites(reqs []string) []string {
// and one whose target is closed closes;
// - a merged gh:pr gate closes, a closed one escalates and stays open;
// - a gh:run gate with a workflow-name hint discovers its run but cannot
// persist await_id over the wire: that gate's error names the await_id
// update and the server, not a Go method, and await_id is untouched;
// persist await_id through a server without issues.update.gates: the
// client refuses the patch before the dial, that gate's error names the
// missing token and the server, not a Go method, and await_id is
// untouched;
// - a persisted proto's gates are templates: listed, but no sweep evaluates
// or writes them, and they take no row of --limit (they sort first here).
//
@ -308,16 +312,16 @@ esac
}
})
t.Run("gh:run await_id persist refuses by name", func(t *testing.T) {
t.Run("gh:run await_id persist refuses by the missing token", func(t *testing.T) {
r := runBD(t, bin, dir, env, "", "gate", "check", "--type=gh:run")
if r.code == 0 {
t.Fatalf("bd gate check --type=gh:run succeeded; the wire cannot carry await_id: %s", r)
t.Fatalf("bd gate check --type=gh:run succeeded; the reference server does not advertise issues.update.gates: %s", r)
}
if w := gateCheckWrites(reqs.take()); len(w) != 0 {
t.Errorf("the refused await_id persist sent writes %v", w)
}
if !strings.Contains(r.stderr, "e2e-g-run-hint") || !strings.Contains(r.stderr, "await_id") {
t.Errorf("gh:run error does not name the gate and the await_id update:\n%s", r)
if !strings.Contains(r.stderr, "e2e-g-run-hint") || !strings.Contains(r.stderr, `does not advertise capability "issues.update.gates"`) {
t.Errorf("gh:run error does not name the gate and the missing issues.update.gates token:\n%s", r)
}
if !strings.Contains(r.stderr, "bd serve at http://"+proxyAddr) {
t.Errorf("gh:run error does not name the server it reached:\n%s", r)
@ -325,7 +329,9 @@ esac
if strings.Contains(r.stderr, "e2e-tpl-run") {
t.Errorf("the template gh:run gate was checked:\n%s", r)
}
for _, leak := range []string{"UpdateIssue", "Lifecycle.Update", "updateIssue"} {
// The capability refusal names the wire operation (updateIssue) that
// needs the token; the role and store methods stay out of it.
for _, leak := range []string{"UpdateIssue", "Lifecycle.Update"} {
if strings.Contains(r.stderr, leak) {
t.Errorf("gh:run error leaks %q:\n%s", leak, r)
}

View file

@ -778,8 +778,11 @@ func updateGateThroughLifecycle(ctx context.Context, gateID string, patch issueo
}
// awaitIDPatchRefusal is the divergence-ledger row a connected HTTP
// workspace's Lifecycle role refuses an await_id edit by, before any request:
// the wire's issue patch has no await_id member.
// workspace's Lifecycle role refused an await_id edit by, before any request,
// while the wire's issue patch had no await_id member. The row is retired: the
// patch carries await_id behind issues.update.gates, and a server that does
// not advertise that token earns the capability error, which
// persistGateCheckAwaitID returns as the role raised it.
const awaitIDPatchRefusal = "W-IssuePatch.AwaitID"
// persistGateCheckAwaitID records a gh:run gate's discovered run ID through

View file

@ -47,7 +47,7 @@ the behavior.
## Summary
262 rows: 201 refuse, 35 degrade, 26 retired.
263 rows: 201 refuse, 35 degrade, 27 retired.
## Whole-behavior divergences (D9 ledger)
@ -119,8 +119,8 @@ Role-request fields on the served writes that the v0 wire publishes no member fo
| W-IssuePatch.Status | retired | — | `bd update -s` used to refuse | RETIRED with client wave ga-7i6by. IssuePatchBody published `status` with upstream #5484 and this client's encoder now emits it; close and reopen still carry the lifecycle semantics a status write has nowhere to put — the reason and session under first-close-wins, the done-status normalization, the already-closed idempotence flag — and stay the operations to reach for. What this member serves is the status moved ALONGSIDE other fields in one transaction, which is the thing two calls cannot do | 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-IssuePatch.Assignee | retired | — | assignment and unassignment through update used to refuse | RETIRED with W-IssuePatch.Status (ga-7i6by). The EMPTY STRING is the half that makes this member more than a rename: it UNASSIGNS, so a client that skipped an empty value would turn a real edit into no edit at all. The anti-steal fence around it is the server's and is unchanged — a transfer away from a live foreign in-progress owner still refuses with already_claimed, and the two bypasses (`force_assignee_transfer` and a matched `expected_assignee`) are both sent — the first since W-UpdateRequest.ForceAssigneeTransfer retired, the second since the guard wave | 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-IssuePatch.Metadata | retired | — | a metadata patch used to refuse | RETIRED with W-IssuePatch.Status (ga-7i6by). IssuePatchBody publishes the same replace/merge/set/unset algebra MetadataPatch carries, member for member, so the client projects it rather than translating it and the ordering rule — merge, then set in key order, then unset, with replace refusing beside the other three — stays the ROLE's, applied by the same body a local workspace runs. The CLEAR is the one state the wire's own struct cannot spell (`omitempty` omits it), which is why the document is built as a map and an empty replacement travels as the empty document. The compare-and-set door is a different question and is served by its own accessor (issues.casMetadata, ga-7i6by's other half) | 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-IssuePatch.AwaitID | retired | — | an await-id edit used to refuse | RETIRED. IssuePatchBody and ApplyPatchBody publish await_id and waiters behind issues.update.gates, and both patch encoders now send them: await_id by presence (the empty string CLEARS it, as on assignee), waiters as a WHOLE-VALUE replacement whose empty or nil value travels as [] (neither member is nullable). They are gated on the token rather than dropped: against a server that does not advertise it, updateIssue and an issues:batchApply plan with any such update item refuse BEFORE the dial with the typed capability error naming issues.update.gates, so a gate's waiter is never silently lost and no partial plan is ever sent. The bounds (await_id <= 255 characters, the waiter list's JSON <= one TEXT column) are the role's (issueops.ValidateGatePatch) and arrive as a 400 naming the member. The waiters edit had its own refusal row only while the wire was being published, and it left with this one | D8 refuse-not-drop | TestUpdateRefusesTheGateMembersAgainstAServerWithoutTheToken |
| W-IssuePatch.SpecID | refuse | `IssuePatch.SpecID` | a spec-id edit refuses | neither IssuePatchBody nor ApplyPatchBody publishes spec_id (internal/httpapi/update.go issuePatchMembers) | 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-IssuePatch.AwaitID | refuse | `IssuePatch.AwaitID` | an await-id edit refuses | neither IssuePatchBody nor ApplyPatchBody publishes await_id (internal/httpapi/update.go issuePatchMembers) | 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-IssuePatch.Owner | refuse | `IssuePatch.Owner` | an owner edit refuses ON updateIssue | IssuePatchBody excludes owner — which the document itself calls an accident of order rather than a decision, since ApplyPatchBody DOES publish it and issues:batchApply's update item carries it (internal/httpapi/update.go issuePatchMembers) | 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-IssuePatch.ClosedBySession | refuse | `IssuePatch.ClosedBySession` | a closed-by-session edit refuses | neither IssuePatchBody nor ApplyPatchBody publishes closed_by_session (internal/httpapi/update.go issuePatchMembers) | 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-IssuePatch.Persistence | refuse | `IssuePatch.Persistence` | a persistence-mode edit refuses ON issues:batchApply | ApplyPatchBody excludes persistence: moving a row between planes mid-plan is a different act from writing its fields. IssuePatchBody publishes it behind issues.update.persistence, and updateIssue's encoder carries it (refusing before the dial against a server without that token) (internal/httpapi/update.go issuePatchMembers) | 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 |
@ -132,8 +132,9 @@ Role-request fields on the served writes that the v0 wire publishes no member fo
| 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 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-CreateRequest.Issue | refuse | `CreateRequest.Issue` | a create whose Issue populates any member outside the wire's twenty-four 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 the four gate members await_type, await_id, timeout and waiters behind issues.create.gates (W-CreateRequest.Gates) — 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, mol_type, wisp_type, work_type, storage_class, source_*, pinned, is_template and the event quartet, which this surface accepts on no 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-CreateRequest.Gates | refuse | — | a create, or an issues:batchApply plan with a create item, whose Issue populates a gate member (await_type, await_id, timeout, waiters) refuses against a server that does not advertise issues.create.gates | createIssue and ApplyCreateItem publish the four gate members behind issues.create.gates, and this client sends them, verbatim, to a server that advertises it: timeout in NANOSECONDS, the encoding Issue.timeout reads back, and the waiter list as given, duplicates kept. A server without the token has never heard of the members, so the create is refused BEFORE the dial with the typed capability error naming the token rather than sent without them: a gate stored without its await_type is a gate nothing ever resolves, and one stored without its waiters wakes nobody. On issues:batchApply the whole plan is checked before the dial, so no partial plan is sent around the refused item. It is a LATE refusal, not a wire gap: the members are carried, and the one row covers both create shapes because one token does (the issues.create.defaultPriority precedent). The bounds (await_type <= 32, await_id <= 255, the waiter list's JSON <= one TEXT column, timeout >= 0) are the role's (issueops.ValidateGateFields) and arrive as a 400 naming the member. issues:batchCreate's item publishes none of them and keeps refusing them under W-BatchCreateItem.Issue | D8 row 16 refuse-not-drop | TestCreateRefusesTheGateMembersAgainstAServerWithoutTheToken |
| W-CreateItem.Issue | refuse | `CreateItem.Issue` | a create ITEM whose Issue populates any member outside the wire's twenty-four 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 the four gate members behind issues.create.gates (W-CreateRequest.Gates) — 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 |

View file

@ -88,6 +88,7 @@ go_test(
"edges_test.go",
"events_test.go",
"events_watch_test.go",
"gate_fields_test.go",
"get_issue_test.go",
"large_apply_client_budget_test.go",
"large_batch_apply_test.go",

File diff suppressed because one or more lines are too long

View file

@ -84,20 +84,20 @@ var (
applyItemMembers = []string{"close", "create", "dep_add", "kind", "update"}
applyRefMembers = []string{"id", "key"}
applyCreateItemMembers = []string{
"acceptance_criteria", "assignee", "defer_until", "description", "design",
"acceptance_criteria", "assignee", "await_id", "await_type", "defer_until", "description", "design",
"due_at", "ephemeral", "estimated_minutes", "external_ref", "id",
"issue_type", "key", "labels", "metadata", "metadata_refs", "no_history",
"notes", "owner", "priority", "sender", "status", "title",
"notes", "owner", "priority", "sender", "status", "timeout", "title", "waiters",
}
applyUpdateItemMembers = []string{
"expected_assignee", "expected_status", "expected_version",
"force_assignee_transfer", "force_close_policy", "force_notes_overwrite", "patch", "target",
}
applyPatchMembers = []string{
"acceptance_criteria", "append_notes", "assignee", "defer_until",
"acceptance_criteria", "append_notes", "assignee", "await_id", "defer_until",
"description", "design", "due_at", "estimated_minutes", "external_ref",
"issue_type", "labels", "metadata", "notes", "owner", "priority",
"status", "title",
"status", "title", "waiters",
}
applyLabelPatchMembers = []string{"add", "remove", "replace"}
applyMetadataPatchMembers = []string{"merge", "replace", "set", "unset"}
@ -426,6 +426,7 @@ func applyCreateItem(prefix string, encoded json.RawMessage, raw map[string]json
if wire.NoHistory != nil {
issue.NoHistory = *wire.NoHistory
}
createGateMembers(issue, wire.AwaitType, wire.AwaitId, wire.Timeout, wire.Waiters)
// An absent `priority` is the role's default (CreateItem.DefaultPriority),
// never a 0 — which is P0 — made up here.
@ -635,6 +636,7 @@ func applyPatch(prefix string, encoded json.RawMessage, raw map[string]json.RawM
if set("defer_until") {
patch.DeferUntil = issueops.Field[*time.Time]{Set: true, Value: wire.DeferUntil}
}
patchGateMembers(&patch, set, wire.AwaitId, wire.Waiters)
if set("labels") {
labels, res := applyLabelPatch(prefix+"labels.", raw["labels"])
if res != nil {
@ -1085,6 +1087,17 @@ func (s *Server) failApplyBatch(w http.ResponseWriter, r *http.Request, request
case errors.Is(err, storage.ErrNotFound):
s.fail(w, r, at(NotFound(), ""))
// A gate member past the role's bound (CapIssuesCreateGates on a create
// item, CapIssuesUpdateGates on an update item's patch), named at its own
// level. Its detail is the caller's own input only (gateFieldParam).
case isGateFieldError(err):
field, detail, _ := gateFieldParam(err)
s.refusedApplyBatch(r, err)
if itemErr != nil && itemErr.Kind == issueops.ItemUpdate {
field = "patch." + field
}
s.fail(w, r, at(InvalidArgument("", ReasonInvalidValue, detail+"; nothing was written"), field))
case errors.Is(err, storage.ErrValidation):
s.refusedApplyBatch(r, err)
s.fail(w, r, at(InvalidArgument("items", ReasonInvalidValue,

View file

@ -6,6 +6,7 @@ import (
"fmt"
"net/http"
"strings"
"time"
"github.com/steveyegge/beads/internal/httpapi/apigen"
"github.com/steveyegge/beads/internal/storage"
@ -49,11 +50,12 @@ const (
// DisallowUnknownFields reports the offender only inside an error string.
var (
createRequestMembers = []string{
"acceptance_criteria", "actor", "assignee", "defer_until", "dependencies",
"acceptance_criteria", "actor", "assignee", "await_id", "await_type",
"defer_until", "dependencies",
"description", "design", "due_at", "ephemeral", "estimated_minutes",
"external_ref", "force_id_prefix", "id", "inherit_labels_from_parent",
"issue_type", "labels", createMetadataMember, "no_history", "notes", "owner",
"parent_id", "priority", "sender", "status", "title", "waits_for",
"parent_id", "priority", "sender", "status", "timeout", "title", "waiters", "waits_for",
}
createDependencyMembers = []string{"metadata", "reverse", "target_id", "type"}
createWaitsForMembers = []string{"gate", "spawner_id"}
@ -217,6 +219,7 @@ func (s *Server) createIssueRequest(w http.ResponseWriter, r *http.Request) (iss
// can be surprised by the request buffer's lifetime.
issue.Metadata = applyRawCopy(raw)
}
createGateMembers(issue, wire.AwaitType, wire.AwaitId, wire.Timeout, wire.Waiters)
request := issueops.CreateRequest{
Actor: actor,
@ -358,6 +361,35 @@ func createWaitsFor(raw map[string]json.RawMessage, wire *apigen.CreateIssueWait
return &issueops.WaitsFor{SpawnerID: wire.SpawnerId, Gate: derefString(wire.Gate)}, nil
}
// createGateMembers projects the four gate members (CapIssuesCreateGates) onto
// the issue, for createIssue and for issues:batchApply's create item alike.
// It checks NOTHING: every bound is the role's (issueops.GateFieldError, run by
// the create role on every create shape), so the wire refuses exactly what a
// local create refuses and no more. `timeout` is nanoseconds, the encoding the
// Issue's own `timeout` reads back.
func createGateMembers(issue *types.Issue, awaitType, awaitID *string, timeout *int64, waiters *[]string) {
issue.AwaitType = derefString(awaitType)
issue.AwaitID = derefString(awaitID)
if timeout != nil {
issue.Timeout = time.Duration(*timeout)
}
if waiters != nil {
issue.Waiters = append([]string{}, *waiters...)
}
}
// gateFieldParam reports the member a role's *issueops.GateFieldError names,
// if err carries one. The error's detail is built from the request's own
// values (a length, a count, a negative duration), never server internals, so
// a refusal may quote it.
func gateFieldParam(err error) (string, string, bool) {
var fieldErr *issueops.GateFieldError
if !errors.As(err, &fieldErr) {
return "", "", false
}
return fieldErr.Field, fieldErr.Detail, true
}
// failCreateIssue answers a refused create, mapping the role's TYPED refusals
// onto the frozen codes.
//
@ -374,7 +406,9 @@ func createWaitsFor(raw map[string]json.RawMessage, wire *apigen.CreateIssueWait
// vocabulary arrives as prose about statuses and types, and a refused edge
// arrives as a driver error naming tables and constraints; 4xx details on this
// surface reflect the caller's own input back rather than server internals. The
// real error goes to the log with the request id.
// real error goes to the log with the request id. The one exception is a
// *issueops.GateFieldError, whose detail is made of the caller's own input
// only (gateFieldParam).
func (s *Server) failCreateIssue(w http.ResponseWriter, r *http.Request, err error) {
var hierarchy *issueops.DependencyHierarchyConflictError
// The 409 constructors take no param, and the document promises one on
@ -414,6 +448,12 @@ func (s *Server) failCreateIssue(w http.ResponseWriter, r *http.Request, err err
case !errors.Is(err, storage.ErrValidation):
s.failErr(w, r, err)
// A gate member past the role's bound (CapIssuesCreateGates), named.
case isGateFieldError(err):
field, detail, _ := gateFieldParam(err)
s.refusedCreateIssue(r, err)
s.fail(w, r, InvalidArgument(field, ReasonInvalidValue, detail+"; nothing was created"))
// The 4xx path does not log by default, so the branches below are the one
// place the real refusal is recorded for the operator.
case errors.Is(err, storage.ErrNotFound):
@ -441,6 +481,13 @@ func (s *Server) failCreateIssue(w http.ResponseWriter, r *http.Request, err err
}
}
// isGateFieldError reports whether err carries the role's
// *issueops.GateFieldError.
func isGateFieldError(err error) bool {
_, _, ok := gateFieldParam(err)
return ok
}
// refusedCreateIssue records the real refusal for the operator, since the 4xx
// path does not log by default and the response carries the server's own words.
func (s *Server) refusedCreateIssue(r *http.Request, err error) {

View file

@ -0,0 +1,327 @@
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)
}
}

View file

@ -265,6 +265,26 @@ const CapIssuesUpdateClaim = "issues.update.claim"
// send the default explicitly rather than omit the member.
const CapIssuesCreateDefaultPriority = "issues.create.defaultPriority"
// CapIssuesCreateGates is the behavior capability that advertises the four
// gate members — await_type, await_id, timeout and waiters — on createIssue's
// body and on issues:batchApply's create item. One token
// covers both create shapes, CapIssuesCreateDefaultPriority's precedent. The
// handlers only decode and project them: every bound is the create role's
// (issueops.GateFieldError, the stored columns' widths and a timeout that is
// not negative), answered as a 400 naming the member. An older server refuses
// each as an unknown member; a client that does not see the token must refuse
// a create carrying one before the dial rather than drop it.
const CapIssuesCreateGates = "issues.create.gates"
// CapIssuesUpdateGates is the behavior capability that advertises await_id and
// waiters (a whole-value replacement; [] clears) on updateIssue's patch and on
// issues:batchApply's update-item patch. await_type and
// timeout are not patch members: no local update route changes them. It is a
// token of its own rather than CapIssuesCreateGates because the callers that
// depend on it (gate add-waiter, gate discover, update --await-id) are a
// separate cutover dependency from gate create.
const CapIssuesUpdateGates = "issues.update.gates"
// 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
@ -1071,6 +1091,7 @@ var behaviorCapabilities = []string{
CapBatchApplyDepAddLineage, CapIssuesUpdateAllowTemplate, CapIssuesCreateDefaultPriority,
CapIssuesCloseAutoCloseMolecule, CapIssuesListSearch,
CapIssuesListNoAssignee, CapIssuesListTitle, CapListIDs, CapIssuesUpdatePersistence, CapDependenciesBlockingIsBlocked, CapIssuesUpdateClaim,
CapIssuesCreateGates, CapIssuesUpdateGates,
}
// Capabilities lists what this build advertises in ContextResponse.capabilities:

View file

@ -639,7 +639,8 @@ func TestCapabilitiesAdvertiseEveryImplementedOperation(t *testing.T) {
"issues.sweep.wispsPlane", "issues.sweep.liveDependents", "issues.sweep.limit",
"issues.batchApply.depAddLineage", "issues.update.allowTemplate", "issues.create.defaultPriority",
"issues.close.autoCloseMolecule", "issues.list.search",
"issues.list.noAssignee", "issues.list.title", "issues.list.ids", "issues.update.persistence", "dependencies.blocking.isBlocked", "issues.update.claim")
"issues.list.noAssignee", "issues.list.title", "issues.list.ids", "issues.update.persistence", "dependencies.blocking.isBlocked", "issues.update.claim",
"issues.create.gates", "issues.update.gates")
slices.Sort(want)
if !slices.Equal(got, want) {
t.Errorf("capabilities = %v, want %v", got, want)

View file

@ -1579,12 +1579,14 @@ paths:
either.
`spec_id`, `await_*`, `mol_type`, `wisp_type`, `work_type`,
`storage_class`, `source_*`, `pinned`, `is_template` and the event
quartet (`event_kind`, `actor`, `target`, `payload`) — workflow and
classification plumbing this surface publishes on no operation, read or
write. `PATCH /v0/beads/issues/{id}` says the same of `spec_id` and
`await_id`.
`spec_id`, `mol_type`, `wisp_type`, `work_type`, `storage_class`,
`source_*`, `pinned`, `is_template` and the event quartet
(`event_kind`, `actor`, `target`, `payload`) — workflow and
classification plumbing this surface accepts on no write. `PATCH
/v0/beads/issues/{id}` says the same of `spec_id`. The gate members
`await_type`, `await_id`, `timeout` and `waiters` ARE published here,
behind `issues.create.gates`, and every read of an `Issue` carries
them.
The per-type `storage-class.<type>` keys in `config.yaml` are CLI-door
@ -2510,8 +2512,13 @@ paths:
import is for.
`spec_id` and `await_id` — workflow plumbing this surface publishes
nowhere yet.
`spec_id` — workflow plumbing this surface accepts on no write.
`await_type` and `timeout` — no local update route changes them, so
the patch does not either; they are written at create
(`issues.create.gates`). `await_id` and `waiters` ARE patch members,
behind `issues.update.gates`.
## Planes
@ -8338,7 +8345,14 @@ components:
announces that `PATCH /v0/beads/issues/{id}` accepts `claim` (see
`UpdateIssueRequest`) and resolves the claimed id on both planes,
so a wisp is claimable there, rather than a `400` naming the
member unknown. One behavior token is
member unknown, and `issues.create.gates`, which announces that
`POST /v0/beads/issues` and `issues:batchApply` create items accept
the gate members `await_type`, `await_id`, `timeout` and `waiters`
(see `CreateIssueRequest`), and `issues.update.gates`, which
announces that `PATCH /v0/beads/issues/{id}`'s `patch` and an
`issues:batchApply` update item's `patch` accept `await_id` and
`waiters` (see `IssuePatchBody`), each rather than a `400` naming
the member unknown. 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
@ -10389,6 +10403,42 @@ components:
Creates the issue on the ephemeral plane WITHOUT history, and
without the garbage collection an ordinary ephemeral row is eligible
for. Mutually exclusive with `ephemeral`.
await_type:
type: string
maxLength: 32
description: >-
The gate's await condition type (`gh:run`, `gh:pr`, `timer`,
`human`, `bead`, or a formula-defined type). Free-form: there is no
vocabulary, and any issue type may carry it, as a local create
allows. At most 32 characters, the stored column's width; a longer
value is a `400` naming this member. Requires the behavior token
`issues.create.gates`.
await_id:
type: string
maxLength: 255
description: >-
The gate's condition identifier (a run id, a PR number, a
`bead:<id>`). Opaque here; at most 255 characters, the stored
column's width, and a longer value is a `400` naming this member.
Requires the behavior token `issues.create.gates`.
timeout:
type: integer
format: int64
minimum: 0
description: >-
The gate's timeout in NANOSECONDS, the encoding `Issue.timeout`
reads back. A negative value is a `400` naming this member.
Requires the behavior token `issues.create.gates`.
waiters:
type: array
items:
type: string
description: >-
The addresses woken when the gate clears, stored as sent:
duplicates are kept and nothing is trimmed, as a local create
stores them. The list's JSON encoding must fit the stored TEXT
column (65535 bytes); a larger one is a `400` naming this member.
Requires the behavior token `issues.create.gates`.
metadata_refs:
type: object
additionalProperties:
@ -10622,6 +10672,25 @@ components:
description: 'RFC 3339. Explicit `null` CLEARS the deferral.'
metadata:
$ref: '#/components/schemas/ApplyMetadataPatch'
await_id:
type: string
maxLength: 255
description: >-
Replaces the gate's condition identifier; the empty string clears
it. Not nullable. At most 255 characters, the stored column's
width; a longer value is a `400` naming this member. Requires the
behavior token `issues.update.gates`.
waiters:
type: array
items:
type: string
description: >-
A WHOLE-VALUE replacement of the gate's waiter list; `[]` clears
it. Not nullable. Stored as sent (duplicates kept: deduplicating
is the caller's, as `bd gate add-waiter` does). The list's JSON
encoding must fit the stored TEXT column (65535 bytes); a larger
one is a `400` naming this member. Requires the behavior token
`issues.update.gates`.
ApplyLabelPatch:
type: object
@ -12238,6 +12307,25 @@ components:
description: 'RFC 3339. Explicit `null` CLEARS the deferral.'
metadata:
$ref: '#/components/schemas/ApplyMetadataPatch'
await_id:
type: string
maxLength: 255
description: >-
Replaces the gate's condition identifier; the empty string clears
it. Not nullable. At most 255 characters, the stored column's
width; a longer value is a `400` naming this member. Requires the
behavior token `issues.update.gates`.
waiters:
type: array
items:
type: string
description: >-
A WHOLE-VALUE replacement of the gate's waiter list; `[]` clears
it. Not nullable. Stored as sent (duplicates kept: deduplicating
is the caller's, as `bd gate add-waiter` does). The list's JSON
encoding must fit the stored TEXT column (65535 bytes); a larger
one is a `400` naming this member. Requires the behavior token
`issues.update.gates`.
persistence:
type: string
maxLength: 255
@ -12497,6 +12585,42 @@ components:
reference and an id belonging to another repository are legitimate
targets, so only an absence this database can SEE is refused —
`ApplyDepAddItem`'s rule, unchanged.
await_type:
type: string
maxLength: 32
description: >-
The gate's await condition type (`gh:run`, `gh:pr`, `timer`,
`human`, `bead`, or a formula-defined type). Free-form: there is no
vocabulary, and any issue type may carry it, as a local create
allows. At most 32 characters, the stored column's width; a longer
value is a `400` naming this member. Requires the behavior token
`issues.create.gates`.
await_id:
type: string
maxLength: 255
description: >-
The gate's condition identifier (a run id, a PR number, a
`bead:<id>`). Opaque here; at most 255 characters, the stored
column's width, and a longer value is a `400` naming this member.
Requires the behavior token `issues.create.gates`.
timeout:
type: integer
format: int64
minimum: 0
description: >-
The gate's timeout in NANOSECONDS, the encoding `Issue.timeout`
reads back. A negative value is a `400` naming this member.
Requires the behavior token `issues.create.gates`.
waiters:
type: array
items:
type: string
description: >-
The addresses woken when the gate clears, stored as sent:
duplicates are kept and nothing is trimmed, as a local create
stores them. The list's JSON encoding must fit the stored TEXT
column (65535 bytes); a larger one is a `400` naming this member.
Requires the behavior token `issues.create.gates`.
waits_for:
$ref: '#/components/schemas/CreateIssueWaitsFor'
force_id_prefix:

View file

@ -47,6 +47,7 @@ var (
"notes", "append_notes", "priority", "issue_type", "status",
"assignee", "parent_id", "labels", "add_labels", "remove_labels", "metadata",
"estimated_minutes", "external_ref", "due_at", "defer_until", "persistence",
"await_id", "waiters",
}
// nullablePatchMembers is the closed set on which explicit `null` CLEARS
// rather than refuses. They are exactly the members the role models as
@ -492,6 +493,7 @@ func (s *Server) issuePatch(w http.ResponseWriter, r *http.Request, id string, m
member.apply(values)
}
patch.Labels = labelEdit
patchGateMembers(&patch, set, wire.AwaitId, wire.Waiters)
// The four nullable members. Set is true whenever the member is present;
// the VALUE is a nil pointer for an explicit null, which is how a clear
@ -515,6 +517,23 @@ func (s *Server) issuePatch(w http.ResponseWriter, r *http.Request, id string, m
return patch, true
}
// patchGateMembers projects the two gate members a patch publishes
// (CapIssuesUpdateGates) onto the role's IssuePatch, for updateIssue and for
// issues:batchApply's update item alike. Neither is nullable — the caller has
// already refused a `null` — so a present member always carries a value: the
// empty string clears await_id, and `[]` clears waiters, which is a WHOLE-VALUE
// replacement. It checks nothing: the bounds are the role's
// (issueops.GateFieldError), so the wire refuses what a local update refuses
// and no more.
func patchGateMembers(patch *issueops.IssuePatch, set func(string) bool, awaitID *string, waiters *[]string) {
if set("await_id") && awaitID != nil {
patch.AwaitID = issueops.Field[string]{Set: true, Value: *awaitID}
}
if set("waiters") && waiters != nil {
patch.Waiters = issueops.Field[[]string]{Set: true, Value: append([]string{}, *waiters...)}
}
}
// isJSONNull reports whether a raw member is the literal `null`.
func isJSONNull(raw json.RawMessage) bool {
return bytes.Equal(bytes.TrimSpace(raw), []byte("null"))
@ -678,6 +697,13 @@ func (s *Server) failUpdate(w http.ResponseWriter, r *http.Request, request issu
case !errors.Is(err, storage.ErrValidation):
s.failErr(w, r, err)
// A gate member past the role's bound (CapIssuesUpdateGates), named. Its
// detail is the caller's own input only (gateFieldParam), so it is quoted.
case isGateFieldError(err):
field, detail, _ := gateFieldParam(err)
refused()
s.fail(w, r, InvalidArgument(patchParam(field), ReasonInvalidValue, detail+"; nothing was written"))
default:
refused()
s.fail(w, r, InvalidArgument(updatePatchMember, ReasonInvalidValue,

View file

@ -181,6 +181,18 @@
"type": "string",
"required": false
},
{
"schema": "ApplyCreateItem",
"member": "await_id",
"type": "string",
"required": false
},
{
"schema": "ApplyCreateItem",
"member": "await_type",
"type": "string",
"required": false
},
{
"schema": "ApplyCreateItem",
"member": "defer_until",
@ -300,12 +312,26 @@
"type": "string",
"required": false
},
{
"schema": "ApplyCreateItem",
"member": "timeout",
"type": "integer",
"format": "int64",
"required": false
},
{
"schema": "ApplyCreateItem",
"member": "title",
"type": "string",
"required": true
},
{
"schema": "ApplyCreateItem",
"member": "waiters",
"type": "array",
"required": false,
"item_type": "string"
},
{
"schema": "ApplyDepAddItem",
"member": "has_spawner",
@ -481,6 +507,12 @@
"type": "string",
"required": false
},
{
"schema": "ApplyPatchBody",
"member": "await_id",
"type": "string",
"required": false
},
{
"schema": "ApplyPatchBody",
"member": "defer_until",
@ -571,6 +603,13 @@
"type": "string",
"required": false
},
{
"schema": "ApplyPatchBody",
"member": "waiters",
"type": "array",
"required": false,
"item_type": "string"
},
{
"schema": "ApplyUpdateItem",
"member": "expected_assignee",
@ -1527,6 +1566,18 @@
"type": "string",
"required": false
},
{
"schema": "CreateIssueRequest",
"member": "await_id",
"type": "string",
"required": false
},
{
"schema": "CreateIssueRequest",
"member": "await_type",
"type": "string",
"required": false
},
{
"schema": "CreateIssueRequest",
"member": "defer_until",
@ -1658,12 +1709,26 @@
"type": "string",
"required": false
},
{
"schema": "CreateIssueRequest",
"member": "timeout",
"type": "integer",
"format": "int64",
"required": false
},
{
"schema": "CreateIssueRequest",
"member": "title",
"type": "string",
"required": true
},
{
"schema": "CreateIssueRequest",
"member": "waiters",
"type": "array",
"required": false,
"item_type": "string"
},
{
"schema": "CreateIssueRequest",
"member": "waits_for",
@ -2850,6 +2915,12 @@
"type": "string",
"required": false
},
{
"schema": "IssuePatchBody",
"member": "await_id",
"type": "string",
"required": false
},
{
"schema": "IssuePatchBody",
"member": "defer_until",
@ -2954,6 +3025,13 @@
"type": "string",
"required": false
},
{
"schema": "IssuePatchBody",
"member": "waiters",
"type": "array",
"required": false,
"item_type": "string"
},
{
"schema": "IssueWithCounts",
"member": "acceptance_criteria",
@ -6257,6 +6335,7 @@
"ApplyCreateItem": "request",
"ApplyCreateItem.labels[]": "request",
"ApplyCreateItem.metadata_refs": "request",
"ApplyCreateItem.waiters[]": "request",
"ApplyDepAddItem": "request",
"ApplyItem": "request",
"ApplyItemResult": "response",
@ -6268,6 +6347,7 @@
"ApplyMetadataPatch.set": "request",
"ApplyMetadataPatch.unset[]": "request",
"ApplyPatchBody": "request",
"ApplyPatchBody.waiters[]": "request",
"ApplyUpdateItem": "request",
"BatchCloseItem": "request",
"BatchCloseRequest": "request",
@ -6303,6 +6383,7 @@
"CreateIssueDependency": "request",
"CreateIssueRequest": "request",
"CreateIssueRequest.labels[]": "request",
"CreateIssueRequest.waiters[]": "request",
"CreateIssueWaitsFor": "request",
"Cycle": "response",
"CycleMember": "response",
@ -6342,6 +6423,7 @@
"IssuePatchBody.add_labels[]": "request",
"IssuePatchBody.labels[]": "request",
"IssuePatchBody.remove_labels[]": "request",
"IssuePatchBody.waiters[]": "request",
"IssueWithCounts": "response",
"IssueWithCounts.labels[]": "response",
"IssueWithCounts.metadata": "response",

View file

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

View file

@ -93,6 +93,9 @@ func (b *httpBatchApplier) ApplyBatch(ctx context.Context, req issueops.ApplyBat
if err != nil {
return issueops.ApplyBatchResult{}, err
}
if err := b.requireGateTokens(ctx, req); err != nil {
return issueops.ApplyBatchResult{}, err
}
var priorities []**int
for i := range body.Items {
if create := body.Items[i].Create; create != nil {
@ -104,7 +107,7 @@ func (b *httpBatchApplier) ApplyBatch(ctx context.Context, req issueops.ApplyBat
}
resp, err := b.wire.ApplyBatch(ctx, body)
if err != nil {
return issueops.ApplyBatchResult{}, applyBatchRefusal(err)
return issueops.ApplyBatchResult{}, applyBatchRefusal(gateFieldRefusal(err))
}
return decodeApplyBatchResult(req, resp)
}
@ -144,6 +147,35 @@ func (b *httpBatchApplier) refuseUnservedDepAddLineage(ctx context.Context, req
return b.store.unsupportedCapability("BatchApplier.ApplyBatch", wire.CapBatchApplyDepAddLineage)
}
// requireGateTokens scans the whole plan once, before the dial, for a create
// item naming a gate member (issues.create.gates) and an update item whose
// patch names one (issues.update.gates), and refuses the request naming the
// first token the cached handshake lacks. The plan is all or nothing, so the
// check is too: no item is ever sent without its gate members, and no partial
// plan is ever sent around one.
func (b *httpBatchApplier) requireGateTokens(ctx context.Context, req issueops.ApplyBatchRequest) error {
var creates, updates bool
for _, item := range req.Items {
switch {
case item.Kind == issueops.ItemCreate && item.Create != nil && issueCarriesGates(item.Create.Issue):
creates = true
case item.Kind == issueops.ItemUpdate && item.Update != nil && patchCarriesGates(item.Update.Patch):
updates = true
}
}
if creates {
if err := b.store.requireCapabilityBeforeDial(ctx, wire.OpApplyBatch, wire.CapIssuesCreateGates); err != nil {
return err
}
}
if updates {
if err := b.store.requireCapabilityBeforeDial(ctx, wire.OpApplyBatch, wire.CapIssuesUpdateGates); err != nil {
return err
}
}
return nil
}
// applyBatchBody projects the role's request onto the wire body.
func applyBatchBody(req issueops.ApplyBatchRequest) (wire.ApplyBatchRequest, error) {
items := make([]wire.ApplyItem, 0, len(req.Items))
@ -252,7 +284,7 @@ func applyItemBody(item issueops.ApplyItem, actor string) (wire.ApplyItem, error
// applyCreateItemBody projects one create item.
//
// The wire's create vocabulary here is EXACTLY createIssue's twenty — the same
// The wire's create vocabulary here is EXACTLY createIssue's twenty-four — the same
// members, spelled the same way — so the allowlist and the refusal sweep are
// the single create's, shared rather than copied. What is different is the
// ledger row the refusal cites: this is a different operation, and a reader
@ -315,6 +347,9 @@ func applyCreateItemBody(item *issueops.CreateItem, actor string) (*apigen.Apply
}
setItemBool(&out.Ephemeral, issue.Ephemeral)
setItemBool(&out.NoHistory, issue.NoHistory)
// The gate members, sent only to a server advertising issues.create.gates:
// ApplyBatch has already refused the plan before the dial otherwise.
setGateMembers(issue, &out.AwaitType, &out.AwaitId, &out.Timeout, &out.Waiters)
if len(item.MetadataRefs) > 0 {
refs := make(map[string]apigen.Ref, len(item.MetadataRefs))
@ -496,21 +531,21 @@ func applyRefBody(ref issueops.Ref) (apigen.Ref, error) {
// absent here, also deliberately: moving a row between planes
// mid-plan is a different act from writing its fields.
//
// The other three — spec_id, await_id, closed_by_session — are absent from
// both bodies.
// spec_id and closed_by_session are absent from both bodies. await_id and
// waiters are carried on both, behind issues.update.gates (ApplyBatch refuses
// the plan before the dial against a server without it).
var applyPatchExcludedMembers = []struct {
member string
ledger string
set func(issueops.IssuePatch) bool
}{
// ParentID is this document's OWN exclusion and gets its own row; SpecID,
// AwaitID and ClosedBySession are absent from both patch bodies, so they
// cite the rows that already refuse them rather than minting a second
// reason for one fact. Persistence cites W-IssuePatch.Persistence, the row
// that refuses it on this operation alone.
// ParentID is this document's OWN exclusion and gets its own row; SpecID
// and ClosedBySession are absent from both patch bodies, so they cite the
// rows that already refuse them rather than minting a second reason for one
// fact. Persistence cites W-IssuePatch.Persistence, the row that refuses it
// on this operation alone.
{"ParentID", "W-ApplyPatch.ParentID", func(p issueops.IssuePatch) bool { return p.ParentID.Set }},
{"SpecID", "W-IssuePatch.SpecID", func(p issueops.IssuePatch) bool { return p.SpecID.Set }},
{"AwaitID", "W-IssuePatch.AwaitID", func(p issueops.IssuePatch) bool { return p.AwaitID.Set }},
{"ClosedBySession", "W-IssuePatch.ClosedBySession", func(p issueops.IssuePatch) bool { return p.ClosedBySession.Set }},
{"Persistence", "W-IssuePatch.Persistence", func(p issueops.IssuePatch) bool { return p.Persistence.Set }},
}
@ -574,6 +609,10 @@ func encodeApplyPatch(patch issueops.IssuePatch) (map[string]any, error) {
if labels := encodeApplyLabelPatch(patch.Labels); len(labels) > 0 {
out["labels"] = labels
}
// The gate members (issues.update.gates), spelled as updateIssue spells
// them; ApplyBatch has already refused the plan before the dial against a
// server without the token.
setGatePatch(out, patch)
return out, nil
}
@ -610,7 +649,7 @@ func encodeApplyLabelPatch(patch issueops.LabelPatch) map[string]any {
// It answers the FIRST offender in declaration order, which is deterministic —
// a caller fixing one member at a time must not see the reported member depend
// on map iteration. It is generalized over the LEDGER ROW because two
// operations publish the identical twenty members — createIssue and
// operations publish the identical twenty-four members — createIssue and
// batchApply's create item — and a caller must be sent to the row for the
// operation they actually called. The partition itself is one partition and is
// shared, so the two cannot disagree about what the wire carries or about what

View file

@ -143,7 +143,7 @@ func TestApplyBatchRefusesEveryMemberTheWireExcludes(t *testing.T) {
}
})
t.Run("the patch's own excluded member refuses, and the four shared ones cite their existing rows", func(t *testing.T) {
t.Run("the patch's own excluded member refuses, and the shared ones cite their existing rows", func(t *testing.T) {
for _, test := range []struct {
member string
row string
@ -155,12 +155,14 @@ func TestApplyBatchRefusesEveryMemberTheWireExcludes(t *testing.T) {
{"SpecID", "W-IssuePatch.SpecID", issueops.IssuePatch{
SpecID: issueops.Field[string]{Set: true, Value: "spec-1"},
}},
{"AwaitID", "W-IssuePatch.AwaitID", issueops.IssuePatch{
AwaitID: issueops.Field[string]{Set: true, Value: "await-1"},
}},
{"ClosedBySession", "W-IssuePatch.ClosedBySession", issueops.IssuePatch{
ClosedBySession: issueops.Field[string]{Set: true, Value: "sess-1"},
}},
// AwaitID and Waiters WERE here: both are carried behind
// issues.update.gates (W-IssuePatch.AwaitID retired).
// TestUpdateSendsTheGateMembersToAServerThatAdvertisesThem
// and TestUpdateRefusesTheGateMembersAgainstAServerWithoutTheToken
// are the positive assertion and the pre-dial capability refusal.
{"Persistence", "W-IssuePatch.Persistence", issueops.IssuePatch{
Persistence: issueops.Field[issueops.PersistenceMode]{Set: true, Value: types.PersistenceModeEphemeral},
}},

View file

@ -721,13 +721,21 @@ func writeSideRows() []Row {
SpecRow: "D8 refuse-not-drop",
PinnedBy: patchMemberPin,
},
{
ID: "W-IssuePatch.AwaitID", Kind: KindRetired,
What: "an await-id edit used to refuse",
Why: "RETIRED. IssuePatchBody and ApplyPatchBody publish await_id and waiters behind issues.update.gates, and both patch encoders now send them: await_id by presence (the empty string CLEARS it, as on assignee), waiters as a WHOLE-VALUE replacement whose empty or nil value travels as [] (neither member is nullable). " +
"They are gated on the token rather than dropped: against a server that does not advertise it, updateIssue and an issues:batchApply plan with any such update item refuse BEFORE the dial with the typed capability error naming issues.update.gates, so a gate's waiter is never silently lost and no partial plan is ever sent. " +
"The bounds (await_id <= 255 characters, the waiter list's JSON <= one TEXT column) are the role's (issueops.ValidateGatePatch) and arrive as a 400 naming the member. The waiters edit had its own refusal row only while the wire was being published, and it left with this one",
SpecRow: "D8 refuse-not-drop",
PinnedBy: "TestUpdateRefusesTheGateMembersAgainstAServerWithoutTheToken",
},
// Four of these are refused by BOTH patch documents — updateIssue's and
// issues:batchApply's — so one row covers both operations rather than a
// second reason being minted for one fact. Owner is the exception and
// says so: ApplyPatchBody publishes it, and the batch's own encoder
// carries it.
patchRow("SpecID", "a spec-id edit refuses", "neither IssuePatchBody nor ApplyPatchBody publishes spec_id"),
patchRow("AwaitID", "an await-id edit refuses", "neither IssuePatchBody nor ApplyPatchBody publishes await_id"),
patchRow("Owner", "an owner edit refuses ON updateIssue",
"IssuePatchBody excludes owner — which the document itself calls an accident of order rather than a decision, since ApplyPatchBody DOES publish it and issues:batchApply's update item carries it"),
patchRow("ClosedBySession", "a closed-by-session edit refuses", "neither IssuePatchBody nor ApplyPatchBody publishes closed_by_session"),
@ -795,14 +803,23 @@ func writeSideRows() []Row {
{
ID: "W-CreateRequest.Issue", Kind: KindRefuse,
Type: tyCreateRequest, Field: "Issue",
What: "a create whose Issue populates any member outside the wire's twenty refuses, naming the member",
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. " +
What: "a create whose Issue populates any member outside the wire's twenty-four refuses, naming the member",
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 the four gate members await_type, await_id, timeout and waiters behind issues.create.gates (W-CreateRequest.Gates) — 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, mol_type, wisp_type, work_type, storage_class, source_*, pinned, is_template and the event quartet, which this surface accepts on no 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",
SpecRow: "D8 row 16 refuse-not-drop",
PinnedBy: createPin,
},
{
ID: "W-CreateRequest.Gates", Kind: KindRefuse, Capability: "issues.create.gates",
What: "a create, or an issues:batchApply plan with a create item, whose Issue populates a gate member (await_type, await_id, timeout, waiters) refuses against a server that does not advertise issues.create.gates",
Why: "createIssue and ApplyCreateItem publish the four gate members behind issues.create.gates, and this client sends them, verbatim, to a server that advertises it: timeout in NANOSECONDS, the encoding Issue.timeout reads back, and the waiter list as given, duplicates kept. " +
"A server without the token has never heard of the members, so the create is refused BEFORE the dial with the typed capability error naming the token rather than sent without them: a gate stored without its await_type is a gate nothing ever resolves, and one stored without its waiters wakes nobody. On issues:batchApply the whole plan is checked before the dial, so no partial plan is sent around the refused item. " +
"It is a LATE refusal, not a wire gap: the members are carried, and the one row covers both create shapes because one token does (the issues.create.defaultPriority precedent). The bounds (await_type <= 32, await_id <= 255, the waiter list's JSON <= one TEXT column, timeout >= 0) are the role's (issueops.ValidateGateFields) and arrive as a 400 naming the member. issues:batchCreate's item publishes none of them and keeps refusing them under W-BatchCreateItem.Issue",
SpecRow: "D8 row 16 refuse-not-drop",
PinnedBy: "TestCreateRefusesTheGateMembersAgainstAServerWithoutTheToken",
},
{
ID: "L-create-notfound", Kind: KindDegrade,
What: "a create whose dependency or waits-for target names no row refuses as issueops.ErrValidation ALONE — not as ErrValidation wrapping ErrNotFound — and does not name the target",
@ -822,7 +839,7 @@ func writeSideRows() []Row {
},
// The issues:batchApply population, from client wave ga-mijra. It is
// SMALL, and that is the operation rather than an oversight: the create
// item publishes createIssue's whole twenty, the close item maps whole,
// item publishes createIssue's whole twenty-four, the close item maps whole,
// the edge item maps whole but for the spawner flag and the thread the
// role gained after the wire was written, and the update item's patch
// is WIDER than updateIssue's in the two places that matter to a plan (a
@ -831,8 +848,8 @@ func writeSideRows() []Row {
{
ID: "W-CreateItem.Issue", Kind: KindRefuse,
Type: tyApplyCreateItem, Field: "Issue",
What: "a create ITEM whose Issue populates any member outside the wire's twenty refuses, naming the member",
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. " +
What: "a create ITEM whose Issue populates any member outside the wire's twenty-four refuses, naming the member",
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 the four gate members behind issues.create.gates (W-CreateRequest.Gates) — 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",

View file

@ -0,0 +1,398 @@
package httpclient
import (
"errors"
"slices"
"strings"
"testing"
"time"
"github.com/steveyegge/beads/internal/httpapi/apigen"
"github.com/steveyegge/beads/internal/httpclient/wire"
"github.com/steveyegge/beads/issueops"
)
// The gate members: await_type, await_id, timeout and
// waiters on createIssue and batchApply create items, behind
// issues.create.gates; await_id and waiters on updateIssue's patch and
// batchApply update items' patch, behind issues.update.gates.
//
// Each pair below is the two sides of version skew:
//
// new client, new server the members are sent, verbatim, and nothing else
// about the request changes.
// new client, old server the cached handshake lacks the token, so the
// request refuses BEFORE the dial with the typed
// capability error naming it. Never a dropped member:
// a gate created without its await_type is a gate
// that never resolves, and a waiter dropped from a
// patch is a wake-up nobody receives.
// old client, either a request naming no gate member is untouched by
// the token, so the client never asks a server for a
// token it does not need.
// gateServer is a server that advertises both gate tokens beside the two
// stubStore's current server advertises.
func gateServer(t *testing.T, w *stubWire, caps ...string) *Store {
t.Helper()
return New(testTarget(t), w, &apigen.ContextResponse{
BdVersion: "1.2.3",
Capabilities: append([]string{wire.CapIssuesUpdateAllowTemplate, wire.CapIssuesUpdateClaim}, caps...),
})
}
func gateIssue() *issueops.Issue {
return &issueops.Issue{
Title: "gate",
IssueType: "gate",
AwaitType: "timer",
AwaitID: "run-42",
Timeout: 90 * time.Second,
Waiters: []string{"rig/workers/a", "rig/workers/a", "mayor"},
}
}
func TestCreateSendsTheGateMembersToAServerThatAdvertisesThem(t *testing.T) {
t.Run("createIssue", func(t *testing.T) {
w := &stubWire{}
lifecycle, err := gateServer(t, w, wire.CapIssuesCreateGates).IssueLifecycle()
if err != nil {
t.Fatal(err)
}
if _, err := lifecycle.Create(t.Context(), issueops.CreateRequest{Actor: "alice", Issue: gateIssue()}); err != nil {
t.Fatalf("Create: %v", err)
}
body := w.lastCreate
if got := derefStringPtr(body.AwaitType); got != "timer" {
t.Errorf("await_type = %q, want timer", got)
}
if got := derefStringPtr(body.AwaitId); got != "run-42" {
t.Errorf("await_id = %q, want run-42", got)
}
if body.Timeout == nil || *body.Timeout != int64(90*time.Second) {
t.Errorf("timeout = %v, want %d nanoseconds", body.Timeout, int64(90*time.Second))
}
// Stored as sent: the duplicate is the caller's to keep or drop.
if body.Waiters == nil || !slices.Equal(*body.Waiters, []string{"rig/workers/a", "rig/workers/a", "mayor"}) {
t.Errorf("waiters = %v, want the list verbatim", body.Waiters)
}
})
t.Run("batchApply create item", func(t *testing.T) {
w := &stubWire{}
applier, err := gateServer(t, w, wire.CapIssuesCreateGates).BatchApplier()
if err != nil {
t.Fatal(err)
}
req := applyOneCreate()
req.Items[0].Create.Issue = gateIssue()
if _, err := applier.ApplyBatch(t.Context(), req); err != nil {
t.Fatalf("ApplyBatch: %v", err)
}
item := w.lastApply.Items[0].Create
if derefStringPtr(item.AwaitType) != "timer" || derefStringPtr(item.AwaitId) != "run-42" {
t.Errorf("await_type/await_id = %v/%v, want timer/run-42", item.AwaitType, item.AwaitId)
}
if item.Timeout == nil || *item.Timeout != int64(90*time.Second) {
t.Errorf("timeout = %v, want %d nanoseconds", item.Timeout, int64(90*time.Second))
}
if item.Waiters == nil || len(*item.Waiters) != 3 {
t.Errorf("waiters = %v, want the three verbatim", item.Waiters)
}
})
}
// TestCreateRefusesTheGateMembersAgainstAServerWithoutTheToken is a new client
// against an old server, one member at a time, on both create shapes.
func TestCreateRefusesTheGateMembersAgainstAServerWithoutTheToken(t *testing.T) {
members := map[string]func(*issueops.Issue){
"AwaitType": func(i *issueops.Issue) { i.AwaitType = "human" },
"AwaitID": func(i *issueops.Issue) { i.AwaitID = "bead:bd-1" },
"Timeout": func(i *issueops.Issue) { i.Timeout = time.Minute },
"Waiters": func(i *issueops.Issue) { i.Waiters = []string{"mayor"} },
}
for name, populate := range members {
t.Run("createIssue/"+name, func(t *testing.T) {
issue := &issueops.Issue{Title: "t"}
populate(issue)
w := &stubWire{}
// The update token alone is not the create token.
lifecycle, err := gateServer(t, w, wire.CapIssuesUpdateGates).IssueLifecycle()
if err != nil {
t.Fatal(err)
}
_, err = lifecycle.Create(t.Context(), issueops.CreateRequest{Actor: "alice", Issue: issue})
requireCapabilityRefusal(t, err, wire.CapIssuesCreateGates, w)
if !errors.Is(err, wire.ErrCapabilityAbsent) {
t.Errorf("err = %v, want it to match wire.ErrCapabilityAbsent", err)
}
if !strings.Contains(err.Error(), wire.CapIssuesCreateGates) {
t.Errorf("refusal %q does not name %s", err.Error(), wire.CapIssuesCreateGates)
}
})
t.Run("batchApply/"+name, func(t *testing.T) {
issue := &issueops.Issue{Title: "t"}
populate(issue)
// The gate item is the SECOND of two: the whole plan is checked
// before the dial, so the plain create ahead of it is never sent
// on its own.
req := applyOneCreate()
req.Items = append(req.Items, issueops.ApplyItem{
Kind: issueops.ItemCreate, Create: &issueops.CreateItem{Issue: issue},
})
w := &stubWire{}
_, err := applyRoleWithSnapshot(t, w, &apigen.ContextResponse{
BdVersion: "1.2.3", Capabilities: []string{wire.CapIssuesUpdateGates},
}).ApplyBatch(t.Context(), req)
requireCapabilityRefusal(t, err, wire.CapIssuesCreateGates, w)
})
}
}
func TestUpdateSendsTheGateMembersToAServerThatAdvertisesThem(t *testing.T) {
for _, tc := range []struct {
name string
patch issueops.IssuePatch
want map[string]any
}{
{"await_id", issueops.IssuePatch{AwaitID: set("12345")}, map[string]any{"await_id": "12345"}},
// The empty string CLEARS await_id, so presence alone decides.
{"await_id clear", issueops.IssuePatch{AwaitID: set("")}, map[string]any{"await_id": ""}},
{"waiters", issueops.IssuePatch{Waiters: set([]string{"a", "a", "b"})}, map[string]any{"waiters": []string{"a", "a", "b"}}},
// A set nil list CLEARS; it travels as [] because null is refused.
{"waiters clear", issueops.IssuePatch{Waiters: set[[]string](nil)}, map[string]any{"waiters": []string{}}},
} {
t.Run("updateIssue/"+tc.name, func(t *testing.T) {
w := &stubWire{update: &apigen.UpdateIssueResponse{Revision: "7", Changed: true}}
lifecycle, err := gateServer(t, w, wire.CapIssuesUpdateGates).IssueLifecycle()
if err != nil {
t.Fatal(err)
}
if _, err := lifecycle.Update(t.Context(), issueops.UpdateRequest{
Actor: "alice", IssueID: "bd-g1", Patch: tc.patch,
}); err != nil {
t.Fatalf("Update: %v", err)
}
assertPatchDocument(t, w.lastPatch, tc.want)
})
t.Run("batchApply/"+tc.name, func(t *testing.T) {
w := &stubWire{}
applier, err := gateServer(t, w, wire.CapIssuesUpdateGates).BatchApplier()
if err != nil {
t.Fatal(err)
}
if _, err := applier.ApplyBatch(t.Context(), applyOneUpdate(tc.patch)); err != nil {
t.Fatalf("ApplyBatch: %v", err)
}
assertPatchDocument(t, w.lastApply.Items[0].Update.Patch, tc.want)
})
}
}
// TestUpdateRefusesTheGateMembersAgainstAServerWithoutTheToken is a new client
// against an old server on both patch documents.
func TestUpdateRefusesTheGateMembersAgainstAServerWithoutTheToken(t *testing.T) {
for name, patch := range map[string]issueops.IssuePatch{
"AwaitID": {AwaitID: set("12345")},
"Waiters": {Waiters: set([]string{"mayor"})},
// Beside an ordinary member the whole update still refuses: sending
// the title alone would be half the edit the caller asked for.
"Waiters beside a title": {Title: set("t"), Waiters: set([]string{"mayor"})},
} {
t.Run("updateIssue/"+name, func(t *testing.T) {
w := &stubWire{update: &apigen.UpdateIssueResponse{Revision: "7"}}
// The create token alone is not the update token.
lifecycle, err := gateServer(t, w, wire.CapIssuesCreateGates).IssueLifecycle()
if err != nil {
t.Fatal(err)
}
_, err = lifecycle.Update(t.Context(), issueops.UpdateRequest{Actor: "alice", IssueID: "bd-g1", Patch: patch})
requireCapabilityRefusal(t, err, wire.CapIssuesUpdateGates, w)
if !strings.Contains(err.Error(), wire.CapIssuesUpdateGates) {
t.Errorf("refusal %q does not name %s", err.Error(), wire.CapIssuesUpdateGates)
}
})
t.Run("batchApply/"+name, func(t *testing.T) {
// A plain create first: no partial plan is ever sent.
req := applyOneCreate()
req.Items = append(req.Items, applyOneUpdate(patch).Items...)
w := &stubWire{}
_, err := applyRoleWithSnapshot(t, w, &apigen.ContextResponse{
BdVersion: "1.2.3", Capabilities: []string{wire.CapIssuesCreateGates},
}).ApplyBatch(t.Context(), req)
requireCapabilityRefusal(t, err, wire.CapIssuesUpdateGates, w)
})
}
}
// TestARequestWithoutGateMembersIgnoresTheGateTokens is the old-client half
// of the skew: a create or patch naming no gate member dials an old server as
// it always has, and carries no gate member to a new one.
func TestARequestWithoutGateMembersIgnoresTheGateTokens(t *testing.T) {
for _, server := range []struct {
name string
caps []string
}{
{"old server", nil},
{"new server", []string{wire.CapIssuesCreateGates, wire.CapIssuesUpdateGates}},
} {
t.Run(server.name, func(t *testing.T) {
w := &stubWire{update: &apigen.UpdateIssueResponse{Revision: "7", Changed: true}}
store := gateServer(t, w, server.caps...)
lifecycle, err := store.IssueLifecycle()
if err != nil {
t.Fatal(err)
}
if _, err := lifecycle.Create(t.Context(), issueops.CreateRequest{
Actor: "alice", Issue: &issueops.Issue{Title: "plain"},
}); err != nil {
t.Fatalf("Create: %v", err)
}
body := w.lastCreate
if body.AwaitType != nil || body.AwaitId != nil || body.Timeout != nil || body.Waiters != nil {
t.Errorf("a plain create carries a gate member: %+v", body)
}
if _, err := lifecycle.Update(t.Context(), issueops.UpdateRequest{
Actor: "alice", IssueID: "bd-1", Patch: issueops.IssuePatch{Title: set("t")},
}); err != nil {
t.Fatalf("Update: %v", err)
}
for _, m := range []string{"await_id", "waiters"} {
if _, sent := w.lastPatch[m]; sent {
t.Errorf("a title patch carries %s: %v", m, w.lastPatch)
}
}
applier, err := store.BatchApplier()
if err != nil {
t.Fatal(err)
}
if _, err := applier.ApplyBatch(t.Context(), applyOneCreate()); err != nil {
t.Fatalf("ApplyBatch: %v", err)
}
if w.lastApply.Items[0].Create.Waiters != nil {
t.Errorf("a plain create item carries waiters")
}
})
}
}
func applyOneUpdate(patch issueops.IssuePatch) issueops.ApplyBatchRequest {
return issueops.ApplyBatchRequest{
Actor: "planner",
Items: []issueops.ApplyItem{{
Kind: issueops.ItemUpdate,
Update: &issueops.UpdateItem{Target: issueops.Ref{ID: "bd-g1"}, Patch: patch},
}},
}
}
func assertPatchDocument(t *testing.T, got, want map[string]any) {
t.Helper()
if len(got) != len(want) {
t.Errorf("patch = %v, want exactly %v", got, want)
}
for member, value := range want {
sent, ok := got[member]
if !ok {
t.Errorf("patch = %v, missing %s", got, member)
continue
}
switch v := value.(type) {
case []string:
list, ok := sent.([]string)
if !ok || list == nil || !slices.Equal(list, v) {
t.Errorf("patch.%s = %#v, want %#v", member, sent, v)
}
default:
if sent != v {
t.Errorf("patch.%s = %#v, want %#v", member, sent, v)
}
}
}
}
// TestABoundRefusalRebuildsTheGateFieldError pins the read side of the bounds:
// the server answers the role's *issueops.GateFieldError as a 400
// invalid_argument / invalid_value with `param` naming the member at its
// level, and each role hands the caller the same typed error a local
// backend raises, the problem still in the chain.
func TestABoundRefusalRebuildsTheGateFieldError(t *testing.T) {
problem := func(param string) error {
return &wire.ProblemError{
Op: "op", Status: 400, Code: "invalid_argument", Reason: "invalid_value",
Param: param, Detail: "the member is past its bound; nothing was written",
Err: issueops.ErrValidation,
}
}
assertField := func(t *testing.T, err error, field string) {
t.Helper()
var fieldErr *issueops.GateFieldError
if !errors.As(err, &fieldErr) {
t.Fatalf("err = %v, want a *GateFieldError naming %s", err, field)
}
if fieldErr.Field != field {
t.Errorf("GateFieldError.Field = %q, want %q", fieldErr.Field, field)
}
if !errors.Is(err, issueops.ErrValidation) {
t.Errorf("err = %v, want ErrValidation through", err)
}
var wireErr *wire.ProblemError
if !errors.As(err, &wireErr) {
t.Errorf("err = %v lost the problem it was read from", err)
}
}
caps := []string{wire.CapIssuesCreateGates, wire.CapIssuesUpdateGates}
t.Run("createIssue", func(t *testing.T) {
w := &stubWire{errs: []error{problem("await_type")}}
lifecycle, err := gateServer(t, w, caps...).IssueLifecycle()
if err != nil {
t.Fatal(err)
}
_, err = lifecycle.Create(t.Context(), issueops.CreateRequest{Actor: "alice", Issue: gateIssue()})
assertField(t, err, issueops.GateFieldAwaitType)
})
t.Run("updateIssue", func(t *testing.T) {
w := &stubWire{errs: []error{problem("patch.waiters")}}
lifecycle, err := gateServer(t, w, caps...).IssueLifecycle()
if err != nil {
t.Fatal(err)
}
_, err = lifecycle.Update(t.Context(), issueops.UpdateRequest{
Actor: "alice", IssueID: "bd-g1", Patch: issueops.IssuePatch{Waiters: set([]string{"a"})},
})
assertField(t, err, issueops.GateFieldWaiters)
})
t.Run("batchApply", func(t *testing.T) {
index := 0
bad := problem("items[0].update.patch.await_id").(*wire.ProblemError)
bad.ItemIndex = &index
kind := "update"
bad.ItemKind = &kind
w := &stubWire{errs: []error{bad}}
applier, err := gateServer(t, w, caps...).BatchApplier()
if err != nil {
t.Fatal(err)
}
_, err = applier.ApplyBatch(t.Context(), applyOneUpdate(issueops.IssuePatch{AwaitID: set("x")}))
assertField(t, err, issueops.GateFieldAwaitID)
var itemErr *issueops.ItemError
if !errors.As(err, &itemErr) || itemErr.Index != 0 {
t.Errorf("err = %v, want the *ItemError naming item 0", err)
}
})
t.Run("a refusal naming another member is untouched", func(t *testing.T) {
w := &stubWire{errs: []error{problem("patch.title")}}
lifecycle, err := gateServer(t, w, caps...).IssueLifecycle()
if err != nil {
t.Fatal(err)
}
_, err = lifecycle.Update(t.Context(), issueops.UpdateRequest{
Actor: "alice", IssueID: "bd-g1", Patch: issueops.IssuePatch{Title: set("t")},
})
var fieldErr *issueops.GateFieldError
if errors.As(err, &fieldErr) {
t.Errorf("err = %v reads as a GateFieldError for a title refusal", err)
}
})
}

View file

@ -10,6 +10,7 @@ import (
"maps"
"reflect"
"slices"
"strings"
"time"
"github.com/steveyegge/beads/internal/httpapi/apigen"
@ -40,12 +41,16 @@ var _ issueops.Lifecycle = (*httpLifecycle)(nil)
// The whole request maps but for two members, and both refuse rather than
// 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)
// every member of the issue outside the wire's twenty-four (W-CreateRequest.Issue)
// — 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.
//
// The four gate members of those twenty-four are carried only to a server
// advertising issues.create.gates; against any other the create refuses
// before the dial naming the token (Store.requireCapabilityBeforeDial).
//
// The RESPONSE is the row as stored — the minted id, the defaulted status, the
// persisted timestamps — so nothing here echoes the request back.
func (l *httpLifecycle) Create(ctx context.Context, req issueops.CreateRequest) (result issueops.CreateResult, err error) {
@ -64,12 +69,18 @@ func (l *httpLifecycle) Create(ctx context.Context, req issueops.CreateRequest)
if err != nil {
return issueops.CreateResult{}, err
}
if issueCarriesGates(req.Issue) {
if err := l.store.requireCapabilityBeforeDial(ctx, wire.OpCreateIssue, wire.CapIssuesCreateGates); err != nil {
return issueops.CreateResult{}, err
}
}
if err := l.store.pinCreateDefaultPriority(ctx, &body.Priority); err != nil {
return issueops.CreateResult{}, err
}
issue, err := l.wire.CreateIssue(ctx, body)
if err != nil {
err = gateFieldRefusal(err)
// The wire's already_exists carries `param: "id"` and no id, because the
// request already said it — the same argument the problem mapper's
// target makes for the conflicts it rebuilds. Putting the caller's own
@ -172,6 +183,7 @@ func createBody(req issueops.CreateRequest) (apigen.CreateIssueRequest, error) {
// explicit trues would.
setItemBool(&body.Ephemeral, issue.Ephemeral)
setItemBool(&body.NoHistory, issue.NoHistory)
setGateMembers(issue, &body.AwaitType, &body.AwaitId, &body.Timeout, &body.Waiters)
setItemBool(&body.InheritLabelsFromParent, req.InheritLabelsFromParent)
setItemBool(&body.ForceIdPrefix, req.ForceIDPrefix)
@ -233,12 +245,18 @@ func requireJSON(member string, raw []byte) error {
return nil
}
// createCarriedIssueMembers is the wire's create vocabulary: the twenty members
// of apigen.CreateIssueRequest that describe the issue itself, keyed by the
// types.Issue field each one carries.
// createCarriedIssueMembers is the wire's create vocabulary: the twenty-four
// members of apigen.CreateIssueRequest that describe the issue itself, keyed by
// the types.Issue field each one carries.
//
// It is the ALLOWLIST half of refuse-not-drop for this operation. What it does
// not name is refused, and there is no third arm — see refuseUnwirableIssueMembers.
//
// The last four, the gate members, are carried only to a server that
// advertises issues.create.gates. Against any other the
// create refuses before the dial naming the token (issueCarriesGates and
// Store.requireCapabilityBeforeDial), so they are never dropped: they are
// carried or the request does not leave.
var createCarriedIssueMembers = map[string]string{
"ID": "id",
"Title": "title",
@ -260,6 +278,40 @@ var createCarriedIssueMembers = map[string]string{
"Labels": "labels",
"Ephemeral": "ephemeral",
"NoHistory": "no_history",
"AwaitType": "await_type",
"AwaitID": "await_id",
"Timeout": "timeout",
"Waiters": "waiters",
}
// issueCarriesGates reports whether a create names any gate member, in the
// same terms setGateMembers sends them: the request needs
// issues.create.gates exactly when the body would carry one.
func issueCarriesGates(issue *issueops.Issue) bool {
return issue != nil && (issue.AwaitType != "" || issue.AwaitID != "" || issue.Timeout != 0 || len(issue.Waiters) > 0)
}
// setGateMembers writes the four gate members of a create body, each only
// when populated, so an empty waiter list is absent rather than []: a create
// has no list to clear, while a patch must spell its clear (setGatePatch).
// The values travel as given: the bounds (await_type <= 32,
// await_id <= 255, the waiter list's JSON <= one TEXT column, timeout >= 0)
// are the role's (issueops.ValidateGateFields) and the server answers a
// breach with a 400 naming the member, so a second copy of them here would
// only be a second definition. Timeout travels in NANOSECONDS, the encoding
// Issue.timeout reads back, and the waiter list verbatim (duplicates kept:
// deduplicating is the caller's).
func setGateMembers(issue *issueops.Issue, awaitType, awaitID **string, timeout **int64, waiters **[]string) {
setItemString(awaitType, issue.AwaitType)
setItemString(awaitID, issue.AwaitID)
if issue.Timeout != 0 {
nanos := int64(issue.Timeout)
*timeout = &nanos
}
if len(issue.Waiters) > 0 {
list := append([]string(nil), issue.Waiters...)
*waiters = &list
}
}
// setItemBool writes an optional wire boolean, leaving it absent when the caller
@ -341,6 +393,11 @@ func (l *httpLifecycle) Update(ctx context.Context, req issueops.UpdateRequest)
if err := l.requirePersistenceMove(ctx, req); err != nil {
return issueops.UpdateResult{}, err
}
if patchCarriesGates(req.Patch) {
if err := l.store.requireCapabilityBeforeDial(ctx, wire.OpUpdateIssue, wire.CapIssuesUpdateGates); err != nil {
return issueops.UpdateResult{}, err
}
}
if req.Claim {
served, err := l.store.servesCapability(ctx, wire.CapIssuesUpdateClaim)
if err != nil {
@ -358,7 +415,7 @@ func (l *httpLifecycle) Update(ctx context.Context, req issueops.UpdateRequest)
res, err := l.wire.UpdateIssue(ctx, req.IssueID, req.Actor, patch, updateGuards(req), updateFlags(req))
if err != nil {
return issueops.UpdateResult{}, err
return issueops.UpdateResult{}, gateFieldRefusal(err)
}
// The stitch releaser.go documents: types.Issue.RowVersion is `json:"-"`, so
// the decoded row carries no token and updateIssue publishes the post-write
@ -464,18 +521,95 @@ func (l *httpLifecycle) requirePersistenceMove(ctx context.Context, req issueops
if !req.Patch.Persistence.Set {
return nil
}
snap, err := l.store.snapshot(ctx)
if err != nil {
return err
}
if snap != nil && slices.Contains(snap.Capabilities, wire.CapIssuesUpdatePersistence) {
return nil
}
// The case-2 text names the server and the token, so `bd promote`
// against an older server says what to upgrade rather than only that the
// operation is unsupported. It unwraps to *storage.ErrUnsupported with
// Capability set, like every other capability refusal.
return wire.NewCapabilityError(wire.OpUpdateIssue, wire.CapIssuesUpdatePersistence, l.store.target.String(), snap)
return l.store.requireCapabilityBeforeDial(ctx, wire.OpUpdateIssue, wire.CapIssuesUpdatePersistence)
}
// requireCapabilityBeforeDial refuses, before anything is dialed, a write
// that needs a behavior token the cached handshake does not advertise. The
// refusal is the typed capability error naming the token
// (*wire.CapabilityError, which unwraps to *storage.ErrUnsupported with
// Capability set), never a dropped member: a server without the token answers
// the member as an unknown parameter at best.
func (s *Store) requireCapabilityBeforeDial(ctx context.Context, op, token string) error {
snap, err := s.snapshot(ctx)
if err != nil {
return err
}
if snap != nil && slices.Contains(snap.Capabilities, token) {
return nil
}
return wire.NewCapabilityError(op, token, s.target.String(), snap)
}
// patchCarriesGates reports whether a patch names a gate member (await_id,
// waiters), which both patch documents carry only to a server advertising
// issues.update.gates.
func patchCarriesGates(patch issueops.IssuePatch) bool {
return patch.AwaitID.Set || patch.Waiters.Set
}
// gateFieldRefusal rebuilds the role's *issueops.GateFieldError from the 400
// a gate member past its bound earns. The server answers the role's refusal
// as invalid_argument / invalid_value with `param` naming the member at its
// level (await_type, patch.waiters, items[2].create.timeout,
// items[0].update.patch.await_id), so the member is read off that typed
// coordinate and never off the prose. The problem itself stays in the chain,
// so errors.Is still reaches its sentinel and a batch refusal still becomes
// its *issueops.ItemError (applyBatchRefusal reads through the wrapper).
func gateFieldRefusal(err error) error {
var problem *wire.ProblemError
if !errors.As(err, &problem) || problem.Code != "invalid_argument" || problem.Reason != "invalid_value" {
return err
}
param := problem.Param
if rest, ok := strings.CutPrefix(param, "items["); ok {
end := strings.Index(rest, "].")
if end < 0 {
return err
}
param = rest[end+2:]
}
for _, level := range []string{"create.", "update.patch.", "patch."} {
if rest, ok := strings.CutPrefix(param, level); ok {
param = rest
break
}
}
switch param {
case issueops.GateFieldAwaitType, issueops.GateFieldAwaitID, issueops.GateFieldTimeout, issueops.GateFieldWaiters:
default:
return err
}
return &gateFieldProblem{
field: &issueops.GateFieldError{Field: param, Detail: problem.Detail},
problem: err,
}
}
// gateFieldProblem carries both the rebuilt *issueops.GateFieldError and the
// problem it was read from, and reads as the problem.
type gateFieldProblem struct {
field *issueops.GateFieldError
problem error
}
func (e *gateFieldProblem) Error() string { return e.problem.Error() }
func (e *gateFieldProblem) Unwrap() []error { return []error{e.field, e.problem} }
// setGatePatch writes the two gate members of a patch document. Presence
// alone decides, as on assignee: an empty await_id CLEARS it, and a set
// waiter list is a WHOLE-VALUE replacement whose nil or empty value clears
// it. The clear travels as the empty array, because neither member is
// nullable and a nil []string marshals to null.
func setGatePatch(out map[string]any, patch issueops.IssuePatch) {
setString(out, "await_id", patch.AwaitID)
if patch.Waiters.Set {
out["waiters"] = append([]string{}, patch.Waiters.Value...)
}
}
// applyTemplateGuardForServer decides, BEFORE the dial and from the cached
@ -836,6 +970,10 @@ func encodeIssuePatch(patch issueops.IssuePatch) (map[string]any, error) {
}
setString(out, "assignee", patch.Assignee)
setString(out, "parent_id", patch.ParentID)
// The gate members (issues.update.gates). Update has already refused them,
// before the dial, against a server that does not advertise the token;
// this only spells them.
setGatePatch(out, patch)
// The plane move (issues.update.persistence). Update has already refused
// it, before the dial, against a server that does not advertise the token;
// this only spells it.
@ -971,8 +1109,6 @@ func refuseExcludedPatchMembers(patch issueops.IssuePatch) error {
return refuse(encode.OpUpdateIssue, "W-IssuePatch.ClosedBySession")
case patch.SpecID.Set:
return refuse(encode.OpUpdateIssue, "W-IssuePatch.SpecID")
case patch.AwaitID.Set:
return refuse(encode.OpUpdateIssue, "W-IssuePatch.AwaitID")
}
return nil
}

View file

@ -275,6 +275,13 @@ func TestServedBatchApplyAppliesTheDefaultPriority(t *testing.T) {
conformance.RunBatchApplyAppliesTheDefaultPriority(t, t.Context(), newServedBatchApplyFixture(t, "hbaprio"))
}
// TestServedBatchApplyCarriesTheGateMembers RUNS: the
// served Config advertises issues.create.gates and issues.update.gates, and
// this client sends the gate members on both create and update items.
func TestServedBatchApplyCarriesTheGateMembers(t *testing.T) {
conformance.RunBatchApplyCarriesTheGateMembers(t, t.Context(), newServedBatchApplyFixture(t, "hbagate"))
}
// TestServedBatchApplyStampsSpawnerIDOnlyWhenNamed wires the dep_add
// HasSpawner/ThreadID lineage conformance case onto the http leg (S5): a
// served default Config always advertises CapBatchApplyDepAddLineage (it is

View file

@ -512,9 +512,10 @@ func TestServedLifecycleUpdatePreservesTheCreationStamp(t *testing.T) {
// The other two of the four race IssuePatch.SpecID/.AwaitID/.Owner updates
// against each other (RunLifecycleUpdateExpectedVersionSingleWinnerWithDisjointColumnsUnderConcurrency,
// RunLifecycleUpdateExpectedVersionSingleWinnerAcrossUpdateAndCloseUnderConcurrency),
// and stay off this leg: those three fields are refused on updateIssue by
// name (W-IssuePatch.SpecID, W-IssuePatch.AwaitID, W-IssuePatch.Owner,
// internal/httpclient/encode/ledger.go), a pre-existing D8 refuse-not-drop
// and stay off this leg: SpecID and Owner are still refused on updateIssue by
// name (W-IssuePatch.SpecID, W-IssuePatch.Owner,
// internal/httpclient/encode/ledger.go; AwaitID is carried
// behind issues.update.gates), a pre-existing D8 refuse-not-drop
// decision this slice does not reopen, not a race outcome the wire could
// report correctly — see issuePatchFieldsNotOnUpdateWireWaiverReason
// (internal/storage/leg_contract_wiring_test.go).
@ -1029,6 +1030,18 @@ func TestServedLifecycleUpdateAllowTemplateEditsATemplate(t *testing.T) {
conformance.RunLifecycleUpdateAllowTemplateEditsATemplate(t, t.Context(), newServedUpdateFixture(t, "hlua"))
}
// TestServedLifecycleUpdatePatchesTheGateMembers RUNS:
// the served Config advertises issues.update.gates and this client sends
// await_id and waiters to a server that does. It and the bounds case below
// were parked on W-IssuePatch.AwaitID, now retired.
func TestServedLifecycleUpdatePatchesTheGateMembers(t *testing.T) {
conformance.RunLifecycleUpdatePatchesTheGateMembers(t, t.Context(), newServedUpdateFixture(t, "hlugate"))
}
func TestServedLifecycleUpdateBoundsTheGateMembers(t *testing.T) {
conformance.RunLifecycleUpdateBoundsTheGateMembers(t, t.Context(), newServedUpdateFixture(t, "hlugbnd"))
}
func TestServedLifecycleUpdateRefusesUnknownIDsAndActorlessRequests(t *testing.T) {
conformance.RunLifecycleUpdateRefusesUnknownIDsAndActorlessRequests(t, t.Context(), newServedUpdateFixture(t, "hluu"))
}

View file

@ -102,7 +102,7 @@ func TestServedLifecycleCreateRefusesAForeignIDPrefix(t *testing.T) {
// park will outlive the ones above.
func TestServedLifecycleCreateWritesEveryScalarField(t *testing.T) {
skipKnownDivergence(t, "W-CreateRequest.Issue", createParkBead,
"the case sets spec_id, await_id, closed_by_session, created_at and a created_by naming someone other than its actor; createIssue publishes none of them and the client refuses each per member rather than dropping it (asserted by TestCreateRefusesEveryMemberTheWireExcludes)")
"the case sets spec_id, closed_by_session, created_at and a created_by naming someone other than its actor; createIssue publishes none of them and the client refuses each per member rather than dropping it (asserted by TestCreateRefusesEveryMemberTheWireExcludes)")
conformance.RunLifecycleCreateWritesEveryScalarField(t, t.Context(), newServedCreateFixture(t, "hlc5"))
}
@ -124,6 +124,20 @@ func TestServedLifecycleCreateAppliesTheDefaultPriority(t *testing.T) {
conformance.RunLifecycleCreateAppliesTheDefaultPriority(t, t.Context(), newServedCreateFixture(t, "hlcprio"))
}
// TestServedLifecycleCreateWritesTheGateMembers RUNS: the
// served Config advertises issues.create.gates, and this client sends
// await_type, await_id, timeout and waiters to a server that does. The two
// cases were parked on W-CreateRequest.Issue until the client slice.
func TestServedLifecycleCreateWritesTheGateMembers(t *testing.T) {
conformance.RunLifecycleCreateWritesTheGateMembers(t, t.Context(), newServedCreateFixture(t, "hlcgate"))
}
// TestServedLifecycleCreateBoundsTheGateMembers RUNS: each bound is the
// role's, reached through the server's 400 naming the member.
func TestServedLifecycleCreateBoundsTheGateMembers(t *testing.T) {
conformance.RunLifecycleCreateBoundsTheGateMembers(t, t.Context(), newServedCreateFixture(t, "hlcgbnd"))
}
// createParkBead is the bead the create-side parks cite. It is separate from
// parkBead — the write-side parks of the close/update wave — because these
// retire on different events: two of them wait on the wire growing a

View file

@ -276,6 +276,19 @@ const CapIssuesUpdatePersistence = "issues.update.persistence"
// ErrUnsupported naming it.
const CapIssuesUpdateClaim = "issues.update.claim"
// CapIssuesCreateGates and CapIssuesUpdateGates are the behavior capabilities
// announcing the gate members, spelled exactly as
// httpapi's constants of the same names: await_type, await_id, timeout and
// waiters on createIssue and batchApply create items, and await_id and
// waiters on updateIssue's and batchApply update items' patch. The encoders
// send the members only to a server advertising the matching token, and
// refuse the request before the dial naming it otherwise
// (W-CreateRequest.Gates; the retired W-IssuePatch.AwaitID).
const (
CapIssuesCreateGates = "issues.create.gates"
CapIssuesUpdateGates = "issues.update.gates"
)
// CapIssuesCreateDefaultPriority is the behavior capability announcing that
// the server stores the create default priority for an ABSENT `priority`
// member on issues.create, issues.batchCreate and issues.batchApply create
@ -436,6 +449,7 @@ var behaviorCapabilities = []string{
CapBatchApplyDepAddLineage, CapIssuesUpdateAllowTemplate, CapIssuesCreateDefaultPriority,
CapCloseAutoCloseMolecule, CapListSearch,
CapListNoAssignee, CapListTitle, CapListIDs, CapIssuesUpdatePersistence, CapBlockingIsBlocked, CapIssuesUpdateClaim,
CapIssuesCreateGates, CapIssuesUpdateGates,
}
// CapabilityFor reports the capability token gating op, and whether op is on

View file

@ -175,6 +175,12 @@ func TestTheProjectIdentityVocabularyMatchesTheServer(t *testing.T) {
if CapSweepLiveDependents != httpapi.CapIssuesSweepLiveDependents {
t.Errorf("CapSweepLiveDependents = %q, server says %q", CapSweepLiveDependents, httpapi.CapIssuesSweepLiveDependents)
}
if CapIssuesCreateGates != httpapi.CapIssuesCreateGates {
t.Errorf("CapIssuesCreateGates = %q, server says %q", CapIssuesCreateGates, httpapi.CapIssuesCreateGates)
}
if CapIssuesUpdateGates != httpapi.CapIssuesUpdateGates {
t.Errorf("CapIssuesUpdateGates = %q, server says %q", CapIssuesUpdateGates, httpapi.CapIssuesUpdateGates)
}
if CapSweepLimit != httpapi.CapIssuesSweepLimit {
t.Errorf("CapSweepLimit = %q, server says %q", CapSweepLimit, httpapi.CapIssuesSweepLimit)
}
@ -218,11 +224,12 @@ func TestTheProjectIdentityVocabularyMatchesTheServer(t *testing.T) {
httpapi.CapBatchApplyDepAddLineage, httpapi.CapIssuesUpdateAllowTemplate, httpapi.CapIssuesCreateDefaultPriority,
httpapi.CapIssuesCloseAutoCloseMolecule, httpapi.CapIssuesListSearch,
httpapi.CapIssuesListNoAssignee, httpapi.CapIssuesListTitle, httpapi.CapListIDs, httpapi.CapIssuesUpdatePersistence, httpapi.CapDependenciesBlockingIsBlocked, httpapi.CapIssuesUpdateClaim,
httpapi.CapIssuesCreateGates, httpapi.CapIssuesUpdateGates,
}) {
t.Errorf("behaviorCapabilities = %v, want the server's project.enforce, issues.batchApplyLarge, issues.list.sort, "+
"issues.count.scope, issues.sweep.wispsPlane, issues.sweep.liveDependents, issues.sweep.limit, "+
"issues.batchApply.depAddLineage, issues.update.allowTemplate, issues.create.defaultPriority, issues.close.autoCloseMolecule, issues.list.search, "+
"issues.list.noAssignee, issues.list.title, issues.list.ids, issues.update.persistence, dependencies.blocking.isBlocked and issues.update.claim tokens", behaviorCapabilities)
"issues.list.noAssignee, issues.list.title, issues.list.ids, issues.update.persistence, dependencies.blocking.isBlocked, issues.update.claim, issues.create.gates and issues.update.gates tokens", behaviorCapabilities)
}
}

View file

@ -162,6 +162,10 @@ func writeShapes() []writeShape {
"notes", "status", "priority", "issue_type", "assignee", "owner",
"estimated_minutes", "external_ref", "due_at", "defer_until",
"sender", "metadata", "labels", "ephemeral", "no_history",
// The gate members, behind issues.create.gates:
// carried to a server that
// advertises it, refused before the dial otherwise.
"await_type", "await_id", "timeout", "waiters",
},
// The members of a types.Issue this vocabulary does NOT
// spell — the creation stamp, the workflow and
@ -177,6 +181,9 @@ func writeShapes() []writeShape {
// Issue spread drives is left out (wirePriority).
"DefaultPriority": absenceOf("priority"),
},
// The gate members sat in a pending set here while the wire
// published them and this client still refused them (the wire
// slice); the client slice moved them into the Issue spread above.
},
{
name: "closeIssue",
@ -324,13 +331,19 @@ func writeShapes() []writeShape {
// W-IssuePatch.Persistence stays a refusal there — the Owner
// row's arrangement, the other way round.
"Persistence": member("persistence"),
// The gate members, behind issues.update.gates.
// They sat in the pending set while the
// wire published them under the W-IssuePatch.AwaitID and
// W-IssuePatch.Waiters refusals; the flip moved them here and
// retired the refusals.
"AwaitID": member("await_id"),
"Waiters": member("waiters"),
},
// NOTHING IS PENDING, and the set is empty rather than absent for the
// reason the second list in accessors.go was: it held the two
// incremental-label members #5510 published under an existing refusal,
// and client wave ga-jpywb moved both into `carried` — which is what
// the map documents a flip as. The next member upstream publishes
// under a live W- row starts it again.
// NOTHING IS PENDING. The set held the two incremental-label
// members #5510 published under an existing refusal until client
// wave ga-jpywb, and await_id and waiters until the gate
// members' client slice, each moved into `carried` — which is what the map
// documents a flip as.
},
{
// The nested metadata document, and the reason it is a shape of its
@ -534,6 +547,8 @@ func writeShapes() []writeShape {
"status", "priority", "issue_type", "assignee", "owner", "estimated_minutes",
"external_ref", "due_at", "defer_until", "sender", "metadata", "labels",
"ephemeral", "no_history",
// The gate members, behind issues.create.gates.
"await_type", "await_id", "timeout", "waiters",
},
partial: "W-CreateItem.Issue",
},
@ -593,6 +608,10 @@ func writeShapes() []writeShape {
// expressible on this document.
"Labels": member("labels"),
"Metadata": member("metadata"),
// The gate members, behind issues.update.gates,
// spelled as on updateIssue.
"AwaitID": member("await_id"),
"Waiters": member("waiters"),
},
},
{

View file

@ -411,7 +411,12 @@ func TestUpdateRefusesEveryMemberTheWireExcludes(t *testing.T) {
"Patch.Owner": {Patch: issueops.IssuePatch{Owner: set("someone")}},
"Patch.ClosedBySession": {Patch: issueops.IssuePatch{ClosedBySession: set("s1")}},
"Patch.SpecID": {Patch: issueops.IssuePatch{SpecID: set("spec")}},
"Patch.AwaitID": {Patch: issueops.IssuePatch{AwaitID: set("await")}},
// Patch.AwaitID and Patch.Waiters WERE here; issues.update.gates
// publishes both.
// TestUpdateSendsTheGateMembersToAServerThatAdvertisesThem is the
// positive assertion, and
// TestUpdateRefusesTheGateMembersAgainstAServerWithoutTheToken the
// pre-dial capability refusal.
// Patch.Persistence WAS here; issues.update.persistence publishes it
// (S21b). TestUpdatePersistenceIsSentOnlyToAServerThatAdvertisesIt
// is the positive assertion and the pre-dial capability refusal.

View file

@ -280,6 +280,11 @@ func TestBatchApplyContract(t *testing.T) {
defer cancel()
conformance.RunBatchApplyAppliesTheDefaultPriority(t, ctx, fixture)
})
t.Run("CarriesTheGateMembers", func(t *testing.T) {
ctx, cancel := testContext(t)
defer cancel()
conformance.RunBatchApplyCarriesTheGateMembers(t, ctx, fixture)
})
}
// newDoltBatchApplyFixture composes the frozen role kit with this backend's

View file

@ -152,6 +152,7 @@ func nonCoordinationPatchSignals(patch issueops.IssuePatch) []bool {
patch.AppendNotes.Set,
patch.SpecID.Set,
patch.AwaitID.Set,
patch.Waiters.Set,
patch.Priority.Set,
patch.IssueType.Set,
patch.Owner.Set,

View file

@ -42,6 +42,12 @@ func TestLifecycleCreateContract(t *testing.T) {
t.Run("AppliesTheDefaultPriority", func(t *testing.T) {
conformance.RunLifecycleCreateAppliesTheDefaultPriority(t, ctx, fixture)
})
t.Run("WritesTheGateMembers", func(t *testing.T) {
conformance.RunLifecycleCreateWritesTheGateMembers(t, ctx, fixture)
})
t.Run("BoundsTheGateMembers", func(t *testing.T) {
conformance.RunLifecycleCreateBoundsTheGateMembers(t, ctx, fixture)
})
}
func newDoltLifecycleCreateFixture(t *testing.T, prefix string) (conformance.LifecycleCreateFixture, context.Context, func()) {

View file

@ -102,6 +102,12 @@ func TestLifecycleUpdateContract(t *testing.T) {
t.Run("AllowTemplateEditsATemplate", func(t *testing.T) {
conformance.RunLifecycleUpdateAllowTemplateEditsATemplate(t, ctx, fixture)
})
t.Run("PatchesTheGateMembers", func(t *testing.T) {
conformance.RunLifecycleUpdatePatchesTheGateMembers(t, ctx, fixture)
})
t.Run("BoundsTheGateMembers", func(t *testing.T) {
conformance.RunLifecycleUpdateBoundsTheGateMembers(t, ctx, fixture)
})
}
func newDoltLifecycleUpdateFixture(t *testing.T, prefix string) (conformance.LifecycleUpdateFixture, context.Context, func()) {

View file

@ -202,6 +202,9 @@ func TestBatchApplyContract(t *testing.T) {
t.Run("AppliesTheDefaultPriority", func(t *testing.T) {
conformance.RunBatchApplyAppliesTheDefaultPriority(t, ctx, fixture)
})
t.Run("CarriesTheGateMembers", func(t *testing.T) {
conformance.RunBatchApplyCarriesTheGateMembers(t, ctx, fixture)
})
}
// newEmbeddedBatchApplyFixture composes the frozen role kit with this backend's

View file

@ -43,6 +43,12 @@ func TestLifecycleCreateContract(t *testing.T) {
t.Run("AppliesTheDefaultPriority", func(t *testing.T) {
conformance.RunLifecycleCreateAppliesTheDefaultPriority(t, ctx, fixture)
})
t.Run("WritesTheGateMembers", func(t *testing.T) {
conformance.RunLifecycleCreateWritesTheGateMembers(t, ctx, fixture)
})
t.Run("BoundsTheGateMembers", func(t *testing.T) {
conformance.RunLifecycleCreateBoundsTheGateMembers(t, ctx, fixture)
})
}
func newEmbeddedLifecycleCreateFixture(t *testing.T, te *testEnv, prefix string) conformance.LifecycleCreateFixture {

View file

@ -103,6 +103,12 @@ func TestLifecycleUpdateContract(t *testing.T) {
t.Run("AllowTemplateEditsATemplate", func(t *testing.T) {
conformance.RunLifecycleUpdateAllowTemplateEditsATemplate(t, ctx, fixture)
})
t.Run("PatchesTheGateMembers", func(t *testing.T) {
conformance.RunLifecycleUpdatePatchesTheGateMembers(t, ctx, fixture)
})
t.Run("BoundsTheGateMembers", func(t *testing.T) {
conformance.RunLifecycleUpdateBoundsTheGateMembers(t, ctx, fixture)
})
}
func newEmbeddedLifecycleUpdateFixture(t *testing.T, te *testEnv, prefix string) conformance.LifecycleUpdateFixture {

View file

@ -56,6 +56,7 @@ go_library(
"execution.go",
"federation.go",
"filters.go",
"gate_fields.go",
"get_issue.go",
"helpers.go",
"history.go",
@ -158,6 +159,7 @@ go_test(
"edge_role_requests_test.go",
"execution_test.go",
"filters_test.go",
"gate_fields_test.go",
"get_issue_test.go",
"helpers_test.go",
"identity_parity_test.go",

View file

@ -48,6 +48,7 @@ func UpdateFields(patch publicops.IssuePatch) map[string]interface{} {
{patch.AppendNotes.Set, OpAppendNotes, patch.AppendNotes.Value},
{patch.SpecID.Set, "spec_id", patch.SpecID.Value},
{patch.AwaitID.Set, "await_id", patch.AwaitID.Value},
{patch.Waiters.Set, "waiters", PatchWaiters(patch.Waiters)},
{patch.Status.Set, "status", patch.Status.Value},
{patch.Priority.Set, "priority", patch.Priority.Value},
{patch.IssueType.Set, "issue_type", patch.IssueType.Value},
@ -66,6 +67,17 @@ func UpdateFields(patch publicops.IssuePatch) map[string]interface{} {
return updates
}
// PatchWaiters is the storage value a set IssuePatch.Waiters writes: a copy of
// the list, with a nil list spelled empty so a clear stores the empty JSON
// array rather than JSON null. Both the issueops and the unit-of-work update
// bodies write through it.
func PatchWaiters(field publicops.Field[[]string]) []string {
if len(field.Value) == 0 {
return []string{}
}
return append([]string(nil), field.Value...)
}
// ValidateUpdateRequest checks mutually exclusive guarded-update options and
// the canonical field values every backend must reject identically. Backends
// call it before touching the row so an invalid patch cannot half-apply.
@ -104,6 +116,9 @@ func ValidateUpdateRequest(request publicops.UpdateRequest) error {
return fmt.Errorf("%w: update estimated_minutes: %w", storage.ErrValidation, err)
}
}
if err := ValidateGatePatch(patch); err != nil {
return err
}
if patch.Persistence.Set && !patch.Persistence.Value.IsValid() {
return fmt.Errorf("%w: invalid persistence mode %q", storage.ErrValidation, patch.Persistence.Value)
}

View file

@ -0,0 +1,107 @@
package issueops
import (
"encoding/json"
"fmt"
"time"
"unicode/utf8"
"github.com/steveyegge/beads/internal/types"
publicops "github.com/steveyegge/beads/issueops"
)
// MaxAwaitTypeLen is the await_type column's width in characters
// (VARCHAR(32), migration 0001).
const MaxAwaitTypeLen = 32
// ValidateGateFields checks an issue's gate members against the stored
// columns, for every create shape of the role: PreparePublicCreateRequest
// runs it, so Lifecycle.Create, BatchCreator items and BatchApplier create
// items share it on every backend.
//
// The widths are the columns' and no more (see publicops.GateFieldError):
// a Dolt column already refused an oversized value with a raw driver error,
// and a Postgres text column accepted it, so this converges the two on one
// typed refusal. The one rule that is not a width, a non-negative timeout, is
// no column's (timeout_ns is a BIGINT); the wire publishes it as minimum 0.
// The raw store creates (CreateIssue, CreateIssues) and import do not run
// this check, 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.
func ValidateGateFields(issue *types.Issue) error {
if issue == nil {
return nil
}
if err := validateAwaitType(issue.AwaitType); err != nil {
return err
}
if err := validateAwaitID(issue.AwaitID); err != nil {
return err
}
if err := validateGateTimeout(issue.Timeout); err != nil {
return err
}
return validateWaiters(issue.Waiters)
}
// ValidateGatePatch checks the gate members an IssuePatch can set — await_id
// and waiters — with ValidateGateFields' rules. await_type and timeout are not
// patch members: no update route has ever changed them.
func ValidateGatePatch(patch publicops.IssuePatch) error {
if patch.AwaitID.Set {
if err := validateAwaitID(patch.AwaitID.Value); err != nil {
return err
}
}
if patch.Waiters.Set {
if err := validateWaiters(patch.Waiters.Value); err != nil {
return err
}
}
return nil
}
func gateFieldError(field, format string, args ...any) error {
return &publicops.GateFieldError{
Field: field,
Detail: fmt.Sprintf("%s: %s", publicops.ErrValidation.Error(), fmt.Sprintf(format, args...)),
}
}
func validateAwaitType(value string) error {
if n := utf8.RuneCountInString(value); n > MaxAwaitTypeLen {
return gateFieldError(publicops.GateFieldAwaitType, "await_type is %d characters (max %d)", n, MaxAwaitTypeLen)
}
return nil
}
func validateAwaitID(value string) error {
if n := utf8.RuneCountInString(value); n > types.MaxFieldLen {
return gateFieldError(publicops.GateFieldAwaitID, "await_id is %d characters (max %d)", n, types.MaxFieldLen)
}
return nil
}
func validateGateTimeout(value time.Duration) error {
if value < 0 {
return gateFieldError(publicops.GateFieldTimeout, "timeout cannot be negative (got %s)", value)
}
return nil
}
// validateWaiters bounds the list by the TEXT column it is stored in, as the
// JSON array every backend writes. Entries are otherwise opaque: blank and
// repeated entries are stored as given, as local updates always stored them.
func validateWaiters(waiters []string) error {
if len(waiters) == 0 {
return nil
}
encoded, err := json.Marshal(waiters)
if err != nil {
return gateFieldError(publicops.GateFieldWaiters, "waiters cannot be encoded: %v", err)
}
if n := len(encoded); n > types.MaxTextBytes {
return gateFieldError(publicops.GateFieldWaiters, "waiters encode to %d bytes (max %d)", n, types.MaxTextBytes)
}
return nil
}

View file

@ -0,0 +1,97 @@
package issueops
import (
"errors"
"strings"
"testing"
"time"
"github.com/steveyegge/beads/internal/types"
publicops "github.com/steveyegge/beads/issueops"
)
func TestValidateGateFieldsBoundsEachMemberAtItsColumn(t *testing.T) {
atBound := &types.Issue{
AwaitType: strings.Repeat("é", MaxAwaitTypeLen),
AwaitID: strings.Repeat("é", types.MaxFieldLen),
Timeout: 0,
Waiters: []string{strings.Repeat("w", types.MaxTextBytes-4)},
}
if err := ValidateGateFields(atBound); err != nil {
t.Fatalf("every member at its bound: %v, want nil", err)
}
// Free-form type, blank and duplicate waiters, any issue type: no rule.
if err := ValidateGateFields(&types.Issue{IssueType: types.TypeTask, AwaitType: "mail", Waiters: []string{"", "a", "a"}}); err != nil {
t.Fatalf("free-form gate members: %v, want nil", err)
}
if err := ValidateGateFields(nil); err != nil {
t.Fatalf("nil issue: %v, want nil", err)
}
for _, test := range []struct {
name string
field string
issue types.Issue
}{
{"await_type", publicops.GateFieldAwaitType, types.Issue{AwaitType: strings.Repeat("é", MaxAwaitTypeLen+1)}},
{"await_id", publicops.GateFieldAwaitID, types.Issue{AwaitID: strings.Repeat("é", types.MaxFieldLen+1)}},
{"timeout", publicops.GateFieldTimeout, types.Issue{Timeout: -time.Nanosecond}},
{"waiters", publicops.GateFieldWaiters, types.Issue{Waiters: []string{strings.Repeat("w", types.MaxTextBytes-3)}}},
} {
t.Run(test.name, func(t *testing.T) {
issue := test.issue
assertGateFieldErr(t, ValidateGateFields(&issue), test.field)
})
}
}
func TestValidateGatePatchChecksOnlySetMembers(t *testing.T) {
if err := ValidateGatePatch(publicops.IssuePatch{}); err != nil {
t.Fatalf("empty patch: %v", err)
}
if err := ValidateGatePatch(publicops.IssuePatch{AwaitID: publicops.Field[string]{Set: true}, Waiters: publicops.Field[[]string]{Set: true}}); err != nil {
t.Fatalf("clearing patch: %v", err)
}
assertGateFieldErr(t, ValidateGatePatch(publicops.IssuePatch{
AwaitID: publicops.Field[string]{Set: true, Value: strings.Repeat("a", types.MaxFieldLen+1)},
}), publicops.GateFieldAwaitID)
assertGateFieldErr(t, ValidateUpdateRequest(publicops.UpdateRequest{Patch: publicops.IssuePatch{
Waiters: publicops.Field[[]string]{Set: true, Value: []string{strings.Repeat("w", types.MaxTextBytes)}},
}}), publicops.GateFieldWaiters)
}
func TestValidatePublicCreateRequestRefusesAGateMemberByName(t *testing.T) {
err := ValidatePublicCreateRequest(publicops.CreateRequest{Actor: "a", Issue: &types.Issue{Title: "t", Timeout: -time.Second}})
assertGateFieldErr(t, err, publicops.GateFieldTimeout)
}
func TestUpdateFieldsMapsWaitersAsAWholeValue(t *testing.T) {
source := []string{"a", "a"}
updates := UpdateFields(publicops.IssuePatch{Waiters: publicops.Field[[]string]{Set: true, Value: source}})
got, ok := updates["waiters"].([]string)
if !ok || len(got) != 2 || got[0] != "a" || got[1] != "a" {
t.Fatalf("waiters update = %#v, want the list as given", updates["waiters"])
}
source[0] = "mutated"
if got[0] != "a" {
t.Fatal("the waiters update aliases the caller's slice")
}
cleared := UpdateFields(publicops.IssuePatch{Waiters: publicops.Field[[]string]{Set: true}})
if got, ok := cleared["waiters"].([]string); !ok || got == nil || len(got) != 0 {
t.Fatalf("cleared waiters update = %#v, want a non-nil empty list (stored as [] rather than null)", cleared["waiters"])
}
if _, present := UpdateFields(publicops.IssuePatch{})["waiters"]; present {
t.Fatal("an unset Waiters wrote the waiters key")
}
}
func assertGateFieldErr(t *testing.T, err error, field string) {
t.Helper()
if !errors.Is(err, publicops.ErrValidation) {
t.Fatalf("error = %v, want ErrValidation", err)
}
var fieldErr *publicops.GateFieldError
if !errors.As(err, &fieldErr) || fieldErr.Field != field {
t.Fatalf("error = %#v, want a *GateFieldError naming %s", err, field)
}
}

View file

@ -47,6 +47,12 @@ func ValidatePublicCreateRequest(request publicops.CreateRequest) error {
if err := types.CheckFieldLen("parent ID", request.ParentID); err != nil {
return publicCreateValidationError(fmt.Errorf("create: %w", err))
}
// The gate members, as a *publicops.GateFieldError naming the member so a
// front door can point at it. Here rather than in PreparePublicCreateRequest
// alone so the unit-of-work backend's early check refuses it too.
if err := ValidateGateFields(request.Issue); err != nil {
return err
}
if err := ValidateCreatePriority(request.Issue.Priority, request.DefaultPriority); err != nil {
return err
}

View file

@ -24,6 +24,7 @@ func CloneCreateRequest(request publicops.CreateRequest) publicops.CreateRequest
func CloneUpdateRequest(request publicops.UpdateRequest) publicops.UpdateRequest {
clone := request
clone.Patch.Labels.Add = append([]string(nil), request.Patch.Labels.Add...)
clone.Patch.Waiters.Value = append([]string(nil), request.Patch.Waiters.Value...)
clone.Patch.Labels.Remove = append([]string(nil), request.Patch.Labels.Remove...)
clone.Patch.Labels.Replace.Value = append([]string(nil), request.Patch.Labels.Replace.Value...)
clone.Patch.Metadata.Replace.Value = cloneRawMessage(request.Patch.Metadata.Replace.Value)

View file

@ -45,7 +45,12 @@ func TestCloneIssueOperationRequestsDeepCopyMutableFields(t *testing.T) {
update.Patch.ExternalRef = publicops.Field[*string]{Set: true, Value: &ref}
update.Patch.DueAt = publicops.Field[*time.Time]{Set: true, Value: &now}
update.Patch.DeferUntil = publicops.Field[*time.Time]{Set: true, Value: &now}
update.Patch.Waiters = publicops.Field[[]string]{Set: true, Value: []string{"waiter"}}
updateClone := CloneUpdateRequest(update)
updateClone.Patch.Waiters.Value[0] = "changed"
if update.Patch.Waiters.Value[0] != "waiter" {
t.Fatal("CloneUpdateRequest() shares the caller's Waiters list")
}
updateClone.Patch.Metadata.Set["key"][0] = '{'
updateClone.Patch.Metadata.Unset[0] = "changed"
updateClone.Patch.Metadata.Replace.Value[0] = '{'
@ -94,6 +99,7 @@ func TestIssueOperationCloneFunctionsKeepFrozenRequestFields(t *testing.T) {
assertFieldValueMutable(t, reflect.TypeOf(publicops.Field[*string]{}), "IssuePatch.ExternalRef")
assertFieldValueMutable(t, reflect.TypeOf(publicops.Field[*time.Time]{}), "IssuePatch.DueAt")
assertFieldValueMutable(t, reflect.TypeOf(publicops.Field[*time.Time]{}), "IssuePatch.DeferUntil")
assertFieldValueMutable(t, reflect.TypeOf(publicops.Field[[]string]{}), "IssuePatch.Waiters")
}
func isMutableKind(kind reflect.Kind) bool {

View file

@ -311,23 +311,27 @@ const issueOperationsUpdateRawSeamWaiverReason = "these three cases take the unt
// because SOME of their racers patch fields updateIssue refuses outright
// rather than ever sending — not a race outcome, a refusal before any
// request leaves the client. internal/httpclient/encode/ledger.go already
// names this gap per field (W-IssuePatch.SpecID, W-IssuePatch.AwaitID,
// W-IssuePatch.Owner, D8 refuse-not-drop): neither IssuePatchBody nor
// ApplyPatchBody publishes spec_id or await_id at all, and Owner is excluded
// names this gap per field (W-IssuePatch.SpecID, W-IssuePatch.Owner, D8
// refuse-not-drop): neither IssuePatchBody nor
// ApplyPatchBody publishes spec_id at all, and Owner is excluded
// from IssuePatchBody specifically (ApplyPatchBody — issues:batchApply's body
// — does carry it, which is a different operation from updateIssue). Closing
// this gap means publishing those fields on IssuePatchBody, a wire change to
// the write role itself, not a client-side wiring exercise — tracked as a
// follow-up slice, S4b: publish owner/spec_id/await_id on the wire. Until
// S4b lands, these two contracts stay off this leg rather than asserting a
// race outcome against a request three of its own racers never send.
// follow-up slice, S4b: publish owner/spec_id/await_id on the wire. await_id
// is published on both patch bodies behind issues.update.gates and sent by
// this client (W-IssuePatch.AwaitID retired), so only
// spec_id and owner remain S4b's. Until they land, these two contracts stay
// off this leg rather than asserting a race outcome against a request some of
// its racers never send.
const issuePatchFieldsNotOnUpdateWireWaiverReason = "PENDING, not permanent (tracked as S4b: publish " +
"owner/spec_id/await_id on the wire): two of the four ExpectedVersion concurrency contracts race " +
"IssuePatch.SpecID/.AwaitID/.Owner edits against updateIssue, and those three fields are refused outright by " +
"IssuePatchBody (W-IssuePatch.SpecID, W-IssuePatch.AwaitID, W-IssuePatch.Owner in " +
"IssuePatch.SpecID/.AwaitID/.Owner edits against updateIssue, and SpecID and Owner are refused outright by " +
"this client (W-IssuePatch.SpecID, W-IssuePatch.Owner in " +
"internal/httpclient/encode/ledger.go, D8 refuse-not-drop) rather than ever reaching the server, so the race " +
"never happens over this wire; closing the gap means publishing those fields on IssuePatchBody, which is a " +
"wire change to the write role (S4b), not something this leg's test wiring can bind around today"
"never happens over this wire; await_id is sent behind issues.update.gates, and " +
"closing the rest of the gap means publishing spec_id and owner on IssuePatchBody, which is a wire change " +
"to the write role (S4b), not something this leg's test wiring can bind around today"
// TestEveryLegWiresEveryRoleContract fails when a backend leg skips a role
// contract the conformance package exports.

View file

@ -172,6 +172,9 @@ func TestBatchApplyContract(t *testing.T) {
t.Run("AppliesTheDefaultPriority", func(t *testing.T) {
conformance.RunBatchApplyAppliesTheDefaultPriority(t, ctx, fixture)
})
t.Run("CarriesTheGateMembers", func(t *testing.T) {
conformance.RunBatchApplyCarriesTheGateMembers(t, ctx, fixture)
})
}
func newUOWBatchApplyFixture(t *testing.T, ctx context.Context, prefix string) conformance.BatchApplyFixture {

View file

@ -313,6 +313,9 @@ func updateSpec(request publicops.UpdateRequest) (domain.UpdateSpec, error) {
setField(fields, "acceptance_criteria", patch.AcceptanceCriteria)
setField(fields, "spec_id", patch.SpecID)
setField(fields, "await_id", patch.AwaitID)
if patch.Waiters.Set {
fields["waiters"] = storageissueops.PatchWaiters(patch.Waiters)
}
setField(fields, "status", patch.Status)
setField(fields, "priority", patch.Priority)
if patch.IssueType.Set {

View file

@ -43,6 +43,12 @@ func TestLifecycleCreateContract(t *testing.T) {
t.Run("AppliesTheDefaultPriority", func(t *testing.T) {
conformance.RunLifecycleCreateAppliesTheDefaultPriority(t, ctx, fixture)
})
t.Run("WritesTheGateMembers", func(t *testing.T) {
conformance.RunLifecycleCreateWritesTheGateMembers(t, ctx, fixture)
})
t.Run("BoundsTheGateMembers", func(t *testing.T) {
conformance.RunLifecycleCreateBoundsTheGateMembers(t, ctx, fixture)
})
}
func newUOWLifecycleCreateFixture(t *testing.T, ctx context.Context, prefix string) conformance.LifecycleCreateFixture {

View file

@ -104,6 +104,12 @@ func TestLifecycleUpdateContract(t *testing.T) {
t.Run("AllowTemplateEditsATemplate", func(t *testing.T) {
conformance.RunLifecycleUpdateAllowTemplateEditsATemplate(t, ctx, fixture)
})
t.Run("PatchesTheGateMembers", func(t *testing.T) {
conformance.RunLifecycleUpdatePatchesTheGateMembers(t, ctx, fixture)
})
t.Run("BoundsTheGateMembers", func(t *testing.T) {
conformance.RunLifecycleUpdateBoundsTheGateMembers(t, ctx, fixture)
})
}
func newUOWLifecycleUpdateFixture(t *testing.T, ctx context.Context, prefix string) conformance.LifecycleUpdateFixture {

View file

@ -68,3 +68,40 @@ func ListGates(ctx context.Context, querier Querier, req GateListRequest) ([]*ty
}
return gates, nil
}
// The gate members a GateFieldError can name, spelled as the wire and the
// stored columns spell them.
const (
GateFieldAwaitType = "await_type"
GateFieldAwaitID = "await_id"
GateFieldTimeout = "timeout"
GateFieldWaiters = "waiters"
)
// GateFieldError reports a gate member a create or an update refused, and the
// one member it is about, so a front door can name that member without parsing
// the message. It wraps ErrValidation.
//
// The widths are the stored columns' and nothing more, so every backend
// refuses the same values a Dolt column always did: await_type at most 32
// characters, await_id at most 255, and the JSON-encoded waiter list at most
// one TEXT column. The one rule no column enforces is a timeout that is not
// negative (timeout_ns is a BIGINT), which the wire publishes as minimum 0;
// the raw store creates do not run it yet (see ValidateGateFields). There is
// deliberately no await_type vocabulary (formula gate types are free-form), no
// gate-type-only rule (any issue may carry the members, as local updates
// always allowed), and no waiter deduplication.
type GateFieldError struct {
// Field is one of the GateField* constants.
Field string
// Detail is the sentence the error reads as. It is prose, and the HTTP
// client's copy ends with the server's own clause ("; nothing was
// created", "; nothing was written"), so a caller dispatches on Field,
// never on Detail.
Detail string
}
func (e *GateFieldError) Error() string { return e.Detail }
// Unwrap makes GateFieldError match ErrValidation.
func (e *GateFieldError) Unwrap() error { return ErrValidation }

View file

@ -125,7 +125,15 @@ type IssuePatch struct {
// AppendNotes appends to the notes and is mutually exclusive with Notes.
AppendNotes Field[string]
SpecID Field[string]
AwaitID Field[string]
// AwaitID replaces the gate's condition identifier; the empty string
// clears it. Its bounds are ValidateGateFields' (GateFieldError).
AwaitID Field[string]
// Waiters is a WHOLE-VALUE replacement of the gate's waiter list; a set
// nil or empty Value clears it. The role stores the list as given:
// duplicates are kept, as local storage always has, and deduplication is
// the caller's (bd gate add-waiter dedups before it writes). Its bounds
// are the column's (GateFieldError naming GateFieldWaiters).
Waiters Field[[]string]
// Status sets the issue's status. A status that crosses from outside the
// configured done category into it answers to close policy: the update
// refuses with CloseOpenChildrenError or ErrCloseBlocked unless