* 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>
231 lines
10 KiB
Go
231 lines
10 KiB
Go
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()))
|
|
}
|