beads/internal/httpapi/delete_test.go
CI Bot 67d38d2620 Trim this series' comments toward the repo's own density
Ten agents over 216 files, one directory-balanced group each, working to a
rubric that named what to cut (duplication narration, restatement of the next
line, the governing rule echoed in every command file, throat-clearing) and
what to keep (traps, invariants, security, tracker ids, behaviour changes, and
the "why a naive simplification destroys this assertion" rationale).

Net 1,523 lines. Density against this repo's own per-directory norm on main:

  cmd/bd              33.6% -> 27.3%   (main 10.7%)
  internal/storage    26.1% -> 23.1%   (main 14.1%)
  backend/conformance 34.0% -> 29.6%   (main 22.8%)
  internal/httpapi    30.9% -> 27.8%   (main 30.6%, now below)
  overall             34.7% -> 31.6%

Every agent landed at 18-25% rather than the 30% asked for, and every one gave
the same reason independently: what remained was on the keep list. Ten separate
judgements agreeing is the most useful result here — the prose is dense, but it
is mostly load-bearing, and the shortfall is the honest answer rather than a
failure to try.

TWO REVERTS, both to protect something worth more than the lines.

issueops/ is back to its pre-trim state, giving up 610 lines. The conformance
contracts cite the leaf docs BY LINE — "pins treewalker.go:52-66" — 155 times.
Trimming the cited files silently repointed those at whatever text moved into
those numbers, across agent boundaries so no agent could see it. A semantic
remapper recovered 141 of them, but 23 needed judgement and several landed on
struct fields. The leaf docs are the spec the contracts are written against;
they are the one place in this change where dense prose IS the deliverable, and
keeping them stable is worth more than the 610 lines. tree_walker_contract.go
and version_reconciler_contract.go went back for the same reason: an agent had
deleted a paragraph containing a citation, so positional restoration could not
align them.

After the reverts, exactly 5 citations point into a still-trimmed file and 2 of
those are weak — both in cmd/bd/config_guard_test.go, which this series never
touched and whose citations were already wrong on main (init.go:361 pointed at
a closing brace; the guard it names is at init.go:1499).

VERIFICATION. A guard strips every comment and all whitespace from each of the
193 modified files at HEAD and in the worktree and requires the two to be
byte-identical, so a code change cannot hide in a comment diff. It handles `//`
inside string and raw-string literals, and was tested against a deliberate code
change before being trusted. gofmt clean, go build, go vet, golangci-lint 0
issues, and the two AST-based tests that PARSE trimmed files — the timed
provider binding pin over claim.go and the serve database-source gate over
serve.go — both pass.

One real defect found while trimming: checkDatabaseSource's doc block ran into
`// sourceRoles is ...` with no blank line, so godoc attached thirty-one lines
of the wrong prose to func sourceRoles and left checkDatabaseSource
undocumented. Fixed by separating them.
2026-08-06 08:06:59 +00:00

298 lines
12 KiB
Go

