beads/cmd/bd/promote_proxied_integration_test.go
Julian Knutsen eaed71fbba
fix(http): bd promote over http through issueops.Promote and issues.update.persistence (S21b) (#7554)
* fix(http): bd promote over http through issueops.Promote and issues.update.persistence (S21b)

`bd promote` refused over a connected HTTP workspace: it called the raw
PromoteFromEphemeral, which the http backend stubs, and updateIssue's patch
did not publish persistence. MC's PR-intake formula
(mol-normalized-issue-pr-v1) runs `gc bd promote <id> --reason ...`, so this
blocked the HTTP cutover.

- One library entry, issueops.Promote(ctx, PromoteRoles{Reader, Lifecycle,
  Commenter}, PromoteRequest{Actor, IssueID, Reason, Provenance}): read the
  row, refuse a non-wisp (*NotAWispError, the sentence bd promote always
  printed), move it with ONE Lifecycle.Update whose patch is Persistence =
  persistent (the role's atomic plane move: same id, labels, deps, events and
  comments carried), then write the promotion comment (a comment failure is
  reported, the promotion stands). A no-op move is a lost race and reports
  NotAWispError without a second comment.
- cmd/bd: the direct route runs it over the store's own role accessors, so a
  connected http workspace and a local one take the same entry. The history
  label is "bd: promote <id>" where the store carries caller labels.
- bd serve: IssuePatchBody.persistence (persistent|ephemeral|no_history,
  anything else a 400 naming patch.persistence) on PATCH
  /v0/beads/issues/{id}, behind the new additive behavior token
  issues.update.persistence. wire_revision unchanged. Spec, apigen and the
  wire-shape golden regenerated; the handler only decodes and passes it to
  the role.
- httpclient: Lifecycle.Update sends patch.persistence only to a server
  advertising the token, and otherwise refuses BEFORE the dial with
  *wire.CapabilityError naming it (unwraps to *storage.ErrUnsupported with
  Capability set). The batchApply item still refuses it
  (W-IssuePatch.Persistence now reads "ON issues:batchApply").
- Conformance: RunLifecycleUpdatePersistentPromotesAWisp on dolt, embedded,
  uow and the served http leg; the served
  PersistentPreservesUnversionedClass case is unparked.
- Served e2e TestE2E_PromoteOverHTTP: the mc-promote shape end to end
  (label kept, comment written, one PATCH, re-promote refused), and under
  the MC server mask a pre-dial refusal naming the token with no write.
- Corpus: mc-promote stays pending, relabelled SRV-1 with the reference
  profile's exact refusal (the 1.3.0 server lacks issues.update.persistence).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(promote): run the proxied-server route through issueops.Promote (bd-4y73m9)

The adoption review found (major) that the proxied-server route still
promoted through the old engine, IssueUseCase.PromoteWisp in one
transaction with the comment, while the PR's docs said every route runs
issueops.Promote. Converge rather than reword: runPromoteProxiedServer
resolves the id, then runs issueops.Promote over the provider's own
notifying role accessors (proxiedIssueReader, proxiedIssueLifecycle,
proxiedCommenter), the entry the direct route runs. Both routes now share
promoteFailure (the error mapping) and reportPromotion (the comment
warning and the output), so neither contract can drift.

What a script sees change on the proxied-server route:
- the move is the persistence branch of Lifecycle.Update, so the child
  counter moves with the row: a promoted parent's next
  `bd create --parent` mints .3 after .1/.2 instead of failing with
  "issue already exists";
- on_update fires twice, for the move and for the comment, as on the
  direct route (it fired once, for the comment);
- a promotion is two Dolt commits, "bd: promote <id>" and
  "bd: comment <id>" (it was one);
- a comment that cannot be written leaves the promotion standing behind
  a warning, as on every other route, instead of rolling it back;
- a dual-plane id is refused rather than merged, the update role's
  template guard applies, and a lost race reads "<id> is not a wisp
  (already persistent)".

The PromoteWisp exemption in TestRecordingIssueUseCaseCoversItsSurface
stays, with its reason corrected: no route calls PromoteWisp now, and
its DoltStorage twin fires no hook either. The doc comments on the old
engine (PromoteFromEphemeral on DoltStore and the db layer, PromoteWisp)
no longer say bd promote uses it.

CHANGELOG: the promote entry now names what a script can see on the
direct and proxied-server routes: the hook firings, the comment row
`bd comments` lists, the child-counter carry, the two-commit shape, and
a comment failure that warns instead of rolling back.

Tests:
- TestEmbeddedPromoteMovesAWispParent promotes a wisp parent with .1/.2
  children, a dependency and a comment under a counting on_update hook:
  the hook fires twice, the dependency and the children's parent edge
  survive, `bd comments` lists the old comment and the promotion reason,
  and the next child is .3. At the pre-PR base it fails (the hook fired
  0 times).
- The proxied journey pins the two commits, and new subtests pin the
  child counter (the child_counters row, next child .3) and the two hook
  firings. Against the contributor head each fails: one commit, no
  counter row and a failing create, one firing.

Review iteration 2:
- TestEmbeddedPromoteMovesAWispParent gets its row in the embedded cmd
  shard manifest (shard 64 of 100, from the generator's incremental
  --write). Without it //scripts:go_test_sources_test fails both the
  NotStale and the bare-write guard, and the generator's --check fails.
- notifying.go no longer lists the promotion comment as a divergence.
  The direct route now writes that comment through st.Commenter(),
  which HookFiringStore wraps, so an embedded promote fires on_update
  for it (TestEmbeddedPromoteMovesAWispParent counts both firings). The
  list counts four, and the empty-commit note becomes the fifth item.
- batchapplier.go no longer says persistence is absent from both patch
  bodies: the update body publishes it behind issues.update.persistence,
  and only batchApply refuses it (W-IssuePatch.Persistence).
- Three comments still tied promotion to the old engine: the
  conformance fixture's PromoteWisp no longer claims to do what
  `bd promote` does, the CLI differential's promote scenario names
  issueops.Promote, and export_source's wisp-relations note names
  issueops.MoveIssuePersistenceInTx.
- The Promote unit test compares the whole update patch with
  reflect.DeepEqual. The helper it replaces checked 9 of the patch's 22
  members, so a Promote that also set Description passed it.

Review iteration 3:
- A refused persistence move answered 500 `internal` over http and
  emitted request_error, though the caller could fix the request. The
  role now returns two refusals as ErrValidation, so bd serve answers
  400 invalid_argument and the client maps that back to ErrValidation:
  an unversioned row asked for ephemeral or no_history (the role wraps
  types.ErrUnversionedWispMove, a new sentinel NormalizePersistenceMode
  returns for that case alone, with its message unchanged), and a
  demotion of a row with retained snapshots. A row that breaks its own
  persistence invariants still answers 500.
- RunLifecycleUpdateWispModesRefuseAnUnversionedRow pins the refusal on
  every leg (dolt, embedded dolt, the unit of work, served http): both
  wisp modes match ErrValidation and leave the row durable, unversioned
  and off the wisp plane. Without the wrap the dolt leg fails, and the
  served leg fails on "answered 500 internal".
- TestMoveIssuePersistenceInTxRefusesDemotionWithRetainedSnapshots is
  the first test of the snapshot refusal, and fails without its wrap.
  The unversioned unit test now requires both sentinels. The types tests
  pin the sentinel, its unchanged message, and that no row-invariant
  error matches it: checking the unversioned class ahead of the
  invariant checks fails them.
- CHANGELOG: the promote entry counts five script-visible changes, the
  fifth being the lost-race refusal sentence, and says the two refusals
  now answer 400 over bd serve and gain a `validation failed: ` prefix
  locally.
- NotAWispError's doc comment records that a no-history wisp is refused
  too: the gate reads the Ephemeral flag, as bd promote always has, and
  `bd update --persistent` is the move for that row.

Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 05:51:53 +00:00

294 lines
12 KiB
Go

//go:build cgo
package main
import (
"database/sql"
"encoding/json"
"fmt"
"runtime"
"slices"
"sort"
"strings"
"testing"
)
// TestProxiedServerPromote is the promote-family journey on the shared
// proxied server. The downstream contract (wyvern wheelhouse portcullis
// salvage) is that promote REWRITES THE ROW IN PLACE: same id, wisp_type
// retained, labels/deps/events/comments and the child counter preserved,
// still visible to `bd list --include-infra --wisp-type <t>`, no longer
// purge-reclaimable, same --json shape and error contract as classic. The
// route runs issueops.Promote, the direct route's entry, so it also fires
// on_update for the move and for the promotion comment.
func TestProxiedServerPromote(t *testing.T) {
requireSharedProxiedServer(t)
t.Parallel()
bd := buildEmbeddedBD(t)
t.Run("journey_rewrites_row_in_place", func(t *testing.T) {
t.Parallel()
p := newSharedProxiedProject(t, bd, "pm")
target := bdProxiedCreate(t, bd, p.dir, "Promote dep target", "--type", "task")
inbound := bdProxiedCreate(t, bd, p.dir, "Inbound dependent", "--type", "task")
wisp := bdProxiedCreate(t, bd, p.dir, "Promote journey wisp",
"--ephemeral", "--wisp-type", "patrol", "--label", "keep-me")
if out, err := bdProxiedRun(t, bd, p.dir, "comment", wisp.ID, "pre-promote note"); err != nil {
t.Fatalf("bd comment: %v\n%s", err, out)
}
db := openProxiedDB(t, p)
// Outbound edge lives in the wisp plane while the issue is a wisp.
if _, err := db.Exec(
"INSERT INTO wisp_dependencies (id, issue_id, depends_on_issue_id, type, created_at, created_by) VALUES (UUID(), ?, ?, ?, NOW(), 'test')",
wisp.ID, target.ID, "blocks"); err != nil {
t.Fatalf("plant outbound wisp edge: %v", err)
}
// Inbound edge from a durable issue targets the wisp column.
if _, err := db.Exec(
"INSERT INTO dependencies (id, issue_id, depends_on_wisp_id, type, created_at, created_by) VALUES (UUID(), ?, ?, ?, NOW(), 'test')",
inbound.ID, wisp.ID, "blocks"); err != nil {
t.Fatalf("plant inbound edge: %v", err)
}
head := proxiedDoltHead(t, db)
stdout, stderr, err := bdProxiedRunBuffers(t, bd, p.dir, "promote", wisp.ID, "--reason", "worth keeping")
if err != nil {
t.Fatalf("bd promote: %v\nstdout:\n%s\nstderr:\n%s", err, stdout, stderr)
}
if !strings.Contains(stdout, "Promoted "+wisp.ID+" to permanent bead") {
t.Errorf("expected promote success line, got: %s", stdout)
}
// Two Dolt commits, one per role transaction: the move under the
// classic message, then the promotion comment under the comment's.
messages := readDoltLogMessagesSince(t, db, head)
sort.Strings(messages)
if want := []string{"bd: comment " + wisp.ID, "bd: promote " + wisp.ID}; !slices.Equal(messages, want) {
t.Errorf("commits since promote = %q, want %q", messages, want)
}
// The row moved planes in place: same id, flag cleared, type retained.
if n := countRows(t, db, "SELECT COUNT(*) FROM wisps WHERE id = ?", wisp.ID); n != 0 {
t.Errorf("expected wisps row gone after promote, found %d", n)
}
var ephemeral bool
var wispType string
if err := db.QueryRow("SELECT ephemeral, wisp_type FROM issues WHERE id = ?", wisp.ID).Scan(&ephemeral, &wispType); err != nil {
t.Fatalf("read promoted issues row: %v", err)
}
if ephemeral {
t.Error("expected promoted row non-ephemeral")
}
if wispType != "patrol" {
t.Errorf("wisp_type = %q, want patrol (retained)", wispType)
}
// Aux rows moved to the permanent tables and the wisp tables emptied.
if n := countRows(t, db, "SELECT COUNT(*) FROM labels WHERE issue_id = ? AND label = 'keep-me'", wisp.ID); n != 1 {
t.Errorf("expected label keep-me in labels, got %d", n)
}
if n := countRows(t, db, "SELECT COUNT(*) FROM wisp_labels WHERE issue_id = ?", wisp.ID); n != 0 {
t.Errorf("expected wisp_labels emptied, got %d", n)
}
if n := countRows(t, db, "SELECT COUNT(*) FROM dependencies WHERE issue_id = ? AND depends_on_issue_id = ?", wisp.ID, target.ID); n != 1 {
t.Errorf("expected outbound dep in dependencies, got %d", n)
}
if n := countRows(t, db, "SELECT COUNT(*) FROM wisp_dependencies WHERE issue_id = ?", wisp.ID); n != 0 {
t.Errorf("expected wisp_dependencies emptied, got %d", n)
}
if n := countRows(t, db, "SELECT COUNT(*) FROM events WHERE issue_id = ?", wisp.ID); n == 0 {
t.Error("expected events carried to events table")
}
if n := countRows(t, db, "SELECT COUNT(*) FROM wisp_events WHERE issue_id = ?", wisp.ID); n != 0 {
t.Errorf("expected wisp_events emptied, got %d", n)
}
// Inbound edge retargeted from the wisp column to the issue column.
if n := countRows(t, db, "SELECT COUNT(*) FROM dependencies WHERE issue_id = ? AND depends_on_issue_id = ? AND depends_on_wisp_id IS NULL", inbound.ID, wisp.ID); n != 1 {
t.Errorf("expected inbound edge retargeted to depends_on_issue_id, got %d", n)
}
// Comments preserved, promotion comment (with reason) appended, all
// in the permanent table.
if n := countRows(t, db, "SELECT COUNT(*) FROM wisp_comments WHERE issue_id = ?", wisp.ID); n != 0 {
t.Errorf("expected wisp_comments emptied, got %d", n)
}
if n := countRows(t, db, "SELECT COUNT(*) FROM comments WHERE issue_id = ? AND text = 'pre-promote note'", wisp.ID); n != 1 {
t.Errorf("expected pre-promote comment preserved, got %d", n)
}
if n := countRows(t, db, "SELECT COUNT(*) FROM comments WHERE issue_id = ? AND text = 'Promoted from Level 0: worth keeping'", wisp.ID); n != 1 {
t.Errorf("expected promotion comment with reason, got %d", n)
}
// Downstream contract: the promoted row is still returned by
// `bd list --include-infra --wisp-type patrol` (callers' -s open
// filters keep working because the default status is unchanged).
listed := bdProxiedListJSON(t, bd, p, "--include-infra", "--wisp-type", "patrol")
if !containsID(listed, wisp.ID) {
t.Errorf("expected promoted %s in list --include-infra --wisp-type patrol, got %d rows", wisp.ID, len(listed))
}
})
// The move carries the child counter, so a promoted wisp parent's next
// child is minted past the children it had as a wisp. The old engine left
// the counter in wisp_child_counters, and the next `bd create --parent`
// minted <parent>.1 again and failed on the wisp child holding that id.
t.Run("promoted_parent_keeps_its_child_counter", func(t *testing.T) {
t.Parallel()
p := newSharedProxiedProject(t, bd, "pmc")
parent := bdProxiedCreate(t, bd, p.dir, "Promoted wisp parent", "--ephemeral")
for i := 1; i <= 2; i++ {
child := bdProxiedCreate(t, bd, p.dir, fmt.Sprintf("Wisp child %d", i), "--ephemeral", "--parent", parent.ID)
if want := fmt.Sprintf("%s.%d", parent.ID, i); child.ID != want {
t.Fatalf("wisp child %d is %s, want %s", i, child.ID, want)
}
}
if out, err := bdProxiedRun(t, bd, p.dir, "promote", parent.ID); err != nil {
t.Fatalf("bd promote: %v\n%s", err, out)
}
db := openProxiedDB(t, p)
if n := countRows(t, db, "SELECT COUNT(*) FROM child_counters WHERE parent_id = ? AND last_child = 2", parent.ID); n != 1 {
t.Errorf("expected the counter (last_child 2) in child_counters, got %d rows", n)
}
if n := countRows(t, db, "SELECT COUNT(*) FROM wisp_child_counters WHERE parent_id = ?", parent.ID); n != 0 {
t.Errorf("expected wisp_child_counters emptied, got %d", n)
}
next := bdProxiedCreate(t, bd, p.dir, "Child after promote", "--parent", parent.ID)
if want := parent.ID + ".3"; next.ID != want {
t.Errorf("next child of the promoted parent is %s, want %s", next.ID, want)
}
})
// on_update fires twice, from the notifying provider: once for the move
// and once for the promotion comment. The old engine fired it only for
// the comment.
t.Run("hooks_fire_on_update_for_the_move_and_the_comment", func(t *testing.T) {
t.Parallel()
if runtime.GOOS == "windows" {
t.Skip("hook script form is POSIX shell")
}
p := newSharedProxiedProject(t, bd, "pmh")
wisp := bdProxiedCreate(t, bd, p.dir, "Promote hook wisp", "--ephemeral")
// Planted after the setup, so every line it logs is the promote's.
hookLog := plantCountingHook(t, p.beadsDir, "on_update")
if out, err := bdProxiedRun(t, bd, p.dir, "promote", wisp.ID, "--reason", "hooked"); err != nil {
t.Fatalf("bd promote: %v\n%s", err, out)
}
waitForHookLines(t, hookLog, wisp.ID, 2)
})
t.Run("json_shape_matches_classic", func(t *testing.T) {
t.Parallel()
p := newSharedProxiedProject(t, bd, "pmj")
wisp := bdProxiedCreate(t, bd, p.dir, "Promote JSON wisp",
"--ephemeral", "--wisp-type", "heartbeat", "--label", "shaped")
out, err := bdProxiedRun(t, bd, p.dir, "promote", wisp.ID, "--json")
if err != nil {
t.Fatalf("bd promote --json: %v\n%s", err, out)
}
var m map[string]interface{}
if err := json.Unmarshal(out, &m); err != nil {
t.Fatalf("parse promote JSON: %v\n%s", err, out)
}
// Classic prints the re-read issue object: id preserved, ephemeral
// cleared (omitempty ⇒ absent), wisp_type retained, labels included.
if m["id"] != wisp.ID {
t.Errorf("expected id=%s, got %v", wisp.ID, m["id"])
}
if eph, ok := m["ephemeral"].(bool); ok && eph {
t.Error("expected promoted JSON not ephemeral")
}
if m["wisp_type"] != "heartbeat" {
t.Errorf("expected wisp_type=heartbeat in JSON, got %v", m["wisp_type"])
}
labels, _ := m["labels"].([]interface{})
foundLabel := false
for _, l := range labels {
if l == "shaped" {
foundLabel = true
}
}
if !foundLabel {
t.Errorf("expected label 'shaped' in promote --json output, got %v", m["labels"])
}
})
t.Run("one_way_purge_no_longer_reclaims", func(t *testing.T) {
t.Parallel()
p := newSharedProxiedProject(t, bd, "pmp")
promoted := bdProxiedCreate(t, bd, p.dir, "Promoted survives purge", "--ephemeral")
control := bdProxiedCreate(t, bd, p.dir, "Control wisp purged", "--ephemeral")
if out, err := bdProxiedRun(t, bd, p.dir, "promote", promoted.ID); err != nil {
t.Fatalf("bd promote: %v\n%s", err, out)
}
for _, id := range []string{promoted.ID, control.ID} {
if out, err := bdProxiedRun(t, bd, p.dir, "close", id); err != nil {
t.Fatalf("bd close %s: %v\n%s", id, err, out)
}
}
if out, err := bdProxiedRun(t, bd, p.dir, "purge", "--force"); err != nil {
t.Fatalf("bd purge --force: %v\n%s", err, out)
}
db := openProxiedDB(t, p)
if n := countRows(t, db, "SELECT COUNT(*) FROM wisps WHERE id = ?", control.ID); n != 0 {
t.Errorf("expected control wisp %s purged (proves purge ran), got %d", control.ID, n)
}
if n := countRows(t, db, "SELECT COUNT(*) FROM issues WHERE id = ?", promoted.ID); n != 1 {
t.Errorf("expected promoted %s to survive purge, got %d rows", promoted.ID, n)
}
})
t.Run("non_wisp_and_missing_id_fail", func(t *testing.T) {
t.Parallel()
p := newSharedProxiedProject(t, bd, "pmf")
durable := bdProxiedCreate(t, bd, p.dir, "Already permanent", "--type", "task")
out, err := bdProxiedRun(t, bd, p.dir, "promote", durable.ID)
if err == nil {
t.Fatalf("expected promote of non-wisp to fail, got:\n%s", out)
}
if !strings.Contains(string(out), "is not a wisp (already persistent)") {
t.Errorf("expected classic non-wisp error text, got: %s", out)
}
out, err = bdProxiedRun(t, bd, p.dir, "promote", "pmf-nope999")
if err == nil {
t.Fatalf("expected promote of missing id to fail, got:\n%s", out)
}
if !strings.Contains(string(out), "no issue found matching") {
t.Errorf("expected classic resolve-failure error, got: %s", out)
}
// A promoted bead cannot be promoted twice (it is no longer a wisp).
wisp := bdProxiedCreate(t, bd, p.dir, "Promote twice", "--ephemeral")
if out, err := bdProxiedRun(t, bd, p.dir, "promote", wisp.ID); err != nil {
t.Fatalf("bd promote: %v\n%s", err, out)
}
out, err = bdProxiedRun(t, bd, p.dir, "promote", wisp.ID)
if err == nil {
t.Fatalf("expected second promote to fail, got:\n%s", out)
}
if !strings.Contains(string(out), "is not a wisp (already persistent)") {
t.Errorf("expected classic already-persistent error text, got: %s", out)
}
})
}
func countRows(t *testing.T, db *sql.DB, query string, args ...interface{}) int {
t.Helper()
var n int
if err := db.QueryRow(query, args...).Scan(&n); err != nil {
t.Fatalf("count query %q: %v", query, err)
}
return n
}