beads/internal/httpapi/roles.go
Julian Knutsen cc3d0bcf3c
Publish POST /v0/beads/issues/{id}/comments, the wire half of issueops.Commenter (ga-rslox) (#5594)
* Publish POST /v0/beads/issues/{id}/comments, the wire half of issueops.Commenter (ga-rslox)

The commenter is one of the facade roles the ext-api-store audit lists with no
wire operation, and comment READS already ride `getIssue?include_comments=true`.
This is the write. The role, its contract and all three legs already exist; this
slice wires them.

Spec first, then `make api-gen`, then the handler.

IT IS A SUB-RESOURCE COLLECTION OF THE ISSUE, and the argument is
listRelatedIssues' applied to a write: the row this creates is the SAME pinned
`Comment` schema `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 the collision worth checking rather than
assuming is the POST wildcard: `/v0/beads/issues/{idop}` matches ONE segment after
`/issues/` and this path has two, so the dispatcher never sees a request for it.
Checked by driving the documented path, not by reading the pattern.

THE COLLECTION PUBLISHES NO GET, and that is a statement rather than a gap. No
role answers a comment PAGE: issueops.Commenter says reading the thread is a
second question with a cursor of its own, so a GET here would be this surface
inventing the role that declined to exist. A GET lands on the catch-all and gets
the 404 every method mismatch here gets; 405 is not in the v0 vocabulary.

`author`, NOT `actor`, AND IT IS STILL CALLER-ASSERTED. The two are not the same
member wearing a different name: an `actor` is the principal a mutation is
attributed to and is no part of what the mutation wrote, while this value IS part
of the row and is echoed back by every read of the thread — so it is spelled the
way the `Comment` element that carries it back spells it. It is NOT the
authenticated principal even where a bearer is required, on the claim's terms: the
token a deployment configures admits a client to the whole surface and names
nobody. A reader of the thread is reading a claim the writer made about itself.

THE TWO MEMBERS ARE VALIDATED TO DIFFERENT DEPTHS, and the difference is the
column. `author` lands in a VARCHAR(255) every renderer of the thread prints, so
it gets `actor`'s rules whole — trim, non-empty, 256 bytes, 255 characters,
no control runes — through validateNameMember, which is validateActor's body
parameterized by the member's spelling rather than a second copy of the bounds.
`text` lands in a TEXT column stored VERBATIM, so it is checked for SHAPE only:
no trim, no length bound, no character rule, because a comment is routinely a
stack trace or a diff and the newlines are the comment. Its one content rule —
blank after trimming — stays in the ROLE, rememberMemory's posture, so `bd comment`
and this endpoint refuse the same input with the same sentence.

A WISP IS A LEGAL TARGET, resolved from the facade body rather than assumed and
pinned against real Dolt: the anchor resolves across both planes, the comment
lands on `wisp_comments` and reads back from the ephemeral thread. Only the
DURABLE trace is absent — a comment on an ephemeral row records NO history entry,
because the wisp tables are dolt-ignored precisely so ephemeral work never ships.

NO CONFLICT CODE AND NO GUARD, and both absences are the contract. A thread is
append-only and this write touches no field of the issue, so there is no row state
for an `expected_version` to be stale about and no concurrent comment to collide
with. Not idempotent either — a retry appends a second row, because two identical
comments are a legitimate thread — and the proxied test asserts that against the
table rather than the handler.

ONE ARM IN THE FAILURE PATH, and the deleted one is evidence rather than taste.
There is no explicit ErrNotFound case: ClassifyError already carries that row, and
adding one back leaves the whole package green — measured, the way #5540 measured
the same redundancy. The 400 names `text` unconditionally because exactly one of
the role's three refusals is reachable: the edge refuses an empty author under
strictly stronger rules, and an empty id cannot arrive at all.

RoleFiresHooks DID NOT KNOW ABOUT THE COMMENTER, and publishing this operation is
what made that matter. hook_commenter.go has fired the update hook for every
comment it lands since it was written, and the switch that stops `bd serve` from
being handed a hook-firing role had no case for it — harmless only while no front
door took the role off a store. An unpeeled commenter runs the workspace's script
once per comment, which is exactly the write an agent makes in a loop. The case is
added and pinned from both ends.

CENSUS +1 EACH: spec path; AddCommentRequest schema; the document's no-query-
parameter list and its two counts; route row; capability prose (the only hand
edit — Capabilities() is derived); OpAddComment; operationCodes row
(getDependencyTree's vocabulary, no code minted); httpapi.Config.Commenter with
sourceRoles, roleSourceNames, the Server field, Listen and s.commenter();
timedProvider.Commenter and its CommenterSource assertion; checkedCommenter; and
the bd serve binding. Plus Commenter on serveRoleSource and both cmd/bd stubs,
which is #5539's return: a named build error in the file that has to grow a method.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Close the RoleFiresHooks blind spot as a CLASS, and finish 0049 on the ephemeral comment plane

Review found the first version of this branch overclaimed twice. Both claims are
now either true or gone, and both are held by a test rather than by prose.

## The hook guard was blind FOUR ways, not one

The commit said the commenter was "the one hook-firing role RoleFiresHooks did
not know about". It was one of four. `*hookReadyClaimer`, `*hookBatchCloser` and
`*hookBatchCreator` were outside the switch too, and all three are served over
PUBLISHED operations — `issues:claimNext`, `issues:batchClose`,
`issues:batchCreate` — through roles `httpapi.Listen` sweeps by way of that exact
switch. A store-derived value for any of the three was therefore ADMITTED and
served, running the workspace's scripts for the life of the process: once per
bead a polling drainer wins, once per landed item plus one for a chained claim,
and once per item of a batch — so a hundred-item create was a hundred
subprocesses inside one HTTP call.

Fixed: three cases, plus the same both-ends pins the commenter got. Store side,
the accessor really hands back a hook-firing value and `serveIssueRoles` peels to
exactly the layer beneath it (the peel-depth half matters — a peel two layers
deep also answers false and silently drops the telemetry span, so the assertions
check identity, not just the predicate). Server side, `Listen` really refuses each
one.

AND THE PROSE IS NOW TRUE BECAUSE A SCAN MAKES IT TRUE.
`internal/storage/hook_decorator.go` has carried the sentence "every case that
exists today is in the switch" while it was false four ways, because every one of
the four was found by hand by whoever happened to publish an operation over that
role. That is a discovery process, not a guarantee, and it left the others
standing each time. `TestRoleFiresHooksKnowsEveryHookFiringRole` now parses this
package's `hook_*.go` for every decorator that holds an `issueOperationHooks` and
requires a case that RETURNS TRUE for it. Source scan rather than reflection, for
the reason backend/conformance's role census gives: these types are unexported
and are never built except through their accessor.

It counts the RETURN, not the case label, which closes the second failure mode
this switch has actually had: a Go type switch does not fall through, so
`case *hookMetadataCAS:` with an empty body answers FALSE, and a rebase shipped
exactly that with the compiler, vet, lint and CI all green. Mutation-verified in
both directions — deleting a case and emptying a case each fail the scan by name.

## `wisp_comments.text` was still TEXT, so the document's bound was false

The spec said `text`'s only cap is the 1 MiB every body shares. That was true on
one plane. Migration 0049 widened `comments.text` to LONGTEXT and did not touch
`wisp_comments.text`, which has been TEXT — 65535 bytes — since 0021 created the
table. Measured live before the fix: a 102,000-byte comment is 200 against a
durable issue and 500 against a wisp. This operation resolves its anchor across
BOTH planes deliberately, so nothing above the storage seam could tell a caller
which side of the bound it was on until the write failed.

Widened rather than caveated: the two planes should not disagree about what a
comment may contain, and a caveat would have to be re-stated by every client. The
handler grows no length check — there was never one to add; the fix was the
column.

MIGRATION 0065 + ignored/0024, and the twin is required rather than offered:
`wisp_comments` is clone-local and dolt-ignored, so a fresh clone materializes it
from the ignored series while the main cursor arrives at-latest and 0065 never
runs there. That is check D of scripts/check-migration-hygiene.sh, and the same
fresh-clone door ignored/0021 — the wisps half of this identical 0049 gap —
already records. Both guarded on 0049's `COLUMN_TYPE = 'text'` probe, so they are
no-ops on an already-widened workspace and idempotent on replay; the `.down` is
0049's intentional no-op, because shrinking back would truncate.

Verified from both ends: red-first against real Dolt (the wisp 500 above, green
after), and `TestEmbeddedIgnoredSeriesConvergesWithFreshInitShape` — the
engine-level backstop behind check D — fails naming `wisp_comments.text` when the
twin is withheld.

### MIGRATION LANE NOTE, for the deployment checklist

THIS MOVES THE MIGRATION CEILING FROM 0064 TO 0065, and the ignored series from
0023 to 0024. Anything pinned to "latest is 0064" — a deployment checklist, a
pre-flight assertion, a fixture bundle — transfers to 0065 when this lands.
Migration files are frozen once merged (hygiene check C), so a follow-up cannot
edit these two; a fix would be a further migration. NOTHING IS DEPLOYED BY THIS
PR: it ships the files, and the schema moves on whatever schedule the deployment
checklist runs.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Review Sim <ci@beads.test>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-10 18:59:57 -07:00

284 lines
13 KiB
Go

package httpapi
import (
"context"
"fmt"
"github.com/steveyegge/beads/issueops"
)
// The role seam, and the one guarantee this package cannot get by asking for
// it.
//
// Two handlers hold a POINTER that a role returned and dereference it the
// moment the error is nil: handleGetIssue writes *details, handleClaim writes
// *result.Issue. Until roles became configuration those dereferences were safe
// BY CONSTRUCTION — s.reader() could only return uow.NewIssueReader(...),
// whose Get routes through workapi.GetIssueOrWisp, and that function exists
// precisely so that no caller can be handed a nil issue with a nil error. A
// role reached through Config is ordinary caller-supplied code, and the same
// dereference is a nil pointer panic on a live server.
//
// So the fold happens here instead, on EVERY role this server hands a handler,
// from either database source. Unconditionally, and that is the point: the
// dereferences above are safe because there is no other way to reach them, not
// because the provider path is separately known to be well behaved. The
// provider path pays one wrapper allocation per request for the privilege of
// making that a single sentence.
//
// The vocabulary is the one ClassifyError already documents: the shared read
// path folds "a nil issue with a nil error" into ErrNotFound, so a reader that
// answers with nothing answers the documented miss. A claim has no such
// reading — a claim that reports success has written a row, or it has not
// succeeded — so it falls to the generic 500, which is where an unrecognized
// error goes.
// checkedReader is the reader every read handler is handed.
//
// Ready and List need nothing from it: both return a VALUE, and wireItems
// already drops a nil element out of a page. Get is the whole reason the type
// exists.
//
// issueops.EdgeReader has no wrapper here for the same reason: it answers with
// a value, and wireEdges drops a nil edge.
//
// issueops.Relations has none either, and it is the case worth stating because
// it is the first role that answers with a SLICE OF POINTERS and still needs no
// wrapper. What decides it is not the pointer, it is whether a handler
// dereferences one it was handed: wireRelated skips a nil element exactly as
// wireEdges and wireItems do, so the only thing a wrapper could add is the
// appearance of a guarantee.
type checkedReader struct{ inner issueops.Reader }
// Ready passes the request through unchanged.
func (c checkedReader) Ready(ctx context.Context, req issueops.ReadyRequest) (issueops.IssuePage, error) {
return c.inner.Ready(ctx, req)
}
// List passes the request through unchanged.
func (c checkedReader) List(ctx context.Context, req issueops.ListRequest) (issueops.IssuePage, error) {
return c.inner.List(ctx, req)
}
// Get folds a detail view that is absent without being an error into the miss
// the document already describes, so the client gets the same 404 an absent
// issue produces rather than a panic recovered into a generic 500.
func (c checkedReader) Get(ctx context.Context, req issueops.GetRequest) (*issueops.IssueDetails, error) {
details, err := c.inner.Get(ctx, req)
if err == nil && details == nil {
return nil, fmt.Errorf("get %q: %w", req.ID, issueops.ErrNotFound)
}
return details, err
}
// checkedBatchCreator is the creator the batch-create handler is handed.
//
// The response body carries issue VALUES where the role answers with pointers,
// so the handler dereferences every entry — checkedClaimer's hazard, once per
// item. An entry that is nil anyway is a broken implementation, so it is the
// generic 500 with the fault in the log and not a panic.
type checkedBatchCreator struct{ inner issueops.BatchCreator }
// CreateBatch refuses a result that reports success without every issue the
// response body is built from.
func (c checkedBatchCreator) CreateBatch(ctx context.Context, req issueops.CreateBatchRequest) (issueops.CreateBatchResult, error) {
result, err := c.inner.CreateBatch(ctx, req)
if err != nil {
return result, err
}
if len(result.Issues) != len(req.Items) {
return issueops.CreateBatchResult{}, fmt.Errorf(
"create batch: the creator reported success with %d issues for %d items", len(result.Issues), len(req.Items))
}
for i, issue := range result.Issues {
if issue == nil {
return issueops.CreateBatchResult{}, fmt.Errorf("create batch: the creator reported success without issue %d", i)
}
}
return result, nil
}
// checkedBatchCloser is the closer the batch-close handler is handed.
//
// It is the one role here whose result is POSITIONAL: the document promises one
// outcome per requested item in request order, and a client walks the array
// against its own argument list rather than matching ids back up. So the two
// broken shapes it folds are at different scopes, and the scope is the whole
// reasoning.
//
// - AN OUTCOME COUNT THAT DOES NOT MATCH THE REQUEST is the whole batch's
// fault: it cannot be walked against the caller's items at all, and
// projecting it anyway would report one item's answer under another item's
// id for the rest of the array — silently, inside a 200. It is
// checkedBatchCreator's whole-batch refusal exactly, and it is the generic
// 500 with the fault in the log, never a partial projection.
//
// - AN OUTCOME CARRYING NEITHER A ROW NOR A REFUSAL has no honest wire shape:
// `code`'s absence promises `issue`, so projected as it stands it is a
// success with no row — the shape closeOutcome's `default` branch already
// refuses to produce. It is folded into THAT ITEM's Err instead, because
// this batch is not all-or-nothing: its survivors have already committed,
// and a whole-batch 500 would hide durable closes from a caller with no way
// to re-read them. The handler maps it through the branch it wrote for
// exactly this, and the rest of the outcomes are untouched.
//
// batchCloser() used to hand this role out unwrapped on the reasoning that
// CloseBatchResult is a value and its issue pointer is forwarded rather than
// dereferenced. That is true, and it is why there is no panic here to prevent —
// but it left the two shapes above reaching a client as answers rather than as
// faults.
type checkedBatchCloser struct{ inner issueops.BatchCloser }
// CloseBatch refuses a miscounted result and folds a neither-row-nor-refusal
// outcome into its own item.
func (c checkedBatchCloser) CloseBatch(ctx context.Context, req issueops.CloseBatchRequest) (issueops.CloseBatchResult, error) {
result, err := c.inner.CloseBatch(ctx, req)
if err != nil {
return result, err
}
if len(result.Outcomes) != len(req.Items) {
return issueops.CloseBatchResult{}, fmt.Errorf(
"close batch: the closer reported %d outcomes for %d items", len(result.Outcomes), len(req.Items))
}
corrected := false
for i := range result.Outcomes {
if result.Outcomes[i].Err != nil || result.Outcomes[i].Issue != nil {
continue
}
if !corrected {
// Correct a COPY. The slice is the role's own, and a role that
// answers from one prepared result would carry this server's
// correction into everything it hands back afterwards.
result.Outcomes = append([]issueops.CloseOutcome(nil), result.Outcomes...)
corrected = true
}
result.Outcomes[i].Err = fmt.Errorf(
"close batch: the closer reported outcome %d (%q) with neither an issue nor a refusal",
i, result.Outcomes[i].IssueID)
}
return result, nil
}
// checkedLifecycle is the lifecycle role every mutation handler is handed.
//
// All four methods are why it exists: every handler over this role writes
// *result.Issue, which is checkedClaimer's hazard exactly.
type checkedLifecycle struct{ inner issueops.Lifecycle }
// Create refuses a result that reports success without the row the response
// body is built from, for Close's reason.
//
// It USED to pass through, because no handler on this surface reached it. The
// single create publishes one, and handleCreateIssue writes *result.Issue
// straight onto the wire, so the same nil-with-nil-error a provider-supplied
// role can return is a panic on a live server without this.
func (c checkedLifecycle) Create(ctx context.Context, req issueops.CreateRequest) (issueops.CreateResult, error) {
result, err := c.inner.Create(ctx, req)
if err == nil && result.Issue == nil {
return issueops.CreateResult{}, fmt.Errorf("create: the lifecycle reported success without an issue")
}
return result, err
}
// Update refuses a result that reports success without the row the response
// body is built from, for Close's reason.
func (c checkedLifecycle) Update(ctx context.Context, req issueops.UpdateRequest) (issueops.UpdateResult, error) {
result, err := c.inner.Update(ctx, req)
if err == nil && result.Issue == nil {
return issueops.UpdateResult{}, fmt.Errorf("update %q: the lifecycle reported success without an issue", req.IssueID)
}
return result, err
}
// Close refuses a result that reports success without the row the response body
// is built from.
//
// There is no wire code for it and there must not be one: `already_closed` says
// the issue was closed earlier and the response still carries the row, and a
// 404 would tell a client the issue does not exist when nothing here knows
// that. It is a broken implementation, so it is the generic 500 — with the
// fault in the log as an error and a request_error line beside it, which is
// what the panic it replaces did not produce.
func (c checkedLifecycle) Close(ctx context.Context, req issueops.CloseRequest) (issueops.CloseResult, error) {
result, err := c.inner.Close(ctx, req)
if err == nil && result.Issue == nil {
return issueops.CloseResult{}, fmt.Errorf("close %q: the lifecycle reported success without an issue", req.IssueID)
}
return result, err
}
// Reopen refuses a result that reports success without the row the response
// body is built from, for Close's reason: handleReopen dereferences it, and a
// broken implementation should be the generic 500 with the fault in the log
// rather than a panic on a live server.
func (c checkedLifecycle) Reopen(ctx context.Context, req issueops.ReopenRequest) (issueops.ReopenResult, error) {
result, err := c.inner.Reopen(ctx, req)
if err == nil && result.Issue == nil {
return issueops.ReopenResult{}, fmt.Errorf("reopen %q: the lifecycle reported success without an issue", req.IssueID)
}
return result, err
}
// checkedClaimer is the claimer the claim handler is handed.
type checkedClaimer struct{ inner issueops.Claimer }
// Claim refuses a result that reports success without the row the response
// body is built from.
//
// There is no wire code for it and there must not be one: `already_claimed`
// says a claim landed earlier and the response still carries the row, and a
// 404 would tell a client the issue does not exist when nothing here knows
// that. It is a broken implementation, so it is the generic 500 — with the
// fault in the log as an error and a request_error line beside it, which is
// what the panic it replaces did not produce.
func (c checkedClaimer) Claim(ctx context.Context, req issueops.ClaimRequest) (issueops.ClaimResult, error) {
result, err := c.inner.Claim(ctx, req)
if err == nil && result.Issue == nil {
return issueops.ClaimResult{}, fmt.Errorf("claim %q: the claimer reported success without an issue", req.IssueID)
}
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
// *result.Issue and reads its RowVersion, so a role that reported success
// without the row would panic on a live server.
type checkedReleaser struct{ inner issueops.Releaser }
// Release refuses a result that reports success without the row the response
// body is built from.
//
// The generic 500, for checkedClaimer's reason and one of its own: there is no
// wire code that fits and there must not be. A 409 would say the row refused
// the release when the role said it did not, and a 404 would say the issue does
// not exist when nothing here knows that. It is a broken implementation.
func (c checkedReleaser) Release(ctx context.Context, req issueops.ReleaseRequest) (issueops.ReleaseResult, error) {
result, err := c.inner.Release(ctx, req)
if err == nil && result.Issue == nil {
return issueops.ReleaseResult{}, fmt.Errorf("release %q: the releaser reported success without an issue", req.IssueID)
}
return result, err
}