package httpapi
import (
"net/http"
"reflect"
"strings"
"testing"
"github.com/steveyegge/beads/issueops"
)
// The pins for POST /v0/beads/issues:delete. As with the sweep, what is
// asserted here is the WIRE EDGE — that the handler decodes the document's five
// members into the role's request faithfully, refuses what the document
// refuses, and does not re-implement anything the role owns.
const deletePath = "/v0/beads/issues:delete"
func (ts *testServer) delete(t *testing.T, body string) *http.Response {
t.Helper()
return ts.claimRequest(t, deletePath, "application/json", body)
}
// TestDeletePathReachesItsHandler is the sweep row's twin: a LITERAL segment
// registered beside the claim's wildcard `/v0/beads/issues/{idop}`, where
// ServeMux precedence is by specificity rather than by registration order. A
// 404 or a claim-shaped refusal here would mean the delete is being parsed as a
// claim of an issue named ":delete".
func TestDeletePathReachesItsHandler(t *testing.T) {
deleter := &roleDeleter{result: issueops.DeleteResult{Deleted: 1}}
ts := newTestServer(t, rolesConfig(Config{Deleter: deleter}))
resp := ts.delete(t, `{"ids":["bd-1"],"force":true}`)
if resp.StatusCode != http.StatusOK {
t.Fatalf("status = %d, want 200: %s", resp.StatusCode, readAll(t, resp))
}
if len(deleter.requests()) != 1 {
t.Fatalf("the delete role was called %d times, want 1 — the path reached another handler",
len(deleter.requests()))
}
}
// TestDeleteForwardsEveryDocumentedMember is the operation's central pin: each
// of the five body members reaches the role's request unchanged.
//
// It is asserted on the REQUEST the role received rather than on the response,
// because a body carrying the right numbers says nothing about which beads went
// — this is the operation where the handler dropping `cascade` deletes a
// subtree the caller did not ask for.
func TestDeleteForwardsEveryDocumentedMember(t *testing.T) {
deleter := &roleDeleter{}
ts := newTestServer(t, rolesConfig(Config{Deleter: deleter}))
resp := ts.delete(t, `{
"ids": ["bd-1", "bd-2"],
"actor": " alice ",
"cascade": true,
"force": true,
"dry_run": true
}`)
if resp.StatusCode != http.StatusOK {
t.Fatalf("status = %d, want 200: %s", resp.StatusCode, readAll(t, resp))
}
reqs := deleter.requests()
if len(reqs) != 1 {
t.Fatalf("%d deletes, want 1", len(reqs))
}
want := issueops.DeleteRequest{
IDs: []string{"bd-1", "bd-2"},
// TRIMMED, by the same rule and the same function the claim's actor
// goes through: it reaches the same commit-message interpolation.
Actor: "alice",
Cascade: true,
Force: true,
DryRun: true,
}
if !reflect.DeepEqual(reqs[0], want) {
t.Errorf("request = %+v, want %+v", reqs[0], want)
}
}
// TestDeleteDefaultsTheOptionalMembers: a body carrying only `ids` reaches the
// role as a GUARDED, non-cascading, real delete.
//
// All three flags default to their zero values, and here — unlike the sweep's
// protect_referenced — false is the GUARDED answer for all three. The zero value
// is the protection, so a handler that "helpfully" defaulted force on is the bug.
func TestDeleteDefaultsTheOptionalMembers(t *testing.T) {
deleter := &roleDeleter{}
ts := newTestServer(t, rolesConfig(Config{Deleter: deleter}))
if resp := ts.delete(t, `{"ids":["bd-1"]}`); resp.StatusCode != http.StatusOK {
t.Fatalf("status = %d, want 200: %s", resp.StatusCode, readAll(t, resp))
}
reqs := deleter.requests()
if len(reqs) != 1 {
t.Fatalf("%d deletes, want 1", len(reqs))
}
want := issueops.DeleteRequest{IDs: []string{"bd-1"}}
if !reflect.DeepEqual(reqs[0], want) {
t.Errorf("request = %+v, want %+v", reqs[0], want)
}
}
// TestDeletePublishesTheWholeResult drives every member of the response body:
// the schema is not x-go-type-pinned, so a field added to the role's result and
// forgotten in the projection would be silently absent from the wire.
func TestDeletePublishesTheWholeResult(t *testing.T) {
deleter := &roleDeleter{result: issueops.DeleteResult{
DryRun: true,
Deleted: 4,
Dependencies: 7,
Labels: 2,
Events: 9,
ReferencesUpdated: 3,
Orphaned: []string{"bd-orphan-a", "bd-orphan-b"},
}}
ts := newTestServer(t, rolesConfig(Config{Deleter: deleter}))
resp := ts.delete(t, `{"ids":["bd-1"],"force":true,"dry_run":true}`)
if resp.StatusCode != http.StatusOK {
t.Fatalf("status = %d, want 200: %s", resp.StatusCode, readAll(t, resp))
}
body := decodeBody(t, resp)
want := map[string]any{
"dry_run": true,
"deleted": float64(4),
"dependencies": float64(7),
"labels": float64(2),
"events": float64(9),
"references_updated": float64(3),
"orphaned": []any{"bd-orphan-a", "bd-orphan-b"},
}
if !reflect.DeepEqual(body, want) {
t.Errorf("body = %#v, want %#v", body, want)
}
}
// TestDeleteOmitsAnEmptyOrphanList: `orphaned` is documented absent rather than
// empty when nothing was orphaned, so a client can tell "this mode cannot
// orphan" from "this mode could and did not".
func TestDeleteOmitsAnEmptyOrphanList(t *testing.T) {
deleter := &roleDeleter{result: issueops.DeleteResult{Deleted: 1}}
ts := newTestServer(t, rolesConfig(Config{Deleter: deleter}))
body := decodeBody(t, ts.delete(t, `{"ids":["bd-1"],"cascade":true}`))
if _, present := body["orphaned"]; present {
t.Errorf("orphaned = %v, want it absent when nothing was orphaned", body["orphaned"])
}
}
func TestDeleteRefusesTheDocumentedBodies(t *testing.T) {
for _, test := range []struct {
name string
body string
param string
}{
{"no ids", `{"force":true}`, "ids"},
{"ids is not an array", `{"ids":"bd-1"}`, "ids"},
{"ids is null", `{"ids":null}`, "ids"},
{"ids is empty", `{"ids":[]}`, "ids"},
{"ids carries a non-string", `{"ids":[3]}`, "ids"},
{"unknown member", `{"ids":["bd-1"],"scope":"all"}`, "scope"},
{"actor is not a string", `{"ids":["bd-1"],"actor":7}`, "actor"},
{"actor is blank", `{"ids":["bd-1"],"actor":" "}`, "actor"},
{"cascade is not a boolean", `{"ids":["bd-1"],"cascade":"yes"}`, "cascade"},
{"force is not a boolean", `{"ids":["bd-1"],"force":1}`, "force"},
{"dry_run is not a boolean", `{"ids":["bd-1"],"dry_run":"yes"}`, "dry_run"},
} {
t.Run(test.name, func(t *testing.T) {
deleter := &roleDeleter{}
ts := newTestServer(t, rolesConfig(Config{Deleter: deleter}))
resp := ts.delete(t, test.body)
if resp.StatusCode != http.StatusBadRequest {
t.Fatalf("status = %d, want 400: %s", resp.StatusCode, readAll(t, resp))
}
body := decodeBody(t, resp)
if body["code"] != string(CodeInvalidArgument) {
t.Errorf("code = %v, want %s", body["code"], CodeInvalidArgument)
}
if body["param"] != test.param {
t.Errorf("param = %v, want %q", body["param"], test.param)
}
// A refused body must never reach the role: this is destructive,
// and "refused after acting" is the one failure shape worth ruling
// out at every edge.
if got := len(deleter.requests()); got != 0 {
t.Errorf("the role was called %d times for a refused body, want 0", got)
}
})
}
}
// TestDeletePublishesTheRolesGuardAsA400 is the reason failDeleteErr exists.
//
// The dependents guard is refused BELOW the wire, by issueops.Deleter — that is
// what makes this endpoint incapable of orphaning a graph by omission. The
// refusal reaching the client as a 500 would tell it the server was broken when
// the request was.
func TestDeletePublishesTheRolesGuardAsA400(t *testing.T) {
// The typed error, not a lookalike: the handler keys on the sentinel it
// wraps.
deleter := &roleDeleter{err: &issueops.DependentsOutsideRequestError{
IssueID: "bd-blocker",
Dependents: []string{"bd-dependent"},
}}
ts := newTestServer(t, rolesConfig(Config{Deleter: deleter}))
resp := ts.delete(t, `{"ids":["bd-blocker"]}`)
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 detail, _ := body["detail"].(string); !strings.Contains(detail, "bd-blocker") {
t.Errorf("detail = %q, want the role's own sentence naming the blocked bead", detail)
}
// No `param`: the refusal is about the absence of a CHOICE between two
// members, and the document declares `param` absent on that case.
if _, present := body["param"]; present {
t.Errorf("param = %v, want it absent for a whole-request refusal", body["param"])
}
}
// TestDeletePublishesAnAbsentIDAsA404 pins the other refusal, and pins that its
// detail does NOT name the ids.
//
// NotFound's fixed sentence is what keeps a handler that decided a miss without
// reading storage indistinguishable from one that read and missed. `bd delete`
// still names them, because it is answering the person who typed them.
func TestDeletePublishesAnAbsentIDAsA404(t *testing.T) {
deleter := &roleDeleter{err: &issueops.NotFoundError{IDs: []string{"bd-nosuch"}}}
ts := newTestServer(t, rolesConfig(Config{Deleter: deleter}))
resp := ts.delete(t, `{"ids":["bd-nosuch"],"force":true}`)
if resp.StatusCode != http.StatusNotFound {
t.Fatalf("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", body["code"], CodeNotFound)
}
if detail, _ := body["detail"].(string); strings.Contains(detail, "bd-nosuch") {
t.Errorf("detail = %q, want this surface's fixed not-found sentence without the id", detail)
}
}
// TestDeleteRefusesAForeignMediaType: the CSRF control the claim documents, for
// the reason the sweep gives — accepting text/plain would let an attacker's
// page drive a delete from any browser on the host, and this one does not even
// need the beads to be closed.
func TestDeleteRefusesAForeignMediaType(t *testing.T) {
deleter := &roleDeleter{}
ts := newTestServer(t, rolesConfig(Config{Deleter: deleter}))
resp := ts.claimRequest(t, deletePath, "text/plain", `{"ids":["bd-1"]}`)
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"])
}
if got := len(deleter.requests()); got != 0 {
t.Errorf("the role was called %d times for a refused media type, want 0", got)
}
}
// TestDeletePublishesNoQueryParameters: this operation's whole vocabulary is
// its body, so a query key is version skew rather than a bad value.
func TestDeletePublishesNoQueryParameters(t *testing.T) {
ts := newTestServer(t, rolesConfig(Config{Deleter: &roleDeleter{}}))
resp := ts.claimRequest(t, deletePath+"?force=true", "application/json", `{"ids":["bd-1"]}`)
if resp.StatusCode != http.StatusBadRequest {
t.Fatalf("status = %d, want 400: %s", resp.StatusCode, readAll(t, resp))
}
body := decodeBody(t, resp)
if body["param"] != "force" || body["reason"] != string(ReasonUnknownParameter) {
t.Errorf("body = %v, want unknown_parameter on param force", body)
}
}
// TestDeleteResponseCarriesEveryRoleField is the guard the missing x-go-type
// pin costs. deleteResponse is a hand-written projection, so a field added to
// issueops.DeleteResult and forgotten there would vanish from the wire with
// nothing to notice; this counts the fields and fails when the two drift.
func TestDeleteResponseCarriesEveryRoleField(t *testing.T) {
role := reflect.TypeOf(issueops.DeleteResult{}).NumField()
wire := reflect.TypeOf(deleteResponse(issueops.DeleteResult{})).NumField()
if role != wire {
t.Fatalf("issueops.DeleteResult has %d fields and the wire type has %d: "+
"a field was added to one and not projected onto the other (see deleteResponse)", role, wire)
}
}