diff --git a/cmd/bd/serve.go b/cmd/bd/serve.go index 1608fd253..0baa4cc6b 100644 --- a/cmd/bd/serve.go +++ b/cmd/bd/serve.go @@ -309,6 +309,7 @@ func runServe() error { EdgeReader: roles.edges, GraphCounter: roles.edgeCounter, Relations: roles.relations, + Commenter: roles.commenter, BlockingAnnotator: roles.blocking, TreeWalker: roles.tree, ReadyCounter: roles.readyCounter, @@ -650,6 +651,7 @@ type serveRoleSource interface { EdgeReader() (issueops.EdgeReader, error) GraphCounter() (issueops.GraphCounter, error) IssueRelations() (issueops.Relations, error) + Commenter() (issueops.Commenter, error) BlockingAnnotator() (issueops.BlockingAnnotator, error) TreeWalker() (issueops.TreeWalker, error) ReadyCounter() (issueops.ReadyCounter, error) @@ -715,6 +717,7 @@ func serveIssueRoles(src serveRoleSource, journalEnabled bool) (serveRoles, erro {"edge reader", func() (err error) { roles.edges, err = src.EdgeReader(); return }}, {"graph counter", func() (err error) { roles.edgeCounter, err = src.GraphCounter(); return }}, {"issue relations", func() (err error) { roles.relations, err = src.IssueRelations(); return }}, + {"commenter", func() (err error) { roles.commenter, err = src.Commenter(); return }}, {"blocking annotator", func() (err error) { roles.blocking, err = src.BlockingAnnotator(); return }}, {"tree walker", func() (err error) { roles.tree, err = src.TreeWalker(); return }}, {"ready counter", func() (err error) { roles.readyCounter, err = src.ReadyCounter(); return }}, @@ -821,6 +824,7 @@ type serveRoles struct { edges issueops.EdgeReader edgeCounter issueops.GraphCounter relations issueops.Relations + commenter issueops.Commenter blocking issueops.BlockingAnnotator tree issueops.TreeWalker readyCounter issueops.ReadyCounter diff --git a/cmd/bd/serve_comment_proxied_integration_test.go b/cmd/bd/serve_comment_proxied_integration_test.go new file mode 100644 index 000000000..d9adba8e4 --- /dev/null +++ b/cmd/bd/serve_comment_proxied_integration_test.go @@ -0,0 +1,252 @@ +//go:build cgo + +package main + +import ( + "encoding/json" + "net/http" + "strings" + "testing" +) + +// End-to-end for the comment append, against real Dolt through a real +// `bd serve` subprocess. +// +// The pure tests in internal/httpapi cover the wire edge on a fake role — the +// request projection, the response shape, the path bound and every refusal this +// edge owns. What only this level can prove is what the STORAGE TRANSACTION did, +// and on this operation that is most of the contract: +// +// - the comment really lands on the thread and reads back from it, with the +// text stored VERBATIM — newlines and surrounding space survive, which no +// fake can be asked about because nothing in between is a column; +// - A WISP IS A LEGAL TARGET. The comment lands on the ephemeral thread and +// reads back from it, which requires the role to have resolved the plane and +// written `wisp_comments`. An implementation that resolved only `issues` +// answers 404 for an id the CLI comments on happily; +// - the append is NOT idempotent: two identical requests are two rows, which +// is a claim about the table rather than about the handler; +// - an id that names neither plane is a 404 and nothing is written. +// +// Every case scopes itself to issues this test creates, so the threads are exact +// whatever else the workspace holds. + +// comments reads one issue's thread back out of the database through the +// documented detail read. It is the read-back every assertion below is made +// against: what the thread holds after a write, not what the write said. +func (sp *serveProcess) comments(t *testing.T, id string) []map[string]any { + t.Helper() + status, body, _ := sp.get(t, "/v0/beads/issues/"+id+"?include_comments=true") + if status != http.StatusOK { + t.Fatalf("GET the thread of %s: status = %d: %v", id, status, body) + } + raw, ok := body["comments"].([]any) + if !ok { + // An issue with no comments omits the member, which is what + // `comments_omitted` reports about. Callers here always expect rows. + t.Fatalf("thread of %s: comments = %#v, want an array", id, body["comments"]) + } + out := make([]map[string]any, 0, len(raw)) + for i, item := range raw { + row, ok := item.(map[string]any) + if !ok { + t.Fatalf("thread of %s: comment %d is %T, want an object", id, i, item) + } + out = append(out, row) + } + return out +} + +func TestProxiedServerServeAddComment(t *testing.T) { + requireSharedProxiedServer(t) + t.Parallel() + bd := buildEmbeddedBD(t) + p := newSharedProxiedProject(t, bd, "srvcomment") + sp := startServe(t, bd, p.dir, bdProxiedEnv(p.dir)) + + // THE ROW IS WHAT THE RESPONSE SAID, and the read-back is what proves it. + // The response's `id` and `created_at` are values the request never sent, so + // this is the case that separates "the server answered plausibly" from "the + // database holds this". + t.Run("the comment lands and reads back verbatim", func(t *testing.T) { + issue := bdProxiedCreate(t, bd, p.dir, "an issue with a thread", "-p", "2") + + // Newlines and surrounding space, because that is what a real comment + // carries and because `text` is the one member on this surface that is + // neither trimmed nor character-filtered. + text := " first line\nsecond line\n" + raw, err := json.Marshal(map[string]string{"author": "alice", "text": text}) + if err != nil { + t.Fatalf("marshal body: %v", err) + } + status, body := sp.postJSON(t, "/v0/beads/issues/"+issue.ID+"/comments", string(raw)) + if status != http.StatusOK { + t.Fatalf("status = %d, want 200: %v", status, body) + } + id, _ := body["id"].(string) + if id == "" { + t.Fatalf("the response carries no id: %v", body) + } + if body["created_at"] == "" || body["created_at"] == nil { + t.Errorf("the response carries no created_at: %v", body) + } + + rows := sp.comments(t, issue.ID) + if len(rows) != 1 { + t.Fatalf("%d comments on the thread, want 1: %v", len(rows), rows) + } + if rows[0]["id"] != id { + t.Errorf("the stored comment is %v, the response reported %q", rows[0]["id"], id) + } + if rows[0]["author"] != "alice" { + t.Errorf("author = %v, want alice", rows[0]["author"]) + } + if rows[0]["text"] != text { + t.Errorf("text = %q, want %q — the column stores what was sent, untrimmed", rows[0]["text"], text) + } + if rows[0]["created_at"] != body["created_at"] { + t.Errorf("created_at = %v, the response reported %v; the response must carry the STORED value", + rows[0]["created_at"], body["created_at"]) + } + }) + + // A WISP IS A LEGAL TARGET, and this is the case a one-plane implementation + // fails. The anchor resolves through the issue-then-wisp fallback and the row + // lands in `wisp_comments`; a server that probed only `issues` would answer + // 404 for an id `bd comment` writes to happily. + t.Run("an ephemeral issue is a legal target", func(t *testing.T) { + wisp := bdProxiedCreate(t, bd, p.dir, "an ephemeral thread", "-p", "2", + "--ephemeral", "--wisp-type", "heartbeat") + + status, body := sp.postJSON(t, "/v0/beads/issues/"+wisp.ID+"/comments", + `{"author":"alice","text":"a note on ephemeral work"}`) + if status != http.StatusOK { + t.Fatalf("commenting on a wisp: status = %d, want 200 — the anchor resolves across both planes: %v", status, body) + } + if body["issue_id"] != wisp.ID { + t.Errorf("issue_id = %v, want the wisp's own id %q", body["issue_id"], wisp.ID) + } + + // And it reads back from the EPHEMERAL thread, which is the half that + // would still be missing if the anchor probe spanned both planes and the + // insert wrote `comments`. + rows := sp.comments(t, wisp.ID) + if len(rows) != 1 || rows[0]["text"] != "a note on ephemeral work" { + t.Fatalf("the wisp's thread = %v, want the one comment just written", rows) + } + }) + + // THE TWO PLANES AGREE ABOUT HOW BIG A COMMENT MAY BE, which is a claim about + // two COLUMNS and therefore has no other home than here. + // + // The document says the only cap on `text` is the 1 MiB every body shares, + // and that was false on one side: 0049 widened comments.text to LONGTEXT and + // missed wisp_comments.text, which stayed TEXT — 65535 bytes — since 0021 + // created the table. So the same comment wrote fine against a durable issue + // and failed with Error 1105 against a wisp, on an operation that resolves + // its anchor across both planes deliberately, so a caller could not know + // which side of the bound it was on until the write failed. 0065 and its + // ignored twin close it; this is the case that says so. + // + // 100 KiB is chosen to sit comfortably past TEXT's 65535 and comfortably + // under the 1 MiB body cap, so a failure here is the COLUMN and never the + // transport. + t.Run("a large comment lands on both planes", func(t *testing.T) { + durable := bdProxiedCreate(t, bd, p.dir, "a durable issue with a big comment", "-p", "2") + wisp := bdProxiedCreate(t, bd, p.dir, "an ephemeral issue with a big comment", "-p", "2", + "--ephemeral", "--wisp-type", "heartbeat") + + big := strings.Repeat("a stack frame that goes on and on\n", 3000) + if len(big) <= 65535 { + t.Fatalf("the fixture is %d bytes, which TEXT would accept; this test proves nothing", len(big)) + } + raw, err := json.Marshal(map[string]string{"author": "alice", "text": big}) + if err != nil { + t.Fatalf("marshal body: %v", err) + } + + for _, target := range []struct{ name, id string }{ + {"durable", durable.ID}, + {"wisp", wisp.ID}, + } { + status, body := sp.postJSON(t, "/v0/beads/issues/"+target.id+"/comments", string(raw)) + if status != http.StatusOK { + t.Fatalf("a %d-byte comment on the %s plane: status = %d, want 200 — the column, not the transport: %v", + len(big), target.name, status, body) + } + rows := sp.comments(t, target.id) + if len(rows) != 1 { + t.Fatalf("%s: %d comments, want 1", target.name, len(rows)) + } + // Read back at full length: a silently truncating column would answer + // 200 and store a shorter row, which is the failure a status check + // alone would miss. + if got, _ := rows[0]["text"].(string); len(got) != len(big) { + t.Errorf("%s: stored %d bytes of a %d-byte comment; the column truncated it", + target.name, len(got), len(big)) + } + } + }) + + // NOT IDEMPOTENT, and the document says so rather than leaving it to be + // discovered: two identical comments are a legitimate thread, so nothing here + // can tell that pair from a retry. This is a claim about the table, which is + // why it is asserted here and not on a fake. + t.Run("a repeated request appends a second row", func(t *testing.T) { + issue := bdProxiedCreate(t, bd, p.dir, "an issue commented on twice", "-p", "2") + + for range 2 { + status, body := sp.postJSON(t, "/v0/beads/issues/"+issue.ID+"/comments", + `{"author":"alice","text":"the same words"}`) + if status != http.StatusOK { + t.Fatalf("status = %d, want 200: %v", status, body) + } + } + if rows := sp.comments(t, issue.ID); len(rows) != 2 { + t.Errorf("%d comments after two identical appends, want 2", len(rows)) + } + }) + + // AN ABSENT ANCHOR IS A 404 and nothing is written — one anchor, so there is + // no other answer to preserve by reporting the miss in the body. + t.Run("an id that names nothing is refused", func(t *testing.T) { + status, body := sp.postJSON(t, "/v0/beads/issues/bd-nosuchbead/comments", + `{"author":"alice","text":"into the void"}`) + if status != http.StatusNotFound { + t.Fatalf("status = %d, want 404: %v", status, body) + } + if body["code"] != "not_found" { + t.Errorf("code = %v, want not_found", body["code"]) + } + }) + + // THE ROLE'S REFUSAL, over the wire, with the parameter named. Blankness is + // judged on a trimmed copy by issueops.Commenter, not at this edge, so this + // is the one case that shows the role's sentence reaching a client as the 400 + // it is rather than as a generic 500. + t.Run("a blank body is refused by name and writes nothing", func(t *testing.T) { + issue := bdProxiedCreate(t, bd, p.dir, "an issue nobody managed to comment on", "-p", "2") + + status, body := sp.postJSON(t, "/v0/beads/issues/"+issue.ID+"/comments", + `{"author":"alice","text":" \n "}`) + if status != http.StatusBadRequest { + t.Fatalf("status = %d, want 400: %v", status, body) + } + if body["code"] != "invalid_argument" || body["param"] != "text" { + t.Errorf("problem = %v, want invalid_argument on param text", body) + } + if detail, _ := body["detail"].(string); !strings.Contains(detail, "empty") { + t.Errorf("detail = %q, want the role's own sentence about empty text", detail) + } + + // Nothing was written: the detail read omits `comments` entirely for a + // thread with no rows, which is what `comments_omitted` reports about. + status, detail, _ := sp.get(t, "/v0/beads/issues/"+issue.ID+"?include_comments=true") + if status != http.StatusOK { + t.Fatalf("read back: status = %d", status) + } + if rows, present := detail["comments"]; present && len(rows.([]any)) != 0 { + t.Errorf("the refused comment was written: %v", rows) + } + }) +} diff --git a/cmd/bd/serve_source_test.go b/cmd/bd/serve_source_test.go index 23ac0c8c4..42db5cd5f 100644 --- a/cmd/bd/serve_source_test.go +++ b/cmd/bd/serve_source_test.go @@ -106,6 +106,8 @@ func TestServeIssueRolesComeFromBeneathTheHookDecorator(t *testing.T) { counter: &serveStubCounter{}, edgeCounter: &serveStubGraphCounter{}, relations: &serveStubRelations{}, + commenter: &serveStubCommenter{}, + batchCreator: &serveStubBatchCreator{}, inner: inner, }} } @@ -181,10 +183,64 @@ func TestServeIssueRolesComeFromBeneathTheHookDecorator(t *testing.T) { t.Fatal("the store's own accessor no longer returns a hook-firing releaser; this test proves nothing") } + // And for the commenter, the SEVENTH — and the one that was OUTSIDE the + // RoleFiresHooks switch entirely until the add-comment operation went on the + // wire. hook_commenter.go has fired the update hook for every comment it + // lands since it was written; nothing took the role off a store, so nothing + // noticed. An unpeeled one runs the workspace's script once per comment. + commenterFromTheStore, err := chained.Commenter() + if err != nil { + t.Fatalf("Commenter: %v", err) + } + if !storage.RoleFiresHooks(commenterFromTheStore) { + t.Fatal("the store's own accessor no longer returns a hook-firing commenter; this test proves nothing") + } + + // THE THREE THAT WERE BLIND BESIDE THE COMMENTER. Each is served over a + // published operation and each was outside the RoleFiresHooks switch, so + // httpapi.Listen admitted a hook-firing value for all three; the class-level + // scan that finds the next one is + // TestRoleFiresHooksKnowsEveryHookFiringRole in internal/storage, and these + // are the store-side halves of the same property. + for _, role := range []struct { + name string + from func() (any, error) + }{ + {"ready claimer", func() (any, error) { return chained.ReadyClaimer() }}, + {"batch closer", func() (any, error) { return chained.BatchCloser() }}, + {"batch creator", func() (any, error) { return chained.BatchCreator() }}, + } { + fromTheStore, err := role.from() + if err != nil { + t.Fatalf("the store's %s accessor: %v", role.name, err) + } + if !storage.RoleFiresHooks(fromTheStore) { + t.Fatalf("the store's own accessor no longer returns a hook-firing %s; this test proves nothing", role.name) + } + } + roles, err := serveIssueRoles(chained, false) if err != nil { t.Fatalf("serveIssueRoles: %v", err) } + if storage.RoleFiresHooks(roles.commenter) { + t.Error("bd serve would run this workspace's hooks on every HTTP comment") + } + // And the peel really landed on the layer beneath the hooks for all three, + // which is what "RoleFiresHooks is false" alone does not say: a peel two + // layers deep would also answer false and would drop the telemetry span. + if storage.RoleFiresHooks(roles.readyClaimer) || roles.readyClaimer != issueops.ReadyClaimer(middle.readyClaimer) { + t.Errorf("ready claimer came from %p, want the layer directly beneath the hooks (%p)", roles.readyClaimer, middle.readyClaimer) + } + if storage.RoleFiresHooks(roles.batchCloser) || roles.batchCloser != issueops.BatchCloser(middle.batchCloser) { + t.Errorf("batch closer came from %p, want the layer directly beneath the hooks (%p)", roles.batchCloser, middle.batchCloser) + } + if storage.RoleFiresHooks(roles.batchCreator) || roles.batchCreator != issueops.BatchCreator(middle.batchCreator) { + t.Errorf("batch creator came from %p, want the layer directly beneath the hooks (%p)", roles.batchCreator, middle.batchCreator) + } + if roles.commenter != issueops.Commenter(middle.commenter) { + t.Errorf("commenter came from %p, want the layer directly beneath the hooks (%p)", roles.commenter, middle.commenter) + } if storage.RoleFiresHooks(roles.releaser) { t.Error("bd serve would run this workspace's hooks on every HTTP release") } @@ -356,6 +412,8 @@ type serveRolesStore struct { counter *serveStubCounter edgeCounter *serveStubGraphCounter relations *serveStubRelations + commenter *serveStubCommenter + batchCreator *serveStubBatchCreator inner storage.DoltStorage } @@ -426,7 +484,6 @@ func (*serveRolesStore) ReadyCounter() (issueops.ReadyCounter, error) func (*serveRolesStore) Querier() (issueops.Querier, error) { return nil, nil } func (*serveRolesStore) Sweeper() (issueops.Sweeper, error) { return nil, nil } func (*serveRolesStore) Deleter() (issueops.Deleter, error) { return nil, nil } -func (*serveRolesStore) BatchCreator() (issueops.BatchCreator, error) { return nil, nil } func (*serveRolesStore) Memories() (memoryops.Memories, error) { return nil, nil } // MetadataCAS carries an identifiable value for the same reason, and it is the @@ -474,6 +531,41 @@ func (s *serveRolesStore) GraphCounter() (issueops.GraphCounter, error) { return // first, measured on the next role rather than asserted about it. func (s *serveRolesStore) IssueRelations() (issueops.Relations, error) { return s.relations, nil } +// BatchCreator carries an identifiable value rather than nil, and it moved off +// nil for the reason the three preconditions below give: it is one of the roles +// the hook decorator wraps, so a peel of the wrong depth hands bd serve a +// creator that runs the workspace's on_create once per item of every batch. +func (s *serveRolesStore) BatchCreator() (issueops.BatchCreator, error) { + return s.batchCreator, nil +} + +// serveStubBatchCreator is the batch-create role's stand-in, ErrUnsupported like +// every stub here. +type serveStubBatchCreator struct{} + +func (*serveStubBatchCreator) CreateBatch(context.Context, issueops.CreateBatchRequest) (issueops.CreateBatchResult, error) { + return issueops.CreateBatchResult{}, errors.ErrUnsupported +} + +// Commenter is the SEVENTH role the hook decorator wraps and the second added +// under the regime IssueRelations describes: omitting it is a build error in +// this file naming the method, not a nil dereference somewhere else. +// +// It carries an identifiable value rather than nil, unlike the reads above, +// because it IS one of the wrapped roles: hook_commenter.go fires the update +// hook for every comment it lands, so a peel of the wrong depth would hand +// bd serve a commenter that runs the workspace's script once per comment — and +// a comment is exactly the write an agent makes in a loop. +func (s *serveRolesStore) Commenter() (issueops.Commenter, error) { return s.commenter, nil } + +// serveStubCommenter is the add-comment role's stand-in, ErrUnsupported like +// every stub here. +type serveStubCommenter struct{} + +func (*serveStubCommenter) AddComment(context.Context, issueops.AddCommentRequest) (issueops.AddCommentResult, error) { + return issueops.AddCommentResult{}, errors.ErrUnsupported +} + // serveStubRelations is the neighbor role's stand-in, ErrUnsupported like every // stub here. type serveStubRelations struct{} diff --git a/cmd/bd/serve_store_identity_test.go b/cmd/bd/serve_store_identity_test.go index 73cc5e074..605ff9c27 100644 --- a/cmd/bd/serve_store_identity_test.go +++ b/cmd/bd/serve_store_identity_test.go @@ -244,6 +244,12 @@ func (*serveIdentityStore) GraphCounter() (issueops.GraphCounter, error) { func (*serveIdentityStore) IssueRelations() (issueops.Relations, error) { return serveIdentityRole{}, nil } + +// Commenter is declared at depth 1 for IssueRelations' reason, and it is the +// second role to arrive as a build error here rather than as a runtime one. +func (*serveIdentityStore) Commenter() (issueops.Commenter, error) { + return serveIdentityRole{}, nil +} func (*serveIdentityStore) BlockingAnnotator() (issueops.BlockingAnnotator, error) { return serveIdentityRole{}, nil } @@ -287,6 +293,7 @@ type serveIdentityRole struct { issueops.EdgeReader issueops.GraphCounter issueops.Relations + issueops.Commenter issueops.BlockingAnnotator issueops.TreeWalker issueops.ReadyCounter diff --git a/internal/httpapi/apigen/types.gen.go b/internal/httpapi/apigen/types.gen.go index b3ede35ef..7501a1a03 100644 --- a/internal/httpapi/apigen/types.gen.go +++ b/internal/httpapi/apigen/types.gen.go @@ -262,6 +262,23 @@ func (e ListReadyWorkParamsSort) Valid() bool { } } +// AddCommentRequest One comment to append. The issue is named by the path, so it is not a member here: a body carrying it too would give one request two spellings of one anchor and a question about what to do when they disagree. +type AddCommentRequest struct { + // Author Who is signing the comment. CALLER-ASSERTED, and not the authenticated principal — see the operation description. + // + // Trimmed of surrounding space, then refused when the result is empty, when it exceeds 256 bytes or 255 characters (the storage column), or when it carries a control character. The bounds and the character rule are `actor`'s, unchanged, because the value lands in a column of the same width that every renderer of the thread prints, where an unfiltered C1 introducer is an escape-sequence payload. + Author string `json:"author"` + + // Text The comment body, stored VERBATIM: newlines, surrounding space and unicode all survive, and nothing trims the value that lands in the row. + // + // NO LENGTH BOUND AND NO CHARACTER RULE, unlike `author` beside it, and both absences are the column: this one is `LONGTEXT` rather than a 255-character field, and a comment that is a stack trace or a diff is an ordinary comment. The only cap is the 1 MiB every body on this surface shares. + // + // BOTH PLANES AGREE ABOUT THAT, which is worth stating because they did not. `wisp_comments.text` was left `TEXT` — 65535 bytes — when the durable column was widened, so a comment past that limit wrote fine against an issue and failed against a wisp, on an operation that resolves its anchor across both planes deliberately. A caller therefore could not know which side of the bound it was on until the write failed. The ephemeral column is widened to match, so this member's bound is one number rather than two. + // + // Blank after trimming is a `400` — a comment of nothing but whitespace carries no information and is almost always a shell quoting accident — and blankness is judged on a TRIMMED COPY while the stored value is untrimmed, so a comment that merely begins with a newline is a comment. + Text string `json:"text"` +} + // AddDependenciesRequest defines model for AddDependenciesRequest. type AddDependenciesRequest struct { // Actor Who is asserting the edges, under `ClaimRequest.actor`'s rules and for the same reasons: the server trims it, refuses an empty result, anything longer than 256 BYTES, and any control character including newline. It is attributed on each `dependency_added` event a genuinely new edge records, and interpolated into the storage commit message. @@ -953,7 +970,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 tokens this server advertises: the OPERATIONS it implements, derived from its route table, and the server-wide BEHAVIORS it enforces. v0's operation vocabulary is `ready.list`, `ready.count`, `issues.list`, `issues.query`, `issues.count`, `issues.get`, `issues.related`, `issues.create`, `issues.batchClose`, `issues.claim`, `issues.claimNext`, `issues.release`, `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.count`, `dependencies.blocking`, `dependencies.tree`, `dependencies.add`, `dependencies.remove`, `memories.list`, `memories.get`, `memories.remember`, `memories.forget`, `events.list`, `events.watch`, `issues.casMetadata`; the one behavior token is `project.enforce`, which announces that a `Bd-Project-Id` stamp for the wrong workspace is refused here rather than silently ignored. The list grows additively, and an operation never appears here unless it is fully implemented. This is how a client checks for an operation or a behavior — never the version string. + // Capabilities The tokens this server advertises: the OPERATIONS it implements, derived from its route table, and the server-wide BEHAVIORS it enforces. v0's operation vocabulary is `ready.list`, `ready.count`, `issues.list`, `issues.query`, `issues.count`, `issues.get`, `issues.related`, `issues.create`, `issues.addComment`, `issues.batchClose`, `issues.claim`, `issues.claimNext`, `issues.release`, `issues.close`, `issues.reopen`, `issues.update`, `issues.sweep`, `issues.delete`, `issues.batchCreate`, `issues.batchApply`, `stats.get`, `config.list`, `config.get`, `dependencies.cycles`, `dependencies.list`, `dependencies.count`, `dependencies.blocking`, `dependencies.tree`, `dependencies.add`, `dependencies.remove`, `memories.list`, `memories.get`, `memories.remember`, `memories.forget`, `events.list`, `events.watch`, `issues.casMetadata`; the one behavior token is `project.enforce`, which announces that a `Bd-Project-Id` stamp for the wrong workspace is refused here rather than silently ignored. The list grows additively, and an operation never appears here unless it is fully implemented. This is how a client checks for an operation or a behavior — never the version string. // // THIS LIST IS BUILD-LEVEL, NOT WORKSPACE-LEVEL. It says which operations this binary serves, and for every entry but two that is the whole answer. `events.list` and `events.watch` are the exceptions: the durable events journal is a per-workspace setting that is OFF by default, so a server that advertises them may still refuse every request to both with 409 `events_journal_disabled` — correctly, because the operations exist and the workspace has no journal. A consumer of either MUST treat the capability as "this server speaks it" and the 409 as "not on this workspace", and must not read the capability as a promise that records will arrive. Capabilities []string `json:"capabilities"` @@ -2474,6 +2491,9 @@ type CreateIssueJSONRequestBody = CreateIssueRequest // UpdateIssueJSONRequestBody defines body for UpdateIssue for application/json ContentType. type UpdateIssueJSONRequestBody = UpdateIssueRequest +// AddCommentJSONRequestBody defines body for AddComment for application/json ContentType. +type AddCommentJSONRequestBody = AddCommentRequest + // CompareAndSetMetadataJSONRequestBody defines body for CompareAndSetMetadata for application/json ContentType. type CompareAndSetMetadataJSONRequestBody = CompareAndSetMetadataRequest diff --git a/internal/httpapi/claim.go b/internal/httpapi/claim.go index 088cb4774..2c28314c3 100644 --- a/internal/httpapi/claim.go +++ b/internal/httpapi/claim.go @@ -223,32 +223,46 @@ func decodeJSONObjectBody(w http.ResponseWriter, r *http.Request) (map[string]js // trim, then refuse an empty result, an over-long value, and any control // character. func validateActor(actor string) (string, *Result) { + return validateNameMember(claimActorMember, actor) +} + +// validateNameMember applies the actor rules to any member that NAMES SOMEONE +// and lands in a 255-character column: `actor` on the mutations, `author` on a +// comment. The rules are one statement parameterized by the member's spelling, +// rather than one statement per member — two copies would be two chances for a +// bound to drift, and the difference between them is a name. +// +// It reports the TRIMMED value, which is what reaches the role. +func validateNameMember(member, value string) (string, *Result) { refuse := func(detail string) *Result { - res := InvalidArgument(claimActorMember, ReasonInvalidValue, detail) + res := InvalidArgument(member, ReasonInvalidValue, detail) return &res } - trimmed := strings.TrimSpace(actor) + trimmed := strings.TrimSpace(value) switch { case trimmed == "": - return "", refuse("`" + claimActorMember + "` is empty after trimming") + return "", refuse("`" + member + "` is empty after trimming") case len(trimmed) > maxActorBytes: return "", refuse(fmt.Sprintf("`%s` is %d bytes; the limit is %d", - claimActorMember, len(trimmed), maxActorBytes)) + member, len(trimmed), maxActorBytes)) // The storage column holds types.MaxFieldLen (255) CHARACTERS, one fewer // than the document's 256-byte cap allows. Refusing that one-character // window here rather than letting it through keeps a documented-looking // value from becoming a 500 from the assignee column, and keeps the check // keyed on storage's own constant instead of a second copy of the number. - case types.CheckFieldLen(claimActorMember, trimmed) != nil: + case types.CheckFieldLen(member, trimmed) != nil: return "", refuse(fmt.Sprintf("`%s` is %d characters; storage holds at most %d", - claimActorMember, utf8.RuneCountInString(trimmed), types.MaxFieldLen)) + member, utf8.RuneCountInString(trimmed), types.MaxFieldLen)) // Newline above all: the actor is interpolated into the storage commit - // message, so a multiline value would forge audit-trail lines. + // message, so a multiline value would forge audit-trail lines. A comment's + // author is not, and is refused anyway — it lands in a column every renderer + // of the thread prints, where an unfiltered C1 introducer is an + // escape-sequence payload. case strings.ContainsFunc(trimmed, isControlChar): - return "", refuse("`" + claimActorMember + "` must not contain control characters") + return "", refuse("`" + member + "` must not contain control characters") } return trimmed, nil } @@ -325,6 +339,7 @@ var ( _ uow.EdgeReaderSource = timedProvider{} _ uow.GraphCounterSource = timedProvider{} _ uow.RelationsSource = timedProvider{} + _ uow.CommenterSource = timedProvider{} _ uow.BlockingAnnotatorSource = timedProvider{} _ uow.TreeWalkerSource = timedProvider{} _ uow.ReadyCounterSource = timedProvider{} @@ -449,6 +464,12 @@ func (p timedProvider) IssueRelations() (issueops.Relations, error) { return uow.NewIssueRelations(p) } +// Commenter builds the add-comment role OVER THIS WRAPPER, for the same reason +// and with the same hazard as IssueReader. +func (p timedProvider) Commenter() (issueops.Commenter, error) { + return uow.NewCommenter(p) +} + // BlockingAnnotator builds the blocking-decoration role OVER THIS WRAPPER, for // the same reason and with the same hazard as IssueReader. func (p timedProvider) BlockingAnnotator() (issueops.BlockingAnnotator, error) { diff --git a/internal/httpapi/comments.go b/internal/httpapi/comments.go new file mode 100644 index 000000000..9cc0f9eb5 --- /dev/null +++ b/internal/httpapi/comments.go @@ -0,0 +1,231 @@ +package httpapi + +import ( + "encoding/json" + "errors" + "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 request body's member vocabulary. The schema is +// additionalProperties: false, so anything else is refused BY NAME, the posture +// every body on this surface takes. +const ( + // addCommentAuthorMember is the signature on the row, and it is deliberately + // NOT `actor`. Every other mutation here names the principal a write is + // attributed to; this value is part of what the write STORED, read back by + // everyone who sees the thread, and it is spelled the way the `Comment` + // element that carries it back spells it. issueops.AddCommentRequest.Author + // owns the distinction. + addCommentAuthorMember = "author" + // addCommentTextMember is the comment body. + addCommentTextMember = "text" +) + +// addCommentRequestMembers is the document's member list for AddCommentRequest. +var addCommentRequestMembers = []string{addCommentAuthorMember, addCommentTextMember} + +// handleAddComment appends one comment to the thread an issue owns: +// POST /v0/beads/issues/{id}/comments, and the write `bd comment` spells. +// +// WHAT IS NOT HERE. Which plane the anchor lives on, whether a history entry is +// recorded, and the atomicity of the append are all issueops.Commenter's, held +// to on three legs by its own contract. This file is a decoder, a path bound and +// a projection. +// +// THE AUTHOR IS CALLER-ASSERTED and is not the authenticated principal, on the +// claim's terms: a configured bearer is shared and surface-wide, so it admits a +// client to everything and names nobody. What is new here is that the value does +// not merely attribute the write — it IS part of the row, so a reader of the +// thread is reading a claim the writer made about itself. +// +// PLANES: the id resolves across BOTH, so a WISP IS A LEGAL TARGET. The comment +// lands on the ephemeral thread and reads back from it; only the durable history +// entry is absent, because the wisp tables are dolt-ignored. Nothing here +// decides that — the role resolves the plane inside the transaction it writes +// in, which is what stops a comment landing on a row an earlier read saw. +func (s *Server) handleAddComment(w http.ResponseWriter, r *http.Request) { + if !s.requireNoQuery(w, r) { + return + } + if !s.requireJSONContent(w, r) { + return + } + // The id is bounded HERE, before the request buys a concurrency slot and a + // database round trip, exactly as handleGetIssue and the custom-method + // dispatcher bound their own. The column is VARCHAR(255) and the document + // calls this an exact canonical id, so a longer one — or one carrying a + // control character, which a percent-escape in the path decodes to — names + // no row that can exist. It is the SAME 404 a real miss gets, for the + // dispatcher's reason: a distinct refusal would let a caller map this + // server's notion of a well-formed id and there is nothing to learn from it. + id := r.PathValue("id") + if !s.acceptIssueID(w, r, id) { + return + } + request, ok := s.addCommentRequest(w, r, id) + if !ok { + return + } + + commenter, err := s.commenter(r) + if err != nil { + s.failAddComment(w, r, err) + return + } + result, err := commenter.AddComment(r.Context(), request) + if err != nil { + s.failAddComment(w, r, err) + return + } + // The row as STORED: the id the insert minted and created_at at the column's + // precision, never the request reflected back. checkedCommenter is what makes + // this dereference safe on a caller-supplied role. + // + // An ASSIGNMENT rather than a conversion, which is pinning.go's idiom: the + // generated type IS types.Comment, so there is no second wire struct here, + // and this line stops compiling the day a regenerated mirror appears. + var comment apigen.Comment = *result.Comment + writeJSON(w, comment) +} + +// addCommentRequest decodes and validates the body, and reports whether the +// request may proceed. Every refusal here happens BEFORE any database work. +// +// The two members are validated to DIFFERENT depths, and the difference is the +// column each lands in. `author` is a 255-character field that renderers print, +// so it gets `actor`'s rules whole. `text` is a TEXT column stored verbatim, so +// it is checked for SHAPE only and its one content rule — blank after trimming — +// is left to the role, which is rememberMemory's posture for the same reason: +// routing it through the role keeps one definition of what a comment is, so +// `bd comment` and this endpoint refuse the same input with the same sentence. +func (s *Server) addCommentRequest(w http.ResponseWriter, r *http.Request, id string) (issueops.AddCommentRequest, bool) { + members, res := decodeJSONObjectBody(w, r) + if res != nil { + s.fail(w, r, *res) + return issueops.AddCommentRequest{}, false + } + if offender, unknown := unknownMember(members, addCommentRequestMembers); unknown { + s.failUnknownMember(w, r, offender, addCommentRequestMembers) + return issueops.AddCommentRequest{}, false + } + + author, ok := s.requiredNameMember(w, r, members, addCommentAuthorMember) + if !ok { + return issueops.AddCommentRequest{}, false + } + text, ok := s.requiredVerbatimMember(w, r, members, addCommentTextMember) + if !ok { + return issueops.AddCommentRequest{}, false + } + + return issueops.AddCommentRequest{Author: author, IssueID: id, Text: text}, true +} + +// requiredNameMember reads a required member that names someone, under the +// actor rules. It is bodyActor generalized over the member's spelling: the +// claim's `actor` and this operation's `author` are the same validation with +// different names, and one body is what keeps them the same validation. +// +// Decoded through a POINTER so that `null` reaches the type-mismatch branch, +// for bodyActor's reason: unmarshaling JSON null into a string is a no-op, +// which would report a null as "empty after trimming" — the right status +// attached to prose that misdescribes what the client sent. +func (s *Server) requiredNameMember( + w http.ResponseWriter, r *http.Request, members map[string]json.RawMessage, name string, +) (string, bool) { + raw, ok := members[name] + if !ok { + s.fail(w, r, InvalidArgument(name, ReasonInvalidValue, "`"+name+"` is required")) + return "", false + } + var value *string + if err := json.Unmarshal(raw, &value); err != nil || value == nil { + s.fail(w, r, InvalidArgument(name, ReasonInvalidValue, "`"+name+"` must be a string")) + return "", false + } + trimmed, res := validateNameMember(name, *value) + if res != nil { + s.fail(w, r, *res) + return "", false + } + return trimmed, true +} + +// requiredVerbatimMember reads a required string member that is stored as sent. +// +// NOTHING IS TRIMMED, BOUNDED OR FILTERED. This is storedTextMember's opposite +// number and the difference is deliberate: that helper serves 255-character +// columns whose values renderers print, and this one serves a LONGTEXT column +// whose value is a document. A length bound would refuse a stack trace, and a +// control rule would refuse the newlines a comment is written in. The only cap +// is decodeJSONObjectBody's 1 MiB, which every body here shares. +// +// THAT IS TRUE ON BOTH PLANES ONLY BECAUSE MIGRATION 0065 MADE IT SO. The +// ephemeral column was left at TEXT's 65535 bytes when the durable one was +// widened, so this handler's "no bound" was a bound of 65535 for any anchor that +// happened to be a wisp — and this operation resolves its anchor across both +// planes, so nothing above the storage seam could have told the caller which one +// it had. There is no length check to add here; the fix was the column. +// +// Explicit `null` is a 400 naming the member rather than an empty value, for +// requiredNameMember's reason. +func (s *Server) requiredVerbatimMember( + w http.ResponseWriter, r *http.Request, members map[string]json.RawMessage, name string, +) (string, bool) { + raw, ok := members[name] + if !ok { + s.fail(w, r, InvalidArgument(name, ReasonInvalidValue, "`"+name+"` is required")) + return "", false + } + var value *string + if err := json.Unmarshal(raw, &value); err != nil || value == nil { + s.fail(w, r, InvalidArgument(name, ReasonInvalidValue, "`"+name+"` must be a string")) + return "", false + } + return *value, true +} + +// acceptIssueID bounds a path id before any database work and reports whether +// the request may proceed, answering the 404 a real miss gets. +// +// It is customMethodTarget's bound, lifted for the sub-resource paths that do +// not go through the custom-method dispatcher and therefore never met it. +func (s *Server) acceptIssueID(w http.ResponseWriter, r *http.Request, id string) bool { + if types.CheckFieldLen("id", id) != nil || strings.ContainsFunc(id, isControlChar) { + s.fail(w, r, NotFound()) + return false + } + return true +} + +// failAddComment answers a failed append. +// +// ONE ARM, and the absences are the reasoning. There is no ErrNotFound case +// because ClassifyError already carries that row, and adding one here would be a +// second definition of the miss that could only ever drift from the first; the +// tests drive an anchor that names nothing to prove the 404 arrives through the +// shared mapping. There is no conflict arm because the role has no conflict to +// raise: a thread is append-only and this write touches no field of the issue. +// +// The 400 NAMES `text` unconditionally, and that is a claim about reachability +// rather than a guess. issueops.Commenter has exactly three ErrValidation +// refusals: an empty author, which the edge refuses first under strictly +// stronger rules; an empty issue id, which cannot arrive because a ServeMux +// wildcard does not match an empty segment and a bad id is already the 404; and +// a blank body, which is the only one a client can reach. It carries the role's +// own sentence, which is what makes `bd comment` and this endpoint say the same +// thing about the same input. +func (s *Server) failAddComment(w http.ResponseWriter, r *http.Request, err error) { + if !errors.Is(err, storage.ErrValidation) { + s.failErr(w, r, err) + return + } + requestInfo(r.Context()).refuse(addCommentTextMember) + s.fail(w, r, InvalidArgument(addCommentTextMember, ReasonInvalidValue, err.Error())) +} diff --git a/internal/httpapi/comments_test.go b/internal/httpapi/comments_test.go new file mode 100644 index 000000000..fea0c08a5 --- /dev/null +++ b/internal/httpapi/comments_test.go @@ -0,0 +1,406 @@ +package httpapi + +import ( + "encoding/json" + "fmt" + "net/http" + "reflect" + "strings" + "testing" + "time" + + "github.com/steveyegge/beads/internal/storage" + "github.com/steveyegge/beads/internal/types" + "github.com/steveyegge/beads/issueops" +) + +// The wire edge of POST /v0/beads/issues/{id}/comments, on a fake role. +// +// Which plane the anchor lives on, whether a history entry is recorded and the +// atomicity of the append are issueops.Commenter's, held to on three legs by its +// own contract and shown against real Dolt in cmd/bd. What only these cases can +// show is that the request a caller SENDS becomes the request the role RECEIVES +// — with the anchor off the path and the two members off the body — that the +// stored row reaches the wire rather than the request reflected back, and that +// each refusal arrives naming the member it is about. + +const commentPath = "/v0/beads/issues/bd-1/comments" + +func (ts *testServer) addComment(t *testing.T, path, body string) *http.Response { + t.Helper() + return ts.postBody(t, path, "application/json", body) +} + +// newCommentServer wires a server over the store-shaped source with a commenter +// the case controls. Every other role is a placeholder: Listen refuses a partial +// source, and an append reaches none of them. +func newCommentServer(t *testing.T, commenter *roleCommenter) *testServer { + t.Helper() + return newTestServer(t, rolesConfig(Config{Commenter: commenter})) +} + +// storedComment is a row as the insert left it: an id the request never sent and +// a timestamp the request never sent either, which is what makes "the response +// is the STORED row" observable rather than a claim. +func storedComment(issueID string) *issueops.Comment { + return &issueops.Comment{ + ID: "3f1b0c8e-0000-4000-8000-000000000001", + IssueID: issueID, + Author: "alice", + Text: "the row's own text", + CreatedAt: time.Date(2026, 8, 10, 12, 0, 0, 0, time.UTC), + } +} + +// TestAddCommentProjectsTheWholeRequest drives the three parts of the request — +// the path anchor and both body members — because they come from two different +// places and a handler that crossed any pair would still answer 200. The +// verbatim cases are the ones with teeth: the role stores `text` as sent, so a +// trim, a normalization or a control-character filter at this edge would be +// invisible in the status and visible in every stored row. +func TestAddCommentProjectsTheWholeRequest(t *testing.T) { + for _, tc := range []struct { + name string + path string + body string + want issueops.AddCommentRequest + }{ + { + name: "the anchor comes from the path and the members from the body", + path: "bd-1", + body: `{"author":"alice","text":"looks good"}`, + want: issueops.AddCommentRequest{Author: "alice", IssueID: "bd-1", Text: "looks good"}, + }, + { + // The anchor is the PATH segment, percent-decoded once. + name: "a percent-escaped anchor is decoded once", + path: "bd%2Fslash", + body: `{"author":"alice","text":"looks good"}`, + want: issueops.AddCommentRequest{Author: "alice", IssueID: "bd/slash", Text: "looks good"}, + }, + { + // A comment is written in newlines. `text` lands in a TEXT column + // and reaches the role EXACTLY as sent — no trim, no filter — which + // is the one property that separates it from every 255-character + // member on this surface. + name: "text keeps its newlines and its surrounding space", + path: "bd-1", + body: `{"author":"alice","text":" first line\nsecond line\n"}`, + want: issueops.AddCommentRequest{Author: "alice", IssueID: "bd-1", Text: " first line\nsecond line\n"}, + }, + { + // The author IS trimmed, because it lands in a 255-character column + // under `actor`'s rules. The two members are deliberately different + // and this pins the difference from both sides. + name: "the author is trimmed", + path: "bd-1", + body: `{"author":" alice ","text":"looks good"}`, + want: issueops.AddCommentRequest{Author: "alice", IssueID: "bd-1", Text: "looks good"}, + }, + } { + t.Run(tc.name, func(t *testing.T) { + commenter := &roleCommenter{comment: storedComment(tc.want.IssueID)} + ts := newCommentServer(t, commenter) + + resp := ts.addComment(t, "/v0/beads/issues/"+tc.path+"/comments", tc.body) + if resp.StatusCode != http.StatusOK { + t.Fatalf("status = %d, want 200: %s", resp.StatusCode, readAll(t, resp)) + } + reqs := commenter.commentRequests() + if len(reqs) != 1 { + t.Fatalf("%d appends ran, want 1", len(reqs)) + } + if !reflect.DeepEqual(reqs[0], tc.want) { + t.Errorf("AddCommentRequest = %+v, want %+v", reqs[0], tc.want) + } + }) + } +} + +// TestAddCommentAnswersTheStoredRow is the response half: the body is the row +// the role reported, not the request reflected back. +// +// The `id` and `created_at` assertions are the load-bearing ones. Neither is +// anything the request sent — the insert minted one and the column stored the +// other — so a handler that echoed its own request would have to invent them, +// and a client using `created_at` as a cursor depends on it being the stored +// value rather than this server's clock. +func TestAddCommentAnswersTheStoredRow(t *testing.T) { + ts := newCommentServer(t, &roleCommenter{comment: storedComment("bd-1")}) + + resp := ts.addComment(t, commentPath, `{"author":"alice","text":"what the caller sent"}`) + if resp.StatusCode != http.StatusOK { + t.Fatalf("status = %d, want 200: %s", resp.StatusCode, readAll(t, resp)) + } + body := decodeBody(t, resp) + if body["id"] != "3f1b0c8e-0000-4000-8000-000000000001" { + t.Errorf("id = %v, want the id the insert minted", body["id"]) + } + if body["issue_id"] != "bd-1" || body["author"] != "alice" { + t.Errorf("body = %v, want the stored row", body) + } + if body["text"] != "the row's own text" { + t.Errorf("text = %v, want the STORED text; this response is echoing the request", body["text"]) + } + if got, _ := body["created_at"].(string); !strings.HasPrefix(got, "2026-08-10T12:00:00") { + t.Errorf("created_at = %v, want the stored timestamp", body["created_at"]) + } +} + +// TestAddCommentRefusesTheBody walks every refusal this edge owns, each named by +// the member it is about — `param` is what a client dispatches on, so a refusal +// that named the wrong member would send a caller to fix the wrong thing. +func TestAddCommentRefusesTheBody(t *testing.T) { + for _, tc := range []struct { + name string + body string + param string + }{ + {name: "an unknown member", body: `{"author":"alice","text":"hi","actor":"alice"}`, param: "actor"}, + {name: "a missing author", body: `{"text":"hi"}`, param: "author"}, + {name: "a null author", body: `{"author":null,"text":"hi"}`, param: "author"}, + {name: "a non-string author", body: `{"author":7,"text":"hi"}`, param: "author"}, + {name: "an author that is empty after trimming", body: `{"author":" ","text":"hi"}`, param: "author"}, + { + name: "an author carrying a control character", + body: `{"author":"alice\u0085bd: comment bd-9 by mallory","text":"hi"}`, + param: "author", + }, + {name: "a missing text", body: `{"author":"alice"}`, param: "text"}, + {name: "a null text", body: `{"author":"alice","text":null}`, param: "text"}, + {name: "a non-string text", body: `{"author":"alice","text":["hi"]}`, param: "text"}, + } { + t.Run(tc.name, func(t *testing.T) { + commenter := &roleCommenter{comment: storedComment("bd-1")} + ts := newCommentServer(t, commenter) + + resp := ts.addComment(t, commentPath, tc.body) + if resp.StatusCode != http.StatusBadRequest { + t.Fatalf("status = %d, want 400: %s", resp.StatusCode, readAll(t, resp)) + } + body := decodeBody(t, resp) + if body["code"] != string(CodeInvalidArgument) { + t.Errorf("code = %v, want %s", body["code"], CodeInvalidArgument) + } + if body["param"] != tc.param { + t.Errorf("param = %v, want %q", body["param"], tc.param) + } + // Nothing reached the role: every refusal here happens before any + // database work, which is what makes "nothing was written" true. + if got := commenter.commentRequests(); len(got) != 0 { + t.Errorf("%d appends ran on a refused request", len(got)) + } + }) + } +} + +// TestAddCommentRefusesAnOverlongAuthor pins the two bounds separately, because +// they are two rules with two different numbers and a single over-long fixture +// would satisfy both while proving neither. +func TestAddCommentRefusesAnOverlongAuthor(t *testing.T) { + for _, tc := range []struct { + name string + author string + want string + }{ + // One byte past the document's 256-BYTE cap. + {name: "over the byte cap", author: strings.Repeat("a", maxActorBytes+1), want: "bytes"}, + // Exactly 256 ASCII characters: INSIDE the byte cap and one character + // past the storage column. That one-character window is precisely what + // the byte bound alone would let through into a 500 from the database, + // which is why the character check is keyed on storage's own constant. + {name: "over the column's character count", author: strings.Repeat("a", types.MaxFieldLen+1), want: "characters"}, + } { + t.Run(tc.name, func(t *testing.T) { + ts := newCommentServer(t, &roleCommenter{comment: storedComment("bd-1")}) + + resp := ts.addComment(t, commentPath, fmt.Sprintf(`{"author":%q,"text":"hi"}`, tc.author)) + if resp.StatusCode != http.StatusBadRequest { + t.Fatalf("status = %d, want 400: %s", resp.StatusCode, readAll(t, resp)) + } + body := decodeBody(t, resp) + if body["param"] != "author" { + t.Errorf("param = %v, want author", body["param"]) + } + if detail, _ := body["detail"].(string); !strings.Contains(detail, tc.want) { + t.Errorf("detail = %q, want it to name the %s bound", detail, tc.want) + } + }) + } +} + +// TestAddCommentAcceptsATextNoOtherMemberWould is the negative space of the +// author rules, and it is the case a reflex "validate every string member the +// same way" edit breaks: a comment is routinely a stack trace or a diff, so the +// body carries newlines and is far longer than any 255-character column. +func TestAddCommentAcceptsATextNoOtherMemberWould(t *testing.T) { + commenter := &roleCommenter{comment: storedComment("bd-1")} + ts := newCommentServer(t, commenter) + + text := strings.Repeat("a stack frame\n", 400) + raw, err := json.Marshal(map[string]string{"author": "alice", "text": text}) + if err != nil { + t.Fatalf("marshal body: %v", err) + } + resp := ts.addComment(t, commentPath, string(raw)) + if resp.StatusCode != http.StatusOK { + t.Fatalf("status = %d, want 200: %s", resp.StatusCode, readAll(t, resp)) + } + reqs := commenter.commentRequests() + if len(reqs) != 1 || reqs[0].Text != text { + t.Fatalf("the role received a text of %d bytes, want the %d sent", len(reqs[0].Text), len(text)) + } +} + +// TestAddCommentRefusesABlankBodyThroughTheRole is the one role refusal this +// wire can reach, and the assertion is that it arrives as the 400 it is with the +// role's own sentence rather than as a generic 500. +// +// It is the ROLE's rule deliberately: refusing blankness at the edge would be a +// second definition of what a comment is, and `bd comment` and this endpoint +// would be one edit away from disagreeing about the same input. +func TestAddCommentRefusesABlankBodyThroughTheRole(t *testing.T) { + ts := newCommentServer(t, &roleCommenter{ + err: fmt.Errorf("%w: comment text cannot be empty", storage.ErrValidation), + }) + + resp := ts.addComment(t, commentPath, `{"author":"alice","text":" "}`) + if resp.StatusCode != http.StatusBadRequest { + t.Fatalf("status = %d, want 400: %s", resp.StatusCode, readAll(t, resp)) + } + body := decodeBody(t, resp) + if body["code"] != string(CodeInvalidArgument) || body["param"] != "text" { + t.Errorf("body = %v, want invalid_argument naming text", body) + } + if detail, _ := body["detail"].(string); !strings.Contains(detail, "comment text cannot be empty") { + t.Errorf("detail = %q, want the role's own sentence", detail) + } +} + +// TestAddCommentMissesAreNotFound covers both ways an anchor can name nothing: +// the role reporting a miss, and an id this server can tell names no row that +// could exist. They are ONE answer deliberately — a distinct refusal for the +// second would let a caller map this server's notion of a well-formed id, and +// there is nothing to learn from it. +func TestAddCommentMissesAreNotFound(t *testing.T) { + t.Run("the role reports a miss", func(t *testing.T) { + ts := newCommentServer(t, &roleCommenter{ + err: fmt.Errorf("issue bd-404: %w", storage.ErrNotFound), + }) + + resp := ts.addComment(t, "/v0/beads/issues/bd-404/comments", `{"author":"alice","text":"hi"}`) + if resp.StatusCode != http.StatusNotFound { + t.Fatalf("status = %d, want 404: %s", resp.StatusCode, readAll(t, resp)) + } + if body := decodeBody(t, resp); body["code"] != string(CodeNotFound) { + t.Errorf("code = %v, want %s", body["code"], CodeNotFound) + } + }) + + t.Run("an id no row could carry never reaches the role", func(t *testing.T) { + commenter := &roleCommenter{comment: storedComment("bd-1")} + ts := newCommentServer(t, commenter) + + // One character past the id column, so it names no row that can exist. + id := strings.Repeat("b", types.MaxFieldLen+1) + resp := ts.addComment(t, "/v0/beads/issues/"+id+"/comments", `{"author":"alice","text":"hi"}`) + if resp.StatusCode != http.StatusNotFound { + t.Fatalf("status = %d, want 404: %s", resp.StatusCode, readAll(t, resp)) + } + if got := commenter.commentRequests(); len(got) != 0 { + t.Errorf("%d appends ran for an id that cannot name a row", len(got)) + } + }) +} + +// TestAddCommentRefusesEverythingButAJSONBody covers the two document-level +// rules on a body-carrying operation, on this operation, because both are +// enforced per handler rather than by middleware. +func TestAddCommentRefusesEverythingButAJSONBody(t *testing.T) { + t.Run("a query parameter", func(t *testing.T) { + ts := newCommentServer(t, &roleCommenter{comment: storedComment("bd-1")}) + resp := ts.addComment(t, commentPath+"?notify=true", `{"author":"alice","text":"hi"}`) + if resp.StatusCode != http.StatusBadRequest { + t.Fatalf("status = %d, want 400: %s", resp.StatusCode, readAll(t, resp)) + } + if body := decodeBody(t, resp); body["reason"] != string(ReasonUnknownParameter) { + t.Errorf("reason = %v, want %s", body["reason"], ReasonUnknownParameter) + } + }) + + t.Run("a form encoding", func(t *testing.T) { + ts := newCommentServer(t, &roleCommenter{comment: storedComment("bd-1")}) + resp := ts.postBody(t, commentPath, "application/x-www-form-urlencoded", `author=alice&text=hi`) + if resp.StatusCode != http.StatusBadRequest { + t.Fatalf("status = %d, want 400: %s", resp.StatusCode, readAll(t, resp)) + } + if body := decodeBody(t, resp); body["param"] != "Content-Type" { + t.Errorf("param = %v, want Content-Type", body["param"]) + } + }) +} + +// TestCommentCollectionPublishesOnlyThePost pins the deliberate absence: no role +// answers a comment PAGE, so this collection has no GET and a reflex addition +// would be this surface inventing a paging contract the role declined. +// +// The answer is a 404 rather than a 405 because 405 is not in the v0 status +// vocabulary — the catch-all handles a method mismatch on a known path. +func TestCommentCollectionPublishesOnlyThePost(t *testing.T) { + ts := newCommentServer(t, &roleCommenter{comment: storedComment("bd-1")}) + + resp := ts.get(t, commentPath) + if resp.StatusCode != http.StatusNotFound { + t.Fatalf("GET status = %d, want 404: %s", resp.StatusCode, readAll(t, resp)) + } + body := decodeBody(t, resp) + if body["code"] != string(CodeNotFound) { + t.Errorf("code = %v, want %s; every non-2xx byte here is a problem document", body["code"], CodeNotFound) + } +} + +// TestAddCommentDoesNotDereferenceAMissingRow is checkedCommenter's whole +// reason. A role reached through Config is caller-supplied code, and the handler +// writes *result.Comment, so a role that reported success without the row is a +// nil pointer dereference on a live server. +// +// THE STATUS IS NOT THE ASSERTION, and this is the trap the claim's own case +// records: the panic middleware recovers into the SAME 500 with the same code, +// so a test that stopped there would pass with the wrapper removed. What differs +// is the log — a recovered panic writes a stack trace and no request_error line +// for an operator to alert on — so the two log assertions are what this case is +// actually made of. +func TestAddCommentDoesNotDereferenceAMissingRow(t *testing.T) { + ts := newCommentServer(t, &roleCommenter{comment: nil}) + + resp := ts.addComment(t, commentPath, `{"author":"alice","text":"hi"}`) + 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, "comment") { + t.Errorf("the 500 is logged without naming the operation that produced it:\n%s", line) + } +} + +// TestAddCommentPathReachesItsHandler drives the documented path against the +// real router, which is the half TestSpecRouteParity cannot see: that test +// compares strings, and the POST wildcard the custom methods share +// (/v0/beads/issues/{idop}) is registered under the same method one segment up. +// If ServeMux ever preferred it, every comment would be dispatched as an +// unrouted custom method and answered 404. +func TestAddCommentPathReachesItsHandler(t *testing.T) { + commenter := &roleCommenter{comment: storedComment("bd-1")} + ts := newCommentServer(t, commenter) + + resp := ts.addComment(t, commentPath, `{"author":"alice","text":"hi"}`) + if resp.StatusCode != http.StatusOK { + t.Fatalf("status = %d, want 200: %s", resp.StatusCode, readAll(t, resp)) + } + if got := commenter.commentRequests(); len(got) != 1 { + t.Fatalf("%d appends reached the role; the documented path is not routed to this handler", len(got)) + } +} diff --git a/internal/httpapi/problem.go b/internal/httpapi/problem.go index eab7482f2..f952208db 100644 --- a/internal/httpapi/problem.go +++ b/internal/httpapi/problem.go @@ -498,6 +498,17 @@ const ( // codes come from: an occupied id, and the graph refusing the edges the // request asked for. OpCreateIssue = "createIssue" + // OpAddComment appends one comment to the thread an issue owns, behind + // issueops.Commenter. It is the surface's first write on a SUB-RESOURCE + // COLLECTION, and a plain collection POST for OpCreateIssue's reason: + // creating one member of the collection a path names is what POST means. + // + // The row it creates is the same pinned Comment getIssue already carries + // under `comments`, which is what puts the operation on the issue rather + // than on a collection of its own. The collection publishes no GET, + // deliberately: no role answers a comment PAGE, and inventing one here + // would be this surface deciding a paging contract the role declined. + OpAddComment = "addComment" // OpBatchCreateIssues creates many issues as one transaction, or none. OpBatchCreateIssues = "batchCreateIssues" // OpApplyBatch applies an ORDERED, heterogeneous plan — creates, updates, @@ -871,6 +882,25 @@ var operationCodes = map[string][]Code{ CodeDependencyCycle, CodeDependencyExists, CodeBusy, CodeDBUnavailable, CodeInternal, }, + // getDependencyTree's row, and it is the same shape for the same two + // reasons: ONE anchor, so an id that names nothing is the 404 it is rather + // than a per-item flag, and a 400 that is BOTH the transport's and the + // ROLE's. + // + // NO CONFLICT CODE, and the absence is the operation's contract. A thread is + // append-only and this write touches no field of the issue, so there is no + // row state a guard could be stale about and no concurrent comment for this + // one to collide with — which is also why there is no `expected_version` + // member to earn a precondition_failed with. + // + // Of the role's three ErrValidation refusals exactly ONE is reachable here. + // An empty author is refused at the edge under `actor`'s rules, which are + // strictly stronger, and an empty issue id cannot arrive at all — a ServeMux + // wildcard does not match an empty segment, and an id that fails the path + // bound is the 404 a real miss gets. So the blank body is the whole of what + // the role can refuse over this wire, which is why failAddComment names one + // parameter rather than re-asking the validator's questions. + OpAddComment: {CodeInvalidArgument, CodeUnauthenticated, CodeNotFound, CodeBusy, CodeDBUnavailable, CodeInternal}, // No 404 and no conflict code: this is an UPSERT with a server-derivable // key, so there is no resource it can fail to address and no row it can // collide with. Its 400 is the body vocabulary plus the ROLE's two diff --git a/internal/httpapi/roles.go b/internal/httpapi/roles.go index a5136f3fe..47511b5fb 100644 --- a/internal/httpapi/roles.go +++ b/internal/httpapi/roles.go @@ -239,6 +239,28 @@ func (c checkedClaimer) Claim(ctx context.Context, req issueops.ClaimRequest) (i return result, err } +// checkedCommenter is the commenter the add-comment handler is handed. +// +// It exists for checkedClaimer's reason exactly: handleAddComment writes +// *result.Comment onto the wire, so a role that reported success without the row +// would panic on a live server. +type checkedCommenter struct{ inner issueops.Commenter } + +// AddComment refuses a result that reports success without the row the response +// body is built from. +// +// The generic 500, for checkedClaimer's reason. There is no wire code that fits +// and there must not be: a 404 would say the issue does not exist when the role +// just said it appended a comment to it, and this operation has no conflict code +// at all. It is a broken implementation. +func (c checkedCommenter) AddComment(ctx context.Context, req issueops.AddCommentRequest) (issueops.AddCommentResult, error) { + result, err := c.inner.AddComment(ctx, req) + if err == nil && result.Comment == nil { + return issueops.AddCommentResult{}, fmt.Errorf("add comment %q: the commenter reported success without a comment", req.IssueID) + } + return result, err +} + // checkedReleaser is the releaser the release handler is handed. // // It exists for checkedClaimer's reason exactly: handleRelease writes diff --git a/internal/httpapi/roles_test.go b/internal/httpapi/roles_test.go index 9d53d2b19..3129fb9c8 100644 --- a/internal/httpapi/roles_test.go +++ b/internal/httpapi/roles_test.go @@ -163,6 +163,35 @@ func (r *roleRelations) relatedRequests() []issueops.RelatedRequest { return append([]issueops.RelatedRequest(nil), r.reqs...) } +// roleCommenter is the append-one-comment role of the store-shaped source. It +// records the whole request, because on this operation the request IS most of +// what the wire edge has to get right: the anchor comes from the path and the +// two members come from the body, so a handler that crossed any of the three +// would still answer 200. +type roleCommenter struct { + comment *issueops.Comment + err error + + mu sync.Mutex + reqs []issueops.AddCommentRequest +} + +func (c *roleCommenter) AddComment(_ context.Context, req issueops.AddCommentRequest) (issueops.AddCommentResult, error) { + c.mu.Lock() + c.reqs = append(c.reqs, req) + c.mu.Unlock() + if c.err != nil { + return issueops.AddCommentResult{}, c.err + } + return issueops.AddCommentResult{Comment: c.comment}, nil +} + +func (c *roleCommenter) commentRequests() []issueops.AddCommentRequest { + c.mu.Lock() + defer c.mu.Unlock() + return append([]issueops.AddCommentRequest(nil), c.reqs...) +} + // roleBlockingAnnotator is the derived-decoration role of the store-shaped // source. It is its own fake beside roleEdgeReader because the two are separate // interfaces for separate questions, and a double answering both would be the @@ -865,6 +894,9 @@ func rolesConfig(cfg Config) Config { if cfg.Relations == nil { cfg.Relations = &roleRelations{} } + if cfg.Commenter == nil { + cfg.Commenter = &roleCommenter{} + } if cfg.BlockingAnnotator == nil { cfg.BlockingAnnotator = &roleBlockingAnnotator{} } @@ -1115,6 +1147,14 @@ func TestListenRequiresExactlyOneDatabaseSource(t *testing.T) { cfg: rolesConfigWithout(func(c *Config) { c.EdgeReader = nil }), wantErr: "no database source", }, + { + // The write on the sub-resource: missing it, the server binds, + // advertises issues.addComment, and nil-dereferences on the first + // request that appends a comment. + name: "no commenter", + cfg: rolesConfigWithout(func(c *Config) { c.Commenter = nil }), + wantErr: "no database source", + }, { name: "no blocking annotator", cfg: rolesConfigWithout(func(c *Config) { c.BlockingAnnotator = nil }), @@ -1820,15 +1860,27 @@ func assertNoPanic(t *testing.T, ts *testServer) { } // hookableStore is the smallest thing storage.NewHookFiringStore will decorate: -// the DoltStorage surface is embedded nil because IssueClaimer is the only -// method this test ever reaches through it. +// the DoltStorage surface is embedded nil, and the accessors declared below are +// exactly the hook-firing roles this test drives through Listen. type hookableStore struct { storage.DoltStorage - claimer issueops.Claimer + claimer issueops.Claimer + commenter issueops.Commenter + readyClaimer issueops.ReadyClaimer + batchCloser issueops.BatchCloser + batchCreator issueops.BatchCreator } func (s hookableStore) IssueClaimer() (issueops.Claimer, error) { return s.claimer, nil } +func (s hookableStore) Commenter() (issueops.Commenter, error) { return s.commenter, nil } + +func (s hookableStore) ReadyClaimer() (issueops.ReadyClaimer, error) { return s.readyClaimer, nil } + +func (s hookableStore) BatchCloser() (issueops.BatchCloser, error) { return s.batchCloser, nil } + +func (s hookableStore) BatchCreator() (issueops.BatchCreator, error) { return s.batchCreator, nil } + // TestListenRefusesARoleThatFiresTheWorkspaceHooks. // // `bd serve` documents that hooks do not fire, and a store is the surface that @@ -1846,7 +1898,13 @@ func TestListenRefusesARoleThatFiresTheWorkspaceHooks(t *testing.T) { // The refusal must not depend on that: the type's job is to fire hooks, and // a server that admitted this one would be a config change away from // breaking its own contract. - hooked := storage.NewHookFiringStore(hookableStore{claimer: &roleClaimer{}}, nil) + hooked := storage.NewHookFiringStore(hookableStore{ + claimer: &roleClaimer{}, + commenter: &roleCommenter{}, + readyClaimer: &roleReadyClaimer{}, + batchCloser: &roleBatchCloser{}, + batchCreator: &roleBatchCreator{}, + }, nil) fromTheStore, err := hooked.IssueClaimer() if err != nil { @@ -1882,6 +1940,69 @@ func TestListenRefusesARoleThatFiresTheWorkspaceHooks(t *testing.T) { t.Fatalf("Listen: %v, want a bound server for the claimer beneath the hook layer", err) } t.Cleanup(func() { _ = srv.http.Close() }) + + // THE FOUR ROLES RoleFiresHooks DID NOT KNOW ABOUT, each driven through the + // same refusal. They were blind for as long as nobody happened to take one + // off a store by hand, and every one of them is served over a PUBLISHED + // operation, so Listen was admitting a hook-firing value for any of the four + // — which is the exact failure this whole guard exists to prevent. + // + // Their per-request cost is what makes them worth naming individually: the + // commenter fires once per comment, which is what an agent posting progress + // into a thread does in a loop; the ready claimer once per bead a polling + // drainer picks up; the batch closer once per landed item plus one for the + // claim it chains; the batch creator once per item, so a hundred-item batch + // is a hundred subprocesses inside one HTTP call. + // + // The class-level guard is TestRoleFiresHooksKnowsEveryHookFiringRole in + // internal/storage, which scans for the NEXT one. These are the both-ends + // pins beneath it: the store really hands back a hook-firing value, and + // Listen really refuses it. + for _, role := range []struct { + name string + from func() (any, error) + bind func(any) Config + }{ + { + name: "commenter", + from: func() (any, error) { return hooked.Commenter() }, + bind: func(v any) Config { return rolesConfig(Config{Commenter: v.(issueops.Commenter)}) }, + }, + { + name: "ready claimer", + from: func() (any, error) { return hooked.ReadyClaimer() }, + bind: func(v any) Config { return rolesConfig(Config{ReadyClaimer: v.(issueops.ReadyClaimer)}) }, + }, + { + name: "batch closer", + from: func() (any, error) { return hooked.BatchCloser() }, + bind: func(v any) Config { return rolesConfig(Config{BatchCloser: v.(issueops.BatchCloser)}) }, + }, + { + name: "batch creator", + from: func() (any, error) { return hooked.BatchCreator() }, + bind: func(v any) Config { return rolesConfig(Config{BatchCreator: v.(issueops.BatchCreator)}) }, + }, + } { + t.Run(role.name, func(t *testing.T) { + fromStore, err := role.from() + if err != nil { + t.Fatalf("the store's %s accessor: %v", role.name, err) + } + if !storage.RoleFiresHooks(fromStore) { + t.Fatalf("RoleFiresHooks does not recognize the hook-firing %s, so Listen would serve one", role.name) + } + cfg := role.bind(fromStore) + cfg.Addr = "127.0.0.1:0" + cfg.Stdout = io.Discard + cfg.Stderr = io.Discard + if _, err := Listen(cfg); err == nil { + t.Errorf("Listen bound a server whose %s runs the workspace's hook scripts", role.name) + } else if !strings.Contains(err.Error(), "hooks") { + t.Errorf("refusal %q does not say what is wrong with the role", err) + } + }) + } } // serveHookRunner stands in for the workspace's script runner. The refusal is diff --git a/internal/httpapi/routes.go b/internal/httpapi/routes.go index f3474ac13..6dbb35154 100644 --- a/internal/httpapi/routes.go +++ b/internal/httpapi/routes.go @@ -314,6 +314,33 @@ var routeTable = []route{ implemented: true, handler: (*Server).handleListRelatedIssues, }, + { + op: OpAddComment, + method: http.MethodPost, + // The second SUB-RESOURCE row and the first that writes, spelled the way + // the neighbor read above is: a LITERAL segment after a single-segment + // wildcard, so pattern and specPath agree, the router registers the + // documented path itself, and the claim row's exception does not apply. + // + // A PLAIN collection POST rather than a custom method, for the single + // create's reason: this creates one member of the collection the path + // names. It is the one place a sub-resource earns the method outright. + // + // It collides with nothing, and the POST wildcard is the collision worth + // checking rather than assuming: `/v0/beads/issues/{idop}` matches ONE + // segment after `/issues/`, and this path has two, so the dispatcher + // never sees a request for it. TestCustomMethodsNarrowThePOSTSurface and + // TestAddCommentPathReachesItsHandler pin the two halves. + // + // The collection has no GET row and must not grow one by reflex: no role + // answers a comment page, and the thread is read through + // `GET /v0/beads/issues/{id}?include_comments=true`. A GET here lands on + // the catch-all, which answers 404 — this surface has no 405. + pattern: "/v0/beads/issues/{id}/comments", + capability: "issues.addComment", + implemented: true, + handler: (*Server).handleAddComment, + }, { op: OpListSettings, method: http.MethodGet, diff --git a/internal/httpapi/server.go b/internal/httpapi/server.go index cd38a6ad1..f4b53889a 100644 --- a/internal/httpapi/server.go +++ b/internal/httpapi/server.go @@ -228,7 +228,15 @@ type Config struct { // this one answers with the hydrated ISSUES on the far end for ONE anchor and // answers ErrNotFound. Different answer shape, different miss policy, // different arity. Required on the same terms as every field here. - Relations issueops.Relations + Relations issueops.Relations + // Commenter is the append-one-comment role behind + // POST /v0/beads/issues/{id}/comments. It is its own field rather than a + // verb on Lifecycle for the role's own reason: a comment is not a patch to + // an issue — it appends a row to a thread the issue owns and leaves every + // field of the issue untouched, so an IssuePatch has nothing to carry and an + // UpdateResult has nowhere to put the comment. Required on the same terms as + // every field here. + Commenter issueops.Commenter BlockingAnnotator issueops.BlockingAnnotator TreeWalker issueops.TreeWalker ReadyCounter issueops.ReadyCounter @@ -349,6 +357,7 @@ type Server struct { issueEdges issueops.EdgeReader issueEdgeCounter issueops.GraphCounter issueRelations issueops.Relations + issueCommenter issueops.Commenter issueBlocking issueops.BlockingAnnotator issueTree issueops.TreeWalker issueReadyCounter issueops.ReadyCounter @@ -500,6 +509,7 @@ func Listen(cfg Config) (*Server, error) { issueEdges: cfg.EdgeReader, issueEdgeCounter: cfg.GraphCounter, issueRelations: cfg.Relations, + issueCommenter: cfg.Commenter, issueBlocking: cfg.BlockingAnnotator, issueTree: cfg.TreeWalker, issueReadyCounter: cfg.ReadyCounter, @@ -617,12 +627,12 @@ func Listen(cfg Config) (*Server, error) { // "all or nothing" would turn an honest condition into a special case inside // three functions. It is checked once, on its own, below. func sourceRoles(cfg Config) []any { - return []any{cfg.Reader, cfg.Claimer, cfg.ReadyClaimer, cfg.Releaser, cfg.Lifecycle, cfg.BatchCloser, cfg.Settings, cfg.Stats, cfg.CycleDetector, cfg.EdgeReader, cfg.GraphCounter, cfg.Relations, cfg.BlockingAnnotator, cfg.TreeWalker, cfg.ReadyCounter, cfg.Counter, cfg.Querier, cfg.Sweeper, cfg.Deleter, cfg.BatchCreator, cfg.DependencyEditor, cfg.BatchApplier, cfg.Memories, cfg.MetadataCAS} + return []any{cfg.Reader, cfg.Claimer, cfg.ReadyClaimer, cfg.Releaser, cfg.Lifecycle, cfg.BatchCloser, cfg.Settings, cfg.Stats, cfg.CycleDetector, cfg.EdgeReader, cfg.GraphCounter, cfg.Relations, cfg.Commenter, cfg.BlockingAnnotator, cfg.TreeWalker, cfg.ReadyCounter, cfg.Counter, cfg.Querier, cfg.Sweeper, cfg.Deleter, cfg.BatchCreator, cfg.DependencyEditor, cfg.BatchApplier, cfg.Memories, cfg.MetadataCAS} } // roleSourceNames spells sourceRoles for the refusal message, in the same // order, so a caller reading the error learns the whole set it must pass. -const roleSourceNames = "Reader, Claimer, ReadyClaimer, Releaser, Lifecycle, BatchCloser, Settings, Stats, CycleDetector, EdgeReader, GraphCounter, Relations, BlockingAnnotator, TreeWalker, ReadyCounter, Counter, Querier, Sweeper, Deleter, BatchCreator, DependencyEditor, BatchApplier, Memories and MetadataCAS" +const roleSourceNames = "Reader, Claimer, ReadyClaimer, Releaser, Lifecycle, BatchCloser, Settings, Stats, CycleDetector, EdgeReader, GraphCounter, Relations, Commenter, BlockingAnnotator, TreeWalker, ReadyCounter, Counter, Querier, Sweeper, Deleter, BatchCreator, DependencyEditor, BatchApplier, Memories and MetadataCAS" func anyRoleSet(cfg Config) bool { return slices.ContainsFunc(sourceRoles(cfg), func(r any) bool { return r != nil }) @@ -955,6 +965,26 @@ func (s *Server) relations(r *http.Request) (issueops.Relations, error) { return src.IssueRelations() } +// commenter returns the append-one-comment surface for one request, built the +// same two ways as every role above and held by INTERFACE so +// uow.CommenterSource is load-bearing rather than decorative. +// +// It goes out WRAPPED, unlike the reads beside it and for checkedClaimer's +// reason: handleAddComment dereferences the pointer the role answers with, so a +// caller-supplied role that reported success without a row would panic on a live +// server rather than reaching the generic 500 with the fault in the log. +func (s *Server) commenter(r *http.Request) (issueops.Commenter, error) { + if s.provider == nil { + return checkedCommenter{inner: s.issueCommenter}, nil + } + var src uow.CommenterSource = timedProvider{inner: s.provider, rec: requestInfo(r.Context())} + c, err := src.Commenter() + if err != nil { + return nil, err + } + return checkedCommenter{inner: c}, nil +} + // blockingAnnotator returns the derived blocking-decoration surface for one // request, on the same terms as every role above and held by INTERFACE so // uow.BlockingAnnotatorSource is load-bearing rather than decorative. It goes diff --git a/internal/httpapi/spec/openapi.v0.yaml b/internal/httpapi/spec/openapi.v0.yaml index 37ff2a200..decbda2a9 100644 --- a/internal/httpapi/spec/openapi.v0.yaml +++ b/internal/httpapi/spec/openapi.v0.yaml @@ -63,10 +63,11 @@ info: outside its own parameter table with `400` / `code: invalid_argument` / `reason: "unknown_parameter"` and `param` naming the offending key. Operations that declare no QUERY parameter at all reject every query key - the same way. Today that is twenty-two of the thirty-eight operations + the same way. Today that is twenty-three of the thirty-nine operations here — `GET /healthz`, `GET /v0/beads/context`, `GET /v0/beads/dependencies/cycles`, `POST /v0/beads/issues`, `PATCH /v0/beads/issues/{id}`, + `POST /v0/beads/issues/{id}/comments`, `POST /v0/beads/issues/{id}:claim`, `POST /v0/beads/issues/{id}:release`, `POST /v0/beads/issues/{id}:close`, @@ -2400,6 +2401,139 @@ paths: '503': $ref: '#/components/responses/Unavailable' + /v0/beads/issues/{id}/comments: + post: + operationId: addComment + summary: Append one comment to an issue's thread + description: >- + Appends ONE comment to the thread the issue owns, as one atomic + mutation — the write behind `bd comment`. It leaves every field of the + issue untouched: a comment is not a patch, which is why it is not a + member of `PATCH /v0/beads/issues/{id}` and why `issueops.Commenter` is + its own role rather than a lifecycle verb. + + + IT IS A SUB-RESOURCE COLLECTION OF THE ISSUE, and the argument is the + one `GET /v0/beads/issues/{id}/related` makes, applied to a write: the + row this creates is the SAME pinned `Comment` + `GET /v0/beads/issues/{id}?include_comments=true` already carries under + `comments`, so the operation that appends one belongs on the resource + whose members it publishes. A PLAIN collection `POST` rather than a + custom method, for `POST /v0/beads/issues`' reason: creating one member + of the collection a path names is what `POST` already means, and a + `{id}:addComment` spelling would in addition need the claim route's + wildcard contortion for no gain. It collides with nothing — the + custom-method dispatcher's pattern is one segment shorter, and this + path's literal final segment is what ServeMux matches whole. + + + THIS COLLECTION PUBLISHES NO `GET`, and the absence is a statement + rather than a gap. No role answers a comment PAGE: reading the thread is + `GET /v0/beads/issues/{id}?include_comments=true`, which returns the + bodies in full, and a paged walk is a second question with a cursor of + its own — `issueops.Commenter` says exactly that, and a `GET` here would + be this surface inventing the role that does not exist. A `GET` on this + path is answered `404`, which is what every method mismatch on this + surface gets; `405` is not in the v0 status vocabulary. + + + ## `author` is caller-asserted, and it is not `actor` + + + The caller always names the author and the server never infers one, for + `POST /v0/beads/issues/{id}:claim`'s reason. IT IS NOT THE AUTHENTICATED + PRINCIPAL even where a bearer is required: the token a deployment + configures admits a client to the whole surface and names nobody, so it + can neither confirm nor contradict the name in `author`. A reader of the + thread is reading a claim the writer made about itself. + + + It is spelled `author` rather than the `actor` every issue mutation here + carries because it is a different thing. An `actor` is the principal a + mutation is attributed to and is not part of what the mutation wrote; + this value IS part of the row, echoed back by every read of the thread, + and it is spelled the way the `Comment` element that carries it back + spells it. `issueops.AddCommentRequest.Author` states the distinction; + this member is that field. + + + ## Planes + + + The id resolves across BOTH planes, as `POST + /v0/beads/issues/{id}:close` does and unlike + `POST /v0/beads/issues/{id}:claim`: A WISP IS A LEGAL TARGET. The + comment lands on the ephemeral thread and reads back from it, and only + the DURABLE trace is missing — a comment on an ephemeral row records NO + history entry, none rather than one, because the wisp tables are + dolt-ignored precisely so ephemeral work never ships. A caller + reconstructing threads from durable history alone will not see it. An id + that names neither plane is a `404` and nothing is written. + + + ## What this operation does not have + + + NO CONFLICT CODE AND NO `expected_version`. A thread is append-only and + this write touches no field of the issue, so there is no row state for a + guard to be stale about and no concurrent comment for this one to + collide with. Two callers commenting at once both succeed, in whatever + order the database commits them. + + + NO IDEMPOTENCY KEY EITHER: a retried request appends a SECOND comment, + because two identical comments are a legitimate thread and nothing here + can tell that pair from a retry. A client that must not double-post + reads the thread. + + + Hooks do not fire and the per-command auto-commit machinery does not + run, as for every write on this surface. The only durable effect is the + single storage commit the role makes inside its own transaction. + parameters: + - $ref: '#/components/parameters/IssueID' + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/AddCommentRequest' + security: + - bearerToken: [] + responses: + '200': + description: >- + The stored comment, with the id and `created_at` the row actually + got — the stored value at the column's precision, not the wall clock + the call happened at, so it is safe to use directly as a + comment-page cursor when one exists. It is the row as STORED, never + the request reflected back. + content: + application/json: + schema: + $ref: '#/components/schemas/Comment' + '400': + description: >- + Invalid request: an unknown query parameter, an unparseable or + oversized body, an unknown body member, a member carrying the wrong + JSON type, an explicit `null` on any member, an `author` that is + missing, empty after trimming, longer than 256 bytes or carrying + control characters, or a `text` that is missing or blank after + trimming. Nothing is written in any of these cases. + x-bd-codes: [invalid_argument] + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + '401': + $ref: '#/components/responses/Unauthenticated' + '404': + $ref: '#/components/responses/NotFound' + '500': + $ref: '#/components/responses/InternalError' + '503': + $ref: '#/components/responses/Unavailable' + /v0/beads/issues/{id}:claim: post: operationId: claimIssue @@ -6432,6 +6566,62 @@ components: text: { type: string } created_at: { type: string, format: date-time } + AddCommentRequest: + type: object + additionalProperties: false + required: [author, text] + description: >- + One comment to append. The issue is named by the path, so it is not a + member here: a body carrying it too would give one request two spellings + of one anchor and a question about what to do when they disagree. + properties: + author: + type: string + minLength: 1 + maxLength: 256 + pattern: '^[^\u0000-\u001F\u007F-\u009F\u2028\u2029]+$' + description: >- + Who is signing the comment. CALLER-ASSERTED, and not the + authenticated principal — see the operation description. + + + Trimmed of surrounding space, then refused when the result is empty, + when it exceeds 256 bytes or 255 characters (the storage column), + or when it carries a control character. The bounds and the character + rule are `actor`'s, unchanged, because the value lands in a column + of the same width that every renderer of the thread prints, where an + unfiltered C1 introducer is an escape-sequence payload. + text: + type: string + description: >- + The comment body, stored VERBATIM: newlines, surrounding space and + unicode all survive, and nothing trims the value that lands in the + row. + + + NO LENGTH BOUND AND NO CHARACTER RULE, unlike `author` beside it, + and both absences are the column: this one is `LONGTEXT` rather than + a 255-character field, and a comment that is a stack trace or a diff + is an ordinary comment. The only cap is the 1 MiB every body on this + surface shares. + + + BOTH PLANES AGREE ABOUT THAT, which is worth stating because they + did not. `wisp_comments.text` was left `TEXT` — 65535 bytes — when + the durable column was widened, so a comment past that limit wrote + fine against an issue and failed against a wisp, on an operation + that resolves its anchor across both planes deliberately. A caller + therefore could not know which side of the bound it was on until the + write failed. The ephemeral column is widened to match, so this + member's bound is one number rather than two. + + + Blank after trimming is a `400` — a comment of nothing but + whitespace carries no information and is almost always a shell + quoting accident — and blankness is judged on a TRIMMED COPY while + the stored value is untrimmed, so a comment that merely begins with + a newline is a comment. + BondRef: type: object description: A constituent of a compound molecule. @@ -6726,7 +6916,7 @@ components: derived from its route table, and the server-wide BEHAVIORS it enforces. v0's operation vocabulary is `ready.list`, `ready.count`, `issues.list`, `issues.query`, `issues.count`, `issues.get`, - `issues.related`, `issues.create`, + `issues.related`, `issues.create`, `issues.addComment`, `issues.batchClose`, `issues.claim`, `issues.claimNext`, `issues.release`, `issues.close`, `issues.reopen`, `issues.update`, diff --git a/internal/httpapi/spec_parity_test.go b/internal/httpapi/spec_parity_test.go index 54bf48f39..bf6436804 100644 --- a/internal/httpapi/spec_parity_test.go +++ b/internal/httpapi/spec_parity_test.go @@ -992,6 +992,46 @@ func TestReleaseRequestMembersMatchTheHandler(t *testing.T) { } } +// TestAddCommentRequestMembersMatchTheHandler is the release's gate for the +// comment body. +// +// The member it is really guarding is `author`. Every other body on this surface +// spells its provenance `actor`, so `author` is the one member here a reflex +// edit would "fix" — and the two are not interchangeable: `actor` attributes a +// mutation and `author` IS part of the row, echoed back by every read of the +// thread. Renamed on either side alone, this fails. +func TestAddCommentRequestMembersMatchTheHandler(t *testing.T) { + accepted := map[string]bool{} + for _, name := range addCommentRequestMembers { + accepted[name] = true + } + + goFields := jsonTagNames(t, reflect.TypeOf(apigen.AddCommentRequest{})) + if extra := diff(goFields, accepted); len(extra) > 0 { + t.Errorf("generated AddCommentRequest declares members the add-comment handler refuses as unknown: %v", extra) + } + if missing := diff(accepted, goFields); len(missing) > 0 { + t.Errorf("the add-comment handler accepts members AddCommentRequest does not declare: %v", missing) + } + + doc := loadSpec(t) + schema := mapAt(t, mapAt(t, mapAt(t, doc, "components"), "schemas"), "AddCommentRequest") + specProps := schemaProperties(t, doc, schema) + if extra := diff(specProps, accepted); len(extra) > 0 { + t.Errorf("the AddCommentRequest schema documents members the add-comment handler refuses: %v", extra) + } + if missing := diff(accepted, specProps); len(missing) > 0 { + t.Errorf("the add-comment handler accepts members the AddCommentRequest schema does not document: %v", missing) + } + + // The issue is the PATH's, and the schema must not publish a second spelling + // of it: a body carrying `issue_id` beside a path `{id}` is one request with + // two anchors and a question about what to do when they disagree. + if accepted["issue_id"] || specProps["issue_id"] { + t.Error("AddCommentRequest publishes `issue_id`; the anchor is the path parameter and must have one spelling") + } +} + // TestUpdateRequestMembersMatchTheHandler is the claim's and the close's gate // for the update body, at BOTH of its levels. // diff --git a/internal/storage/hook_decorator.go b/internal/storage/hook_decorator.go index bb506943d..3062f20a9 100644 --- a/internal/storage/hook_decorator.go +++ b/internal/storage/hook_decorator.go @@ -78,10 +78,22 @@ func (h *HookFiringStore) Unwrap() DoltStorage { return h.inner } // to fire them, and a server that admitted it would be one config change away // from breaking its own. // -// NOT ENFORCED, because the assertion is on the type: a role this decorator -// produced and something else then wrapped is invisible here, and so is a -// future decorator elsewhere that fires hooks of its own. Every case that -// exists today is in the switch, and a new one belongs there too. +// THE SET IS ENFORCED, and it is enforced because saying "every case that +// exists today is in the switch" did not make it so. That sentence stood here +// while FOUR decorators were missing — the commenter, the ready claimer, the +// batch closer and the batch creator — each of them found by hand by whoever +// happened to publish an operation over that role, which is a discovery process +// and not a guarantee. TestRoleFiresHooksKnowsEveryHookFiringRole now scans this +// package's source for every decorator that holds an issueOperationHooks and +// requires a case here that RETURNS TRUE for it, so the fifth cannot repeat the +// first four. It counts the return rather than the case label because an empty +// case answers false, which is how *hookMetadataCAS spent time silently +// disarmed. +// +// WHAT IS STILL NOT ENFORCED, narrowly and deliberately: the assertion is on the +// TYPE, so a role this decorator produced and something ELSE then wrapped is +// invisible here, and so is a future decorator in another package that fires +// hooks of its own. Both are outside what a scan of this package can see. func RoleFiresHooks(role any) bool { switch role.(type) { case *hookIssueClaimer: @@ -116,6 +128,31 @@ func RoleFiresHooks(role any) bool { // unpeeled is a hundred user subprocesses inside one request. case *hookBatchApplier: return true + // The commenter fires the update hook for every comment it lands + // (hook_commenter.go), because the legacy comment path fired it and a + // comment is a change to the issue as far as a hook script is concerned. + case *hookCommenter: + return true + // The ready claimer fires the update hook for every row it WINS + // (hook_ready_claimer.go) — a claim sets the assignee and moves the status, + // so it is an update as far as a hook script is concerned. It is the one + // whose caller is a polling loop by design: an agent draining a queue + // through POST /v0/beads/issues:claimNext would run the workspace's script + // once per bead it picked up. + case *hookReadyClaimer: + return true + // The batch closer fires the close hook once per LANDED ITEM and the update + // hook for the claim it may chain (hook_batch_closer.go), so one request + // through POST /v0/beads/issues:batchClose is N+1 subprocesses. + case *hookBatchCloser: + return true + // The batch creator fires the create hook once PER ITEM + // (hook_batch_creator.go), so a hundred-item + // POST /v0/beads/issues:batchCreate served unpeeled is a hundred of the + // workspace's subprocesses inside one HTTP call — the batch applier's + // hazard, on the operation that reaches it with nothing else in the way. + case *hookBatchCreator: + return true } return false } diff --git a/internal/storage/hook_role_census_test.go b/internal/storage/hook_role_census_test.go new file mode 100644 index 000000000..aec5ef70e --- /dev/null +++ b/internal/storage/hook_role_census_test.go @@ -0,0 +1,166 @@ +package storage + +import ( + "go/ast" + "go/parser" + "go/token" + "path/filepath" + "sort" + "strings" + "testing" +) + +// TestRoleFiresHooksKnowsEveryHookFiringRole is the CLASS-level guard on +// RoleFiresHooks, and it exists because the instance-level pins were not enough. +// +// That switch is the only thing standing between a store-derived role and a +// `bd serve` that runs a user's subprocess per landed mutation: httpapi.Listen +// sweeps every configured role through it and refuses the ones it recognizes. A +// role the switch does not know about is ADMITTED — served, silently, firing the +// workspace's scripts for as long as the process is up. +// +// The switch's own comment used to say "every case that exists today is in the +// switch", and it was false four ways at once: the commenter, the ready claimer, +// the batch closer and the batch creator all wrapped a role and fired hooks with +// no case here. Each was found by hand, one at a time, by whoever happened to +// publish an operation over that role — which is a discovery process, not a +// guarantee, and it left the other three standing every time. +// +// So the property is asserted over the CLASS instead: a decorator that carries +// an issueOperationHooks is a decorator that fires them, and every one of them +// must have a case. The scan reads SOURCE rather than reflecting, for the reason +// backend/conformance's role census does: these types are unexported, they are +// never instantiated except through their accessor, and a reflective sweep would +// have to build every decorator to see one. +// +// IT ALSO CATCHES THE EMPTY CASE, which is the other way this guard has failed: +// a Go type switch does not fall through, so `case *hookMetadataCAS:` with +// nothing under it answers FALSE, and a rebase left exactly that for a while +// with the compiler, vet, lint and CI all green. A case counts here only if its +// body returns true. +func TestRoleFiresHooksKnowsEveryHookFiringRole(t *testing.T) { + fired := hookFiringWrappers(t) + if len(fired) == 0 { + t.Fatal("the scan found no hook-firing decorators at all; it has stopped reading what it thinks it reads") + } + known := roleFiresHooksCases(t) + + if missing := missingFrom(fired, known); len(missing) > 0 { + t.Errorf("these decorators fire the workspace's hooks and RoleFiresHooks answers FALSE for them: %v\n"+ + "each one is a role httpapi.Listen would ADMIT and serve, running a user's subprocess per landed mutation.\n"+ + "Add a `case *: return true` to RoleFiresHooks, and pin it from both ends the way the others are.", + missing) + } + if extra := missingFrom(known, fired); len(extra) > 0 { + t.Errorf("RoleFiresHooks names types that no longer carry an issueOperationHooks: %v\n"+ + "either the decorator stopped firing hooks and the case is dead, or the scan has drifted", extra) + } +} + +// hookFiringWrappers is every decorator type in this package that holds an +// issueOperationHooks — which is what "this value fires the workspace's hooks" +// is spelled as, and the one property all ten of them share. +func hookFiringWrappers(t *testing.T) map[string]bool { + t.Helper() + files, err := filepath.Glob("hook_*.go") + if err != nil { + t.Fatalf("glob the decorator files: %v", err) + } + out := map[string]bool{} + fset := token.NewFileSet() + for _, path := range files { + if strings.HasSuffix(path, "_test.go") { + continue + } + file, err := parser.ParseFile(fset, path, nil, 0) + if err != nil { + t.Fatalf("parse %s: %v", path, err) + } + ast.Inspect(file, func(n ast.Node) bool { + spec, ok := n.(*ast.TypeSpec) + if !ok { + return true + } + structType, ok := spec.Type.(*ast.StructType) + if !ok || structType.Fields == nil { + return true + } + for _, field := range structType.Fields.List { + if ident, ok := field.Type.(*ast.Ident); ok && ident.Name == "issueOperationHooks" { + out[spec.Name.Name] = true + return true + } + } + return true + }) + } + return out +} + +// roleFiresHooksCases is every type RoleFiresHooks answers TRUE for, read off +// the switch itself. A case whose body does not return true does not count: an +// empty one answers false, and that has shipped. +func roleFiresHooksCases(t *testing.T) map[string]bool { + t.Helper() + fset := token.NewFileSet() + file, err := parser.ParseFile(fset, "hook_decorator.go", nil, 0) + if err != nil { + t.Fatalf("parse hook_decorator.go: %v", err) + } + + out := map[string]bool{} + found := false + for _, decl := range file.Decls { + fn, ok := decl.(*ast.FuncDecl) + if !ok || fn.Name.Name != "RoleFiresHooks" || fn.Recv != nil { + continue + } + found = true + ast.Inspect(fn.Body, func(n ast.Node) bool { + clause, ok := n.(*ast.CaseClause) + if !ok || !clauseReturnsTrue(clause) { + return true + } + for _, expr := range clause.List { + star, ok := expr.(*ast.StarExpr) + if !ok { + continue + } + if ident, ok := star.X.(*ast.Ident); ok { + out[ident.Name] = true + } + } + return true + }) + } + if !found { + t.Fatal("RoleFiresHooks is not a function in hook_decorator.go; this scan proves nothing") + } + return out +} + +// clauseReturnsTrue reports whether a case clause answers true, which is the +// only thing that makes it a guard rather than a comment with a colon on it. +func clauseReturnsTrue(clause *ast.CaseClause) bool { + for _, stmt := range clause.Body { + ret, ok := stmt.(*ast.ReturnStmt) + if !ok || len(ret.Results) != 1 { + continue + } + if ident, ok := ret.Results[0].(*ast.Ident); ok && ident.Name == "true" { + return true + } + } + return false +} + +func missingFrom(want, have map[string]bool) []string { + var out []string + for name := range want { + if !have[name] { + out = append(out, name) + } + } + sort.Strings(out) + return out +} diff --git a/internal/storage/schema/migrations/0065_widen_wisp_comments_text.down.sql b/internal/storage/schema/migrations/0065_widen_wisp_comments_text.down.sql new file mode 100644 index 000000000..7fa0c7da1 --- /dev/null +++ b/internal/storage/schema/migrations/0065_widen_wisp_comments_text.down.sql @@ -0,0 +1,4 @@ +-- Reverse of 0065: not reversible without potential data loss, for 0049's +-- reason exactly. Shrinking LONGTEXT back to TEXT would silently truncate any +-- comment longer than 65535 bytes that was successfully stored after the +-- migration. Intentional no-op. diff --git a/internal/storage/schema/migrations/0065_widen_wisp_comments_text.up.sql b/internal/storage/schema/migrations/0065_widen_wisp_comments_text.up.sql new file mode 100644 index 000000000..80e95b38f --- /dev/null +++ b/internal/storage/schema/migrations/0065_widen_wisp_comments_text.up.sql @@ -0,0 +1,41 @@ +-- Migration 0065: finish 0049 on the ephemeral plane — wisp_comments.text. +-- +-- 0049 widened every large-content column it could name from TEXT to LONGTEXT: +-- issues and wisps description/design/acceptance_criteria/notes/close_reason, +-- and comments.text. It MISSED wisp_comments.text, which has been TEXT since +-- 0021 created the table, and the miss was invisible for as long as nothing +-- published a comment write that could carry a large body. +-- +-- THE TWO COMMENT PLANES DISAGREED ABOUT A MEMBER BOUND. TEXT caps at 65535 +-- bytes, so the same comment — a stack trace, a diff, a captured agent +-- transcript — writes fine against a durable issue and fails with MySQL Error +-- 1105 against a wisp. That is a wire-visible divergence on one documented +-- member: `POST /v0/beads/issues/{id}/comments` resolves its anchor across both +-- planes deliberately, so a caller cannot know which side of the bound it is on +-- until the write fails. Widening is the fix rather than a documented caveat — +-- the planes should not diverge on what a comment may contain, and the caveat +-- would have to be re-stated by every client. +-- +-- Guarded on the same COLUMN_TYPE = 'text' probe 0049 uses, so this is a no-op +-- on a workspace already carrying LONGTEXT and idempotent on replay. The column +-- was created NOT NULL with no default (0021) and intentionally keeps none, +-- exactly as comments.text does in 0049 — MODIFY COLUMN replaces the whole +-- definition, so anything restated here would become the new definition. +-- +-- IT SHIPS WITH AN IGNORED-SERIES TWIN (ignored/0024), which is not optional: +-- wisp_comments is a clone-local dolt-ignored table, so a fresh clone +-- materializes it from the ignored series while the main cursor arrives +-- at-latest and never runs this file. That is check D of +-- scripts/check-migration-hygiene.sh, and the mechanism ignored/0021 (the wisps +-- half of this same 0049 gap), ignored/0020 and ignored/0013 each record. +SET @wisp_comments_needs_fix = ( + SELECT IF(COLUMN_TYPE = 'text', 1, 0) + FROM INFORMATION_SCHEMA.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = 'wisp_comments' + AND COLUMN_NAME = 'text' +); +SET @sql = IF(@wisp_comments_needs_fix = 1, + 'ALTER TABLE wisp_comments MODIFY COLUMN text LONGTEXT NOT NULL', + 'SELECT 1'); +PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; diff --git a/internal/storage/schema/migrations/ignored/0024_widen_wisp_comments_text.up.sql b/internal/storage/schema/migrations/ignored/0024_widen_wisp_comments_text.up.sql new file mode 100644 index 000000000..0d158bce0 --- /dev/null +++ b/internal/storage/schema/migrations/ignored/0024_widen_wisp_comments_text.up.sql @@ -0,0 +1,28 @@ +-- Ignored migration 0024: ensure wisp_comments.text is LONGTEXT on every clone. +-- +-- The twin of synced migration 0065, and required by check D of +-- scripts/check-migration-hygiene.sh rather than offered: wisp_comments is +-- clone-local and dolt-ignored, so a fresh clone materializes it from +-- ignored/0001 — whose CREATE still carries `text TEXT NOT NULL` — while the +-- main cursor arrives at-latest and 0065 never runs there. Without this file a +-- large comment on a wisp would write fine on an in-place-upgraded workspace +-- and fail with Error 1105 on a fresh clone, which is the same fresh-clone door +-- ignored/0021 (the wisps half of the same 0049 gap), ignored/0020 +-- (storage_class) and ignored/0013 (row_lock) each record. +-- +-- The definition mirrors 0065 exactly, including the absent default: the column +-- was created NOT NULL with no default and MODIFY COLUMN replaces the whole +-- definition. Guarded on the same COLUMN_TYPE = 'text' probe, so it is a no-op +-- on the fresh-init door and on an already-widened clone, and idempotent on +-- replay. +SET @wisp_comments_needs_fix = ( + SELECT IF(COLUMN_TYPE = 'text', 1, 0) + FROM INFORMATION_SCHEMA.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = 'wisp_comments' + AND COLUMN_NAME = 'text' +); +SET @sql = IF(@wisp_comments_needs_fix = 1, + 'ALTER TABLE wisp_comments MODIFY COLUMN text LONGTEXT NOT NULL', + 'SELECT 1'); +PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;