beads/backend/http/e2e_promote_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

115 lines
4.1 KiB
Go

//go:build cgo
package bdhttp_test
import (
"encoding/json"
"strings"
"testing"
)
// TestE2E_PromoteOverHTTP runs `bd promote <wisp> --reason ...` — the shape
// MC's PR-intake formula (mol-normalized-issue-pr-v1) issues, corpus shape
// mc-promote — through the real `bd` binary against an in-process `bd serve`
// (slice S21b).
//
// The CLI runs issueops.Promote, the entry the direct route runs too: one
// updateIssue carrying `patch.persistence: persistent` (the role's plane move,
// in one server transaction) and then the promotion comment. Against a server
// that does not advertise issues.update.persistence — the MC server's
// handshake shape — the client refuses BEFORE the dial, naming the token, and
// nothing is written.
func TestE2E_PromoteOverHTTP(t *testing.T) {
skipUnlessEmbeddedDolt(t)
bin := buildBD(t)
addr := startE2EServer(t)
t.Run("advertised", func(t *testing.T) {
proxyAddr, counter := startCountingProxy(t, addr)
f := newHTTPFixture(t, bin, proxyAddr)
wisp := f.create("wisp to keep", "--ephemeral", "-l", "keep-me")
if !showJSONBool(t, f.mustRun(nil, "show", wisp, "--json").stdout, "ephemeral") {
t.Fatalf("created %s is not ephemeral; nothing to promote", wisp)
}
counter.reset()
r := f.mustRun(nil, "promote", wisp, "--reason", "keep it")
if !strings.Contains(r.stdout, "Promoted "+wisp+" to permanent bead") {
t.Errorf("bd promote output = %q, want the promotion line", r.stdout)
}
if strings.Contains(r.stderr, "Warning") {
t.Errorf("bd promote warned: %s", r.stderr)
}
patches := 0
for _, p := range counter.snapshot() {
if strings.HasPrefix(p, "PATCH /v0/beads/issues/") {
patches++
}
}
if patches != 1 {
t.Errorf("bd promote sent %d updateIssue requests, want exactly one: %v", patches, counter.snapshot())
}
show := f.mustRun(nil, "show", wisp, "--json").stdout
if showJSONBool(t, show, "ephemeral") {
t.Errorf("%s is still ephemeral after bd promote: %s", wisp, show)
}
if !strings.Contains(show, "keep-me") {
t.Errorf("%s lost its label across the promotion: %s", wisp, show)
}
comments := f.mustRun(nil, "comments", wisp, "--json").stdout
if !strings.Contains(comments, "Promoted from Level 0: keep it") {
t.Errorf("%s carries no promotion comment: %s", wisp, comments)
}
// A durable row is refused with the sentence bd promote always printed,
// and so is a second promotion of the same row.
again := f.run(nil, "promote", wisp)
if again.code == 0 || !strings.Contains(again.stderr, "is not a wisp (already persistent)") {
t.Errorf("re-promote: exit %d stderr=%s, want the not-a-wisp refusal", again.code, again.stderr)
}
missing := f.run(nil, "promote", "e2e-absent-wisp9")
if missing.code == 0 {
t.Errorf("promote of an absent id exited 0: %s", missing.stdout)
}
})
t.Run("MC server mask", func(t *testing.T) {
proxyAddr, counter := startMaskingProxy(t, addr, mcContextMask)
f := newHTTPFixture(t, bin, proxyAddr)
wisp := f.create("wisp the old server cannot promote", "--ephemeral")
counter.reset()
r := f.run(nil, "promote", wisp, "--reason", "keep it")
if r.code == 0 {
t.Fatalf("bd promote against a server without issues.update.persistence exited 0: %s", r.stdout)
}
if !strings.Contains(r.stderr, "issues.update.persistence") {
t.Errorf("refusal does not name the missing capability: %s", r.stderr)
}
for _, p := range counter.snapshot() {
if !strings.HasPrefix(p, "GET ") {
t.Errorf("a refused promote wrote %s; the refusal must come before any write", p)
}
}
if !showJSONBool(t, f.mustRun(nil, "show", wisp, "--json").stdout, "ephemeral") {
t.Errorf("%s left the wisp plane though the promote was refused", wisp)
}
})
}
// showJSONBool reads a boolean member of `bd show --json`'s first row; an
// absent member (omitempty) reads false.
func showJSONBool(t *testing.T, out, field string) bool {
t.Helper()
var generic any
if err := json.Unmarshal([]byte(strings.TrimSpace(out)), &generic); err != nil {
t.Fatalf("parse bd show --json: %v\n%s", err, out)
}
if rows, ok := generic.([]any); ok && len(rows) > 0 {
generic = rows[0]
}
row, _ := generic.(map[string]any)
b, _ := row[field].(bool)
return b
}