From a7fe6aea505de1f064b19ec58061bc1ddaf419fa Mon Sep 17 00:00:00 2001 From: Julian Knutsen Date: Wed, 30 Sep 2026 15:42:37 -0700 Subject: [PATCH] feat(httpapi): PATCH /v0/beads/issues/{id} accepts claim, the wire spelling of bd update --claim (#6890) The update operation had no way to express a claim, so an HTTP client of `bd serve` had to refuse `bd update --claim` outright. The request now carries a `claim` boolean that passes straight through to issueops.UpdateRequest.Claim on the same lifecycle role the direct route uses, so the claim and the patch land in one transaction with the direct route's semantics: same-actor re-claim is idempotent (changed: false), a foreign holder is 409 already_claimed and an unclaimable status 409 not_claimable, both naming `claim` and carrying {id}:claim's extension members (shared through claimRefusal), and a refused claim writes none of the patch. With claim: true the patch may be empty (the claim is the whole write). claim beside expected_assignee, expected_status or force_assignee_transfer is refused at the edge as a 400 naming `claim` rather than surfacing the role's ErrValidation as the generic patch 400. No capability token: per the document's version-skew rules, member presence is probed, and an older server refuses `claim` as unknown_parameter before any database work. Co-authored-by: Claude Opus 5.5 (1M context) Co-authored-by: Eddie the Engineer --- CHANGELOG.md | 14 ++ cmd/bd/BUILD.bazel | 1 + ...e_update_claim_proxied_integration_test.go | 142 +++++++++++++ internal/httpapi/apigen/types.gen.go | 7 +- internal/httpapi/claim.go | 13 +- internal/httpapi/problem.go | 5 +- internal/httpapi/spec/openapi.v0.yaml | 74 ++++++- internal/httpapi/update.go | 65 +++++- internal/httpapi/update_test.go | 188 +++++++++++++++++- 9 files changed, 486 insertions(+), 23 deletions(-) create mode 100644 cmd/bd/serve_update_claim_proxied_integration_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index aee59b70d..f95a78ec2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -503,6 +503,20 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 partial, and the count alone cannot tell the two apart. +- **`PATCH /v0/beads/issues/{id}` accepts `claim: true`**, the wire spelling of + `bd update --claim`. It passes through to the same lifecycle role the + direct route uses (`issueops.UpdateRequest.Claim`), so the claim and the + patch land in one transaction with the direct route's semantics: a + same-actor re-claim is idempotent (`changed: false`), a foreign holder is + 409 `already_claimed` and an unclaimable status 409 `not_claimable` — both + naming `claim` and carrying `{id}:claim`'s `assignee` / `issue_status` + members — and a refused claim writes none of the patch. With `claim: true` + the `patch` may be empty. `claim` beside `expected_assignee`, + `expected_status` or `force_assignee_transfer` is a 400. A server that + predates the member refuses it as `unknown_parameter` before any database + work, so an HTTP client can forward `bd update --claim` instead of refusing + it, and can never mistake an older server for one that dropped the claim. + ### Fixed - **`bd show` counts a wisp's comments instead of reporting `comment_count: 0`** diff --git a/cmd/bd/BUILD.bazel b/cmd/bd/BUILD.bazel index c47697a15..ca40a43c9 100644 --- a/cmd/bd/BUILD.bazel +++ b/cmd/bd/BUILD.bazel @@ -1040,6 +1040,7 @@ go_test( "serve_source_test.go", "serve_store_identity_test.go", "serve_test.go", + "serve_update_claim_proxied_integration_test.go", "serve_update_proxied_integration_test.go", "set_state_proxied_integration_test.go", "setup_embedded_test.go", diff --git a/cmd/bd/serve_update_claim_proxied_integration_test.go b/cmd/bd/serve_update_claim_proxied_integration_test.go new file mode 100644 index 000000000..6e180508c --- /dev/null +++ b/cmd/bd/serve_update_claim_proxied_integration_test.go @@ -0,0 +1,142 @@ +//go:build cgo + +package main + +import ( + "net/http" + "testing" +) + +// End-to-end for PATCH /v0/beads/issues/{id} with `claim: true`, against real +// Dolt through a real `bd serve` subprocess. The pure tests in internal/httpapi +// pin the projection onto issueops.UpdateRequest.Claim and the refusal mapping +// on a fake role; what only this level can prove is the SEMANTICS the member +// promises by passing through to the role `bd update --claim` uses: the claim +// lands, a same-actor re-claim is idempotent, a foreign holder and an +// unclaimable status refuse, and a refused claim writes none of the patch it +// rode beside. +func TestProxiedServerServeUpdateClaim(t *testing.T) { + requireSharedProxiedServer(t) + t.Parallel() + bd := buildEmbeddedBD(t) + p := newSharedProxiedProject(t, bd, "srvupdcl") + sp := startServe(t, bd, p.dir, bdProxiedEnv(p.dir)) + + t.Run("a claim alone lands, and the same actor's re-claim is idempotent", func(t *testing.T) { + issue := bdProxiedCreate(t, bd, p.dir, "claim via update", "-p", "2") + + status, body := sp.updateIssue(t, issue.ID, `{"actor":"agent-a","claim":true,"patch":{}}`) + if status != http.StatusOK { + t.Fatalf("status = %d, want 200: %v", status, body) + } + if body["changed"] != true { + t.Errorf("changed = %v, want true on a fresh claim", body["changed"]) + } + claimed, _ := body["issue"].(map[string]any) + if claimed["assignee"] != "agent-a" || claimed["status"] != "in_progress" { + t.Errorf("answered issue = %v, want it held by agent-a and in progress", claimed) + } + shown := bdProxiedShow(t, bd, p.dir, issue.ID) + if shown.Assignee != "agent-a" || string(shown.Status) != "in_progress" { + t.Fatalf("row = %q/%q, want agent-a/in_progress", shown.Assignee, shown.Status) + } + + // The direct route's idempotence: held by the same actor and in + // progress already is a success that changes nothing. + status, body = sp.updateIssue(t, issue.ID, `{"actor":"agent-a","claim":true,"patch":{}}`) + if status != http.StatusOK { + t.Fatalf("re-claim: status = %d, want 200: %v", status, body) + } + if body["changed"] != false { + t.Errorf("re-claim: changed = %v, want false", body["changed"]) + } + + // And a re-claim that rides a field edit applies the edit. + status, body = sp.updateIssue(t, issue.ID, `{"actor":"agent-a","claim":true,"patch":{"title":"still mine"}}`) + if status != http.StatusOK { + t.Fatalf("re-claim with a title: status = %d, want 200: %v", status, body) + } + if shown := bdProxiedShow(t, bd, p.dir, issue.ID); shown.Title != "still mine" || shown.Assignee != "agent-a" { + t.Errorf("row = %q held by %q, want the retitle under agent-a's claim", shown.Title, shown.Assignee) + } + }) + + t.Run("a claim and a patch land in one write", func(t *testing.T) { + issue := bdProxiedCreate(t, bd, p.dir, "claim and edit", "-p", "3") + + status, body := sp.updateIssue(t, issue.ID, + `{"actor":"agent-a","claim":true,"patch":{"priority":1,"notes":"picked up"}}`) + if status != http.StatusOK { + t.Fatalf("status = %d, want 200: %v", status, body) + } + shown := bdProxiedShow(t, bd, p.dir, issue.ID) + if shown.Assignee != "agent-a" || string(shown.Status) != "in_progress" { + t.Errorf("row = %q/%q, want agent-a/in_progress", shown.Assignee, shown.Status) + } + if shown.Priority != 1 || shown.Notes != "picked up" { + t.Errorf("row priority %d notes %q, want the patch beside the claim", shown.Priority, shown.Notes) + } + }) + + t.Run("a foreign holder refuses the claim and the patch", func(t *testing.T) { + issue := bdProxiedCreate(t, bd, p.dir, "held", "-p", "2") + if status, body := sp.updateIssue(t, issue.ID, `{"actor":"agent-a","claim":true,"patch":{}}`); status != http.StatusOK { + t.Fatalf("seed claim: status = %d: %v", status, body) + } + + status, problem := sp.updateIssue(t, issue.ID, `{"actor":"agent-b","claim":true,"patch":{"title":"stolen"}}`) + if status != http.StatusConflict { + t.Fatalf("status = %d, want 409: %v", status, problem) + } + if problem["code"] != "already_claimed" || problem["param"] != "claim" { + t.Errorf("code/param = %v/%v, want already_claimed/claim", problem["code"], problem["param"]) + } + if problem["assignee"] != "agent-a" { + t.Errorf("assignee = %v, want the holder read by the refusing transaction", problem["assignee"]) + } + shown := bdProxiedShow(t, bd, p.dir, issue.ID) + if shown.Title != "held" || shown.Assignee != "agent-a" { + t.Errorf("row = %q held by %q; a refused claim wrote its patch or moved the claim", shown.Title, shown.Assignee) + } + }) + + t.Run("an unclaimable status refuses the claim and the patch", func(t *testing.T) { + issue := bdProxiedCreate(t, bd, p.dir, "done already", "-p", "2") + if out, err := bdProxiedRun(t, bd, p.dir, "close", issue.ID); err != nil { + t.Fatalf("bd close: %v\n%s", err, out) + } + + status, problem := sp.updateIssue(t, issue.ID, `{"actor":"agent-a","claim":true,"patch":{"priority":0}}`) + if status != http.StatusConflict { + t.Fatalf("status = %d, want 409: %v", status, problem) + } + if problem["code"] != "not_claimable" || problem["param"] != "claim" { + t.Errorf("code/param = %v/%v, want not_claimable/claim", problem["code"], problem["param"]) + } + if problem["issue_status"] != "closed" { + t.Errorf("issue_status = %v, want closed", problem["issue_status"]) + } + shown := bdProxiedShow(t, bd, p.dir, issue.ID) + if shown.Priority != 2 || shown.Assignee != "" || string(shown.Status) != "closed" { + t.Errorf("row priority %d assignee %q status %q; a refused claim wrote", shown.Priority, shown.Assignee, shown.Status) + } + }) + + // The other direction of atomicity: a patch the role refuses leaves no + // claim behind. + t.Run("a refused patch leaves no claim behind", func(t *testing.T) { + issue := bdProxiedCreate(t, bd, p.dir, "bad patch", "-p", "2") + + status, body := sp.updateIssue(t, issue.ID, + `{"actor":"agent-a","claim":true,"patch":{"issue_type":"not-a-configured-type"}}`) + if status != http.StatusBadRequest { + t.Fatalf("status = %d, want 400: %v", status, body) + } + shown := bdProxiedShow(t, bd, p.dir, issue.ID) + if shown.Assignee != "" || string(shown.Status) != "open" { + t.Errorf("row = %q/%q; the refused update left a claim", shown.Assignee, shown.Status) + } + }) + + sp.shutdown(t) +} diff --git a/internal/httpapi/apigen/types.gen.go b/internal/httpapi/apigen/types.gen.go index 870046d99..ba640cb66 100644 --- a/internal/httpapi/apigen/types.gen.go +++ b/internal/httpapi/apigen/types.gen.go @@ -1324,7 +1324,7 @@ type IssueCount struct { // IssueDetails An `Issue` with its labels, dependency edges and cardinalities — the body of `GET /v0/beads/issues/{id}`. `dependencies` and `dependents` carry FULL issue objects plus the edge type, not bare edges. Property semantics are documented on `Issue`. type IssueDetails = types.IssueDetails -// IssuePatchBody The fields to write. Every member is optional and PRESENCE is the signal: a member present is written, a member absent is untouched. An empty object is a `400` — a write that writes nothing is a client bug. +// IssuePatchBody The fields to write. Every member is optional and PRESENCE is the signal: a member present is written, a member absent is untouched. An empty object is a `400` — a write that writes nothing is a client bug — except on `updateIssue` beside `claim: true`, where the claim is the write. // // This is a deliberate SUBSET of the fields an issue carries; the members it does not spell are future surface rather than oversights, and `updateIssue`'s own description says which and why. // @@ -1909,6 +1909,9 @@ type UpdateIssueRequest struct { // Actor Who is editing the issue. `ClaimRequest.actor`'s rules exactly: the server trims it, then refuses an empty result, anything longer than 256 BYTES (the `maxLength` above counts characters — the byte limit is the binding one), and any control character including newline. The value reaches the history entry's attribution and the storage commit message, so an unvalidated newline would forge audit-trail lines. Actor string `json:"actor"` + // Claim Claims the issue for `actor` in the same transaction as `patch`: `bd update --claim`, served by the same role. The claim sets `assignee` to `actor` and `status` to `in_progress`, then the patch applies, so a `patch.assignee` or `patch.status` overrides the claim's value. Eligibility is `{id}:claim`'s: a claimable status, and unassigned, already held by `actor`, or held by a configured claim pool. Held by `actor` and `in_progress` already is an idempotent success. A refusal is `409 already_claimed` or `409 not_claimable` naming `claim`, and writes nothing — the patch included. With `claim: true` the `patch` may be empty. It must not be combined with `expected_assignee`, `expected_status` or `force_assignee_transfer`; a request that does is a `400` naming `claim`. + Claim *bool `json:"claim,omitempty"` + // ExpectedAssignee Requires the issue's assignee to equal this value before the patch. A match AUTHORIZES the requested `patch.assignee` transfer: this compare-and-set replaces the ordinary anti-steal fence, so it must not be combined with `force_assignee_transfer`. A miss refuses the whole request with `409 precondition_failed`. ExpectedAssignee *string `json:"expected_assignee,omitempty"` @@ -1930,7 +1933,7 @@ type UpdateIssueRequest struct { // ForceClosePolicy Bypasses ONLY close policy — the open-children refusal and the live blocker refusal — for a `patch.status` that crosses into the workspace's done category. It has no effect without such a status change, and it never bypasses validation, the preconditions above, or the assignee fence. ForceClosePolicy *bool `json:"force_close_policy,omitempty"` - // Patch The fields to write. Every member is optional and PRESENCE is the signal: a member present is written, a member absent is untouched. An empty object is a `400` — a write that writes nothing is a client bug. + // Patch The fields to write. Every member is optional and PRESENCE is the signal: a member present is written, a member absent is untouched. An empty object is a `400` — a write that writes nothing is a client bug — except on `updateIssue` beside `claim: true`, where the claim is the write. // // This is a deliberate SUBSET of the fields an issue carries; the members it does not spell are future surface rather than oversights, and `updateIssue`'s own description says which and why. // diff --git a/internal/httpapi/claim.go b/internal/httpapi/claim.go index 2c28314c3..58590b313 100644 --- a/internal/httpapi/claim.go +++ b/internal/httpapi/claim.go @@ -298,7 +298,18 @@ func (s *Server) failClaim(w http.ResponseWriter, r *http.Request, err error) { s.failErr(w, r, err) return } + s.fail(w, r, claimRefusal(err)) +} + +// claimRefusal classifies a refused claim and attaches the extension members +// the role's typed conflict reports. It is shared with the update's `claim` +// member, so a claim refused on either operation reads the same. +func claimRefusal(err error) Result { res := ClassifyError(err) + var conflict *issueops.ClaimConflictError + if !errors.As(err, &conflict) { + return res + } // `assignee` is documented with already_claimed only: an issue refused for // its STATUS may well carry a stale assignee, and publishing it there would // tell a client someone holds work they do not. @@ -308,7 +319,7 @@ func (s *Server) failClaim(w http.ResponseWriter, r *http.Request, err error) { if conflict.Status != "" { res = res.WithIssueStatus(string(conflict.Status)) } - s.fail(w, r, res) + return res } // timedProvider records how long a request spent obtaining units of work, so diff --git a/internal/httpapi/problem.go b/internal/httpapi/problem.go index 4be427015..4ae319907 100644 --- a/internal/httpapi/problem.go +++ b/internal/httpapi/problem.go @@ -842,10 +842,13 @@ var operationCodes = map[string][]Code{ // workspace-vocabulary issue_type or status, a metadata key the query layer // could not spell, a field-length refusal that slipped the edge check — // through failUpdate. + // + // not_claimable arrived with `claim`, beside the already_claimed it shares + // with the fence: a refused claim answers as claimIssue does. OpUpdateIssue: { CodeInvalidArgument, CodeUnauthenticated, CodeNotFound, CodePreconditionFailed, CodeNotClosable, CodeAlreadyClaimed, - CodeDependencyCycle, CodeDependencyExists, + CodeNotClaimable, CodeDependencyCycle, CodeDependencyExists, CodeBusy, CodeDBUnavailable, CodeInternal, }, // No not_found. The role refuses an edge whose target names nothing, and diff --git a/internal/httpapi/spec/openapi.v0.yaml b/internal/httpapi/spec/openapi.v0.yaml index bbc9130df..ad273a79a 100644 --- a/internal/httpapi/spec/openapi.v0.yaml +++ b/internal/httpapi/spec/openapi.v0.yaml @@ -2199,7 +2199,32 @@ paths: An EMPTY `patch` object is a `400`: a write that writes nothing is a client bug, the same judgement `issues:batchCreate` makes about an - empty `items`. + empty `items`. The one exception is an empty `patch` beside + `claim: true`, where the claim is the whole write. + + + ## Claim + + + `claim: true` claims the issue for `actor` IN THE SAME TRANSACTION as + the patch — what `bd update --claim` does on the direct route, + through the same role, so eligibility, claim pools and the conflict + vocabulary are one definition. The claim sets `assignee` to `actor` and + `status` to `in_progress` first and the patch applies after it, so a + `patch.assignee` or `patch.status` overrides the claim's own value. An + issue already `in_progress` and held by `actor` is an idempotent + success (`changed: false` when the patch changes nothing either). A + refused claim writes NOTHING, the patch included. It cannot be + combined with `expected_assignee`, `expected_status` or + `force_assignee_transfer` — the claim is its own compare-and-set — + and it may be combined with `expected_version`, which is checked + before the claim. + + + A server that predates this member refuses it as an unknown member + (`400`, `reason: "unknown_parameter"`, `param: "claim"`) before any + database work, so a client can never mistake an older server for one + that dropped the claim. `labels` is COMPLETE REPLACEMENT. It is the only shape whose result the @@ -2229,8 +2254,9 @@ paths: preconditions above, or the other's guard. - Three members carry policy, which is where this operation's `409`s come - from. `status` crossing into the workspace's done category answers to + Four members carry policy, which is where this operation's `409`s come + from. `claim` answers exactly as `{id}:claim` does (`already_claimed`, + `not_claimable`). `status` crossing into the workspace's done category answers to close policy (`not_closable`). `assignee` transferring away from a live foreign in-progress owner answers to the assignee fence (`already_claimed`). `parent_id` is a graph edit and answers to the @@ -2313,7 +2339,8 @@ paths: value outside its documented bounds, `notes` together with `append_notes`, `metadata.replace` together with any other metadata edit, `force_assignee_transfer` without `patch.assignee` or beside - `expected_assignee`, a `patch.parent_id` naming the issue itself or + `expected_assignee`, `claim` beside `expected_assignee`, + `expected_status` or `force_assignee_transfer`, a `patch.parent_id` naming the issue itself or naming no issue this workspace holds — or a value this workspace's own validation refuses, such as an `issue_type` or `status` outside its configured vocabulary. @@ -2335,12 +2362,21 @@ paths: '409': description: >- The request is well-formed and the STATE refuses it, and NOTHING WAS - WRITTEN. Five codes, each inherited from the operation that already - publishes it rather than minted here, and described in the four + WRITTEN. Six codes, each inherited from the operation that already + publishes it rather than minted here, and described in the paragraphs below — `dependency_cycle` and `dependency_exists` share one, because they are one member reaching the graph. + `already_claimed` and `not_claimable` with `param: "claim"` are a + refused `claim`, answered as `POST /v0/beads/issues/{id}:claim` + answers them: `already_claimed` when another actor holds the issue + (with the `assignee` extension member when the refusing transaction + reported the holder), `not_claimable` when its status is not + claimable (with `issue_status`). Nothing was written, the patch + included. + + `precondition_failed` is `expected_version`, `expected_status` or `expected_assignee` missing. `param` names the guard member and the `expected_*` member echoes what the request asked for; the @@ -2356,7 +2392,8 @@ paths: `force_close_policy` is the bypass. - `already_claimed` is the assignee fence: a `patch.assignee` that + `already_claimed` with `param: "patch.assignee"` is the assignee + fence: a `patch.assignee` that transfers work away from a live foreign in-progress owner. `force_assignee_transfer` is the bypass and `expected_assignee` is the compare-and-set that replaces the fence outright. The `assignee` @@ -2383,7 +2420,7 @@ paths: scheduling cycle, every time. x-bd-codes: [already_claimed, dependency_cycle, dependency_exists, - not_closable, precondition_failed] + not_claimable, not_closable, precondition_failed] content: application/problem+json: schema: @@ -10306,6 +10343,23 @@ components: lines. patch: $ref: '#/components/schemas/IssuePatchBody' + claim: + type: boolean + default: false + description: >- + Claims the issue for `actor` in the same transaction as `patch`: + `bd update --claim`, served by the same role. The claim sets + `assignee` to `actor` and `status` to `in_progress`, then the patch + applies, so a `patch.assignee` or `patch.status` overrides the + claim's value. Eligibility is `{id}:claim`'s: a claimable status, + and unassigned, already held by `actor`, or held by a configured + claim pool. Held by `actor` and `in_progress` already is an + idempotent success. A refusal is `409 already_claimed` or `409 + not_claimable` naming `claim`, and writes nothing — the patch + included. With `claim: true` the `patch` may be empty. It must not + be combined with `expected_assignee`, `expected_status` or + `force_assignee_transfer`; a request that does is a `400` naming + `claim`. expected_version: type: string description: >- @@ -10376,7 +10430,9 @@ components: description: >- The fields to write. Every member is optional and PRESENCE is the signal: a member present is written, a member absent is untouched. An - empty object is a `400` — a write that writes nothing is a client bug. + empty object is a `400` — a write that writes nothing is a client bug — + except on `updateIssue` beside `claim: true`, where the claim is the + write. This is a deliberate SUBSET of the fields an issue carries; the members diff --git a/internal/httpapi/update.go b/internal/httpapi/update.go index 12757e940..2cd504db9 100644 --- a/internal/httpapi/update.go +++ b/internal/httpapi/update.go @@ -22,6 +22,10 @@ const ( // closed set that can grow without ever colliding with a request-level // member. updatePatchMember = "patch" + // updateClaimMember asks the update to CLAIM the issue for `actor` in the + // same transaction as the patch: issueops.UpdateRequest.Claim, which is + // what `bd update --claim` sends on the direct route. + updateClaimMember = "claim" // maxUpdateBodyBytes bounds the request body. A patch can carry a // description, a design and acceptance criteria at once, so the claim's // megabyte is too tight and the batch's four is the right order. @@ -34,7 +38,7 @@ const ( // error string. var ( updateRequestMembers = []string{ - "actor", "expected_assignee", "expected_status", "expected_version", + "actor", updateClaimMember, "expected_assignee", "expected_status", "expected_version", "force_assignee_transfer", "force_close_policy", updatePatchMember, } issuePatchMembers = []string{ @@ -141,7 +145,13 @@ func (s *Server) updateRequest(w http.ResponseWriter, r *http.Request, id string if !ok { return issueops.UpdateRequest{}, false } - patch, ok := s.issuePatch(w, r, id, members) + // Read BEFORE the patch, because it decides whether an empty patch is a + // request: a claim that edits nothing else is `bd update --claim`. + claim, ok := s.booleanMember(w, r, members, updateClaimMember) + if !ok { + return issueops.UpdateRequest{}, false + } + patch, ok := s.issuePatch(w, r, id, members, claim) if !ok { return issueops.UpdateRequest{}, false } @@ -167,6 +177,30 @@ func (s *Server) updateRequest(w http.ResponseWriter, r *http.Request, id string if !ok { return issueops.UpdateRequest{}, false } + // The role refuses a claim beside the assignee and status guards, and a + // claim beside the forced transfer (ValidateUpdateRequest): the claim is + // its own compare-and-set, with claim-pool eligibility the guards do not + // know. Refused HERE, naming `claim`, for the reason the pair below is — a + // role ErrValidation would otherwise reach the client as the generic + // "a patch value was refused" 400, naming a member the caller never got + // wrong. `expected_version` is NOT refused: the role checks it before the + // claim, exactly as on the direct route. + if claim { + for _, conflicting := range []struct { + present bool + member string + }{ + {expectedAssignee != nil, "expected_assignee"}, + {expectedStatus != nil, "expected_status"}, + {forceAssigneeTransfer, "force_assignee_transfer"}, + } { + if conflicting.present { + s.fail(w, r, InvalidArgument(updateClaimMember, ReasonInvalidValue, + "`claim` is its own compare-and-set; it cannot be combined with `"+conflicting.member+"`")) + return issueops.UpdateRequest{}, false + } + } + } // The role documents both combinations as invalid, and refusing them HERE // keeps the 400 a statement about the request rather than a translated // storage error — the `notes`/`append_notes` rule, applied to the two @@ -185,13 +219,16 @@ func (s *Server) updateRequest(w http.ResponseWriter, r *http.Request, id string } } - // Claim stays ZERO — acquiring work is `{id}:claim`, which carries its own - // eligibility rules — and so does IssuePlaneOnly, because this operation - // resolves across both planes. + // Claim is passed through, not re-implemented: the lifecycle role applies + // the same claim `bd update --claim` gets on the direct route — eligibility, + // claim pools, same-actor idempotence — in the transaction that applies the + // patch, so a refused claim writes none of it. IssuePlaneOnly stays ZERO, + // because this operation resolves across both planes. return issueops.UpdateRequest{ Actor: actor, IssueID: id, Patch: patch, + Claim: claim, ExpectedVersion: expectedVersion, ExpectedStatus: expectedStatus, ExpectedAssignee: expectedAssignee, @@ -245,7 +282,10 @@ const updateProvenance = "bd serve: update issue" // because it models both as a nil pointer. Explicit `null` is a third state // this reads directly off the raw bytes — a clear on the four nullable members, // and a 400 naming the member everywhere else. -func (s *Server) issuePatch(w http.ResponseWriter, r *http.Request, id string, members map[string]json.RawMessage) (issueops.IssuePatch, bool) { +// +// An EMPTY patch is a request only beside `claim`: the claim is then the whole +// write, which is `bd update --claim` with no other flag. +func (s *Server) issuePatch(w http.ResponseWriter, r *http.Request, id string, members map[string]json.RawMessage, claim bool) (issueops.IssuePatch, bool) { refuse := func(member, detail string) (issueops.IssuePatch, bool) { s.fail(w, r, InvalidArgument(patchParam(member), ReasonInvalidValue, detail)) return issueops.IssuePatch{}, false @@ -260,9 +300,12 @@ func (s *Server) issuePatch(w http.ResponseWriter, r *http.Request, id string, m return refuse("", "`"+updatePatchMember+"` must be a JSON object") } if len(fields) == 0 { + if claim { + return issueops.IssuePatch{}, true + } // A write that writes nothing is a client bug, not a no-op to answer — // the batch-create empty-items judgement, applied to a patch. - return refuse("", "`"+updatePatchMember+"` must carry at least one field; an update that updates nothing is refused rather than answered") + return refuse("", "`"+updatePatchMember+"` must carry at least one field, or ride beside `"+updateClaimMember+"`; an update that updates nothing is refused rather than answered") } if offender, unknown := unknownMember(fields, issuePatchMembers); unknown { s.failUnknownMember(w, r, patchParam(offender), issuePatchMembers) @@ -509,6 +552,14 @@ func (s *Server) failUpdate(w http.ResponseWriter, r *http.Request, request issu errors.Is(err, issueops.ErrAssigneeMismatch): s.fail(w, r, updatePreconditionResult(request, err)) + // A REFUSED CLAIM, answered exactly as `{id}:claim` answers it — + // `already_claimed` with the holder, `not_claimable` with the status — and + // naming `claim`, the member that earned it. Matched BEFORE the assignee + // fence's arm below, which shares the `already_claimed` sentinel but blames + // `patch.assignee` and steers toward a force this request cannot send. + case request.Claim && (errors.Is(err, storage.ErrAlreadyClaimed) || errors.Is(err, storage.ErrNotClaimable)): + s.fail(w, r, named(claimRefusal(err), updateClaimMember)) + case errors.Is(err, issueops.ErrCloseOpenChildren): res := named(newResult(CodeNotClosable, "`patch.status` closes an issue with open children; close them first, or send `force_close_policy`"), diff --git a/internal/httpapi/update_test.go b/internal/httpapi/update_test.go index fcca7d714..975a89572 100644 --- a/internal/httpapi/update_test.go +++ b/internal/httpapi/update_test.go @@ -645,10 +645,10 @@ func TestUpdateForwardsTheGuardedMembers(t *testing.T) { if !req.ForceClosePolicy || req.ForceAssigneeTransfer { t.Errorf("force flags = %v/%v, want close-policy only", req.ForceClosePolicy, req.ForceAssigneeTransfer) } - // Claim stays zero: acquiring work is `{id}:claim`, which has its own - // eligibility rules and its own conflict vocabulary. + // Claim stays zero when the request sent no `claim`: an absent member is + // never a claim. if req.Claim { - t.Error("the update claimed the issue; that operation is `{id}:claim`") + t.Error("the update claimed the issue though the request sent no `claim`") } if req.IssuePlaneOnly { t.Error("the update narrowed itself to the issue plane; this operation resolves across both") @@ -1174,3 +1174,185 @@ func TestUpdateBoundsEveryLabelMember(t *testing.T) { }) } } + +// TestUpdateForwardsTheClaimMember pins the pass-through of `claim` onto +// issueops.UpdateRequest.Claim — the field `bd update --claim` sets on the +// direct route — both beside a patch and alone, where the claim is the whole +// write and an empty `patch` is therefore a request rather than a client bug. +func TestUpdateForwardsTheClaimMember(t *testing.T) { + for _, tc := range []struct { + name string + body string + wantTitle bool + }{ + {"beside a patch", `{"actor":"alice","claim":true,"expected_version":"7","force_close_policy":true,"patch":{"title":"t"}}`, true}, + {"alone, with an empty patch", `{"actor":"alice","claim":true,"patch":{}}`, false}, + } { + t.Run(tc.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, tc.body) + 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)) + } + req := got[0] + if !req.Claim { + t.Fatal("`claim: true` did not reach the role as UpdateRequest.Claim") + } + if req.Actor != "alice" || req.IssueID != "bd-1" { + t.Errorf("the role received actor %q id %q", req.Actor, req.IssueID) + } + if req.Patch.Title.Set != tc.wantTitle { + t.Errorf("patch.title set = %v, want %v", req.Patch.Title.Set, tc.wantTitle) + } + if tc.wantTitle { + // The members the claim may ride beside still ride. + if req.ExpectedVersion == nil || *req.ExpectedVersion != 7 { + t.Errorf("expected_version = %v, want 7 beside the claim", req.ExpectedVersion) + } + if !req.ForceClosePolicy { + t.Error("force_close_policy was dropped beside the claim") + } + } + }) + } +} + +// TestUpdateClaimFalseIsNoClaim: an explicit false is the absent member, and it +// does not unlock the empty patch. +func TestUpdateClaimFalseIsNoClaim(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","claim":false,"patch":{"title":"t"}}`) + if resp.StatusCode != http.StatusOK { + t.Fatalf("status = %d, want 200: %s", resp.StatusCode, readAll(t, resp)) + } + if got := lifecycle.updateRequests(); len(got) != 1 || got[0].Claim { + t.Fatalf("role requests = %+v, want one with Claim false", got) + } + + resp = ts.updateIssue(t, updatePath, `{"actor":"alice","claim":false,"patch":{}}`) + if resp.StatusCode != http.StatusBadRequest { + t.Fatalf("empty patch beside claim:false: status = %d, want 400: %s", resp.StatusCode, readAll(t, resp)) + } + if body := decodeBody(t, resp); body["param"] != "patch" { + t.Errorf("param = %v, want patch", body["param"]) + } +} + +// TestUpdateRefusesTheClaimShapesTheRoleRefuses: the combinations +// ValidateUpdateRequest refuses are refused at the edge, naming `claim`, before +// the role is reached — and a claim that is not a boolean is refused by name. +func TestUpdateRefusesTheClaimShapesTheRoleRefuses(t *testing.T) { + for _, tc := range []struct { + name string + body string + param string + }{ + {"claim beside expected_assignee", `{"actor":"alice","claim":true,"patch":{},"expected_assignee":""}`, "claim"}, + {"claim beside expected_status", `{"actor":"alice","claim":true,"patch":{},"expected_status":"open"}`, "claim"}, + {"claim beside force_assignee_transfer", `{"actor":"alice","claim":true,"patch":{"assignee":"bob"},"force_assignee_transfer":true}`, "claim"}, + {"null claim", `{"actor":"alice","claim":null,"patch":{"title":"t"}}`, "claim"}, + {"claim is a string", `{"actor":"alice","claim":"yes","patch":{"title":"t"}}`, "claim"}, + // The claim does not relax the patch's own rules. + {"claim with a null patch", `{"actor":"alice","claim":true,"patch":null}`, "patch"}, + {"claim with no patch", `{"actor":"alice","claim":true}`, "patch"}, + {"claim with a bad patch member", `{"actor":"alice","claim":true,"patch":{"priority":9}}`, "patch.priority"}, + } { + t.Run(tc.name, func(t *testing.T) { + lifecycle := &roleLifecycle{updateResult: issueops.UpdateResult{Issue: updatedIssue("bd-1")}} + ts := newUpdateServer(t, lifecycle) + + resp := ts.updateIssue(t, updatePath, tc.body) + 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"] != tc.param { + t.Errorf("param = %v, want %q", body["param"], tc.param) + } + if got := lifecycle.updateRequests(); len(got) != 0 { + t.Errorf("a refused body reached the role: %+v", got) + } + }) + } +} + +// TestUpdateAnswersARefusedClaimAsTheClaimDoes: a claim refused inside the +// update is answered with `{id}:claim`'s codes and extension members, naming +// `claim` — never as the assignee fence, which shares the already_claimed +// sentinel but blames `patch.assignee` and steers toward a force a claim +// cannot send. +func TestUpdateAnswersARefusedClaimAsTheClaimDoes(t *testing.T) { + for _, tc := range []struct { + name string + body string + err error + wantCode Code + wantAssignee any + wantStatus any + }{ + { + name: "held by another actor", + body: `{"actor":"alice","claim":true,"patch":{"title":"t"}}`, + err: fmt.Errorf("update: %w", &issueops.ClaimConflictError{IssueID: "bd-1", Assignee: "bob", Status: types.StatusInProgress, + Err: fmt.Errorf("%w by bob", storage.ErrAlreadyClaimed)}), + wantCode: CodeAlreadyClaimed, + wantAssignee: "bob", + wantStatus: "in_progress", + }, + { + name: "status is not claimable", + body: `{"actor":"alice","claim":true,"patch":{}}`, + err: fmt.Errorf("update: %w", &issueops.ClaimConflictError{IssueID: "bd-1", Assignee: "bob", Status: types.StatusClosed, + Err: fmt.Errorf("%w: status closed", storage.ErrNotClaimable)}), + wantCode: CodeNotClaimable, + wantStatus: "closed", + // No holder on not_claimable: a stale assignee must not read as + // someone holding the work. + }, + { + // The assignee fence fires before the claim when the claim rides a + // patch.assignee; under a claim it is still the claim that refused. + name: "the fence refusing a claim that rides an assignee edit", + body: `{"actor":"alice","claim":true,"patch":{"assignee":"carol"}}`, + err: fmt.Errorf("update: %w: issue bd-1 is assigned to %q", storage.ErrAlreadyClaimed, "bob"), + wantCode: CodeAlreadyClaimed, + }, + } { + t.Run(tc.name, func(t *testing.T) { + lifecycle := &roleLifecycle{updateErr: tc.err} + ts := newUpdateServer(t, lifecycle) + + resp := ts.updateIssue(t, updatePath, tc.body) + if resp.StatusCode != http.StatusConflict { + t.Fatalf("status = %d, want 409: %s", resp.StatusCode, readAll(t, resp)) + } + body := decodeBody(t, resp) + if body["code"] != string(tc.wantCode) { + t.Errorf("code = %v, want %s", body["code"], tc.wantCode) + } + if body["param"] != "claim" { + t.Errorf("param = %v, want claim", body["param"]) + } + if body["assignee"] != tc.wantAssignee { + t.Errorf("assignee = %v, want %v", body["assignee"], tc.wantAssignee) + } + if body["issue_status"] != tc.wantStatus { + t.Errorf("issue_status = %v, want %v", body["issue_status"], tc.wantStatus) + } + if detail, _ := body["detail"].(string); strings.Contains(detail, "force_assignee_transfer") || strings.Contains(detail, "by bob") { + t.Errorf("detail = %q; a refused claim must neither steer to the fence's force nor quote the role", detail) + } + }) + } +}