diff --git a/cmd/bd/serve_create_proxied_integration_test.go b/cmd/bd/serve_create_proxied_integration_test.go new file mode 100644 index 000000000..ef3f4a218 --- /dev/null +++ b/cmd/bd/serve_create_proxied_integration_test.go @@ -0,0 +1,250 @@ +//go:build cgo + +package main + +import ( + "net/http" + "strings" + "testing" +) + +// End-to-end for the single create, against real Dolt through a real `bd serve` +// subprocess. The pure tests in internal/httpapi cover the wire edge on a fake +// role and assert the projection onto issueops.CreateRequest member by member; +// what only this level can prove is that the projection LANDS — that the whole +// published vocabulary reaches the ROW, that the edges reach the GRAPH, and +// that the two members no fake can exercise at all do what the document says. +// +// Those two are the point of this file. `ephemeral` decides which TABLE the row +// is written to, so a fake role reporting "I was handed Ephemeral: true" proves +// nothing about where the write went — and `ephemeral` together with `metadata` +// and `sender` in ONE transaction is the shape a real programmatic caller +// composes. The occupied-id `409` is the other: `ErrAlreadyExists` comes from +// the create-only guard inside the transaction, so only a stored row can show +// the refusal is reachable rather than merely mapped. + +// EVERY BODY BELOW SPELLS `issue_type`, and that is this workspace's rule +// rather than tidiness. The schema makes the member optional and the ROLE +// refuses an empty type — types.Issue.ValidateWithCustom rejects "" because it +// is neither built-in nor configured — so an absent one is a 400 carrying this +// workspace's own validation refusal. It is not this operation's rule either: +// every `issues:batchCreate` call in this repo's e2e tests spells +// `"issue_type":"task"` for the same reason. The document says so on the member. + +// createIssue posts a create and returns the status and decoded body. +func (sp *serveProcess) createIssue(t *testing.T, body string) (int, map[string]any) { + t.Helper() + return sp.postJSON(t, "/v0/beads/issues", body) +} + +// storedEdgeTypes indexes the edges leaving id by their target, so an assertion +// names the pair it cares about rather than an index into a list whose order is +// the graph read's business. +func storedEdgeTypes(edges []map[string]any) map[string]string { + byTarget := make(map[string]string, len(edges)) + for _, edge := range edges { + target, _ := edge["depends_on_id"].(string) + edgeType, _ := edge["type"].(string) + byTarget[target] = edgeType + } + return byTarget +} + +func TestProxiedServerServeCreate(t *testing.T) { + requireSharedProxiedServer(t) + t.Parallel() + bd := buildEmbeddedBD(t) + p := newSharedProxiedProject(t, bd, "srvcrt") + sp := startServe(t, bd, p.dir, bdProxiedEnv(p.dir)) + + // THE WHOLE PUBLISHED VOCABULARY IN ONE REQUEST, read back out of the row + // and out of the graph. A create is atomic, so a member that did not land + // means the issue should not exist either — which is why the edges are read + // through the documented stored-edge endpoint rather than trusted from the + // response. + t.Run("every published member lands in one transaction", func(t *testing.T) { + parent := bdProxiedCreate(t, bd, p.dir, "the parent", "-p", "2") + blocker := bdProxiedCreate(t, bd, p.dir, "the blocker", "-p", "2") + + const id = "srvcrt-wire1" + status, body := sp.createIssue(t, `{ + "actor":"http-agent", + "id":"`+id+`", + "title":"the wire row", + "description":"body", + "design":"how", + "acceptance_criteria":"done when", + "notes":"scratch", + "issue_type":"bug", + "status":"in_progress", + "priority":1, + "assignee":"http-agent", + "owner":"carol", + "labels":["api","wire"], + "estimated_minutes":30, + "external_ref":"gh-9", + "sender":"planner", + "metadata":{"lane":"wire"}, + "parent_id":"`+parent.ID+`", + "dependencies":[{"target_id":"`+blocker.ID+`","type":"blocks"}] + }`) + if status != http.StatusOK { + t.Fatalf("status = %d, want 200: %v", status, body) + } + + // The response is the STORED row: the document promises the id, the + // status and the persisted timestamps, none of which the request + // carried in the form the row holds them. + if body["id"] != id { + t.Errorf("response id = %v, want %s", body["id"], id) + } + if body["status"] != "in_progress" { + t.Errorf("response status = %v, want in_progress", body["status"]) + } + if body["created_at"] == nil || body["updated_at"] == nil { + t.Errorf("the response omitted the persisted timestamps: %v", body) + } + + stored := bdProxiedShow(t, bd, p.dir, id) + for _, tc := range []struct { + member string + got, want any + }{ + {"title", stored.Title, "the wire row"}, + {"description", stored.Description, "body"}, + {"design", stored.Design, "how"}, + {"acceptance_criteria", stored.AcceptanceCriteria, "done when"}, + {"notes", stored.Notes, "scratch"}, + {"issue_type", string(stored.IssueType), "bug"}, + {"status", string(stored.Status), "in_progress"}, + {"priority", stored.Priority, 1}, + {"assignee", stored.Assignee, "http-agent"}, + {"owner", stored.Owner, "carol"}, + // `sender` is one of the five members issues:batchCreate cannot + // spell, and the reason a message-shaped row cannot be created + // through that operation at all. + {"sender", stored.Sender, "planner"}, + } { + if tc.got != tc.want { + t.Errorf("stored %s = %v, want %v", tc.member, tc.got, tc.want) + } + } + if stored.EstimatedMinutes == nil || *stored.EstimatedMinutes != 30 { + t.Errorf("stored estimated_minutes = %v, want 30", stored.EstimatedMinutes) + } + if stored.ExternalRef == nil || *stored.ExternalRef != "gh-9" { + t.Errorf("stored external_ref = %v, want gh-9", stored.ExternalRef) + } + if !strings.Contains(string(stored.Metadata), `"lane"`) { + t.Errorf("stored metadata = %s, want the document the request sent", stored.Metadata) + } + if len(stored.Labels) != 2 { + t.Errorf("stored labels = %v, want the authoritative two-element set", stored.Labels) + } + + // The edges, out of the graph rather than out of the response. Both + // were written in the create's own transaction: `parent_id` as a typed + // parent-child edge and `dependencies` as the edge it names. + edges := storedEdgeTypes(sp.storedEdges(t, id)) + if got := edges[parent.ID]; got != "parent-child" { + t.Errorf("edge to the parent = %q, want parent-child (all edges: %v)", got, edges) + } + if got := edges[blocker.ID]; got != "blocks" { + t.Errorf("edge to the blocker = %q, want blocks (all edges: %v)", got, edges) + } + }) + + // THE CLAIM A PROGRAMMATIC CALLER HANGS OFF, and the one a fake role can + // never make: `ephemeral` chooses the TABLE, so "the role was handed + // Ephemeral: true" says nothing about where the row went. Sent together + // with `metadata` and `sender` because that is the row such a caller + // actually composes, and because all three land in one transaction or none + // of them do. + t.Run("an ephemeral create lands on the wisp plane carrying its metadata and sender", func(t *testing.T) { + status, body := sp.createIssue(t, `{ + "actor":"http-agent", + "title":"a wisp", + "issue_type":"task", + "ephemeral":true, + "sender":"planner", + "metadata":{"lane":"wisp"} + }`) + if status != http.StatusOK { + t.Fatalf("status = %d, want 200: %v", status, body) + } + if body["ephemeral"] != true { + t.Errorf("response ephemeral = %v, want true", body["ephemeral"]) + } + id, ok := body["id"].(string) + if !ok || id == "" { + t.Fatalf("the response carries no minted id: %v", body) + } + + stored := bdProxiedShow(t, bd, p.dir, id) + if !stored.Ephemeral { + t.Errorf("stored ephemeral = false; the row did not land on the wisp plane") + } + if stored.NoHistory { + t.Errorf("stored no_history = true; `ephemeral` and `no_history` are different retention modes") + } + if stored.Sender != "planner" { + t.Errorf("stored sender = %q, want planner", stored.Sender) + } + if !strings.Contains(string(stored.Metadata), `"lane"`) { + t.Errorf("stored metadata = %s, want the document the request sent", stored.Metadata) + } + }) + + // THE 409, against a row that really exists. ErrAlreadyExists comes from + // the create-only guard inside the transaction, so this is the one arm a + // fake role can only assert is MAPPED — never that it is reachable. + t.Run("an occupied explicit id is a 409 and overwrites nothing", func(t *testing.T) { + const id = "srvcrt-taken" + status, body := sp.createIssue(t, + `{"actor":"http-agent","id":"`+id+`","issue_type":"task","title":"the first row","description":"untouched"}`) + if status != http.StatusOK { + t.Fatalf("first create: status = %d, want 200: %v", status, body) + } + + conflictStatus, problem := sp.createIssue(t, + `{"actor":"http-agent","id":"`+id+`","issue_type":"task","title":"the second row"}`) + if conflictStatus != http.StatusConflict { + t.Fatalf("second create: status = %d, want 409: %v", conflictStatus, problem) + } + if problem["code"] != "already_exists" { + t.Errorf("code = %v, want already_exists", problem["code"]) + } + if problem["param"] != "id" { + t.Errorf("param = %v, want id", problem["param"]) + } + + // NEVER AN ADOPTION AND NEVER AN OVERWRITE: the refusal must leave the + // stored row exactly as the first create left it. + stored := bdProxiedShow(t, bd, p.dir, id) + if stored.Title != "the first row" || stored.Description != "untouched" { + t.Errorf("the refused create wrote to the stored row: %+v", stored) + } + }) + + // A dependency target this workspace holds no row for is a refusal of the + // BODY, not of a resource this request addressed — there is no id in the + // path to have missed. Nothing is created, which is the half only a real + // store can show. + t.Run("a dependency target that names nothing is a 400 and creates nothing", func(t *testing.T) { + const id = "srvcrt-dangling" + status, problem := sp.createIssue(t, + `{"actor":"http-agent","id":"`+id+`","issue_type":"task","title":"never created","dependencies":[{"target_id":"srvcrt-nosuchissue","type":"blocks"}]}`) + if status != http.StatusBadRequest { + t.Fatalf("status = %d, want 400: %v", status, problem) + } + if problem["code"] != "invalid_argument" { + t.Errorf("code = %v, want invalid_argument", problem["code"]) + } + if problem["param"] != "dependencies" { + t.Errorf("param = %v, want dependencies", problem["param"]) + } + if getStatus, _, _ := sp.get(t, "/v0/beads/issues/"+id); getStatus != http.StatusNotFound { + t.Errorf("GET the refused id: status = %d, want 404 — a refused create must write no row", getStatus) + } + }) +} diff --git a/cmd/bd/serve_proxied_integration_test.go b/cmd/bd/serve_proxied_integration_test.go index 4893c0e51..4116ccab6 100644 --- a/cmd/bd/serve_proxied_integration_test.go +++ b/cmd/bd/serve_proxied_integration_test.go @@ -148,7 +148,7 @@ var servedCapabilities = []any{ "dependencies.list", "dependencies.remove", "dependencies.tree", "events.list", "events.watch", "issues.batchApply", "issues.batchCreate", "issues.casMetadata", "issues.claim", - "issues.close", "issues.delete", + "issues.close", "issues.create", "issues.delete", "issues.get", "issues.list", "issues.query", "issues.reopen", "issues.sweep", "issues.update", "memories.forget", "memories.get", "memories.list", "memories.remember", diff --git a/internal/httpapi/apigen/types.gen.go b/internal/httpapi/apigen/types.gen.go index 5105d729c..9c6f38fe0 100644 --- a/internal/httpapi/apigen/types.gen.go +++ b/internal/httpapi/apigen/types.gen.go @@ -722,7 +722,7 @@ type ContextResponse struct { // BeadsDir Absolute path of the served workspace's `.beads` directory. A host path, kept because it is the single-workspace server's only workspace-identity handshake; disclosing it to network peers is part of what an operator accepts when binding beyond loopback. BeadsDir string `json:"beads_dir"` - // Capabilities The operations this server actually implements, derived from its route table. v0's vocabulary is `ready.list`, `ready.count`, `issues.list`, `issues.query`, `issues.get`, `issues.claim`, `issues.close`, `issues.reopen`, `issues.update`, `issues.sweep`, `issues.delete`, `issues.batchCreate`, `issues.batchApply`, `stats.get`, `config.list`, `config.get`, `dependencies.cycles`, `dependencies.list`, `dependencies.blocking`, `dependencies.tree`, `dependencies.add`, `dependencies.remove`, `memories.list`, `memories.get`, `memories.remember`, `memories.forget`, `events.list`, `events.watch`, `issues.casMetadata`; it grows additively, and an operation never appears here unless it is fully implemented. This is how a client checks for an operation — never the version string. + // Capabilities The operations this server actually implements, derived from its route table. v0's vocabulary is `ready.list`, `ready.count`, `issues.list`, `issues.query`, `issues.get`, `issues.create`, `issues.claim`, `issues.close`, `issues.reopen`, `issues.update`, `issues.sweep`, `issues.delete`, `issues.batchCreate`, `issues.batchApply`, `stats.get`, `config.list`, `config.get`, `dependencies.cycles`, `dependencies.list`, `dependencies.blocking`, `dependencies.tree`, `dependencies.add`, `dependencies.remove`, `memories.list`, `memories.get`, `memories.remember`, `memories.forget`, `events.list`, `events.watch`, `issues.casMetadata`; it grows additively, and an operation never appears here unless it is fully implemented. This is how a client checks for an operation — never the version string. // // THIS LIST IS BUILD-LEVEL, NOT WORKSPACE-LEVEL. It says which operations this binary serves, and for every entry but two that is the whole answer. `events.list` and `events.watch` are the exceptions: the durable events journal is a per-workspace setting that is OFF by default, so a server that advertises them may still refuse every request to both with 409 `events_journal_disabled` — correctly, because the operations exist and the workspace has no journal. A consumer of either MUST treat the capability as "this server speaks it" and the 409 as "not on this workspace", and must not read the capability as a promise that records will arrive. Capabilities []string `json:"capabilities"` @@ -743,6 +743,122 @@ type ContextResponse struct { SchemaVersion int `json:"schema_version"` } +// CreateIssueDependency One edge created with the issue. It carries `reverse` where `BatchCreateDependency` does not, because that operation's items have no id a target could point back at and this one's issue does. +type CreateIssueDependency struct { + // Metadata One metadata value: ANY JSON value — string, number, boolean, null, array or object — because typed values enter through the explicit JSON metadata path and persist in older rows. It is not a string, and a client must not decode it as one. + // + // Where a member of this type is OMITTED, the key is absent; where it is present holding `null`, the key exists and holds null. Those are different states and this surface reports both. + Metadata MetadataValue `json:"metadata,omitempty"` + + // Reverse Writes the edge from `target_id` TO the new issue rather than from it. It is what lets a create declare an edge that points INTO the row being minted — the id no caller could have spelled beforehand — and it is the member that makes `dependency_cycle` reachable on this operation at all. + Reverse *bool `json:"reverse,omitempty"` + + // TargetId The other endpoint of the edge. + TargetId string `json:"target_id"` + + // Type The edge type, from the same OPEN vocabulary `Dependency.type` carries: checked for BEING a storable value, never for membership of a known-types list, so a workspace's own type passes. + Type string `json:"type"` +} + +// CreateIssueRequest One issue, its parent, its explicit edges and its waits-for gate, created as one act. +// +// It is FLAT rather than nesting the issue's fields under an `issue` member, unlike `UpdateIssueRequest`'s `patch`: a patch has to distinguish a member that is absent from one set to its zero value, and a create has no such distinction to make — an absent member is the workspace default, which is the same answer a nested object would have given. +// +// The issue members mirror `ApplyCreateItem` exactly, minus that schema's two plan-only members (`key` and `metadata_refs`, which name items of a request this operation has only one of). What this adds is the edge vocabulary that operation moves into `dep_add` items: `parent_id`, `inherit_labels_from_parent`, `dependencies` and `waits_for`. +type CreateIssueRequest struct { + AcceptanceCriteria *string `json:"acceptance_criteria,omitempty"` + + // Actor Who is creating 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 created edges' author column, the history entry's attribution and the storage commit message, so an unvalidated newline would forge audit-trail lines. + // + // It is NOT the issue's `created_by`, which this operation does not publish: this is the caller-asserted provenance of the ACT, and the row's own author column is left to the implementation. + Actor string `json:"actor"` + Assignee *string `json:"assignee,omitempty"` + + // DeferUntil RFC 3339. The issue is hidden from ready work until then. Not nullable, for `estimated_minutes`' reason. + DeferUntil *time.Time `json:"defer_until,omitempty"` + + // Dependencies The complete set of explicit edges created with the issue. Authoritative, not a patch. Every edge is written in the same transaction as the row, so an edge this request cannot write means no issue either. + // + // A TARGET NEED NOT BE A ROW THIS DATABASE HOLDS: an `external:` 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. + Dependencies *[]CreateIssueDependency `json:"dependencies,omitempty"` + Description *string `json:"description,omitempty"` + Design *string `json:"design,omitempty"` + + // DueAt RFC 3339. Not nullable, for `estimated_minutes`' reason. + DueAt *time.Time `json:"due_at,omitempty"` + + // Ephemeral Creates the issue on the EPHEMERAL plane rather than the durable one, exactly as it does for `POST /v0/beads/issues:batchApply`. Mutually exclusive with `no_history`. + Ephemeral *bool `json:"ephemeral,omitempty"` + + // EstimatedMinutes An estimate in minutes. Absent leaves it unset. NOT nullable, unlike `IssuePatchBody.estimated_minutes`: a create has nothing to clear, so `null` here would be a second spelling of omission and is a `400`. + EstimatedMinutes *int `json:"estimated_minutes,omitempty"` + + // ExternalRef e.g. `gh-9`. Not nullable, for `estimated_minutes`' reason. + ExternalRef *string `json:"external_ref,omitempty"` + + // ForceIdPrefix Permits an explicit `id` outside the workspace's configured issue prefix. It bypasses ONLY that check: it is not a force on the create-only guard, so an occupied id is still a `409`. + ForceIdPrefix *bool `json:"force_id_prefix,omitempty"` + + // Id An explicit id for the new row, CREATE-ONLY: an id that already names a stored row is a `409` `already_exists` and nothing is written — never an adoption and never an overwrite. It is checked against the workspace's configured issue prefix unless `force_id_prefix` is set. Absent is the ordinary case and the server mints one. + Id *string `json:"id,omitempty"` + + // InheritLabelsFromParent Copies the parent's labels onto the new issue at creation, on top of `labels`. It has no effect without `parent_id`. + // + // The DEFAULT IS FALSE and diverges from `bd create --parent`, whose default is to inherit. A wire caller sends what it means: this operation has no `--no-inherit-labels` to turn off, and a create that silently acquired labels the request never named would be a set the caller has to read back to learn. + InheritLabelsFromParent *bool `json:"inherit_labels_from_parent,omitempty"` + + // IssueType Issue type. Spelled `issue_type` rather than `type`, matching the member `Issue` carries, and validated against the built-ins plus the workspace's configured custom types by the ROLE — this server cannot read that vocabulary without a transaction, so it checks only what this schema declares and an unknown one arrives as a `400`. + // + // SEND ONE. The member is optional in this schema and the role validates the EMPTY type against the same vocabulary as any other, where it is neither a built-in nor a configured type — so an omitted `issue_type` is refused with everything else the request asked for. It stays optional because the vocabulary belongs to the workspace and a deployment may configure a default this server cannot read, but it is not optional in practice on any workspace shipped today. `POST /v0/beads/issues:batchCreate` has the same property and does not say so, which is why this member does. + IssueType *string `json:"issue_type,omitempty"` + + // Labels The complete label set the issue is created with. Authoritative, not a patch — a create has nothing to add to. `inherit_labels_from_parent` adds the parent's labels on top of it. + Labels *[]string `json:"labels,omitempty"` + + // Metadata One metadata value: ANY JSON value — string, number, boolean, null, array or object — because typed values enter through the explicit JSON metadata path and persist in older rows. It is not a string, and a client must not decode it as one. + // + // Where a member of this type is OMITTED, the key is absent; where it is present holding `null`, the key exists and holds null. Those are different states and this surface reports both. + Metadata MetadataValue `json:"metadata,omitempty"` + + // NoHistory 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`. + NoHistory *bool `json:"no_history,omitempty"` + Notes *string `json:"notes,omitempty"` + + // Owner The human owner, which is a different member from `assignee`: the assignee is who is working it now, the owner is who it is attributed to. + Owner *string `json:"owner,omitempty"` + + // ParentId Creates a typed `parent-child` edge from the new issue to this target. It must not duplicate an edge `dependencies` already spells; naming the same pair twice with two types is a `400`. + ParentId *string `json:"parent_id,omitempty"` + + // Priority 0 is P0/critical. Absent means the workspace default. + Priority *int `json:"priority,omitempty"` + + // Sender Who sent this, for the message-shaped rows an orchestrator creates. Stored verbatim and interpreted by nothing on this surface. + Sender *string `json:"sender,omitempty"` + + // Status The status the issue is created in, from this workspace's own configured vocabulary. Absent means the workspace's own default, which is `open` today — unlike `issue_type`, the role fills this one in before it validates. + Status *string `json:"status,omitempty"` + + // Title The issue's title. Must not be blank after trimming. + Title string `json:"title"` + + // WaitsFor A typed `waits-for` edge from the new issue to a spawner whose children gate it. It records a readiness primitive; it does not define scheduling or execution policy. + // + // IT IS A TYPED MEMBER HERE AND A METADATA BLOB ON `POST /v0/beads/issues:batchApply`, and the difference follows the ROLE rather than taste: `CreateRequest.WaitsFor` is a typed field that gets the gate defaulted and the "must not duplicate an explicit edge" check, while that operation's `dep_add` item is one generic edge with no typed field to reach. One spelling per operation, and each is its role's. + WaitsFor *CreateIssueWaitsFor `json:"waits_for,omitempty"` +} + +// CreateIssueWaitsFor A typed `waits-for` edge from the new issue to a spawner whose children gate it. It records a readiness primitive; it does not define scheduling or execution policy. +// +// IT IS A TYPED MEMBER HERE AND A METADATA BLOB ON `POST /v0/beads/issues:batchApply`, and the difference follows the ROLE rather than taste: `CreateRequest.WaitsFor` is a typed field that gets the gate defaulted and the "must not duplicate an explicit edge" check, while that operation's `dep_add` item is one generic edge with no typed field to reach. One spelling per operation, and each is its role's. +type CreateIssueWaitsFor struct { + // Gate The readiness condition: `all-children` or `any-children`. Absent or empty defaults to `all-children`. A value that is neither is refused by the ROLE and reaches the client as a `400`. + Gate *string `json:"gate,omitempty"` + + // SpawnerId The dependency target whose children are observed. It must not duplicate an edge `dependencies` or `parent_id` already spells. + SpawnerId string `json:"spawner_id"` +} + // Cycle One circular blocking dependency: its members in EDGE ORDER, so `members[i]` blocks on `members[i+1]` and the last member blocks on the first. The closing edge is implied and is not repeated as a final member. // // The rotation is canonical — the lowest id comes first — which is what makes two snapshots of an unchanged workspace comparable. @@ -1712,6 +1828,9 @@ type AddDependenciesJSONRequestBody = AddDependenciesRequest // RemoveDependencyJSONRequestBody defines body for RemoveDependency for application/json ContentType. type RemoveDependencyJSONRequestBody = RemoveDependencyRequest +// CreateIssueJSONRequestBody defines body for CreateIssue for application/json ContentType. +type CreateIssueJSONRequestBody = CreateIssueRequest + // UpdateIssueJSONRequestBody defines body for UpdateIssue for application/json ContentType. type UpdateIssueJSONRequestBody = UpdateIssueRequest diff --git a/internal/httpapi/create.go b/internal/httpapi/create.go new file mode 100644 index 000000000..f444e4a99 --- /dev/null +++ b/internal/httpapi/create.go @@ -0,0 +1,490 @@ +package httpapi + +import ( + "encoding/json" + "errors" + "fmt" + "net/http" + "strings" + + "github.com/steveyegge/beads/internal/httpapi/apigen" + "github.com/steveyegge/beads/internal/storage" + "github.com/steveyegge/beads/internal/types" + "github.com/steveyegge/beads/issueops" +) + +// The wire adapter over issueops.Lifecycle.Create: ONE issue, its parent, its +// explicit edges and its waits-for gate, written as one transaction. +// +// It carries the claim's posture verbatim. The actor is caller-ASSERTED +// provenance for the audit trail and not authenticated identity; hooks do not +// fire and the per-command auto-commit machinery does not run. The only durable +// effect is the single storage commit the role makes inside its own +// transaction. +// +// EVERYTHING ABOVE THE ROLE IS ARGUMENT VALIDATION. The id minting, the prefix +// check, the create-only guard, the workspace's status and type vocabularies, +// the plane routing, the edge write and the graph gates all belong to +// issueops.Lifecycle. This file decodes a body two levels deep, refuses the +// shapes the document refuses, and marshals the row that came back. + +const ( + // maxCreateBodyBytes bounds the request body. One issue can carry a + // description, a design, acceptance criteria, notes and a metadata document + // at once, so this is the update's bound rather than the claim's megabyte. + maxCreateBodyBytes = 4 << 20 + // maxCreateDependencies is the document's cap on `dependencies`. It bounds + // how long one request may hold a write transaction — not create semantics, + // which have no edge count in them. + maxCreateDependencies = 100 + // createMetadataMember is the one member whose explicit `null` is not + // refused at the edge: its bytes are the metadata plane's own, and the role + // is the single definition of what that plane accepts. + createMetadataMember = "metadata" +) + +// The document's member list at each of this body's levels. Every schema is +// additionalProperties: false, so anything else is refused BY NAME — which is +// why each level is decoded as raw members first: encoding/json's +// DisallowUnknownFields reports the offender only inside an error string. +var ( + createRequestMembers = []string{ + "acceptance_criteria", "actor", "assignee", "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", + } + createDependencyMembers = []string{"metadata", "reverse", "target_id", "type"} + createWaitsForMembers = []string{"gate", "spawner_id"} +) + +// handleCreateIssue creates one issue, or creates nothing. +// +// A PLAIN COLLECTION POST rather than a custom method: this creates one member +// of the collection the path names, which is what POST already means — the +// argument rememberMemory makes on its own collection. The path was left free +// for exactly this operation when issues:batchCreate chose a custom method. +func (s *Server) handleCreateIssue(w http.ResponseWriter, r *http.Request) { + if !s.requireNoQuery(w, r) { + return + } + if !s.requireJSONContent(w, r) { + return + } + request, ok := s.createIssueRequest(w, r) + if !ok { + return + } + + lifecycle, err := s.lifecycle(r) + if err != nil { + s.failCreateIssue(w, r, err) + return + } + result, err := lifecycle.Create(r.Context(), request) + if err != nil { + s.failCreateIssue(w, r, err) + return + } + // The row as STORED, never the request reflected back: the role clones its + // request, so the minted id, the defaulted status and the persisted + // timestamps exist only on this snapshot. checkedLifecycle.Create is what + // makes the dereference safe. + writeJSON(w, *result.Issue) +} + +// createIssueRequest decodes and validates the body, and reports whether the +// request may proceed. Every refusal here happens BEFORE any database work, +// which is what lets these 400s reflect the caller's own input back. +func (s *Server) createIssueRequest(w http.ResponseWriter, r *http.Request) (issueops.CreateRequest, bool) { + refuse := func(res *Result) (issueops.CreateRequest, bool) { + s.fail(w, r, *res) + return issueops.CreateRequest{}, false + } + + members, res := decodeJSONObject(w, r, maxCreateBodyBytes) + if res != nil { + return refuse(res) + } + if offender, unknown := unknownMember(members, createRequestMembers); unknown { + s.failUnknownMember(w, r, offender, createRequestMembers) + return issueops.CreateRequest{}, false + } + // Explicit null, before any typed decode. NO MEMBER OF A CREATE IS + // NULLABLE: a create has nothing to clear, so `null` is never a third state + // here — unmarshaling it into *T yields nil, which is indistinguishable + // from omission, and the value the client asked for would be silently + // replaced by the workspace default. `metadata` is the one exception and + // travels unparsed for the reason applyDepAddItem gives about an edge blob: + // the role is the single definition of what that plane accepts, and a + // second parse here would be a second definition. + for name, value := range members { + if name != createMetadataMember && isJSONNull(value) { + return refuse(createRefusal(name, "`"+name+"` is not nullable; omit it to leave it at the workspace default")) + } + } + + // The two members with a level below them are shaped BEFORE the typed + // decode, applyItems' order and for its reason: the whole-body decode fails + // as one unit, so a `waits_for` that is a string would otherwise be reported + // against the body rather than against the member the client can fix. + rawEdges, res := createRawEdges(members) + if res != nil { + return refuse(res) + } + rawWaitsFor, res := createRawWaitsFor(members) + if res != nil { + return refuse(res) + } + + actor, ok := s.bodyActor(w, r, members) + if !ok { + return issueops.CreateRequest{}, false + } + + // The typed decode, which is what makes a member's type the DOCUMENT's + // type: `priority: "high"` is refused here rather than reaching a role that + // would have to guess what the caller meant. + var wire apigen.CreateIssueRequest + if err := json.Unmarshal(rawObject(members), &wire); err != nil { + return refuse(createRefusal("", "a request member carries the wrong JSON type")) + } + if strings.TrimSpace(wire.Title) == "" { + return refuse(createRefusal("title", "`title` is required and must not be blank")) + } + // The role validates the type, the status and the id prefix against the + // workspace's own configuration, which this server cannot read without a + // transaction; what is checked here is only what the schema declares. A + // SLICE and not a map, so a request breaking two rules always names the same + // offender: `param` is what a client dispatches on and it must not depend on + // map order. + for _, bounded := range []struct { + member string + value *string + }{ + {"id", wire.Id}, {"title", &wire.Title}, {"issue_type", wire.IssueType}, + {"status", wire.Status}, {"assignee", wire.Assignee}, {"owner", wire.Owner}, + {"external_ref", wire.ExternalRef}, {"sender", wire.Sender}, + {"parent_id", wire.ParentId}, + } { + if res := applyBoundedText("", bounded.member, bounded.value); res != nil { + return refuse(res) + } + } + if wire.Priority != nil && (*wire.Priority < 0 || *wire.Priority > 4) { + return refuse(createRefusal("priority", fmt.Sprintf("`priority` is %d; the range is 0 to 4", *wire.Priority))) + } + if wire.Labels != nil { + if res := applyBoundedLabels("", "labels", *wire.Labels); res != nil { + return refuse(res) + } + } + if derefBool(wire.Ephemeral) && derefBool(wire.NoHistory) { + return refuse(createRefusal("no_history", "`ephemeral` and `no_history` select different retention modes; send one")) + } + + issue := &types.Issue{ + ID: derefString(wire.Id), + Title: wire.Title, + Description: derefString(wire.Description), + Design: derefString(wire.Design), + AcceptanceCriteria: derefString(wire.AcceptanceCriteria), + Notes: derefString(wire.Notes), + Status: types.Status(derefString(wire.Status)), + IssueType: types.IssueType(derefString(wire.IssueType)), + Assignee: derefString(wire.Assignee), + Owner: derefString(wire.Owner), + EstimatedMinutes: wire.EstimatedMinutes, + ExternalRef: wire.ExternalRef, + DueAt: wire.DueAt, + DeferUntil: wire.DeferUntil, + Sender: derefString(wire.Sender), + Ephemeral: derefBool(wire.Ephemeral), + NoHistory: derefBool(wire.NoHistory), + } + if wire.Priority != nil { + issue.Priority = *wire.Priority + } + if wire.Labels != nil { + issue.Labels = append([]string(nil), *wire.Labels...) + } + if raw, present := members[createMetadataMember]; present { + // COPIED rather than aliasing the decoded body, so nothing downstream + // can be surprised by the request buffer's lifetime. + issue.Metadata = applyRawCopy(raw) + } + + request := issueops.CreateRequest{ + Actor: actor, + Issue: issue, + ParentID: derefString(wire.ParentId), + InheritLabelsFromParent: derefBool(wire.InheritLabelsFromParent), + ForceIDPrefix: derefBool(wire.ForceIdPrefix), + } + // IDPrefix stays ZERO, and its absence is a decision rather than an + // omission. It exists because a workspace's own config.yaml prefix wins over + // the database's and only a local front door can read that file + // (CreateRequest.IDPrefix). A remote client's config.yaml describes a + // workspace this server does not serve, so publishing it would let a caller + // override the served workspace's prefix rule from outside it. + + dependencies, res := createDependencies(rawEdges, wire.Dependencies) + if res != nil { + return refuse(res) + } + request.Dependencies = dependencies + + waitsFor, res := createWaitsFor(rawWaitsFor, wire.WaitsFor) + if res != nil { + return refuse(res) + } + request.WaitsFor = waitsFor + return request, true +} + +// createRawEdges reads `dependencies` as raw members, so an unknown member +// INSIDE an edge is refused by name and a member that is not an array of +// objects is refused against `dependencies` rather than against the body. +// +// It answers nil for an absent member, which is what "no edges" means. +func createRawEdges(members map[string]json.RawMessage) ([]map[string]json.RawMessage, *Result) { + raw, present := members["dependencies"] + if !present { + return nil, nil + } + var edges []map[string]json.RawMessage + if err := json.Unmarshal(raw, &edges); err != nil || edges == nil { + return nil, createRefusal("dependencies", "`dependencies` must be an array of edges") + } + for i, edge := range edges { + if edge == nil { + return nil, createRefusal(strings.TrimSuffix(createDependencyParam(i, ""), "."), "an edge must be a JSON object") + } + } + return edges, nil +} + +// createRawWaitsFor reads `waits_for` as raw members, for createRawEdges' +// reason. It answers nil for an absent member, which is what "no gate" means. +func createRawWaitsFor(members map[string]json.RawMessage) (map[string]json.RawMessage, *Result) { + raw, present := members["waits_for"] + if !present { + return nil, nil + } + var gate map[string]json.RawMessage + if err := json.Unmarshal(raw, &gate); err != nil || gate == nil { + return nil, createRefusal("waits_for", "`waits_for` must be a JSON object naming a `spawner_id`") + } + return gate, nil +} + +// createDependencies validates `dependencies` and projects it onto the role's +// edges. The raw members are re-read beside the generated slice so an unknown +// member INSIDE an edge is refused by name like every other one. +func createDependencies(rawEdges []map[string]json.RawMessage, wire *[]apigen.CreateIssueDependency) ([]issueops.CreateDependency, *Result) { + if wire == nil { + return nil, nil + } + if len(*wire) > maxCreateDependencies { + return nil, createRefusal("dependencies", + fmt.Sprintf("`dependencies` carries %d edges; the limit is %d per request", len(*wire), maxCreateDependencies)) + } + edges := make([]issueops.CreateDependency, 0, len(*wire)) + for i, edge := range *wire { + if offender, unknown := unknownMember(rawEdgeAt(rawEdges, i), createDependencyMembers); unknown { + return nil, applyUnknownMember(createDependencyParam(i, ""), offender, createDependencyMembers) + } + if edge.TargetId == "" { + return nil, createRefusal(createDependencyParam(i, "target_id"), "`target_id` is required and must not be empty") + } + if res := applyBoundedText(createDependencyParam(i, ""), "target_id", &edge.TargetId); res != nil { + return nil, res + } + // A value at all, and one the column holds — never membership of a + // known-types list. The edge vocabulary is OPEN, as EdgeReadRequest.Types + // says, so a workspace's own type passes and only an unstorable one is + // refused. + if !types.DependencyType(edge.Type).IsValid() { + return nil, createRefusal(createDependencyParam(i, "type"), + fmt.Sprintf("`type` must be 1 to %d characters", types.MaxDependencyTypeLen)) + } + created := issueops.CreateDependency{ + TargetID: edge.TargetId, + Type: types.DependencyType(edge.Type), + Reverse: derefBool(edge.Reverse), + } + // The blob travels as the bytes the caller sent, applyDepAddItem's rule + // unchanged: the role is the single definition of what it will accept. + if raw := rawEdgeMember(rawEdges, i, "metadata"); raw != nil { + created.Metadata = string(raw) + } + // ThreadID stays zero: CreateDependency carries one, this document + // publishes it on no operation, and a discussion-thread id nothing on + // this surface can read back is write-only state. + edges = append(edges, created) + } + return edges, nil +} + +// createWaitsFor validates `waits_for` and projects it onto the role's typed +// gate. The gate VOCABULARY is the role's — an unknown one is its ErrValidation +// reaching the wire — so only the schema's own bounds are applied here. +func createWaitsFor(raw map[string]json.RawMessage, wire *apigen.CreateIssueWaitsFor) (*issueops.WaitsFor, *Result) { + if raw == nil || wire == nil { + return nil, nil + } + if offender, unknown := unknownMember(raw, createWaitsForMembers); unknown { + return nil, applyUnknownMember("waits_for.", offender, createWaitsForMembers) + } + if wire.SpawnerId == "" { + return nil, createRefusal("waits_for.spawner_id", "`spawner_id` is required and must not be empty") + } + for _, bounded := range []struct { + member string + value *string + }{{"spawner_id", &wire.SpawnerId}, {"gate", wire.Gate}} { + if res := applyBoundedText("waits_for.", bounded.member, bounded.value); res != nil { + return nil, res + } + } + return &issueops.WaitsFor{SpawnerID: wire.SpawnerId, Gate: derefString(wire.Gate)}, nil +} + +// failCreateIssue answers a refused create, mapping the role's TYPED refusals +// onto the frozen codes. +// +// THERE IS NO 404 BRANCH, and its absence is this operation's posture rather +// than an oversight. A dependency, parent or waits-for target that names +// nothing arrives as ErrValidation WRAPPING ErrNotFound, and it is a statement +// about the request body rather than about a resource this operation was asked +// to address — there is no id in the path to have missed. That is +// batchCreateIssues' argument and addDependencies', applied to a single create. +// The ErrValidation check therefore has to run before any ErrNotFound reading, +// exactly as failBatchCreate's does. +// +// NOTHING HERE QUOTES THE ROLE'S MESSAGE. A refusal from the workspace's own +// 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. +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 + // every problem but the body that failed to parse, so the conflicts name + // the member that earned them here. + named := func(res Result, param string) Result { + res.Problem.Param = ¶m + return res + } + + switch { + // An occupied explicit id is a 409: the body is well-formed and stays + // well-formed, and what refuses it is STATE the client cannot see without + // reading it — so recovery is to look at that state (adopt the row with + // PATCH, pick another id, or stop) rather than to fix a malformed request. + // The identical body succeeded before the id was taken. Matched before + // ErrValidation because the create path can wrap both. + case errors.Is(err, storage.ErrAlreadyExists): + s.refusedCreateIssue(r, err) + s.fail(w, r, named(newResult(CodeAlreadyExists, + "`id` already names a stored row; nothing was created"), "id")) + + // The hierarchy refusal and the plain scheduling cycle share one code, and + // the three extension members are what tells them apart — presence is the + // discriminator, so the hierarchy arm must be matched first. + case errors.As(err, &hierarchy): + s.refusedCreateIssue(r, err) + s.fail(w, r, named(newResult(CodeDependencyCycle, + "a blocking edge against the new issue's own ancestor or descendant would never clear"). + WithHierarchyConflict(hierarchy.IssueID, hierarchy.BlockerID, hierarchy.BlockerIsAncestor), "dependencies")) + + case errors.Is(err, issueops.ErrDependencyCycle): + s.refusedCreateIssue(r, err) + s.fail(w, r, named(newResult(CodeDependencyCycle, + "the requested edges would create a dependency cycle; nothing was created"), "dependencies")) + + case !errors.Is(err, storage.ErrValidation): + s.failErr(w, r, err) + + // 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): + s.refusedCreateIssue(r, err) + s.fail(w, r, InvalidArgument("dependencies", ReasonInvalidValue, + "a dependency, parent or waits-for target names no issue in this workspace; nothing was created")) + + case errors.Is(err, issueops.ErrSelfDependency): + s.refusedCreateIssue(r, err) + s.fail(w, r, InvalidArgument("dependencies", ReasonInvalidValue, + "an issue cannot depend on itself; nothing was created")) + + case errors.Is(err, issueops.ErrPrefixMismatch): + s.refusedCreateIssue(r, err) + s.fail(w, r, InvalidArgument("id", ReasonInvalidValue, + "`id` is outside this workspace's configured issue prefix; send `force_id_prefix` to create it anyway")) + + default: + s.refusedCreateIssue(r, err) + // No `param`: the remaining refusals are the workspace's own + // vocabularies, which can name a member this request does not carry. + // deleteIssues draws the same line for the same reason. + s.fail(w, r, InvalidArgument("", ReasonInvalidValue, + "the request was refused by this workspace's own validation; nothing was created")) + } +} + +// 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) { + s.event("request_refused", "request_id", requestInfo(r.Context()).id, "error", err.Error()) +} + +// createRefusal is the 400 this body's levels raise, with `param` already +// spelled the way the client reads it back. +func createRefusal(param, detail string) *Result { + res := InvalidArgument(param, ReasonInvalidValue, detail) + return &res +} + +// createDependencyParam spells the `param` member for a refusal inside +// `dependencies`, so a client dispatching on it learns WHICH edge and WHICH +// member. An empty member names the edge itself, and the trailing dot is what +// the nested unknown-member refusal appends its offender to. +func createDependencyParam(index int, member string) string { + return fmt.Sprintf("dependencies[%d].%s", index, member) +} + +// rawEdgeMember reads one member off a decoded edge, or nil when the edge or +// the member is absent. +func rawEdgeMember(edges []map[string]json.RawMessage, index int, member string) json.RawMessage { + edge := rawEdgeAt(edges, index) + if edge == nil { + return nil + } + raw, ok := edge[member] + if !ok { + return nil + } + return raw +} + +// rawObject re-encodes a decoded object so the generated struct can be +// unmarshaled from the same bytes the raw member check ran over. The two +// decodes have to see one document, and re-encoding the members is cheaper than +// buffering the body twice. +func rawObject(members map[string]json.RawMessage) []byte { + encoded, err := json.Marshal(members) + if err != nil { + // json.RawMessage values came out of a successful decode, so this + // cannot fail; `null` keeps the typed decode's own refusal honest. + return []byte("null") + } + return encoded +} + +// derefBool reads an optional boolean member, defaulting to false — the +// document's default for every flag on this surface. +func derefBool(value *bool) bool { + return value != nil && *value +} diff --git a/internal/httpapi/create_test.go b/internal/httpapi/create_test.go new file mode 100644 index 000000000..d0c53c33d --- /dev/null +++ b/internal/httpapi/create_test.go @@ -0,0 +1,665 @@ +package httpapi + +import ( + "encoding/json" + "fmt" + "net/http" + "strings" + "testing" + "time" + + "github.com/steveyegge/beads/internal/httpapi/apigen" + "github.com/steveyegge/beads/internal/storage" + "github.com/steveyegge/beads/internal/types" + "github.com/steveyegge/beads/issueops" +) + +// The pins for POST /v0/beads/issues. What is asserted here is the WIRE EDGE — +// that the whole create vocabulary reaches the role faithfully, that the edge +// members arrive as typed edges rather than as fields on the issue, that the +// response is the STORED row, and that each of the role's refusals arrives as +// the documented code. Everything below the wire is the role's, and +// TestProxiedServerServeCreate is where a real row proves it. + +const createPath = "/v0/beads/issues" + +func newCreateServer(t *testing.T, lifecycle *roleLifecycle) *testServer { + t.Helper() + return newTestServer(t, rolesConfig(Config{Lifecycle: lifecycle})) +} + +// createdIssue is the row a fake role answers with: deliberately unlike the +// request, so a case that asserted on the response could not pass by reflecting +// the body back. +func createdIssue(id string) *types.Issue { + return &types.Issue{ + ID: id, + Title: "as stored", + Status: types.StatusOpen, + Priority: 2, + IssueType: types.TypeTask, + CreatedAt: time.Date(2026, 8, 1, 9, 0, 0, 0, time.UTC), + UpdatedAt: time.Date(2026, 8, 1, 9, 0, 0, 0, time.UTC), + } +} + +func (ts *testServer) createIssue(t *testing.T, body string) *http.Response { + t.Helper() + return ts.claim(t, createPath, body) +} + +// TestCreatePathReachesItsHandler drives the plain collection POST, which +// shares its path with listIssues' GET and sits beside three literal `:verb` +// siblings and the claim's wide `/v0/beads/issues/{idop}` wildcard. A 404 or a +// batch response here would mean the request reached one of them. +func TestCreatePathReachesItsHandler(t *testing.T) { + lifecycle := &roleLifecycle{createResult: issueops.CreateResult{Issue: createdIssue("bd-1")}} + ts := newCreateServer(t, lifecycle) + + resp := ts.createIssue(t, `{"actor":"alice","title":"one"}`) + if resp.StatusCode != http.StatusOK { + t.Fatalf("status = %d, want 200: %s", resp.StatusCode, readAll(t, resp)) + } + if len(lifecycle.createRequests()) != 1 { + t.Fatalf("the role was called %d times, want 1 — the path reached another handler", len(lifecycle.createRequests())) + } + // The batch beside it must still be reachable: ServeMux prefers the literal + // segment, and a row that broke that would answer batches here. + if got := ts.claim(t, "/v0/beads/issues:batchCreate", `{"actor":"alice","items":[{"title":"one"}]}`); got.StatusCode != http.StatusOK { + t.Fatalf("issues:batchCreate status = %d, want 200: %s", got.StatusCode, readAll(t, got)) + } + if len(lifecycle.createRequests()) != 1 { + t.Errorf("the batch reached the single-create handler; the literal segment must win over the collection POST") + } +} + +// TestCreateForwardsEveryDocumentedMember is the operation's central pin. This +// body publishes the whole create vocabulary and every member is projected by +// hand, so one request drives all of them and asserts the request the role +// received, field by field. +// +// It is the R1 lesson made mechanical: issues:batchCreate's item publishes nine +// members, and the five its absence made unusable — status, sender, metadata, +// ephemeral and an explicit id — are asserted here alongside the rest. +func TestCreateForwardsEveryDocumentedMember(t *testing.T) { + lifecycle := &roleLifecycle{createResult: issueops.CreateResult{Issue: createdIssue("bd-7")}} + ts := newCreateServer(t, lifecycle) + + resp := ts.createIssue(t, `{ + "actor": " alice ", + "id": "bd-7", + "force_id_prefix": true, + "title": "the row", + "description": "body", + "design": "how", + "acceptance_criteria": "done when", + "notes": "scratch", + "issue_type": "bug", + "status": "in_progress", + "priority": 1, + "assignee": "bob", + "owner": "carol", + "labels": ["api", "wire"], + "estimated_minutes": 30, + "external_ref": "gh-9", + "due_at": "2026-01-02T03:04:05Z", + "defer_until": "2026-01-01T00:00:00Z", + "sender": "planner", + "metadata": {"plan": true}, + "ephemeral": true, + "parent_id": "bd-parent", + "inherit_labels_from_parent": true, + "dependencies": [ + {"target_id":"bd-2","type":"blocks"}, + {"target_id":"bd-3","type":"related","reverse":true,"metadata":{"why":"mirror"}} + ], + "waits_for": {"spawner_id":"bd-4","gate":"any-children"} + }`) + if resp.StatusCode != http.StatusOK { + t.Fatalf("status = %d, want 200: %s", resp.StatusCode, readAll(t, resp)) + } + + got := lifecycle.createRequests() + if len(got) != 1 { + t.Fatalf("the role was called %d times, want 1", len(got)) + } + req := got[0] + if req.Actor != "alice" { + t.Errorf("actor = %q, want the trimmed %q", req.Actor, "alice") + } + if req.Issue == nil { + t.Fatal("the role received no issue") + } + issue := req.Issue + + for _, tc := range []struct { + name string + got, want any + }{ + {"id", issue.ID, "bd-7"}, + {"title", issue.Title, "the row"}, + {"description", issue.Description, "body"}, + {"design", issue.Design, "how"}, + {"acceptance_criteria", issue.AcceptanceCriteria, "done when"}, + {"notes", issue.Notes, "scratch"}, + {"issue_type", issue.IssueType, types.IssueType("bug")}, + {"status", issue.Status, types.Status("in_progress")}, + {"priority", issue.Priority, 1}, + {"assignee", issue.Assignee, "bob"}, + {"owner", issue.Owner, "carol"}, + {"sender", issue.Sender, "planner"}, + {"ephemeral", issue.Ephemeral, true}, + {"no_history", issue.NoHistory, false}, + {"parent_id", req.ParentID, "bd-parent"}, + {"inherit_labels_from_parent", req.InheritLabelsFromParent, true}, + {"force_id_prefix", req.ForceIDPrefix, true}, + } { + if tc.got != tc.want { + t.Errorf("%s = %v, want %v", tc.name, tc.got, tc.want) + } + } + if strings.Join(issue.Labels, ",") != "api,wire" { + t.Errorf("labels = %v, want the authoritative two-element set", issue.Labels) + } + if issue.EstimatedMinutes == nil || *issue.EstimatedMinutes != 30 { + t.Errorf("estimated_minutes = %v, want 30", issue.EstimatedMinutes) + } + if issue.ExternalRef == nil || *issue.ExternalRef != "gh-9" { + t.Errorf("external_ref = %v, want gh-9", issue.ExternalRef) + } + wantDue := time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC) + if issue.DueAt == nil || !issue.DueAt.Equal(wantDue) { + t.Errorf("due_at = %v, want %v", issue.DueAt, wantDue) + } + wantDefer := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) + if issue.DeferUntil == nil || !issue.DeferUntil.Equal(wantDefer) { + t.Errorf("defer_until = %v, want %v", issue.DeferUntil, wantDefer) + } + if got := strings.ReplaceAll(string(issue.Metadata), " ", ""); got != `{"plan":true}` { + t.Errorf("metadata = %s, want the caller's own bytes", issue.Metadata) + } + + // IDPrefix is deliberately unpublished: a remote client's config.yaml + // describes a workspace this server does not serve. + if req.IDPrefix != "" { + t.Errorf("the handler published IDPrefix (%q); the served workspace's prefix rule is not the caller's to override", req.IDPrefix) + } + // The issue's own edge lists must stay empty — the role refuses a request + // that carries them, and the edges travel as request fields instead. + if len(issue.Dependencies) != 0 || len(issue.Comments) != 0 { + t.Errorf("the handler put edges or comments on the issue (%d/%d); they belong to the request's own members", + len(issue.Dependencies), len(issue.Comments)) + } + // created_at/created_by are unpublished, so a fresh row must reach the role + // with both zero and take the implementation's own values. + if !issue.CreatedAt.IsZero() || issue.CreatedBy != "" { + t.Errorf("the handler set created_at/created_by (%v/%q); neither is published on this operation", + issue.CreatedAt, issue.CreatedBy) + } + + if len(req.Dependencies) != 2 { + t.Fatalf("the role received %d edges, want 2", len(req.Dependencies)) + } + if req.Dependencies[0] != (issueops.CreateDependency{TargetID: "bd-2", Type: types.DependencyType("blocks")}) { + t.Errorf("dependencies[0] = %+v, want a forward blocks edge", req.Dependencies[0]) + } + reverse := req.Dependencies[1] + if reverse.TargetID != "bd-3" || reverse.Type != types.DependencyType("related") || !reverse.Reverse { + t.Errorf("dependencies[1] = %+v, want a reverse related edge", reverse) + } + if got := strings.ReplaceAll(reverse.Metadata, " ", ""); got != `{"why":"mirror"}` { + t.Errorf("dependencies[1].metadata = %s, want the caller's own bytes", reverse.Metadata) + } + if reverse.ThreadID != "" { + t.Errorf("dependencies[1].thread_id = %q; this document publishes no thread id", reverse.ThreadID) + } + + if req.WaitsFor == nil { + t.Fatal("the role received no waits-for gate") + } + if *req.WaitsFor != (issueops.WaitsFor{SpawnerID: "bd-4", Gate: "any-children"}) { + t.Errorf("waits_for = %+v, want the typed spawner and gate", *req.WaitsFor) + } +} + +// TestCreateCarriesTheWaitsForGateAsSentOrDefaulted pins the one member whose +// meaning is split between the wire and the role: an omitted `gate` reaches the +// role EMPTY rather than defaulted here, because the role documents empty as +// all-children and a second default at the edge would be a second definition. +func TestCreateCarriesTheWaitsForGateAsSentOrDefaulted(t *testing.T) { + for _, test := range []struct { + name string + body string + wantGate string + }{ + {"gate omitted", `{"actor":"alice","title":"one","waits_for":{"spawner_id":"bd-4"}}`, ""}, + {"gate sent", `{"actor":"alice","title":"one","waits_for":{"spawner_id":"bd-4","gate":"all-children"}}`, "all-children"}, + } { + t.Run(test.name, func(t *testing.T) { + lifecycle := &roleLifecycle{createResult: issueops.CreateResult{Issue: createdIssue("bd-1")}} + ts := newCreateServer(t, lifecycle) + + if resp := ts.createIssue(t, test.body); 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].WaitsFor == nil { + t.Fatalf("the role received no waits-for gate") + } + if got[0].WaitsFor.Gate != test.wantGate { + t.Errorf("gate = %q, want %q", got[0].WaitsFor.Gate, test.wantGate) + } + if got[0].WaitsFor.SpawnerID != "bd-4" { + t.Errorf("spawner_id = %q, want bd-4", got[0].WaitsFor.SpawnerID) + } + }) + } +} + +// TestCreateAnswersTheStoredRow pins that the response is the role's snapshot +// and not the request reflected back. The minted id, the defaulted status and +// the persisted timestamps exist nowhere else, and a handler that echoed the +// body would look correct on every field the caller happened to send. +func TestCreateAnswersTheStoredRow(t *testing.T) { + lifecycle := &roleLifecycle{createResult: issueops.CreateResult{Issue: createdIssue("bd-minted")}} + ts := newCreateServer(t, lifecycle) + + resp := ts.createIssue(t, `{"actor":"alice","title":"as sent","priority":0}`) + if resp.StatusCode != http.StatusOK { + t.Fatalf("status = %d, want 200: %s", resp.StatusCode, readAll(t, resp)) + } + body := decodeBody(t, resp) + if body["id"] != "bd-minted" { + t.Errorf("id = %v, want the id the role minted", body["id"]) + } + if body["title"] != "as stored" { + t.Errorf("title = %v, want the STORED title; the request's own was %q", body["title"], "as sent") + } + if body["created_at"] == nil || body["updated_at"] == nil { + t.Errorf("the response omitted the persisted timestamps: %v", body) + } +} + +// TestCreateRefusesAnOccupiedExplicitID pins the 409 and its `param`. It is a +// conflict rather than a 400 because the body is well-formed and stays +// well-formed: the identical request succeeded before the id was taken. +func TestCreateRefusesAnOccupiedExplicitID(t *testing.T) { + lifecycle := &roleLifecycle{createErr: fmt.Errorf("create bd-7: %w", storage.ErrAlreadyExists)} + ts := newCreateServer(t, lifecycle) + + resp := ts.createIssue(t, `{"actor":"alice","title":"one","id":"bd-7"}`) + if resp.StatusCode != http.StatusConflict { + t.Fatalf("status = %d, want 409: %s", resp.StatusCode, readAll(t, resp)) + } + body := decodeBody(t, resp) + if body["code"] != "already_exists" { + t.Errorf("code = %v, want already_exists", body["code"]) + } + if body["param"] != "id" { + t.Errorf("param = %v, want id — the member that earned the refusal", body["param"]) + } +} + +// TestCreateRefusesAGraphTheEdgesWouldBreak pins both arms of the one +// dependency_cycle code, and the member PRESENCE that tells them apart. The +// hierarchy refusal carries issue_id/blocker_id/blocker_is_ancestor and the +// plain scheduling cycle carries none, which is the discriminator the document +// promises for POST /v0/beads/dependencies:add and inherits here. +func TestCreateRefusesAGraphTheEdgesWouldBreak(t *testing.T) { + for _, test := range []struct { + name string + err error + wantHierarchy bool + }{ + { + name: "scheduling cycle", + err: fmt.Errorf("%w: %w", storage.ErrValidation, issueops.ErrDependencyCycle), + }, + { + name: "hierarchy conflict", + err: fmt.Errorf("%w: %w", storage.ErrValidation, &issueops.DependencyHierarchyConflictError{ + IssueID: "bd-7", BlockerID: "bd-parent", BlockerIsAncestor: true, + }), + wantHierarchy: true, + }, + } { + t.Run(test.name, func(t *testing.T) { + lifecycle := &roleLifecycle{createErr: test.err} + ts := newCreateServer(t, lifecycle) + + resp := ts.createIssue(t, `{"actor":"alice","title":"one","parent_id":"bd-parent","dependencies":[{"target_id":"bd-parent","type":"blocks"}]}`) + if resp.StatusCode != http.StatusConflict { + t.Fatalf("status = %d, want 409: %s", resp.StatusCode, readAll(t, resp)) + } + body := decodeBody(t, resp) + if body["code"] != "dependency_cycle" { + t.Errorf("code = %v, want dependency_cycle", body["code"]) + } + _, hasIssue := body["issue_id"] + _, hasBlocker := body["blocker_id"] + _, hasAncestor := body["blocker_is_ancestor"] + present := hasIssue && hasBlocker && hasAncestor + if present != test.wantHierarchy { + t.Errorf("hierarchy members present = %v, want %v — presence is the discriminator: %v", + present, test.wantHierarchy, body) + } + if test.wantHierarchy && body["blocker_is_ancestor"] != true { + t.Errorf("blocker_is_ancestor = %v, want true", body["blocker_is_ancestor"]) + } + }) + } +} + +// TestCreateAnswersAMissingEdgeTargetWithA400 is the operation's not-found +// posture, and the case that proves it has none. The role wraps a dangling +// target in BOTH ErrValidation and ErrNotFound; answering 404 would tell a +// client its request went to the wrong place, when this operation names no +// resource in its path at all. +func TestCreateAnswersAMissingEdgeTargetWithA400(t *testing.T) { + lifecycle := &roleLifecycle{createErr: fmt.Errorf("create: dependency target does not exist: %w: %w", + storage.ErrValidation, storage.ErrNotFound)} + ts := newCreateServer(t, lifecycle) + + resp := ts.createIssue(t, `{"actor":"alice","title":"one","dependencies":[{"target_id":"bd-gone","type":"blocks"}]}`) + if resp.StatusCode != http.StatusBadRequest { + t.Fatalf("status = %d, want 400: %s", resp.StatusCode, readAll(t, resp)) + } + body := decodeBody(t, resp) + if body["code"] != "invalid_argument" { + t.Errorf("code = %v, want invalid_argument", body["code"]) + } + if body["param"] != "dependencies" { + t.Errorf("param = %v, want dependencies", body["param"]) + } + if detail, _ := body["detail"].(string); strings.Contains(detail, "dependency target does not exist") { + t.Errorf("detail quotes the role's own message: %q", detail) + } +} + +// TestCreateMapsTheRolesOwnRefusals pins the remaining 400s: each one names the +// member a client can act on where there is one, and none of them quotes the +// role's prose. +func TestCreateMapsTheRolesOwnRefusals(t *testing.T) { + for _, test := range []struct { + name string + err error + wantParam any + }{ + { + name: "prefix mismatch names the id", + err: fmt.Errorf("%w: %w", storage.ErrValidation, issueops.ErrPrefixMismatch), + wantParam: "id", + }, + { + name: "self dependency names the edges", + err: fmt.Errorf("%w: %w", storage.ErrValidation, issueops.ErrSelfDependency), + wantParam: "dependencies", + }, + { + // The workspace's own vocabularies can refuse a member this request + // does not carry, so there is nothing honest to name. + name: "workspace vocabulary names nothing", + err: fmt.Errorf("%w: unknown issue type", storage.ErrValidation), + wantParam: nil, + }, + } { + t.Run(test.name, func(t *testing.T) { + lifecycle := &roleLifecycle{createErr: test.err} + ts := newCreateServer(t, lifecycle) + + resp := ts.createIssue(t, `{"actor":"alice","title":"one","id":"xx-1"}`) + if resp.StatusCode != http.StatusBadRequest { + t.Fatalf("status = %d, want 400: %s", resp.StatusCode, readAll(t, resp)) + } + body := decodeBody(t, resp) + if body["param"] != test.wantParam { + t.Errorf("param = %v, want %v", body["param"], test.wantParam) + } + if detail, _ := body["detail"].(string); strings.Contains(detail, "unknown issue type") { + t.Errorf("detail quotes the role's own message: %q", detail) + } + }) + } +} + +// TestCreateRefusesUnknownMembersAtEveryLevel is the version-skew pin. An +// unknown member is refused BY NAME at each of the three levels, which is what +// makes additionalProperties: false enforceable by a client that has stopped +// parsing prose. +func TestCreateRefusesUnknownMembersAtEveryLevel(t *testing.T) { + for _, test := range []struct { + name string + body string + wantParam string + }{ + { + name: "request level", + body: `{"actor":"alice","title":"one","created_at":"2026-01-01T00:00:00Z"}`, + wantParam: "created_at", + }, + { + name: "edge level", + body: `{"actor":"alice","title":"one","dependencies":[{"target_id":"bd-2","type":"blocks","thread_id":"t1"}]}`, + wantParam: "dependencies[0].thread_id", + }, + { + name: "waits-for level", + body: `{"actor":"alice","title":"one","waits_for":{"spawner_id":"bd-4","also_blocks":true}}`, + wantParam: "waits_for.also_blocks", + }, + } { + t.Run(test.name, func(t *testing.T) { + lifecycle := &roleLifecycle{} + ts := newCreateServer(t, lifecycle) + + resp := ts.createIssue(t, test.body) + if resp.StatusCode != http.StatusBadRequest { + t.Fatalf("status = %d, want 400: %s", resp.StatusCode, readAll(t, resp)) + } + body := decodeBody(t, resp) + if body["param"] != test.wantParam { + t.Errorf("param = %v, want %q: a client learns WHICH level and WHICH member from this alone", + body["param"], test.wantParam) + } + if body["reason"] != "unknown_parameter" { + t.Errorf("reason = %v, want unknown_parameter", body["reason"]) + } + if len(lifecycle.createRequests()) != 0 { + t.Error("the role was called for a refused request; nothing may reach it") + } + }) + } +} + +// TestCreateRefusesTheShapesTheDocumentRefuses walks the rest of the body +// vocabulary. Every one of these is refused BEFORE any database work, which is +// what lets the detail reflect the caller's own input back. +func TestCreateRefusesTheShapesTheDocumentRefuses(t *testing.T) { + for _, test := range []struct { + name string + body string + wantParam any + }{ + {"no title", `{"actor":"alice"}`, "title"}, + {"blank title", `{"actor":"alice","title":" "}`, "title"}, + {"no actor", `{"title":"one"}`, "actor"}, + {"blank actor", `{"actor":" ","title":"one"}`, "actor"}, + {"actor with a newline", "{\"actor\":\"a\\nb\",\"title\":\"one\"}", "actor"}, + {"priority out of range", `{"actor":"alice","title":"one","priority":9}`, "priority"}, + {"priority is a string", `{"actor":"alice","title":"one","priority":"high"}`, ""}, + {"both retention modes", `{"actor":"alice","title":"one","ephemeral":true,"no_history":true}`, "no_history"}, + {"control character in a stored column", "{\"actor\":\"alice\",\"title\":\"one\",\"sender\":\"a\\u0001b\"}", "sender"}, + {"edge with no target", `{"actor":"alice","title":"one","dependencies":[{"target_id":"","type":"blocks"}]}`, "dependencies[0].target_id"}, + {"edge with an unstorable type", `{"actor":"alice","title":"one","dependencies":[{"target_id":"bd-2","type":""}]}`, "dependencies[0].type"}, + {"waits-for with no spawner", `{"actor":"alice","title":"one","waits_for":{"gate":"all-children"}}`, "waits_for.spawner_id"}, + {"waits-for is not an object", `{"actor":"alice","title":"one","waits_for":"bd-4"}`, "waits_for"}, + {"body is not an object", `["actor"]`, nil}, + } { + t.Run(test.name, func(t *testing.T) { + lifecycle := &roleLifecycle{} + ts := newCreateServer(t, lifecycle) + + resp := ts.createIssue(t, test.body) + if resp.StatusCode != http.StatusBadRequest { + t.Fatalf("status = %d, want 400: %s", resp.StatusCode, readAll(t, resp)) + } + body := decodeBody(t, resp) + if test.wantParam == "" { + // A member whose TYPE is wrong is reported against the whole + // body: the typed decode reports the offender only inside an + // error string, which this surface does not quote. + if body["param"] != "" && body["param"] != nil { + t.Errorf("param = %v, want the body-level refusal", body["param"]) + } + } else if body["param"] != test.wantParam { + t.Errorf("param = %v, want %v", body["param"], test.wantParam) + } + if len(lifecycle.createRequests()) != 0 { + t.Error("the role was called for a refused request; nothing may reach it") + } + }) + } +} + +// TestCreateRefusesAnExplicitNullOnEveryMemberButMetadata pins the rule that +// makes this body's nullable set empty. +// +// A null unmarshals into *T as nil, which is indistinguishable from omission, +// so without the check the value the client asked for would be silently +// replaced by the workspace default. `metadata` is the exception and its bytes +// reach the role verbatim, because the metadata plane is the one place where +// `null` is a value rather than an absence — and the role, not this handler, is +// the definition of what that plane accepts. +func TestCreateRefusesAnExplicitNullOnEveryMemberButMetadata(t *testing.T) { + for _, member := range []string{"priority", "ephemeral", "labels", "estimated_minutes", "external_ref", "due_at", "parent_id", "dependencies", "waits_for"} { + 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") + } + }) + } + + t.Run("metadata null reaches the role", func(t *testing.T) { + lifecycle := &roleLifecycle{createResult: issueops.CreateResult{Issue: createdIssue("bd-1")}} + ts := newCreateServer(t, lifecycle) + + resp := ts.createIssue(t, `{"actor":"alice","title":"one","metadata":null}`) + 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", len(got)) + } + if string(got[0].Issue.Metadata) != "null" { + t.Errorf("metadata = %q, want the literal null the caller sent", got[0].Issue.Metadata) + } + }) + + t.Run("metadata absent leaves the document unset", 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":"one"}`); 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", len(got)) + } + if got[0].Issue.Metadata != nil { + t.Errorf("metadata = %q, want nil: an absent member and a present null are different requests", got[0].Issue.Metadata) + } + }) +} + +// TestCreateIssueRequestDecodesAPresentNullMetadata is the client-side half of +// the rule above, and the one nothing else can see. +// +// `metadata` is a MetadataValue, and a *json.RawMessage cannot READ a present +// null: encoding/json sets the pointer to nil before any UnmarshalJSON runs, so +// a generated client would send `{"metadata":null}` and decode it back as an +// omitted member. The wire does not change in either direction, which is why +// only a decode INTO the generated struct catches a regenerated spec that lost +// x-go-type-skip-optional-pointer. +func TestCreateIssueRequestDecodesAPresentNullMetadata(t *testing.T) { + var present apigen.CreateIssueRequest + if err := json.Unmarshal([]byte(`{"actor":"alice","title":"one","metadata":null}`), &present); err != nil { + t.Fatalf("decode a present null: %v", err) + } + if string(present.Metadata) != "null" { + t.Errorf("metadata = %q, want the literal null; the generated member cannot carry a present null anymore", present.Metadata) + } + + var absent apigen.CreateIssueRequest + if err := json.Unmarshal([]byte(`{"actor":"alice","title":"one"}`), &absent); err != nil { + t.Fatalf("decode an absent member: %v", err) + } + if absent.Metadata != nil { + t.Errorf("metadata = %q, want nil for an absent member", absent.Metadata) + } +} + +// TestCreateRefusesARoleThatReportsSuccessWithoutARow pins the fold +// checkedLifecycle.Create exists for. The handler writes *result.Issue straight +// onto the wire, and a provider-supplied role is ordinary caller code, so a nil +// with a nil error must be the generic 500 with the fault in the log. +// +// THE STATUS ALONE CANNOT SEE THE FOLD, which is the whole reason this case is +// written the way the claimer's twin is: a handler that dereferenced the nil +// panics, the server recovers it into the SAME 500 with the same body, and a +// case that asserted only the status would stay green against the exact +// regression it is named for. What distinguishes them is the LOG: the fold's +// own sentence reaches the request_error line, and no panic is recovered. +// +// The substring matched below is the FOLD'S MESSAGE, not an operation field — +// the request line carries the op, the error line carries the error, and this +// case is about the second. Reword the fold and reword this. +func TestCreateRefusesARoleThatReportsSuccessWithoutARow(t *testing.T) { + lifecycle := &roleLifecycle{createResult: issueops.CreateResult{}} + ts := newCreateServer(t, lifecycle) + + resp := ts.createIssue(t, `{"actor":"alice","title":"one"}`) + if resp.StatusCode != http.StatusInternalServerError { + t.Fatalf("status = %d, want 500: %s", resp.StatusCode, readAll(t, resp)) + } + if body := decodeBody(t, resp); body["code"] != string(CodeInternal) { + t.Errorf("code = %v, want %s", body["code"], CodeInternal) + } + assertNoPanic(t, ts) + if line := findLogLine(t, ts.stderr.String(), "event=request_error"); !strings.Contains(line, "reported success without an issue") { + t.Errorf("the 500 is logged without the fold's own reason, so an operator cannot tell it from any other internal error:\n%s", line) + } +} + +// TestCreateRefusesTheWrongMediaTypeAndAnyQuery keeps the two uniform rules on +// this operation: a body this server will not read, and a parameter it does not +// know. Neither may reach the role. +func TestCreateRefusesTheWrongMediaTypeAndAnyQuery(t *testing.T) { + lifecycle := &roleLifecycle{} + ts := newCreateServer(t, lifecycle) + + if resp := ts.postBody(t, createPath, "text/plain", `{"actor":"alice","title":"one"}`); resp.StatusCode != http.StatusBadRequest { + t.Errorf("text/plain status = %d, want 400", resp.StatusCode) + } + resp := ts.claim(t, createPath+"?dry_run=true", `{"actor":"alice","title":"one"}`) + if resp.StatusCode != http.StatusBadRequest { + t.Fatalf("query status = %d, want 400: %s", resp.StatusCode, readAll(t, resp)) + } + if body := decodeBody(t, resp); body["param"] != "dry_run" || body["reason"] != "unknown_parameter" { + t.Errorf("param/reason = %v/%v, want dry_run/unknown_parameter", body["param"], body["reason"]) + } + if len(lifecycle.createRequests()) != 0 { + t.Error("the role was called for a refused request") + } +} diff --git a/internal/httpapi/problem.go b/internal/httpapi/problem.go index e5326af1e..31a1b01fa 100644 --- a/internal/httpapi/problem.go +++ b/internal/httpapi/problem.go @@ -324,6 +324,17 @@ const ( // refusals include a question about the GRAPH — a named bead with a // dependent the request did not name. OpDeleteIssues = "deleteIssues" + // OpCreateIssue creates ONE issue, with its parent, its explicit edges and + // its waits-for gate, as one transaction. It is the plain collection POST + // batchCreateIssues left free by spelling itself as a custom method. + // + // It publishes the whole create vocabulary rather than that operation's + // narrow item — `status`, `sender`, `metadata`, `ephemeral`, `no_history` + // and an explicit `id` included — which is what makes it usable for a + // caller composing a real row, and which is also where its two conflict + // codes come from: an occupied id, and the graph refusing the edges the + // request asked for. + OpCreateIssue = "createIssue" // OpBatchCreateIssues creates many issues as one transaction, or none. OpBatchCreateIssues = "batchCreateIssues" // OpApplyBatch applies an ORDERED, heterogeneous plan — creates, updates, @@ -503,6 +514,32 @@ var operationCodes = map[string][]Code{ // item can collide with a stored row and the role's ErrAlreadyExists is // unreachable from the wire. OpBatchCreateIssues: {CodeInvalidArgument, CodeBusy, CodeDBUnavailable, CodeInternal}, + // The batch's row plus the two codes its narrower vocabulary cannot earn, + // and both additions are members rather than judgement calls. + // + // already_exists arrives with `id`: that operation publishes none, so its + // items can never collide with a stored row and the role's ErrAlreadyExists + // is unreachable from its wire. Here it is reachable and it is a 409 for + // CodeNotClosable's reason — the body is well-formed and STATE refuses it. + // + // dependency_cycle arrives with `parent_id` and `dependencies[].reverse`: + // the first places the new row inside a hierarchy the caller cannot see, so + // a blocking edge against its own ancestor is refusable, and the second + // writes an edge INTO the id being minted, which is the only way a create + // can close a scheduling cycle at all. It is addDependencies' 409 unchanged, + // including the hierarchy discriminator. + // + // NO 404 and no dependency_exists. A target that names nothing is a + // statement about the request body rather than a resource this operation was + // asked to address — batchCreateIssues' argument, and there is no id in this + // path to have missed. And the only type conflict a create can raise is + // between two edges of the SAME request, which is a malformed body: no + // stored edge can name a pair whose endpoint is an id this request is + // minting. + OpCreateIssue: { + CodeInvalidArgument, CodeAlreadyExists, CodeDependencyCycle, + CodeBusy, CodeDBUnavailable, CodeInternal, + }, // The widest row here, and every code on it is inherited from an operation // that already has it: this one performs the lifecycle's writes, the claim's // assignee transfer and the graph's edge assertions inside one transaction, diff --git a/internal/httpapi/roles.go b/internal/httpapi/roles.go index 61bdda24e..78ef43a98 100644 --- a/internal/httpapi/roles.go +++ b/internal/httpapi/roles.go @@ -93,16 +93,23 @@ func (c checkedBatchCreator) CreateBatch(ctx context.Context, req issueops.Creat // checkedLifecycle is the lifecycle role every mutation handler is handed. // -// Update, Close and Reopen are why it exists: all three handlers write -// *result.Issue, which is checkedClaimer's hazard exactly. Create passes -// through because no handler on this surface reaches it — a single create is -// unpublished here, and batchCreateIssues goes to issueops.BatchCreator. +// All four methods are why it exists: every handler over this role writes +// *result.Issue, which is checkedClaimer's hazard exactly. type checkedLifecycle struct{ inner issueops.Lifecycle } -// Create passes the request through unchanged: this surface publishes no -// create-one operation (batchCreateIssues reaches issueops.BatchCreator). +// Create refuses a result that reports success without the row the response +// body is built from, for Close's reason. +// +// It USED to pass through, because no handler on this surface reached it. The +// single create publishes one, and handleCreateIssue writes *result.Issue +// straight onto the wire, so the same nil-with-nil-error a provider-supplied +// role can return is a panic on a live server without this. func (c checkedLifecycle) Create(ctx context.Context, req issueops.CreateRequest) (issueops.CreateResult, error) { - return c.inner.Create(ctx, req) + result, err := c.inner.Create(ctx, req) + if err == nil && result.Issue == nil { + return issueops.CreateResult{}, fmt.Errorf("create: the lifecycle reported success without an issue") + } + return result, err } // Update refuses a result that reports success without the row the response diff --git a/internal/httpapi/roles_test.go b/internal/httpapi/roles_test.go index 9c0d57f9b..bf64f1579 100644 --- a/internal/httpapi/roles_test.go +++ b/internal/httpapi/roles_test.go @@ -456,6 +456,8 @@ func (c *roleClaimer) claimRequests() []issueops.ClaimRequest { // rules and the problem shapes, with the transaction and the policy left to the // integration test against real Dolt. type roleLifecycle struct { + createResult issueops.CreateResult + createErr error closeResult issueops.CloseResult closeErr error reopenResult issueops.ReopenResult @@ -464,13 +466,28 @@ type roleLifecycle struct { updateErr error mu sync.Mutex + creates []issueops.CreateRequest closes []issueops.CloseRequest reopens []issueops.ReopenRequest updates []issueops.UpdateRequest } -func (l *roleLifecycle) Create(_ context.Context, _ issueops.CreateRequest) (issueops.CreateResult, error) { - return issueops.CreateResult{}, errors.New("create is not published on this surface") +func (l *roleLifecycle) Create(_ context.Context, req issueops.CreateRequest) (issueops.CreateResult, error) { + l.mu.Lock() + l.creates = append(l.creates, req) + l.mu.Unlock() + if l.createErr != nil { + return issueops.CreateResult{}, l.createErr + } + return l.createResult, nil +} + +// createRequests is closeRequests' twin, and the one the create tests read the +// whole projection off: an empty list means nothing reached the role. +func (l *roleLifecycle) createRequests() []issueops.CreateRequest { + l.mu.Lock() + defer l.mu.Unlock() + return append([]issueops.CreateRequest(nil), l.creates...) } func (l *roleLifecycle) Update(_ context.Context, req issueops.UpdateRequest) (issueops.UpdateResult, error) { diff --git a/internal/httpapi/routes.go b/internal/httpapi/routes.go index ea1c9417a..1be8c535f 100644 --- a/internal/httpapi/routes.go +++ b/internal/httpapi/routes.go @@ -279,6 +279,24 @@ var routeTable = []route{ implemented: true, handler: (*Server).handleDependencyTree, }, + { + op: OpCreateIssue, + method: http.MethodPost, + // THE PLAIN COLLECTION POST, and the row the batch below deliberately + // left this path free for: creating one member of the collection a path + // names is what POST already means, so a single create needs no custom + // method and squatting on the path with a batch would have made this + // operation unnameable. + // + // It shares its pattern with no other row. The claim's wide + // /v0/beads/issues/{idop} wildcard requires the separating slash this + // path has none of, and every batch beside it is a literal `:verb` + // segment ServeMux matches whole. + pattern: "/v0/beads/issues", + capability: "issues.create", + implemented: true, + handler: (*Server).handleCreateIssue, + }, { op: OpBatchCreateIssues, method: http.MethodPost, @@ -288,9 +306,10 @@ var routeTable = []route{ // That pattern is /v0/beads/issues/{idop} and requires the separating // slash; this path has none, so the two never match the same request. // - // It also leaves POST /v0/beads/issues free. A collection POST is where - // a single create belongs when one is published, and squatting on it - // with a batch would have made that operation unnameable. + // Nor with the single create above, which took the plain collection + // POST this row was spelled as a custom method to leave free: ServeMux + // prefers the literal `:batchCreate` segment, and the two paths differ + // in any case. pattern: "/v0/beads/issues:batchCreate", capability: "issues.batchCreate", implemented: true, diff --git a/internal/httpapi/server_test.go b/internal/httpapi/server_test.go index 6cb4cf659..6196783d0 100644 --- a/internal/httpapi/server_test.go +++ b/internal/httpapi/server_test.go @@ -598,7 +598,7 @@ func TestCapabilitiesAdvertiseEveryImplementedOperation(t *testing.T) { "dependencies.cycles", "dependencies.list", "dependencies.remove", "dependencies.tree", "events.list", "events.watch", "issues.batchApply", "issues.batchCreate", "issues.casMetadata", - "issues.claim", "issues.close", "issues.delete", "issues.get", "issues.list", + "issues.claim", "issues.close", "issues.create", "issues.delete", "issues.get", "issues.list", "issues.query", "issues.reopen", "issues.sweep", "issues.update", "memories.forget", "memories.get", "memories.list", "memories.remember", "ready.count", "ready.list", diff --git a/internal/httpapi/spec/openapi.v0.yaml b/internal/httpapi/spec/openapi.v0.yaml index 9b8c7fd92..4dcc56481 100644 --- a/internal/httpapi/spec/openapi.v0.yaml +++ b/internal/httpapi/spec/openapi.v0.yaml @@ -1117,6 +1117,168 @@ paths: '503': $ref: '#/components/responses/Unavailable' + post: + operationId: createIssue + summary: Create one issue + description: >- + Creates one issue, with its parent, its explicit edges and its waits-for + gate, as ONE transaction. A plain collection `POST` rather than a custom + method, because creating one member of the collection the path names is + what `POST` already means — the same argument `memories.remember` makes + on its own collection. + + + ## It publishes the whole create vocabulary + + + Every member the role accepts and this surface publishes anywhere is + here, and that is deliberate: `POST /v0/beads/issues:batchCreate` spells + nine of them, which is what makes it unusable for a caller composing a + real row — no `status`, no `sender`, no `metadata`, no `ephemeral`, no + `no_history`, no `id`. This operation is the single-issue create with + `ApplyCreateItem`'s vocabulary, and the two agree member for member + except where a difference is stated below. + + + THE EDGES ARE HERE, unlike on `issues:batchApply`. That operation splits + edges into their own `dep_add` items so a plan's edge order is total; + one create has no ordering to express, so `parent_id`, `dependencies` + and `waits_for` ride on the request the way `bd create --parent`, + `--deps` and `--waits-for` do. Every edge lands in the same transaction + as the row: an edge this request could not write is a `400` and the + issue is not created either. + + + ## The explicit id + + + `id` is CREATE-ONLY. An id that already names a stored row — on either + plane — is a `409 already_exists` and nothing is written. It is never an + adoption and never an overwrite: `PATCH /v0/beads/issues/{id}` acts on a + row that already exists, and `bd import` is the upsert surface, which + this API does not publish. Absent is the ordinary case and the server + mints one. + + + ## What this operation deliberately cannot set + + + `created_at` and `created_by` — a create whose stored creation time and + author come from the caller makes the row's own timestamp disagree with + the journal entry that records it, and re-dating history is what an + import is for. `issues:batchApply`'s create item publishes neither + 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`. + + + `comments` and an inline `dependencies` list on the issue itself — the + role refuses both, because edges belong to the request's own + `dependencies` member where their direction can be stated. + + + ## Planes + + + `ephemeral` and `no_history` create the row on the EPHEMERAL plane + rather than the durable one, exactly as they do for `issues:batchApply`. + They are mutually exclusive; sending both is a `400`. An edge between + rows on opposite planes is refused with everything else the request + asked for. + + + ## Hooks and auto-commit + + + Hooks do not fire and the per-command auto-commit machinery does not + run, exactly as for `POST /v0/beads/issues/{id}:claim`. The only durable + effect is the single storage commit the role makes in its own + transaction. + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/CreateIssueRequest' + responses: + '200': + description: >- + The created issue, hydrated with its labels and the edges this + request wrote. It is the row as STORED — the minted id, the + defaulted status and the persisted timestamps — never the request + reflected back. + content: + application/json: + schema: + $ref: '#/components/schemas/Issue' + '400': + description: >- + Invalid request: an unknown query parameter, an unparseable or + oversized body, an unknown body member at any level, an `actor` that + is empty after trimming, longer than 256 bytes or carrying control + characters, a blank or missing `title`, a member carrying the wrong + JSON type, an explicit `null` on any member, a value outside its + documented bounds, `ephemeral` together with `no_history` — or a + value this workspace's own validation refuses, such as an + `issue_type` or `status` outside its configured vocabulary, an + OMITTED `issue_type` (see that member), an `id` outside its + configured prefix, an edge from the new issue to itself, the same + pair named twice by two members, or a dependency, parent or + waits-for target that names nothing this workspace holds. + + + A DEPENDENCY TARGET THAT NAMES NOTHING IS A `400`, NOT A `404`, + conforming to `POST /v0/beads/dependencies:add` and + `POST /v0/beads/issues:batchCreate`: an edge describes a relation + rather than a resource this request was asked to address, and this + operation names no id in its path to have missed. Nothing is created + in any of these cases. + x-bd-codes: [invalid_argument] + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + '409': + description: >- + The request is well-formed and the STATE refuses it, and NOTHING WAS + WRITTEN. + + + `already_exists` is an explicit `id` that already names a stored row. + `param` is `id`. There is no force bypass and no upsert: the + identical body succeeded before the id was taken and would succeed + against a workspace that never took it, which is why this is a `409` + rather than a `400` — recovery is to look at the state (adopt the row + with `PATCH`, choose another id, or stop) rather than to fix a + malformed request. + + + `dependency_cycle` is the graph refusing the edges this request + asked for, spelled exactly as `POST /v0/beads/dependencies:add` + spells it and covering both of that operation's refusals: a + scheduling cycle, and a blocking edge against the new issue's own + ancestor or descendant. The hierarchy case — and only it — + additionally carries `issue_id`, `blocker_id` and + `blocker_is_ancestor`, so member presence is the discriminator. + Neither has a force bypass; both are reachable here because + `parent_id` places the new row in a hierarchy the caller cannot see + and `dependencies[].reverse` writes an edge INTO it. + x-bd-codes: [already_exists, dependency_cycle] + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + '500': + $ref: '#/components/responses/InternalError' + '503': + $ref: '#/components/responses/Unavailable' + /v0/beads/issues:query: get: operationId: queryIssues @@ -4631,7 +4793,8 @@ components: description: >- The operations this server actually implements, derived from its route table. v0's vocabulary is `ready.list`, `ready.count`, - `issues.list`, `issues.query`, `issues.get`, `issues.claim`, + `issues.list`, `issues.query`, `issues.get`, `issues.create`, + `issues.claim`, `issues.close`, `issues.reopen`, `issues.update`, `issues.sweep`, `issues.delete`, `issues.batchCreate`, `issues.batchApply`, @@ -6891,6 +7054,276 @@ components: patch is a 200 with `changed: false` rather than an error — idempotent, like every replay answer on this surface. + CreateIssueRequest: + type: object + additionalProperties: false + required: [actor, title] + description: >- + One issue, its parent, its explicit edges and its waits-for gate, + created as one act. + + + It is FLAT rather than nesting the issue's fields under an `issue` + member, unlike `UpdateIssueRequest`'s `patch`: a patch has to distinguish + a member that is absent from one set to its zero value, and a create has + no such distinction to make — an absent member is the workspace default, + which is the same answer a nested object would have given. + + + The issue members mirror `ApplyCreateItem` exactly, minus that schema's + two plan-only members (`key` and `metadata_refs`, which name items of a + request this operation has only one of). What this adds is the edge + vocabulary that operation moves into `dep_add` items: `parent_id`, + `inherit_labels_from_parent`, `dependencies` and `waits_for`. + properties: + actor: + type: string + minLength: 1 + maxLength: 256 + pattern: '^[^\u0000-\u001F\u007F-\u009F\u2028\u2029]+$' + description: >- + Who is creating 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 created edges' author column, the history + entry's attribution and the storage commit message, so an + unvalidated newline would forge audit-trail lines. + + + It is NOT the issue's `created_by`, which this operation does not + publish: this is the caller-asserted provenance of the ACT, and the + row's own author column is left to the implementation. + id: + type: string + minLength: 1 + maxLength: 255 + description: >- + An explicit id for the new row, CREATE-ONLY: an id that already + names a stored row is a `409` `already_exists` and nothing is + written — never an adoption and never an overwrite. It is checked + against the workspace's configured issue prefix unless + `force_id_prefix` is set. Absent is the ordinary case and the server + mints one. + title: + type: string + minLength: 1 + maxLength: 255 + description: The issue's title. Must not be blank after trimming. + description: + type: string + design: + type: string + acceptance_criteria: + type: string + notes: + type: string + issue_type: + type: string + maxLength: 255 + description: >- + Issue type. Spelled `issue_type` rather than `type`, matching the + member `Issue` carries, and validated against the built-ins plus the + workspace's configured custom types by the ROLE — this server cannot + read that vocabulary without a transaction, so it checks only what + this schema declares and an unknown one arrives as a `400`. + + + SEND ONE. The member is optional in this schema and the role + validates the EMPTY type against the same vocabulary as any other, + where it is neither a built-in nor a configured type — so an omitted + `issue_type` is refused with everything else the request asked for. + It stays optional because the vocabulary belongs to the workspace and + a deployment may configure a default this server cannot read, but it + is not optional in practice on any workspace shipped today. + `POST /v0/beads/issues:batchCreate` has the same property and does + not say so, which is why this member does. + status: + type: string + maxLength: 255 + description: >- + The status the issue is created in, from this workspace's own + configured vocabulary. Absent means the workspace's own default, + which is `open` today — unlike `issue_type`, the role fills this one + in before it validates. + priority: + type: integer + minimum: 0 + maximum: 4 + description: 0 is P0/critical. Absent means the workspace default. + assignee: + type: string + maxLength: 255 + owner: + type: string + maxLength: 255 + description: >- + The human owner, which is a different member from `assignee`: the + assignee is who is working it now, the owner is who it is attributed + to. + labels: + type: array + items: + type: string + maxLength: 255 + description: >- + The complete label set the issue is created with. Authoritative, not + a patch — a create has nothing to add to. `inherit_labels_from_parent` + adds the parent's labels on top of it. + estimated_minutes: + type: integer + description: >- + An estimate in minutes. Absent leaves it unset. NOT nullable, unlike + `IssuePatchBody.estimated_minutes`: a create has nothing to clear, so + `null` here would be a second spelling of omission and is a `400`. + external_ref: + type: string + maxLength: 255 + description: 'e.g. `gh-9`. Not nullable, for `estimated_minutes`'' reason.' + due_at: + type: string + format: date-time + description: 'RFC 3339. Not nullable, for `estimated_minutes`'' reason.' + defer_until: + type: string + format: date-time + description: >- + RFC 3339. The issue is hidden from ready work until then. Not + nullable, for `estimated_minutes`' reason. + sender: + type: string + maxLength: 255 + description: >- + Who sent this, for the message-shaped rows an orchestrator creates. + Stored verbatim and interpreted by nothing on this surface. + metadata: + $ref: '#/components/schemas/MetadataValue' + ephemeral: + type: boolean + default: false + description: >- + Creates the issue on the EPHEMERAL plane rather than the durable one, + exactly as it does for `POST /v0/beads/issues:batchApply`. Mutually + exclusive with `no_history`. + no_history: + type: boolean + default: false + description: >- + 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`. + parent_id: + type: string + maxLength: 255 + description: >- + Creates a typed `parent-child` edge from the new issue to this + target. It must not duplicate an edge `dependencies` already spells; + naming the same pair twice with two types is a `400`. + inherit_labels_from_parent: + type: boolean + default: false + description: >- + Copies the parent's labels onto the new issue at creation, on top of + `labels`. It has no effect without `parent_id`. + + + The DEFAULT IS FALSE and diverges from `bd create --parent`, whose + default is to inherit. A wire caller sends what it means: this + operation has no `--no-inherit-labels` to turn off, and a create that + silently acquired labels the request never named would be a set the + caller has to read back to learn. + dependencies: + type: array + maxItems: 100 + items: + $ref: '#/components/schemas/CreateIssueDependency' + description: >- + The complete set of explicit edges created with the issue. + Authoritative, not a patch. Every edge is written in the same + transaction as the row, so an edge this request cannot write means no + issue either. + + + A TARGET NEED NOT BE A ROW THIS DATABASE HOLDS: an `external:` + 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. + waits_for: + $ref: '#/components/schemas/CreateIssueWaitsFor' + force_id_prefix: + type: boolean + default: false + description: >- + Permits an explicit `id` outside the workspace's configured issue + prefix. It bypasses ONLY that check: it is not a force on the + create-only guard, so an occupied id is still a `409`. + + CreateIssueDependency: + type: object + additionalProperties: false + required: [target_id, type] + description: >- + One edge created with the issue. It carries `reverse` where + `BatchCreateDependency` does not, because that operation's items have no + id a target could point back at and this one's issue does. + properties: + target_id: + type: string + minLength: 1 + maxLength: 255 + description: The other endpoint of the edge. + type: + type: string + minLength: 1 + maxLength: 255 + description: >- + The edge type, from the same OPEN vocabulary `Dependency.type` + carries: checked for BEING a storable value, never for membership of + a known-types list, so a workspace's own type passes. + reverse: + type: boolean + default: false + description: >- + Writes the edge from `target_id` TO the new issue rather than from + it. It is what lets a create declare an edge that points INTO the row + being minted — the id no caller could have spelled beforehand — and + it is the member that makes `dependency_cycle` reachable on this + operation at all. + metadata: + $ref: '#/components/schemas/MetadataValue' + + CreateIssueWaitsFor: + type: object + additionalProperties: false + required: [spawner_id] + description: >- + A typed `waits-for` edge from the new issue to a spawner whose children + gate it. It records a readiness primitive; it does not define scheduling + or execution policy. + + + IT IS A TYPED MEMBER HERE AND A METADATA BLOB ON + `POST /v0/beads/issues:batchApply`, and the difference follows the ROLE + rather than taste: `CreateRequest.WaitsFor` is a typed field that gets + the gate defaulted and the "must not duplicate an explicit edge" check, + while that operation's `dep_add` item is one generic edge with no typed + field to reach. One spelling per operation, and each is its role's. + properties: + spawner_id: + type: string + minLength: 1 + maxLength: 255 + description: >- + The dependency target whose children are observed. It must not + duplicate an edge `dependencies` or `parent_id` already spells. + gate: + type: string + maxLength: 255 + description: >- + The readiness condition: `all-children` or `any-children`. Absent or + empty defaults to `all-children`. A value that is neither is refused + by the ROLE and reaches the client as a `400`. + Problem: type: object description: >- diff --git a/internal/httpapi/spec_parity_test.go b/internal/httpapi/spec_parity_test.go index c0e34246c..27dde87a3 100644 --- a/internal/httpapi/spec_parity_test.go +++ b/internal/httpapi/spec_parity_test.go @@ -804,6 +804,84 @@ func TestUpdateRequestMembersMatchTheHandler(t *testing.T) { } } +// TestCreateIssueRequestMembersMatchTheHandler is the update's gate for the +// single create, at ALL THREE of its levels. +// +// It carries the weight the batch create's narrow item did not. That operation +// publishes nine members and its handler's copy of the list is small enough to +// eyeball; this one publishes the whole create vocabulary, so a spec revision +// adding an optional member would leave `make api-check` and every other spec +// test green while the server refused the newly documented member as +// unknown_parameter — and the reverse, a member the handler honors that the +// document never promised, is undisclosed write surface on a mutation that can +// mint a row at an id the caller chose. +func TestCreateIssueRequestMembersMatchTheHandler(t *testing.T) { + doc := loadSpec(t) + schemas := mapAt(t, mapAt(t, doc, "components"), "schemas") + + for _, tc := range []struct { + schema string + accepted []string + goType reflect.Type + }{ + {"CreateIssueRequest", createRequestMembers, reflect.TypeOf(apigen.CreateIssueRequest{})}, + {"CreateIssueDependency", createDependencyMembers, reflect.TypeOf(apigen.CreateIssueDependency{})}, + {"CreateIssueWaitsFor", createWaitsForMembers, reflect.TypeOf(apigen.CreateIssueWaitsFor{})}, + } { + t.Run(tc.schema, func(t *testing.T) { + accepted := map[string]bool{} + for _, name := range tc.accepted { + accepted[name] = true + } + + goFields := jsonTagNames(t, tc.goType) + if extra := diff(goFields, accepted); len(extra) > 0 { + t.Errorf("generated %s declares members the create handler refuses as unknown: %v\n"+ + "teach the handler to honor them, or the document promises a member the server turns down", tc.schema, extra) + } + if missing := diff(accepted, goFields); len(missing) > 0 { + t.Errorf("the create handler accepts members %s does not declare: %v", tc.schema, missing) + } + + specProps := schemaProperties(t, doc, mapAt(t, schemas, tc.schema)) + if extra := diff(specProps, accepted); len(extra) > 0 { + t.Errorf("the %s schema documents members the create handler refuses: %v", tc.schema, extra) + } + if missing := diff(accepted, specProps); len(missing) > 0 { + t.Errorf("the create handler accepts members the %s schema does not document: %v", tc.schema, missing) + } + }) + } +} + +// TestCreateIssueRequestPublishesNoNullableMember pins the create side of the +// rule TestNullablePatchMembersAreExactlyTheDocumentsNullableOnes pins for the +// patch: on this body the nullable set is EMPTY, and the handler refuses an +// explicit null on every member but `metadata`. +// +// The two can drift in the direction that matters. A member marked nullable +// here would promise a clear on a create — a create has nothing to clear, so +// the promise could only be kept by writing a zero value the caller did not ask +// for — while the handler would keep answering 400. Asserting the empty set is +// what makes the four members that ARE nullable on `IssuePatchBody` a statement +// about patching rather than about the field. +func TestCreateIssueRequestPublishesNoNullableMember(t *testing.T) { + doc := loadSpec(t) + for _, schema := range []string{"CreateIssueRequest", "CreateIssueDependency", "CreateIssueWaitsFor"} { + node := mapAt(t, mapAt(t, mapAt(t, doc, "components"), "schemas"), schema) + for name, raw := range mapAt(t, node, "properties") { + prop, ok := raw.(map[string]any) + if !ok { + t.Fatalf("%s property %q is %T, want a mapping", schema, name, raw) + } + if nullable, _ := prop["nullable"].(bool); nullable { + t.Errorf("%s.%s is documented nullable and the create handler refuses a null on it; "+ + "a create has nothing to clear, so a nullable member here promises a write nobody asked for", schema, name) + } + } + } +} + // TestReopenRequestMembersMatchTheHandler is the claim's and the close's gate // for the reopen body. The reopen decodes raw members for the same reason its // mirror does — so a refusal can name the offending one, which is what makes