beads/cmd/bd/serve_close_proxied_integration_test.go
Isis Anisoptera 45a116d1a7
fix(update): fence unforced --notes overwrites behind --force across all surfaces (#5946)
* fix(update): fence unforced --notes overwrites behind --force across all surfaces

bd update --notes silently replaced existing notes, destroying handoff
history. The contract now refuses an unforced overwrite of non-empty
notes with ErrNotesOverwrite (409 notes_overwrite_refused over HTTP,
force_notes_overwrite to override), enforced inside the mutation
transaction on both the dolt and uow backends, for single updates and
batch apply alike. CAS guards keep precedence: a stale
--if-assignee/--if-status still surfaces as the exit-13 mismatch, on
both backends, before the fence speaks.

CLI: --force and --if-assignee are no longer mutually exclusive (that
exclusion made overwriting under a guard impossible); both update
routes translate the fence's sentinel into the same actionable advice
(--force to overwrite, --append-notes to preserve history), and the
post---force warning is worded as an audit statement. The shipped
plugin skill docs and bd note help now prescribe --append-notes for
handoffs instead of the newly fenced bare --notes.

The fence is the single enforcement point: no client-side pre-read
copies of the rule. Conformance contracts, unit tests for
AuthorizeNotesOverwrite, and embedded/proxied/httpapi regression
coverage included.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MAFpn9pUw8WKMfymteZHbh

* fix(update): exempt explicit clears from the notes fence; share its predicate

CI surfaced three gaps in the fence's reach:

- Clearing notes (--notes "" / patch.notes: "") was refused, diverging
  from every sibling text field's clear and from the backend behavior
  contracts. The fence now targets only its actual footgun — replacing
  non-empty notes with different non-empty content — via a single shared
  predicate, issueops.NotesReplacement, used by both the contract's
  AuthorizeNotesOverwrite and the CLI's warning path, so the two can no
  longer drift. Prose updated to match everywhere the rule is stated
  (ErrNotesOverwrite, ForceNotesOverwrite, OpenAPI spec + regenerated
  types).
- The revision-CAS integration tests' incidental concurrent writes now
  patch design instead of notes, so they no longer depend on notes-fence
  semantics at all.
- The historical-upgrade harness deliberately replaces fixture notes and
  asserts the new value; its two bd update --notes calls now pass
  --force.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MAFpn9pUw8WKMfymteZHbh

* fix(update): address review — changelog BREAKING entry, problem.go doc block, close-policy-under-guard test

Review follow-ups on #5946 (bee-ghosttrack, MERGE-AFTER-FIXES):

- CHANGELOG: BREAKING entry under [Unreleased] ### Changed for the notes
  fence on both wires (CLI exit 1, HTTP 409 notes_overwrite_refused), with
  the --force / --append-notes migration line. It also names the two
  deliberate edges: the explicit-clear exemption, and --force widening to
  the close-policy half under --if-assignee now that the flag pair is legal.
- problem.go: CodeNotesOverwrite's comment had landed inside
  CodeDependencyCycle's doc block; each const now sits under its own docs.
- assign_fence_embedded_test.go: pin the previously untested close-policy
  half of --force under --if-assignee (refused unforced, authorized forced).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JyuQ6Tjv3D7tpNqeb2WDED

* test(update): align TestWarnNotesReplacement with the post-fence warning copy

The test landed on main after this branch was cut and pins the pre-fence
wording, where the warning fired on any unforced overwrite. Since the fence,
an unforced overwrite is refused outright and warnNotesReplacement fires only
after a forced one — the audit trail for a habitual --force — so the copy it
pins is now '--force replaced existing notes'.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JyuQ6Tjv3D7tpNqeb2WDED

* docs(import): record bd import's notes-fence exemption as by-design (GH#6190)

Import consults none of the per-field live-state fences — notes overwrite,
live-claim reassign, close policy — and that is the intended shape, not an
omission: its contract is wholesale row replacement, guarded by its own
staleness check (only strictly-newer rows rewrite local state, --allow-stale
is the single deliberate-overwrite opt-in) and reported field-by-field in
updated_issues. Named in AuthorizeNotesOverwrite's enforcement-boundary
comment and in bd import's help; the published CLI docs pick the help text
up at the next release pin bump.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JyuQ6Tjv3D7tpNqeb2WDED

* fix(update): refuse --notes "" and add --clear-notes; stop --notes help reading as additive

GH#6021: an empty --notes wiped the whole notes field at exit 0 behind the
same ✓ Updated receipt as a successful write — and the empty string is
exactly what a dead command substitution collapses to. The empty value is
now refused on both CLI routes (the accident and the deliberate clear are
the same bytes at the flag layer), and the deliberate clear gets its own
verb, --clear-notes, mutually exclusive with --notes/--append-notes. A verb
rather than the proposed --allow-empty-notes opt-in: what needs authorizing
is an intent, not an input path — --allow-empty-description unblocks
stdin/file plumbing, which notes does not have — and an opt-in passed
habitually would silently disarm the guard while a habitual --clear-notes
fails loudly. --force does not bypass the refusal; the fence's clear
exemption stands, so the verb alone authorizes the erase. The HTTP API is
unchanged: patch.notes "" still clears.

GH#6272: bd update --help called --notes "Additional notes" and the prime
text said "Add supplementary notes" — both read as appending, so agents
following the injected guidance faithfully clobbered prior context. The
update help now names the operation with the --append-notes contrast at the
point of use, the shared/create help is field-named like --description and
--design, and the prime line points at bd update --append-notes.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JyuQ6Tjv3D7tpNqeb2WDED

* fix(bazel): enumerate the PR-new files in cmd/bd and issueops srcs

The base added cmd/bd/BUILD.bazel and internal/storage/issueops/BUILD.bazel
with EXPLICIT srcs lists after this branch was cut, so the three files this
PR adds were never enumerated:

  cmd/bd/update_notes_guard.go        (go_library bd_lib)
  cmd/bd/update_notes_guard_test.go   (go_test bd_test)
  internal/storage/issueops/aggregate_authorize_notes_test.go (go_test)

The go_library omission is a hard build break, not a silent skip:
update.go:215,220 and update_input.go:106,111 are enumerated and call
validateNotesUpdate / clearNotesRequested, so //cmd/bd:bd_lib compiles the
callers without the callee. bazel.yml arms unconditionally for fork PRs
(head.repo.fork == true) and builds //cmd/bd:bd + //cmd/bd:bd_test, so this
reds the lane. make bazel-sync-check cannot see it -- go_srcs.py only
validates the glob-based go_srcs filegroup, never the rule srcs lists.

Generated by make bazel-sync (gazelle), not hand-edited, so the workflow's
own BUILD-files-in-sync drift step agrees byte-for-byte.

* fix(notes): name --clear-notes in bd note's rm guidance, correct the fence boundary comment, pin both request-shape rules

Takes all three non-gating minors from the review. No behavior change: two
prose fixes and two test cases.

1. cmd/bd/note.go's rm|remove|delete branch advised
   `bd update <id> --notes "text" --force` under "To change or clear notes",
   but clearing through --notes is exactly what this PR made impossible --
   validateNotesUpdate refuses an empty value unconditionally and --force does
   not reach it. The branch now names both verbs separately: --notes --force to
   replace, --clear-notes to clear. The edit and update branches speak only of
   replacing and were already correct, so they are untouched.

2. aggregate.go's enforcement-boundary comment claimed the UpdateIssueInTx
   funnel's "one notes-replacing caller is bd edit". Under this PR's own
   NotesReplacement predicate there are at least four more (bd note's
   read-combine-write, bd defer --reason, bd rename and delete-tombstoning's
   mechanical ID rewrites, bd compact's clears). The exemption is still sound --
   every funnel writer derives its new value from the current notes -- so the
   comment now names those CLASSES instead of a single caller, which is the
   claim that is actually true and that a future fence auditor can check.

3. Both branches this PR adds to ValidateUpdateRequest were uncovered: the
   batch apply leg reaches them here and nowhere else, while the single-issue
   HTTP handler's own pre-check returns before storage. Added a sibling table
   (the existing one varies only the patch; these two rules are properties of
   the REQUEST) with a case each. Mutation-checked, disjoint: neutralizing the
   force-without-notes branch reds only the first case, neutralizing the
   notes+append branch reds only the second, and the pre-existing
   canonical-fields table stays green under both.

Not an amend of 5ffcc9c16c: that commit's message states it was generated by
make bazel-sync and not hand-edited, so folding hand-written Go into it would
falsify the claim its own BUILD-files-in-sync argument rests on. No new files,
so the srcs lists it repaired stay correct.

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
2026-10-01 05:02:40 -07:00

572 lines
25 KiB
Go

//go:build cgo
package main
import (
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"testing"
)
// End-to-end for the close, against real Dolt through a real `bd serve`
// subprocess. The pure tests in internal/httpapi cover the wire edge on a fake
// role; what only this level can prove is the TRANSACTION — that first-close-
// wins is a property of the stored row rather than of a fake's bookkeeping, and
// that the open-children refusal and its force bypass are the real policy the
// CLI enforces, over a graph a fake has no way to hold.
//
// The role-level transition itself is owned against a real store by
// internal/storage/uow/lifecycle_close_reopen_contract_test.go. This test owns
// the wire-to-role seam and cites that one rather than duplicating it.
// lifecycleVerbRaw posts a custom method for id and returns the status and the
// UNDECODED body, so a caller can choose how to read a member rather than
// inheriting encoding/json's default for `any`.
//
// It exists for `revision`, and the update slice paid for the lesson: live
// row_lock tokens run past 5e17, where a float64's ulp is already 64, so a
// token read through `map[string]any` is a value NEAR the token and is not it.
// The decoded helpers below stay as they were — a case comparing prose members
// wants the ordinary decode — and the guarded cases read the raw bytes.
func (sp *serveProcess) lifecycleVerbRaw(t *testing.T, verb, id, body string) (int, []byte) {
t.Helper()
req, err := http.NewRequest(http.MethodPost, sp.url("/v0/beads/issues/"+id+":"+verb), strings.NewReader(body))
if err != nil {
t.Fatalf("new %s request: %v", verb, err)
}
req.Header.Set("Content-Type", "application/json")
resp, err := sp.client.Do(req)
if err != nil {
t.Fatalf("POST %s %s: %v\nstderr:\n%s", verb, id, err, sp.stderr.String())
}
defer func() { _ = resp.Body.Close() }()
raw, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatalf("read %s body: %v", verb, err)
}
return resp.StatusCode, raw
}
// decodeVerbBody is the ordinary decode the unguarded cases use.
func decodeVerbBody(t *testing.T, verb string, raw []byte) map[string]any {
t.Helper()
var m map[string]any
if len(raw) > 0 {
if err := json.Unmarshal(raw, &m); err != nil {
t.Fatalf("decode %s body %q: %v", verb, raw, err)
}
}
return m
}
// closeIssueRaw posts a close and returns the status and the undecoded body.
func (sp *serveProcess) closeIssueRaw(t *testing.T, id, body string) (int, []byte) {
t.Helper()
return sp.lifecycleVerbRaw(t, "close", id, body)
}
// closeIssue posts a close for id and returns the status and decoded body.
func (sp *serveProcess) closeIssue(t *testing.T, id, body string) (int, map[string]any) {
t.Helper()
status, raw := sp.closeIssueRaw(t, id, body)
return status, decodeVerbBody(t, "close", raw)
}
// reopenIssueRaw posts a reopen and returns the status and the undecoded body.
func (sp *serveProcess) reopenIssueRaw(t *testing.T, id, body string) (int, []byte) {
t.Helper()
return sp.lifecycleVerbRaw(t, "reopen", id, body)
}
// reopenIssue posts a reopen for id and returns the status and decoded body.
func (sp *serveProcess) reopenIssue(t *testing.T, id, body string) (int, map[string]any) {
t.Helper()
status, raw := sp.reopenIssueRaw(t, id, body)
return status, decodeVerbBody(t, "reopen", raw)
}
func TestProxiedServerServeClose(t *testing.T) {
requireSharedProxiedServer(t)
t.Parallel()
bd := buildEmbeddedBD(t)
p := newSharedProxiedProject(t, bd, "srvclo")
sp := startServe(t, bd, p.dir, bdProxiedEnv(p.dir))
// THE FIRST-CLOSE-WINS PROOF, read back through a second close. A fake role
// can report Changed false; only a real store can show that the second
// close left the first one's reason and session in the columns.
t.Run("the first close wins and a re-close does not rewrite it", func(t *testing.T) {
issue := bdProxiedCreate(t, bd, p.dir, "close over http", "-p", "1")
status, body := sp.closeIssue(t, issue.ID, `{"actor":"http-agent","reason":"shipped it","session":"session-a"}`)
if status != http.StatusOK {
t.Fatalf("first close: status = %d, want 200: %v", status, body)
}
if body["already_closed"] != false {
t.Errorf("already_closed = %v, want false on a fresh close", body["already_closed"])
}
closed, ok := body["issue"].(map[string]any)
if !ok {
t.Fatalf("issue = %#v, want an object", body["issue"])
}
if closed["status"] != "closed" || closed["close_reason"] != "shipped it" {
t.Errorf("the response does not describe the closed row: %v", closed)
}
// The CLI reads the same row through its own path.
shown := bdProxiedShow(t, bd, p.dir, issue.ID)
if string(shown.Status) != "closed" || shown.CloseReason != "shipped it" || shown.ClosedBySession != "session-a" {
t.Fatalf("bd show reports status %q reason %q session %q; the HTTP close did not land",
shown.Status, shown.CloseReason, shown.ClosedBySession)
}
// The replay. It succeeds, reports the idempotent flag, and — the whole
// point — writes NEITHER value, so the record of why the work ended
// cannot be rewritten by a client replaying its own recovery.
status, body = sp.closeIssue(t, issue.ID, `{"actor":"other-agent","reason":"REWRITTEN","session":"session-b"}`)
if status != http.StatusOK {
t.Fatalf("re-close: status = %d, want 200: %v", status, body)
}
if body["already_closed"] != true {
t.Errorf("already_closed = %v, want true for a re-close", body["already_closed"])
}
after := bdProxiedShow(t, bd, p.dir, issue.ID)
if after.CloseReason != "shipped it" {
t.Errorf("close_reason = %q after the replay, want the FIRST close's value", after.CloseReason)
}
if after.ClosedBySession != "session-a" {
t.Errorf("closed_by_session = %q after the replay, want the FIRST close's value", after.ClosedBySession)
}
})
// THE FORCED-CLOSE PROOF. The open-children refusal is the role's, over a
// real parent-child edge; the count in the problem body comes from the
// transaction that refused, and the force bypass is what a caller does next.
t.Run("open children refuse an unforced close and force bypasses them", func(t *testing.T) {
parent := bdProxiedCreate(t, bd, p.dir, "the parent", "-p", "1")
for i := range 2 {
child := bdProxiedCreate(t, bd, p.dir, fmt.Sprintf("child %d", i), "-p", "2")
if out, err := bdProxiedRun(t, bd, p.dir, "dep", "add", child.ID, parent.ID, "--type", "parent-child"); err != nil {
t.Fatalf("bd dep add: %v\n%s", err, out)
}
}
status, body := sp.closeIssue(t, parent.ID, `{"actor":"http-agent","reason":"too soon"}`)
if status != http.StatusConflict {
t.Fatalf("unforced close over open children: status = %d, want 409: %v", status, body)
}
if body["code"] != "not_closable" {
t.Errorf("code = %v, want not_closable", body["code"])
}
// Read inside the refusing transaction, never parsed out of the prose.
if body["open_children"] != float64(2) {
t.Errorf("open_children = %v, want 2", body["open_children"])
}
if body["request_id"] == nil {
t.Error("no request_id on the problem body")
}
// A refusal writes nothing.
if shown := bdProxiedShow(t, bd, p.dir, parent.ID); string(shown.Status) == "closed" {
t.Fatalf("the refused close closed the issue anyway: status %q", shown.Status)
}
status, body = sp.closeIssue(t, parent.ID, `{"actor":"http-agent","reason":"closing anyway","force":true}`)
if status != http.StatusOK {
t.Fatalf("forced close: status = %d, want 200: %v", status, body)
}
// A forced close reports what it bypassed, which is exactly what the
// caller who bypassed it wants to know.
if body["open_children"] != float64(2) {
t.Errorf("open_children = %v on the forced close, want the 2 it bypassed", body["open_children"])
}
if shown := bdProxiedShow(t, bd, p.dir, parent.ID); string(shown.Status) != "closed" {
t.Errorf("bd show reports status %q after a forced close", shown.Status)
}
})
// The rule-8 oracle. Every other operation on this surface is checked
// against its CLI equivalent by comparing FULL item JSON, and "parity holds
// by construction" is exactly the reasoning that rule exists to forbid: a
// later CLI-side enrichment of close output must fail here rather than drift
// silently against the HTTP body.
//
// The CLI side is an idempotent RE-close, the claim oracle's device: it
// writes nothing under first-close-wins, so both surfaces describe the same
// row from the same post-state snapshot. `bd show --json` is deliberately
// not the oracle — it answers IssueDetails, with the counts and the revision
// this response does not carry, so it would compare two different shapes.
t.Run("the closed issue matches bd close --json element 0", func(t *testing.T) {
issue := bdProxiedCreate(t, bd, p.dir, "parity oracle", "-p", "1",
"-d", "described", "--acceptance", "accepted", "--label", "oracle")
status, body := sp.closeIssue(t, issue.ID, `{"actor":"parity-agent","reason":"done","session":"oracle-session"}`)
if status != http.StatusOK {
t.Fatalf("status = %d, want 200: %v", status, body)
}
fromHTTP, ok := body["issue"].(map[string]any)
if !ok {
t.Fatalf("issue = %#v, want an object", body["issue"])
}
fromCLI := bdProxiedCloseOneRaw(t, bd, p.dir, issue.ID, "--reason", "ignored under first-close-wins")
// The allowlist is EMPTY: both surfaces marshal the same canonical
// struct from the same post-state snapshot, so any difference at all is
// a real divergence and belongs in review, not in this list.
if diff := diffJSONObjects(fromHTTP, fromCLI, nil); diff != "" {
t.Errorf("CloseIssueResponse.issue and `bd close --json`[0] disagree:\n%s", diff)
}
})
// THE ROUND-TRIP PROOF for reopenIssue. A fake role can report Changed; only
// a real store can show that the reopen CLEARED the close record — which is
// what makes the close's first-close-wins rule survivable, since the way to
// write a new reason is to reopen and close again.
t.Run("a close and reopen round trip clears the close record", func(t *testing.T) {
issue := bdProxiedCreate(t, bd, p.dir, "round trip", "-p", "1")
if status, body := sp.closeIssue(t, issue.ID, `{"actor":"http-agent","reason":"shipped","session":"session-x"}`); status != http.StatusOK {
t.Fatalf("close: status = %d, want 200: %v", status, body)
}
closed := bdProxiedShow(t, bd, p.dir, issue.ID)
if closed.CloseReason != "shipped" || closed.ClosedBySession != "session-x" {
t.Fatalf("the close did not record its reason/session: %q/%q", closed.CloseReason, closed.ClosedBySession)
}
status, body := sp.reopenIssue(t, issue.ID, `{"actor":"http-agent","reason":"the fix regressed"}`)
if status != http.StatusOK {
t.Fatalf("reopen: status = %d, want 200: %v", status, body)
}
if body["already_open"] != false {
t.Errorf("already_open = %v, want false on a reopen that changed the row", body["already_open"])
}
reopened, ok := body["issue"].(map[string]any)
if !ok {
t.Fatalf("issue = %#v, want an object", body["issue"])
}
if reopened["status"] != "open" {
t.Errorf("the response reports status %v, want open", reopened["status"])
}
after := bdProxiedShow(t, bd, p.dir, issue.ID)
if string(after.Status) != "open" {
t.Fatalf("bd show reports status %q; the HTTP reopen did not land", after.Status)
}
if after.CloseReason != "" || after.ClosedBySession != "" {
t.Errorf("the reopen left close_reason %q and closed_by_session %q; both describe a closure that no longer holds",
after.CloseReason, after.ClosedBySession)
}
// The reason is recorded on the EVENT, which is where the document tells
// a client to read it back — not on a field of the issue, and not in the
// response.
events, err := bdProxiedRun(t, bd, p.dir, "history", issue.ID, "--events")
if err != nil {
t.Fatalf("bd history --events: %v\n%s", err, events)
}
if !strings.Contains(string(events), "the fix regressed") {
t.Errorf("the reopen reason is not on the issue's event stream:\n%s", events)
}
// And the round trip really is a round trip: the issue is claimable
// again, which is the recovery flow this pair exists to serve.
if status, claim := sp.claim(t, issue.ID, "http-agent"); status != http.StatusOK {
t.Errorf("claim after reopen: status = %d, want 200: %v", status, claim)
}
})
// The idempotent half, against the real store: a reopen of an issue that was
// never done changes nothing and succeeds.
t.Run("reopening an issue that was never done is idempotent", func(t *testing.T) {
issue := bdProxiedCreate(t, bd, p.dir, "never closed", "-p", "2")
status, body := sp.reopenIssue(t, issue.ID, `{"actor":"http-agent"}`)
if status != http.StatusOK {
t.Fatalf("status = %d, want 200: %v", status, body)
}
if body["already_open"] != true {
t.Errorf("already_open = %v, want true for an issue that was never done", body["already_open"])
}
if shown := bdProxiedShow(t, bd, p.dir, issue.ID); string(shown.Status) != "open" {
t.Errorf("bd show reports status %q after an idempotent reopen", shown.Status)
}
})
t.Run("a closed issue is no longer claimable", func(t *testing.T) {
issue := bdProxiedCreate(t, bd, p.dir, "closed then claimed", "-p", "2")
if status, body := sp.closeIssue(t, issue.ID, `{"actor":"http-agent"}`); status != http.StatusOK {
t.Fatalf("close: status = %d: %v", status, body)
}
// The two operations agree about the row they share, which is the whole
// reason the lifecycle pair belongs on this surface.
status, body := sp.claim(t, issue.ID, "http-agent")
if status != http.StatusConflict {
t.Fatalf("claim of a closed issue: status = %d, want 409: %v", status, body)
}
if body["code"] != "not_claimable" || body["issue_status"] != "closed" {
t.Errorf("claim refusal = %v, want not_claimable/closed", body)
}
})
t.Run("unknown ids are 404 and refused bodies write nothing", func(t *testing.T) {
status, body := sp.closeIssue(t, "bd-nosuchissue", `{"actor":"http-agent"}`)
if status != http.StatusNotFound {
t.Fatalf("unknown id: status = %d, want 404: %v", status, body)
}
if body["code"] != "not_found" {
t.Errorf("code = %v, want not_found", body["code"])
}
issue := bdProxiedCreate(t, bd, p.dir, "never closed", "-p", "2")
for _, refused := range []string{
`{"actor":" "}`,
`{"actor":"agent\nbd serve: close bd-0 by mallory"}`,
`{"actor":"agent","reason":"` + strings.Repeat("x", 300) + `"}`,
`{"actor":"agent","cascade":true}`,
`{"actor":"agent","force":"yes"}`,
} {
status, problem := sp.closeIssue(t, issue.ID, refused)
if status != http.StatusBadRequest {
t.Fatalf("body %.40q: status = %d, want 400: %v", refused, status, problem)
}
if problem["code"] != "invalid_argument" {
t.Errorf("body %.40q: code = %v, want invalid_argument", refused, problem["code"])
}
}
// The refusals are wire-edge refusals: nothing reached the database.
if shown := bdProxiedShow(t, bd, p.dir, issue.ID); string(shown.Status) != "open" {
t.Errorf("a refused close wrote to the row: status %q", shown.Status)
}
})
// THE GUARD, AS A REAL READ-MODIFY-WRITE LOOP. The pure tests assert the
// projection onto issueops.CloseRequest and the shape of the 409; what only
// this level can show is that the token a write ANSWERS with is the one the
// next request must send, that a stale one really refuses against a store,
// and — the claim a fake has no way to hold — that the guard is evaluated
// BEFORE the idempotent re-close.
//
// The stale token is made by a real concurrent writer rather than by
// arithmetic. The token is opaque and compared for equality alone, so
// `revision - 1` is not "the previous revision"; there is no way to
// construct a stale one except to let something move the row.
t.Run("a guarded close and reopen compose from the revision the write answered", func(t *testing.T) {
issue := bdProxiedCreate(t, bd, p.dir, "guarded lifecycle", "-p", "2")
// The first guarded write has to seed itself from an unguarded one:
// no READ on this surface publishes a revision yet, which is the gap
// the document names on every one of these members.
status, raw := sp.updateIssueRaw(t, issue.ID, `{"actor":"http-agent","patch":{"notes":"seeded"}}`)
if status != http.StatusOK {
t.Fatalf("the seeding write: status = %d, want 200: %s", status, raw)
}
first := revisionOf(t, raw)
status, raw = sp.updateIssueRaw(t, issue.ID, `{"actor":"other-agent","patch":{"design":"moved"}}`)
if status != http.StatusOK {
t.Fatalf("the concurrent write: status = %d, want 200: %s", status, raw)
}
second := revisionOf(t, raw)
if second == first {
t.Fatalf("revision = %q after a second write; a write that does not move the token makes every guard vacuous", second)
}
// The stale close. Nothing is written, and the 409 names the member.
status, problem := sp.closeIssue(t, issue.ID,
`{"actor":"http-agent","reason":"never","expected_version":`+revisionGuard(first)+`}`)
if status != http.StatusConflict {
t.Fatalf("stale close: status = %d, want 409: %v", status, problem)
}
if problem["code"] != "precondition_failed" || problem["param"] != "expected_version" {
t.Errorf("stale close: code = %v param = %v, want precondition_failed / expected_version", problem["code"], problem["param"])
}
if shown := bdProxiedShow(t, bd, p.dir, issue.ID); string(shown.Status) != "open" || shown.CloseReason != "" {
t.Errorf("a refused guard closed the row anyway: status %q reason %q", shown.Status, shown.CloseReason)
}
// FORCE DOES NOT BYPASS IT. `force` bypasses close POLICY; the guard is
// about whether this is still the row the caller read, which force says
// nothing about.
status, problem = sp.closeIssue(t, issue.ID,
`{"actor":"http-agent","force":true,"expected_version":`+revisionGuard(first)+`}`)
if status != http.StatusConflict {
t.Fatalf("forced stale close: status = %d, want 409 — force bypasses policy, never a precondition: %v", status, problem)
}
if shown := bdProxiedShow(t, bd, p.dir, issue.ID); string(shown.Status) != "open" {
t.Errorf("a forced stale close closed the row: status %q", shown.Status)
}
// The fresh guard lands, and answers with the token the close minted.
status, raw = sp.closeIssueRaw(t, issue.ID,
`{"actor":"http-agent","reason":"shipped","expected_version":`+revisionGuard(second)+`}`)
if status != http.StatusOK {
t.Fatalf("guarded close: status = %d, want 200: %s", status, raw)
}
closed := revisionOf(t, raw)
if closed == second {
t.Errorf("revision = %q after a close that wrote; the token did not move", closed)
}
if shown := bdProxiedShow(t, bd, p.dir, issue.ID); string(shown.Status) != "closed" {
t.Fatalf("the guarded close did not land: status %q", shown.Status)
}
// THE CLAIM ONLY A REAL STORE CAN SHOW: the guard is checked BEFORE the
// idempotent re-close. The same body that earns a 200 with
// `already_closed` unguarded is a 409 when it carries a token the close
// itself has already invalidated — which is what lets a client read
// `already_closed` as "and nothing has happened here since".
status, problem = sp.closeIssue(t, issue.ID,
`{"actor":"http-agent","expected_version":`+revisionGuard(second)+`}`)
if status != http.StatusConflict {
t.Fatalf("guarded re-close with a pre-close token: status = %d, want 409: %v", status, problem)
}
// Unguarded, that same replay is the ordinary idempotent answer.
status, raw = sp.closeIssueRaw(t, issue.ID, `{"actor":"http-agent","reason":"REWRITTEN"}`)
if status != http.StatusOK {
t.Fatalf("unguarded re-close: status = %d, want 200: %s", status, raw)
}
replay := decodeVerbBody(t, "close", raw)
if replay["already_closed"] != true {
t.Errorf("already_closed = %v, want true", replay["already_closed"])
}
afterReplay := revisionOf(t, raw)
if afterReplay != closed {
t.Errorf("revision = %q after an idempotent re-close, want the unchanged %q: a replay that writes nothing must not move the token",
afterReplay, closed)
}
// The reopen's own guard, on the mirror. Stale first.
status, problem = sp.reopenIssue(t, issue.ID,
`{"actor":"http-agent","expected_version":`+revisionGuard(second)+`}`)
if status != http.StatusConflict {
t.Fatalf("stale reopen: status = %d, want 409: %v", status, problem)
}
if problem["code"] != "precondition_failed" || problem["param"] != "expected_version" {
t.Errorf("stale reopen: code = %v param = %v", problem["code"], problem["param"])
}
if shown := bdProxiedShow(t, bd, p.dir, issue.ID); string(shown.Status) != "closed" {
t.Errorf("a refused guard reopened the row: status %q", shown.Status)
}
// And the loop closes: the token the last successful write answered
// with is the one that lands.
status, raw = sp.reopenIssueRaw(t, issue.ID,
`{"actor":"http-agent","expected_version":`+revisionGuard(afterReplay)+`}`)
if status != http.StatusOK {
t.Fatalf("guarded reopen: status = %d, want 200: %s", status, raw)
}
if reopened := revisionOf(t, raw); reopened == afterReplay {
t.Errorf("revision = %q after a reopen that wrote; the token did not move", reopened)
}
if shown := bdProxiedShow(t, bd, p.dir, issue.ID); string(shown.Status) != "open" || shown.CloseReason != "" {
t.Errorf("the guarded reopen did not land: status %q reason %q", shown.Status, shown.CloseReason)
}
})
// THE BLOCKER-NAMING PROOF, against the CLI's own sentence. A live blocker
// refuses with a `blockers` member read from the refusing check's typed
// list, and `detail` opens with exactly what `bd close` records in
// failed[].error for the same refusal — so an HTTP client can render the
// direct route's message instead of an anonymous "blocked".
t.Run("a live blocker refusal names its blockers as the CLI does", func(t *testing.T) {
blocker := bdProxiedCreate(t, bd, p.dir, "the blocker", "-p", "1")
local := bdProxiedCreate(t, bd, p.dir, "blocked locally", "-p", "1")
if out, err := bdProxiedRun(t, bd, p.dir, "dep", "add", local.ID, blocker.ID); err != nil {
t.Fatalf("bd dep add: %v\n%s", err, out)
}
external := bdProxiedCreate(t, bd, p.dir, "blocked externally", "-p", "1")
const ref = "external:remote:payments"
if out, err := bdProxiedRun(t, bd, p.dir, "dep", "add", external.ID, ref); err != nil {
t.Fatalf("bd dep add external: %v\n%s", err, out)
}
for _, tc := range []struct {
id string
want string
}{
{local.ID, `[{"id":"` + blocker.ID + `","kind":"local","type":"blocks"}]`},
{external.ID, `[{"id":"` + ref + `","kind":"external"}]`},
} {
status, body := sp.closeIssue(t, tc.id, `{"actor":"http-agent"}`)
if status != http.StatusConflict || body["code"] != "not_closable" {
t.Fatalf("close %s: status = %d code = %v, want 409 not_closable: %v", tc.id, status, body["code"], body)
}
if _, present := body["open_children"]; present {
t.Errorf("close %s: open_children on the blocker refusal: %v", tc.id, body)
}
got, err := json.Marshal(body["blockers"])
if err != nil {
t.Fatalf("re-encode blockers: %v", err)
}
if string(got) != tc.want {
t.Errorf("close %s: blockers = %s, want %s", tc.id, got, tc.want)
}
cli := bdProxiedCloseFailedError(t, bd, p.dir, tc.id)
if want := cli + "; clear the blocker or close with force"; body["detail"] != want {
t.Errorf("close %s: detail = %q, want the CLI's failed[].error %q plus the HTTP hint", tc.id, body["detail"], cli)
}
}
})
sp.shutdown(t)
}
// bdProxiedCloseFailedError runs an unforced `bd close --json` of id that must
// be refused and returns the failed[].error it reports for id — the
// route-independent spelling of the refusal (see assertCloseFailedErrorIsTyped).
// A closable companion rides along because the failure report is the
// partial-batch shape: a lone refused id prints no failed[] array.
func bdProxiedCloseFailedError(t *testing.T, bd, dir, id string) string {
t.Helper()
companion := bdProxiedCreate(t, bd, dir, "closable companion", "-p", "2")
stdout, stderr, err := bdProxiedRunBuffers(t, bd, dir, "close", "--json", companion.ID, id)
if err == nil {
t.Fatalf("bd close %s succeeded; it must be refused\nstdout:\n%s", id, stdout)
}
var report struct {
Failed []struct {
ID string `json:"id"`
Error string `json:"error"`
} `json:"failed"`
}
line := lastJSONObjectLine(stderr)
if jsonErr := json.Unmarshal([]byte(line), &report); jsonErr != nil || len(report.Failed) != 1 || report.Failed[0].ID != id {
t.Fatalf("bd close %s failure report = %+v (%v)\nstderr:\n%s", id, report, jsonErr, stderr)
}
return report.Failed[0].Error
}
// bdProxiedCloseOneRaw runs `bd close --json` and decodes the one item it
// reports as a generic object rather than into types.Issue: the parity oracle
// compares the JSON both surfaces actually emit, and decoding through the
// struct would hide exactly the field-level drift it exists to catch.
func bdProxiedCloseOneRaw(t *testing.T, bd, dir, id string, args ...string) map[string]any {
t.Helper()
full := append([]string{"close", id, "--json"}, args...)
out, err := bdProxiedRun(t, bd, dir, full...)
if err != nil {
t.Fatalf("bd close %s --json failed: %v\n%s", id, err, out)
}
s := string(out)
start := strings.Index(s, "[")
if start < 0 {
t.Fatalf("no JSON array in show output:\n%s", s)
}
var items []map[string]any
if err := json.Unmarshal([]byte(s[start:]), &items); err != nil {
t.Fatalf("parse show JSON: %v\nraw: %s", err, s[start:])
}
if len(items) != 1 {
t.Fatalf("show returned %d items, want 1:\n%s", len(items), s[start:])
}
return items[0]
}