From eaed71fbba485418b2e8974fa7d17c0ef037190a Mon Sep 17 00:00:00 2001 From: Julian Knutsen Date: Wed, 14 Oct 2026 05:51:53 +0000 Subject: [PATCH] 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 --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 " 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 * 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 " and "bd: comment " (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 " 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 --------- Co-authored-by: Claude Opus 5.5 --- .github/scripts/embedded-cmd-test-shards.txt | 1 + CHANGELOG.md | 34 +++ .../conformance/lifecycle_update_contract.go | 93 +++++++- backend/conformance/reader_contract.go | 6 +- backend/conformance/role_bundle_cases.go | 2 + backend/http/BUILD.bazel | 1 + backend/http/corpus/testdata/corpus.yaml | 2 +- backend/http/e2e_promote_test.go | 115 ++++++++++ cmd/bd/export_source.go | 2 +- cmd/bd/promote.go | 119 ++++++---- cmd/bd/promote_embedded_test.go | 105 +++++++++ cmd/bd/promote_proxied_integration_test.go | 79 +++++-- cmd/bd/promote_proxied_server.go | 105 ++++----- engdocs/design/http-divergence-ledger.md | 2 +- internal/httpapi/apigen/types.gen.go | 13 +- internal/httpapi/routes.go | 12 +- internal/httpapi/server_test.go | 2 +- internal/httpapi/spec/openapi.v0.yaml | 39 +++- internal/httpapi/update.go | 14 +- internal/httpapi/update_test.go | 37 +++- .../httpapi/wireshape/testdata/golden.json | 6 + internal/httpclient/BUILD.bazel | 1 + internal/httpclient/batchapplier.go | 17 +- internal/httpclient/encode/ledger.go | 4 +- internal/httpclient/lifecycle.go | 38 +++- .../httpclient/served_claim_lifecycle_test.go | 37 ++-- .../httpclient/update_persistence_test.go | 85 +++++++ internal/httpclient/wire/handshake.go | 10 +- internal/httpclient/wire/vocabulary_test.go | 4 +- internal/httpclient/write_ledger_test.go | 6 + internal/httpclient/write_roles_test.go | 4 +- internal/storage/dolt/ephemeral_routing.go | 3 +- .../dolt/issue_operations_persistence_test.go | 37 +++- .../dolt/lifecycle_update_contract_test.go | 6 + internal/storage/domain/db/issue.go | 11 +- internal/storage/domain/issue.go | 6 +- .../lifecycle_update_contract_test.go | 6 + internal/storage/issueops/persistence.go | 15 +- .../uow/lifecycle_update_contract_test.go | 6 + internal/storage/uow/notifying.go | 15 +- internal/storage/uow/notifying_parity_test.go | 5 +- internal/types/storage_class_test.go | 21 +- internal/types/types.go | 11 +- issueops/BUILD.bazel | 2 + issueops/promote.go | 118 ++++++++++ issueops/promote_test.go | 207 ++++++++++++++++++ test/conformance/e2e_test.go | 2 +- 47 files changed, 1275 insertions(+), 191 deletions(-) create mode 100644 backend/http/e2e_promote_test.go create mode 100644 internal/httpclient/update_persistence_test.go create mode 100644 issueops/promote.go create mode 100644 issueops/promote_test.go diff --git a/.github/scripts/embedded-cmd-test-shards.txt b/.github/scripts/embedded-cmd-test-shards.txt index ed764b6b4..ce1179ad6 100644 --- a/.github/scripts/embedded-cmd-test-shards.txt +++ b/.github/scripts/embedded-cmd-test-shards.txt @@ -151,6 +151,7 @@ 100 63 TestEmbeddedDepAndLinkBatchAutoCommitDoesNotAdvanceHead 100 64 TestEmbeddedGateWaiterCheckLifecycle +100 64 TestEmbeddedPromoteMovesAWispParent 100 65 TestEmbeddedIfRevisionPreflightGoneIsPreconditionFailedOnEveryVerb 100 65 TestEmbeddedSupersede diff --git a/CHANGELOG.md b/CHANGELOG.md index 73857d206..241e92c95 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,40 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- `bd promote` works over a connected HTTP workspace (S21b). Its one library + entry, `issueops.Promote(ctx, PromoteRoles{Reader, Lifecycle, Commenter}, + PromoteRequest)`, reads the row, refuses one that is not a wisp + (`*issueops.NotAWispError`, the sentence `bd promote` always printed), moves + it with ONE `Lifecycle.Update` whose patch is `Persistence = persistent` + (labels, dependencies, events, comments and the child counter move with it + in the role's transaction), then records the promotion comment. The direct + and proxied-server routes run it over their own roles, so a local promote + now makes the same plane move `bd update --persistent` makes, honoring + `dolt.auto-commit`. That changes five things a script can see on those + routes: the workspace's `on_update` hook fires twice, once for the move and + once for the comment (the direct route never fired it, the proxied-server + route fired it once); the promotion comment is a row `bd comments` lists + (the direct route recorded only a `commented` event); a promoted parent + keeps its child counter, so its next `bd create --parent` mints the number + after its wisp children's instead of failing with + `issue already exists: .1`; a promotion records two Dolt + commits, `bd: promote ` for the move and `bd: comment ` for the + comment (an embedded workspace recorded one, `bd: promote (auto-commit)`, + and the proxied-server route one, `bd: promote `); and a promote that + loses a race to a concurrent one fails with the not-a-wisp sentence instead + of `promoting : wisp not found`. A comment that cannot + be written leaves the promotion standing behind a warning on every route; + the proxied-server route used to roll the promotion back. `bd serve` + publishes the move as `patch.persistence` on `PATCH /v0/beads/issues/{id}` + behind the new `issues.update.persistence` capability (additive; + `wire_revision` is unchanged), which also carries `bd update --persistent`, + `--ephemeral` and `--no-history` over HTTP. Against a server without the + token the client refuses before the dial, naming it; nothing is written. A + move the workspace refuses (an `unversioned`-class row asked for + `--ephemeral` or `--no-history`, or a demotion of a row with retained + snapshots) matches `ErrValidation` on every route: `bd serve` answers it + `400 invalid_argument`, and the local refusal gains a `validation failed: ` + prefix. - `issueops.LeaseReclaimer`, the stale-lease sweep behind `bd reclaim`, is a role on every leg (dolt, embedded dolt, the unit-of-work provider and the HTTP client), and `bd serve` publishes it as `POST /v0/beads/issues:reclaim` diff --git a/backend/conformance/lifecycle_update_contract.go b/backend/conformance/lifecycle_update_contract.go index d58cc0536..ae5e0a420 100644 --- a/backend/conformance/lifecycle_update_contract.go +++ b/backend/conformance/lifecycle_update_contract.go @@ -6,6 +6,7 @@ import ( "errors" "fmt" "reflect" + "slices" "sort" "sync" "testing" @@ -1919,10 +1920,10 @@ func RunLifecycleUpdateParentIDReplacesEveryParent(t *testing.T, ctx context.Con // RunLifecycleUpdatePersistentPreservesUnversionedClass pins the half of the // Persistence clause nobody else asserts: "Persistent preserves an existing -// durable unversioned class" (issueops/issueops.go:135-136). The refusal beside -// it — an unversioned row cannot be demoted to a wisp mode — is pinned -// elsewhere; this clause says the legal direction is a no-op that does NOT -// normalize the row into versioned storage. +// durable unversioned class" (issueops/issueops.go:149). The refusal beside +// it — an unversioned row cannot be demoted to a wisp mode — is +// RunLifecycleUpdateWispModesRefuseAnUnversionedRow; this clause says the legal +// direction is a no-op that does NOT normalize the row into versioned storage. // // WHAT A PERSISTENCE RESTATEMENT MUST NOT DO is where the two observations come // in. A persistence MOVE deletes the row from one plane and re-inserts it into @@ -1963,6 +1964,90 @@ func RunLifecycleUpdatePersistentPreservesUnversionedClass(t *testing.T, ctx con assertLifecycleUpdateWispAbsent(t, ctx, fixture, id, "after the persistent restatement") } +// RunLifecycleUpdateWispModesRefuseAnUnversionedRow pins the refusal beside +// that clause: Ephemeral and NoHistory "select wisp retention modes, never +// durable unversioned storage" (issueops/issueops.go:150-151), so an +// unversioned row asked for either is refused. The refusal is the request's, +// a deterministic validation failure, so it matches ErrValidation on every +// leg — over http that is the 400 naming the patch rather than a 500 that +// drops the reason and alerts the operator — and it leaves the row where it +// was: durable, still unversioned, and absent from the wisp plane. +func RunLifecycleUpdateWispModesRefuseAnUnversionedRow(t *testing.T, ctx context.Context, fixture LifecycleUpdateFixture) { + t.Helper() + + id := fixture.IssuePrefix + "-lup-unversioned-wisp" + seeded := lifecycleUpdateIssue(id) + seeded.StorageClass = types.StorageClassUnversioned + seedLifecycleUpdateIssue(t, ctx, fixture, seeded) + + for _, mode := range []publicops.PersistenceMode{publicops.PersistenceModeEphemeral, publicops.PersistenceModeNoHistory} { + label := "after the refused " + string(mode) + " move" + before := lifecycleUpdateRow(t, ctx, fixture, id) + if _, err := fixture.Lifecycle.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: id, Patch: publicops.IssuePatch{ + Persistence: publicops.Field[publicops.PersistenceMode]{Set: true, Value: mode}, + }}); !errors.Is(err, storage.ErrValidation) { + t.Fatalf("move unversioned %s to %s: error = %v, want ErrValidation", id, mode, err) + } + assertLifecycleUpdateRowUnchanged(t, ctx, fixture, id, label, before) + after := lifecycleUpdateRow(t, ctx, fixture, id) + if after.Ephemeral || after.NoHistory || after.StorageClass != types.StorageClassUnversioned { + t.Errorf("%s %s = {ephemeral %v, no-history %v, class %q}, want the durable unversioned row it was", + id, label, after.Ephemeral, after.NoHistory, after.StorageClass) + } + assertLifecycleUpdateWispAbsent(t, ctx, fixture, id, label) + } +} + +// RunLifecycleUpdatePersistentPromotesAWisp pins the move `bd promote` makes +// (issueops.Promote): Persistence = persistent on an ephemeral wisp is a +// MUTATION that leaves the row on the durable plane under the same id, with +// its labels carried across and nothing left behind on the wisp plane. A +// second identical request is the no-op the "same current mode" clause +// promises, which is how Promote tells a lost race from a promotion. +func RunLifecycleUpdatePersistentPromotesAWisp(t *testing.T, ctx context.Context, fixture LifecycleUpdateFixture) { + t.Helper() + if fixture.CreateWisp == nil { + t.Skip("fixture has no CreateWisp: this backend has no wisp plane to promote from") + } + + id := fixture.IssuePrefix + "-lup-promote" + seedLifecycleUpdateWisp(t, ctx, fixture, lifecycleUpdateIssue(id, "keep-me")) + if got := lifecycleUpdateRow(t, ctx, fixture, id); !got.Ephemeral { + t.Fatalf("seeded %s is not ephemeral; the case has nothing to promote", id) + } + + promote := publicops.UpdateRequest{Actor: "writer", IssueID: id, Patch: publicops.IssuePatch{ + Persistence: publicops.Field[publicops.PersistenceMode]{Set: true, Value: publicops.PersistenceModePersistent}, + }} + promoted, err := fixture.Lifecycle.Update(ctx, promote) + if err != nil { + t.Fatalf("promote %s: %v", id, err) + } + if !promoted.Changed { + t.Errorf("promoting wisp %s reported Changed = false, want a mutation", id) + } + if promoted.Issue == nil || promoted.Issue.ID != id || promoted.Issue.Ephemeral { + t.Errorf("promote result issue = %+v, want %s on the durable plane", promoted.Issue, id) + } + + after := lifecycleUpdateRow(t, ctx, fixture, id) + if after.Ephemeral || after.NoHistory { + t.Errorf("%s came back {ephemeral %v, no-history %v} after the promotion, want a durable-plane row", id, after.Ephemeral, after.NoHistory) + } + if !slices.Contains(after.Labels, "keep-me") { + t.Errorf("%s labels after the promotion = %v, want the wisp's label carried across", id, after.Labels) + } + assertLifecycleUpdateWispAbsent(t, ctx, fixture, id, "after the promotion") + + again, err := fixture.Lifecycle.Update(ctx, promote) + if err != nil { + t.Fatalf("re-promote %s: %v", id, err) + } + if again.Changed { + t.Errorf("re-promoting durable %s reported Changed = true, want the same-mode no-op", id) + } +} + // RunLifecycleUpdateProvenanceLabelsHistory pins UpdateRequest.Provenance // against the history the backend actually writes // (issueops/issueops.go:261-270): the entry reads as the caller's own string, diff --git a/backend/conformance/reader_contract.go b/backend/conformance/reader_contract.go index d19fea047..2f93f818c 100644 --- a/backend/conformance/reader_contract.go +++ b/backend/conformance/reader_contract.go @@ -113,9 +113,9 @@ type ReaderFixture struct { AddDependency func(context.Context, *types.Dependency, string) error // AddComment puts one comment on a durable issue. AddComment func(ctx context.Context, issueID, author, text string) error - // PromoteWisp moves a seeded wisp into the durable plane, as `bd promote` - // does. It is the only way to seed a DURABLE row of an infra type: creating - // one routes it to the wisps plane on every backend. + // PromoteWisp moves a seeded wisp into the durable plane. It is the only + // way to seed a DURABLE row of an infra type: creating one routes it to the + // wisps plane on every backend. PromoteWisp func(ctx context.Context, id, actor string) error } diff --git a/backend/conformance/role_bundle_cases.go b/backend/conformance/role_bundle_cases.go index 3453eedaa..caaa5dc7a 100644 --- a/backend/conformance/role_bundle_cases.go +++ b/backend/conformance/role_bundle_cases.go @@ -488,6 +488,8 @@ var roleContractCases = []roleContract{ RunLifecycleUpdateParentIDReplacesTheParentEdge, RunLifecycleUpdateParentIDReplacesEveryParent, RunLifecycleUpdatePersistentPreservesUnversionedClass, + RunLifecycleUpdateWispModesRefuseAnUnversionedRow, + RunLifecycleUpdatePersistentPromotesAWisp, RunLifecycleUpdateProvenanceLabelsHistory, RunLifecycleUpdateRefusesATemplate, RunLifecycleUpdateAllowTemplateEditsATemplate, diff --git a/backend/http/BUILD.bazel b/backend/http/BUILD.bazel index 045b68860..c2eaf0468 100644 --- a/backend/http/BUILD.bazel +++ b/backend/http/BUILD.bazel @@ -35,6 +35,7 @@ go_test( "e2e_export_test.go", "e2e_list_filters_test.go", "e2e_mol_test.go", + "e2e_promote_test.go", "e2e_recompute_blocked_test.go", "e2e_remote_roles_test.go", "e2e_search_test.go", diff --git a/backend/http/corpus/testdata/corpus.yaml b/backend/http/corpus/testdata/corpus.yaml index 9c3d2e485..44bf8e392 100644 --- a/backend/http/corpus/testdata/corpus.yaml +++ b/backend/http/corpus/testdata/corpus.yaml @@ -685,7 +685,7 @@ shapes: source: mc mol-normalized-issue-pr-v1 (promote --reason) args: [promote, e2e-wisp-p, --reason, "keep it"] compare: exit - pending: {slice: "S21b", reason: "promote has no served operation (B3 #16): the http Store stubs PromoteFromEphemeral, updateIssue's patch does not publish persistence (W-IssuePatch.Persistence), and no server has a promote route; it needs a new additive capability, then SRV-1"} + pending: {slice: "SRV-1", reason: "the reference server does not advertise issues.update.persistence, so the client refuses at its capability preflight"} - id: mc-mol-burn source: mc review fixtures (mol burn --force) args: [mol, burn, e2e-wisp-m, --force] diff --git a/backend/http/e2e_promote_test.go b/backend/http/e2e_promote_test.go new file mode 100644 index 000000000..0c5062c77 --- /dev/null +++ b/backend/http/e2e_promote_test.go @@ -0,0 +1,115 @@ +//go:build cgo + +package bdhttp_test + +import ( + "encoding/json" + "strings" + "testing" +) + +// TestE2E_PromoteOverHTTP runs `bd promote --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 +} diff --git a/cmd/bd/export_source.go b/cmd/bd/export_source.go index 8b28b6eaa..d51666c69 100644 --- a/cmd/bd/export_source.go +++ b/cmd/bd/export_source.go @@ -295,7 +295,7 @@ func (s *uowExportSource) LoadExportRelations(ctx context.Context, issues []*typ // The wisp_labels / wisp_comments rows of a wisp are keyed by an issue_id // that lives in the WISPS table (promotion moves them to the durable - // tables, issueops.PromoteFromEphemeralInTx), so the three wisp readers + // tables, issueops.MoveIssuePersistenceInTx), so the three wisp readers // below only need the ids that are wisps right now. Handing them the // whole workspace was pure waste — on a 19k-issue rig with no wisps it // was three 19k-placeholder statements answering nothing (wy-237yfi). diff --git a/cmd/bd/promote.go b/cmd/bd/promote.go index 44a42eea0..275fe0647 100644 --- a/cmd/bd/promote.go +++ b/cmd/bd/promote.go @@ -1,6 +1,7 @@ package main import ( + "context" "errors" "fmt" "os" @@ -11,19 +12,9 @@ import ( "github.com/steveyegge/beads/internal/types" "github.com/steveyegge/beads/internal/ui" "github.com/steveyegge/beads/internal/utils" + "github.com/steveyegge/beads/issueops" ) -// promotionComment is the audit comment both routes record on the promoted -// bead. Shared by the classic and proxied-server paths so the text cannot -// drift. -func promotionComment(reason string) string { - comment := "Promoted from Level 0" - if reason != "" { - comment += ": " + reason - } - return comment -} - // printPromoteResult renders the `bd promote` success output. updated is the // best-effort post-promote re-read used only by --json (it may be nil, in // which case the JSON path prints nothing, matching the classic behavior). @@ -86,39 +77,93 @@ Examples: return HandleErrorRespectJSON("resolving %s: %v", id, err) } - issue, err := store.GetIssue(ctx, fullID) + promoted, err := promoteDirect(ctx, store, fullID, reason) if err != nil { - if errors.Is(err, storage.ErrNotFound) { - return HandleErrorRespectJSON("issue %s not found", fullID) - } - return HandleErrorRespectJSON("getting issue %s: %v", fullID, err) + return promoteFailure(fullID, err) } - if !issue.Ephemeral { - return HandleErrorRespectJSON("%s is not a wisp (already persistent)", fullID) - } - - if err := store.PromoteFromEphemeral(ctx, fullID, currentActor()); err != nil { - return HandleErrorRespectJSON("promoting %s: %v", fullID, err) - } - - // Add promotion comment (issue is now in permanent table, AddComment routes correctly - // via GetIssue fallback) - if err := store.AddComment(ctx, fullID, currentActor(), promotionComment(reason)); err != nil { - fmt.Fprintf(os.Stderr, "Warning: failed to add promotion comment to %s: %v\n", fullID, err) - } - - commandDidWrite.Store(true) - - var updated *types.Issue - if jsonOutput { - updated, _ = store.GetIssue(ctx, fullID) - } - return printPromoteResult(fullID, updated) + return reportPromotion(fullID, promoted, func() *types.Issue { + updated, _ := store.GetIssue(ctx, fullID) + return updated + }) }, } +// promoteFailure maps a promotion that did not land to the command's error: +// the typed refusal for a row that is not a wisp, the classic sentence for a +// row that is gone, and the id for anything else. Shared by the direct and +// proxied-server routes, which both run issueops.Promote, so the error +// contract cannot drift. +func promoteFailure(fullID string, err error) error { + var notWisp *issueops.NotAWispError + switch { + case errors.As(err, ¬Wisp): + return HandleErrorRespectJSON("%v", err) + case errors.Is(err, storage.ErrNotFound): + return HandleErrorRespectJSON("issue %s not found", fullID) + } + return HandleErrorRespectJSON("promoting %s: %v", fullID, err) +} + +// reportPromotion reports a promotion that landed, for both routes: a comment +// that could not be written is a warning (the move stands, as +// issueops.PromoteResult.CommentErr says), then the success output. reread is +// the best-effort --json re-read, called only under --json. +func reportPromotion(fullID string, promoted issueops.PromoteResult, reread func() *types.Issue) error { + if promoted.CommentErr != nil { + fmt.Fprintf(os.Stderr, "Warning: failed to add promotion comment to %s: %v\n", fullID, promoted.CommentErr) + } + + commandDidWrite.Store(true) + + var updated *types.Issue + if jsonOutput { + updated = reread() + } + return printPromoteResult(fullID, updated) +} + func init() { promoteCmd.Flags().StringP("reason", "r", "", "Reason for promotion") promoteCmd.ValidArgsFunction = issueIDCompletion rootCmd.AddCommand(promoteCmd) } + +// promoteDirect runs `bd promote` on the direct route through +// issueops.Promote, the one library entry every route shares (the +// proxied-server route runs it over the provider's roles, +// runPromoteProxiedServer), over the store's own role accessors (so its +// decorator stack — hooks, telemetry — wraps the move and the comment). On a +// connected http workspace the same entry dials updateIssue with +// `patch.persistence`, and a server without the issues.update.persistence +// capability refuses before the dial, naming it. +// +// The history label is the classic "bd: promote " where the store can +// carry a caller label, and the server's own where it cannot (S6d's rule, +// remote_backend.go). +func promoteDirect(ctx context.Context, st storage.DoltStorage, fullID, reason string) (issueops.PromoteResult, error) { + opsCtx, err := issueOpsContext(ctx) + if err != nil { + return issueops.PromoteResult{}, err + } + reader, err := st.IssueReader() + if err != nil { + return issueops.PromoteResult{}, err + } + lifecycle, err := writeOps(st) + if err != nil { + return issueops.PromoteResult{}, err + } + commenter, err := st.Commenter() + if err != nil { + return issueops.PromoteResult{}, err + } + provenance := "" + if storeCarriesCallerAttribution(st) { + provenance = "bd: promote " + fullID + } + return issueops.Promote(opsCtx, issueops.PromoteRoles{ + Reader: reader, Lifecycle: lifecycle, Commenter: commenter, + }, issueops.PromoteRequest{ + Actor: currentActor(), IssueID: fullID, Reason: reason, Provenance: provenance, + }) +} diff --git a/cmd/bd/promote_embedded_test.go b/cmd/bd/promote_embedded_test.go index b93d3d9cf..4c781779d 100644 --- a/cmd/bd/promote_embedded_test.go +++ b/cmd/bd/promote_embedded_test.go @@ -7,9 +7,11 @@ import ( "fmt" "os" "os/exec" + "path/filepath" "strings" "sync" "testing" + "time" ) // bdPromote runs "bd promote" with the given args and returns stdout. @@ -40,6 +42,49 @@ func bdPromoteFail(t *testing.T, bd, dir string, args ...string) string { return string(out) } +// plantCountingHook installs the workspace hook name as a script that appends +// its issue id ($1) to a log, one line per firing, and returns the log's path. +func plantCountingHook(t *testing.T, beadsDir, name string) string { + t.Helper() + hookLog := filepath.Join(t.TempDir(), name+".log") + hooksDir := filepath.Join(beadsDir, "hooks") + if err := os.MkdirAll(hooksDir, 0o755); err != nil { + t.Fatalf("mkdir hooks: %v", err) + } + script := "#!/bin/sh\necho \"$1\" >> " + shellQuote(hookLog) + "\n" + if err := os.WriteFile(filepath.Join(hooksDir, name), []byte(script), 0o755); err != nil { //nolint:gosec // G306: a hook must be executable to run at all + t.Fatalf("plant %s: %v", name, err) + } + return hookLog +} + +// waitForHookLines polls a plantCountingHook log until it names id want times. +// The command has returned by then, and a command waits for the hooks it +// fired before it exits, so a count past want is a hook that fired too often. +func waitForHookLines(t *testing.T, hookLog, id string, want int) { + t.Helper() + deadline := time.Now().Add(15 * time.Second) + for { + data, _ := os.ReadFile(hookLog) // #nosec G304 -- this test's own temp file + got := 0 + for _, line := range strings.Fields(string(data)) { + if line == id { + got++ + } + } + if got > want { + t.Fatalf("hook fired %d times for %s, want %d; log:\n%s", got, id, want, data) + } + if got == want { + return + } + if time.Now().After(deadline) { + t.Fatalf("hook fired %d times for %s, want %d; log:\n%s", got, id, want, data) + } + time.Sleep(50 * time.Millisecond) + } +} + func TestEmbeddedPromoteCLI(t *testing.T) { if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" { t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded dolt integration tests") @@ -153,6 +198,66 @@ func TestEmbeddedPromoteCLI(t *testing.T) { }) } +// TestEmbeddedPromoteMovesAWispParent pins what the direct route's +// persistence move carries for a wisp with children, a dependency and a +// comment. The dependency and the comment reach the durable tables, the +// children keep their parent, and the child counter carries, so the next +// `bd create --parent` mints .3 rather than colliding with the wisp child .1. +// `bd comments` lists the promotion reason, and on_update fires twice: once +// for the move and once for the promotion comment. +func TestEmbeddedPromoteMovesAWispParent(t *testing.T) { + if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" { + t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded dolt integration tests") + } + t.Parallel() + + bd := buildEmbeddedBD(t) + dir, beadsDir, _ := bdInit(t, bd, "--prefix", "pw") + + target := bdCreate(t, bd, dir, "Promote dep target", "--type", "task") + parent := bdCreate(t, bd, dir, "Promoted wisp parent", "--ephemeral") + var children []string + for i := 1; i <= 2; i++ { + child := bdCreate(t, bd, 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) + } + children = append(children, child.ID) + } + bdDepAdd(t, bd, dir, parent.ID, target.ID) + bdComment(t, bd, dir, parent.ID, "pre-promote note") + + // Planted after the setup, so every line it logs is the promote's. + hookLog := plantCountingHook(t, beadsDir, "on_update") + bdPromote(t, bd, dir, parent.ID, "--reason", "worth keeping") + waitForHookLines(t, hookLog, parent.ID, 2) + + if got := bdShow(t, bd, dir, parent.ID); got.Ephemeral { + t.Errorf("%s still ephemeral after promote", parent.ID) + } + assertDepExists(t, beadsDir, "pw", parent.ID, target.ID) + for _, id := range children { + var shown struct { + Parent *string `json:"parent"` + } + if err := json.Unmarshal(parseShowJSON(t, bdShowJSON(t, bd, dir, id)), &shown); err != nil { + t.Fatalf("decode bd show %s: %v", id, err) + } + if shown.Parent == nil || *shown.Parent != parent.ID { + t.Errorf("%s parent after promote = %v, want %s", id, shown.Parent, parent.ID) + } + } + comments := bdComments(t, bd, dir, parent.ID) + for _, text := range []string{"pre-promote note", "Promoted from Level 0: worth keeping"} { + if !strings.Contains(comments, text) { + t.Errorf("bd comments %s does not list %q:\n%s", parent.ID, text, comments) + } + } + if next := bdCreate(t, bd, dir, "Child after promote", "--parent", parent.ID); next.ID != parent.ID+".3" { + t.Errorf("next child of the promoted parent is %s, want %s", next.ID, parent.ID+".3") + } +} + // TestEmbeddedPromoteCLIConcurrent exercises promote concurrently. func TestEmbeddedPromoteCLIConcurrent(t *testing.T) { if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" { diff --git a/cmd/bd/promote_proxied_integration_test.go b/cmd/bd/promote_proxied_integration_test.go index 501ec1c4c..cc65b162e 100644 --- a/cmd/bd/promote_proxied_integration_test.go +++ b/cmd/bd/promote_proxied_integration_test.go @@ -5,6 +5,10 @@ package main import ( "database/sql" "encoding/json" + "fmt" + "runtime" + "slices" + "sort" "strings" "testing" ) @@ -12,9 +16,11 @@ import ( // 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 preserved, still visible to -// `bd list --include-infra --wisp-type `, no longer purge-reclaimable, -// same --json shape and error contract as classic. +// retained, labels/deps/events/comments and the child counter preserved, +// still visible to `bd list --include-infra --wisp-type `, 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() @@ -56,16 +62,12 @@ func TestProxiedServerPromote(t *testing.T) { t.Errorf("expected promote success line, got: %s", stdout) } - // Exactly one Dolt commit, carrying the classic commit message. - if n := proxiedDoltCommitCountSince(t, db, head); n != 1 { - t.Errorf("expected exactly 1 Dolt commit for promote, got %d", n) - } - var msg string - if err := db.QueryRow("SELECT message FROM DOLT_LOG('HEAD', '--not', ?)", head).Scan(&msg); err != nil { - t.Fatalf("read promote commit message: %v", err) - } - if msg != "bd: promote "+wisp.ID { - t.Errorf("commit message = %q, want %q", msg, "bd: promote "+wisp.ID) + // 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. @@ -130,6 +132,57 @@ func TestProxiedServerPromote(t *testing.T) { } }) + // 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 .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") diff --git a/cmd/bd/promote_proxied_server.go b/cmd/bd/promote_proxied_server.go index 38f6fb547..7deb0471e 100644 --- a/cmd/bd/promote_proxied_server.go +++ b/cmd/bd/promote_proxied_server.go @@ -2,88 +2,77 @@ package main import ( "context" - "errors" - "fmt" - "github.com/steveyegge/beads/internal/storage" - "github.com/steveyegge/beads/internal/storage/uow" "github.com/steveyegge/beads/internal/types" "github.com/steveyegge/beads/internal/utils" - "github.com/steveyegge/beads/internal/workapi" + "github.com/steveyegge/beads/issueops" ) // runPromoteProxiedServer is the proxied-server route for `bd promote`. It -// mirrors the classic route: resolve the id, refuse a non-wisp with the same -// error text, then promote through the domain PromoteWisp verb — which runs -// the exact issueops implementation the classic route runs, so the row is -// rewritten in place (same id, wisp_type retained, labels/deps/events/ -// comments carried to the permanent tables, inbound edges retargeted). +// runs issueops.Promote, the entry the direct route runs, over the provider's +// own role accessors, so the two routes promote the same way: one +// Lifecycle.Update whose patch is the persistence move (the move +// `bd update --persistent` makes on this route: same id, wisp_type retained, +// labels/deps/events/comments and the child counter carried to the permanent +// tables, inbound edges retargeted), then the promotion comment through the +// Commenter. The hooks fire from the notifying provider (main.go): on_update +// for the move and again for the comment, as on the direct route. // -// Commit semantics: the cross-plane move and the promotion comment land in -// ONE transaction under one Dolt commit ("bd: promote ", the classic -// dolt commit message). The wisp-side deletes touch dolt_ignored tables so -// only the issues-plane rows are versioned by that commit, but the single -// transaction still makes the wisp delete and the issues insert atomic. -// -// One deliberate tightening vs classic: classic adds the promotion comment -// in a separate write after the promote has committed, so a failed comment -// write can only degrade to a stderr warning. Here the comment shares the -// promote's transaction, so a comment failure rolls the whole promote back — -// atomic beats warn-and-continue, and a comment insert on a row this same -// transaction just promoted has no realistic standalone failure mode. +// Each role runs its own transaction, so a promotion is two Dolt commits, the +// move's ("bd: promote ", the classic message) and the comment's +// ("bd: comment "), and a comment that fails leaves the promotion standing +// behind a warning, as on every other route. func runPromoteProxiedServer(ctx context.Context, id, reason string) error { if uowProvider == nil { return HandleErrorRespectJSON("proxied-server UOW provider not initialized") } - // Resolve + precondition checks on a read UOW, mirroring the classic - // route's resolve/get/ephemeral-check before its write transaction. The - // promote below re-verifies the wisp is still active inside the write - // transaction (a lost race fails with "wisp not found", as classic). ruw, err := proxiedOpenReadUOW(ctx) if err != nil { return err } fullID, err := utils.ResolvePartialID(ctx, uowMolReader{uw: ruw}, id) - if err != nil { - ruw.Close(ctx) - return HandleErrorRespectJSON("resolving %s: %v", id, err) - } - issue, _, err := workapi.GetIssueOrWisp(ctx, workapi.NewUOWDetailSource(ruw), fullID) ruw.Close(ctx) if err != nil { - if errors.Is(err, storage.ErrNotFound) { - return HandleErrorRespectJSON("issue %s not found", fullID) - } - return HandleErrorRespectJSON("getting issue %s: %v", fullID, err) - } - if !issue.Ephemeral { - return HandleErrorRespectJSON("%s is not a wisp (already persistent)", fullID) + return HandleErrorRespectJSON("resolving %s: %v", id, err) } - err = uow.RunTx(ctx, uowProvider, func(ctx context.Context, uw uow.UnitOfWork) (string, error) { - if err := uw.IssueUseCase().PromoteWisp(ctx, fullID, currentActor()); err != nil { - return "", err - } - if _, err := uw.CommentUseCase().AddCommentToIssue(ctx, fullID, currentActor(), promotionComment(reason)); err != nil { - return "", fmt.Errorf("adding promotion comment: %w", err) - } - return fmt.Sprintf("bd: promote %s", fullID), nil + roles, err := proxiedPromoteRoles() + if err != nil { + return HandleErrorRespectJSON("%v", err) + } + promoted, err := issueops.Promote(ctx, roles, issueops.PromoteRequest{ + Actor: currentActor(), IssueID: fullID, Reason: reason, Provenance: "bd: promote " + fullID, }) if err != nil { - return HandleErrorRespectJSON("promoting %s: %v", fullID, err) + return promoteFailure(fullID, err) } - - commandDidWrite.Store(true) - - var updated *types.Issue - if jsonOutput { - // Best-effort post-promote re-read for --json, matching the classic - // route's ignore-error re-read (labels included, like GetIssueInTx). - if uwr, rerr := proxiedOpenReadUOW(ctx); rerr == nil { - updated, _ = uowMolReader{uw: uwr}.GetIssue(ctx, fullID) - uwr.Close(ctx) + return reportPromotion(fullID, promoted, func() *types.Issue { + // Labels included, like the direct route's store.GetIssue. + uwr, err := proxiedOpenReadUOW(ctx) + if err != nil { + return nil } + defer uwr.Close(ctx) + updated, _ := uowMolReader{uw: uwr}.GetIssue(ctx, fullID) + return updated + }) +} + +// proxiedPromoteRoles asks the provider for the three roles issueops.Promote +// composes, each through its own accessor, so each is the notifying one. +func proxiedPromoteRoles() (issueops.PromoteRoles, error) { + reader, err := proxiedIssueReader() + if err != nil { + return issueops.PromoteRoles{}, err } - return printPromoteResult(fullID, updated) + lifecycle, err := proxiedIssueLifecycle() + if err != nil { + return issueops.PromoteRoles{}, err + } + commenter, err := proxiedCommenter() + if err != nil { + return issueops.PromoteRoles{}, err + } + return issueops.PromoteRoles{Reader: reader, Lifecycle: lifecycle, Commenter: commenter}, nil } diff --git a/engdocs/design/http-divergence-ledger.md b/engdocs/design/http-divergence-ledger.md index 01d95c9a3..b3f006887 100644 --- a/engdocs/design/http-divergence-ledger.md +++ b/engdocs/design/http-divergence-ledger.md @@ -122,7 +122,7 @@ Role-request fields on the served writes that the v0 wire publishes no member fo | W-IssuePatch.AwaitID | refuse | `IssuePatch.AwaitID` | an await-id edit refuses | neither IssuePatchBody nor ApplyPatchBody publishes await_id (internal/httpapi/update.go issuePatchMembers) | D8 refuse-not-drop | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the in-repo divergence ledger, engdocs/design/http-divergence-ledger.md, for the discipline | | W-IssuePatch.Owner | refuse | `IssuePatch.Owner` | an owner edit refuses ON updateIssue | IssuePatchBody excludes owner — which the document itself calls an accident of order rather than a decision, since ApplyPatchBody DOES publish it and issues:batchApply's update item carries it (internal/httpapi/update.go issuePatchMembers) | D8 refuse-not-drop | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the in-repo divergence ledger, engdocs/design/http-divergence-ledger.md, for the discipline | | W-IssuePatch.ClosedBySession | refuse | `IssuePatch.ClosedBySession` | a closed-by-session edit refuses | neither IssuePatchBody nor ApplyPatchBody publishes closed_by_session (internal/httpapi/update.go issuePatchMembers) | D8 refuse-not-drop | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the in-repo divergence ledger, engdocs/design/http-divergence-ledger.md, for the discipline | -| W-IssuePatch.Persistence | refuse | `IssuePatch.Persistence` | a persistence-mode edit refuses | neither body publishes persistence: moving a row between planes mid-plan is a different act from writing its fields (internal/httpapi/update.go issuePatchMembers) | D8 refuse-not-drop | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the in-repo divergence ledger, engdocs/design/http-divergence-ledger.md, for the discipline | +| W-IssuePatch.Persistence | refuse | `IssuePatch.Persistence` | a persistence-mode edit refuses ON issues:batchApply | ApplyPatchBody excludes persistence: moving a row between planes mid-plan is a different act from writing its fields. IssuePatchBody publishes it behind issues.update.persistence, and updateIssue's encoder carries it (refusing before the dial against a server without that token) (internal/httpapi/update.go issuePatchMembers) | D8 refuse-not-drop | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the in-repo divergence ledger, engdocs/design/http-divergence-ledger.md, for the discipline | | W-IssuePatch.ParentID | retired | — | a parent re-hang through update used to refuse | RETIRED with W-IssuePatch.Status (ga-7i6by). It is ONE call rather than a remove-then-add pair, which is the whole reason the member exists: the two-call spelling leaves the issue parentless if the second call fails, and dependencies:add/remove — still the general write side of the graph over this wire — cannot express the atomic replacement. The empty string removes every parent-child edge, so it travels like `assignee`'s empty string rather than being skipped. The graph refusals it earns are the server's and arrive typed: a cycle through the issue's own descendant as the PLAIN dependency_cycle, and an existing edge of another type as dependency_exists | D8 refuse-not-drop | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the in-repo divergence ledger, engdocs/design/http-divergence-ledger.md, for the discipline | | W-CreateBatchRequest.Provenance | refuse | `CreateBatchRequest.Provenance` | labeling a batch create's history entry refuses | batchCreateIssues publishes actor and items only, and the server writes its own label; see W-UpdateRequest.Provenance. It is the one Provenance whose ABSENCE is visible in shipped history — the surface this role serves has always named its source file in the entry (`bd: create 3 issue(s) from plan.md`) | D8 row 14 refuse-not-drop | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the in-repo divergence ledger, engdocs/design/http-divergence-ledger.md, for the discipline | | W-CreateBatchRequest.ForceIDPrefix | refuse | `CreateBatchRequest.ForceIDPrefix` `--force` | permitting explicit ids outside the workspace's configured prefix refuses | the wire publishes no such member — and could not honor one, since it publishes no explicit id for the flag to permit (W-BatchCreateItem.Issue). Dropping it would answer a request about WHERE ids may be written with a batch whose ids the server chose | D8 row 14 refuse-not-drop | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the in-repo divergence ledger, engdocs/design/http-divergence-ledger.md, for the discipline | diff --git a/internal/httpapi/apigen/types.gen.go b/internal/httpapi/apigen/types.gen.go index 7a65483eb..f0f16b608 100644 --- a/internal/httpapi/apigen/types.gen.go +++ b/internal/httpapi/apigen/types.gen.go @@ -675,7 +675,7 @@ type ApplyMetadataPatch struct { // // `labels` is a full patch rather than a complete replacement, and that one is a real difference: a plan has to be able to REMOVE one label without knowing the rest of the set, because it edits a set it did not compose. A caller patching one row it just read already knows the set. // -// `parent_id` is deliberately absent, and its absence is this operation's one-edge-one-spelling rule: a parent is a `dep_add` item of type `parent-child`, so the order of every edge in the request stays total. The single patch has no ordering to express and publishes it directly. `persistence` is absent from both — moving a row between planes mid-plan is a different act from writing its fields, and nothing has asked for it here. +// `parent_id` is deliberately absent, and its absence is this operation's one-edge-one-spelling rule: a parent is a `dep_add` item of type `parent-child`, so the order of every edge in the request stays total. The single patch has no ordering to express and publishes it directly. `persistence` is absent here — moving a row between planes mid-plan is a different act from writing its fields, and nothing has asked for it here. The single patch publishes it (`IssuePatchBody.persistence`, behind `issues.update.persistence`), where the move is the patch's last step. type ApplyPatchBody struct { AcceptanceCriteria *string `json:"acceptance_criteria,omitempty"` @@ -764,7 +764,7 @@ type ApplyUpdateItem struct { // // `labels` is a full patch rather than a complete replacement, and that one is a real difference: a plan has to be able to REMOVE one label without knowing the rest of the set, because it edits a set it did not compose. A caller patching one row it just read already knows the set. // - // `parent_id` is deliberately absent, and its absence is this operation's one-edge-one-spelling rule: a parent is a `dep_add` item of type `parent-child`, so the order of every edge in the request stays total. The single patch has no ordering to express and publishes it directly. `persistence` is absent from both — moving a row between planes mid-plan is a different act from writing its fields, and nothing has asked for it here. + // `parent_id` is deliberately absent, and its absence is this operation's one-edge-one-spelling rule: a parent is a `dep_add` item of type `parent-child`, so the order of every edge in the request stays total. The single patch has no ordering to express and publishes it directly. `persistence` is absent here — moving a row between planes mid-plan is a different act from writing its fields, and nothing has asked for it here. The single patch publishes it (`IssuePatchBody.persistence`, behind `issues.update.persistence`), where the move is the patch's last step. Patch ApplyPatchBody `json:"patch"` // Target Names ONE issue, either by an id that already exists or by the `key` a create item earlier in the same request gave itself. @@ -1101,7 +1101,7 @@ type ContextResponse struct { // OPTIONAL, and absent means only that this server does not disclose its filesystem layout — never that it has no workspace. A client MUST NOT require it, MUST NOT treat absence as an error, and has no use for the value beyond display: it is a path on the SERVER's filesystem, which the client cannot open. Identify the workspace by `project_id` and `database`, which are required. BeadsDir *string `json:"beads_dir,omitempty"` - // Capabilities The tokens this server advertises: the OPERATIONS it implements, derived from its route table, and the server-wide BEHAVIORS it enforces. v0's operation vocabulary is `ready.list`, `ready.count`, `issues.list`, `issues.query`, `issues.count`, `issues.get`, `issues.related`, `issues.create`, `issues.addComment`, `issues.batchClose`, `issues.claim`, `issues.claimNext`, `issues.release`, `issues.close`, `issues.reopen`, `issues.update`, `issues.sweep`, `issues.delete`, `issues.batchGet`, `issues.reclaim`, `issues.batchCreate`, `issues.batchApply`, `stats.get`, `config.list`, `config.get`, `config.set`, `config.unset`, `dependencies.cycles`, `dependencies.list`, `dependencies.count`, `dependencies.blocking`, `dependencies.tree`, `dependencies.add`, `dependencies.remove`, `memories.list`, `memories.get`, `memories.remember`, `memories.forget`, `events.list`, `events.watch`, `issues.casMetadata`, `issues.advanceMolecule`; the behavior tokens are `project.enforce`, which announces that a `Bd-Project-Id` stamp for the wrong workspace is refused here rather than silently ignored, `issues.batchApplyLarge`, which announces that `POST /v0/beads/issues:batchApply` accepts the RAISED envelope — up to 1000 items (`ApplyBatchRequest.items.maxItems`), a 16 MiB body, and (for a request over 100 items) a run budget that EXTENDS to an operator-configured ceiling (`bd serve --large-apply-ceiling`, 5 minutes by default) — rather than the original 100-item, 4 MiB bound. The ceiling is a flat whole-run budget, not a value scaled by item count: a 101-item request and a 1000-item request both get the same extended budget. A request at or under 100 items is unaffected either way and keeps the server's ordinary deadline exactly as before. A client that checks for this token before sending a plan over 100 items learns whether THIS server accepts it without paying for a round trip an older server would refuse anyway, and `issues.list.sort`, which announces that `GET /v0/beads/issues` accepts the `sort` query parameter (two closed, pageable total orders — see that parameter) rather than silently answering `unknown_parameter`, and `issues.count.scope`, which announces that `GET /v0/beads/issues:count` accepts `parent`, `no_parent`, `exclude_type`, and `exclude_status` (see those parameters) rather than silently answering `unknown_parameter` for all four, `issues.sweep.wispsPlane`, which announces that `POST /v0/beads/issues:sweep` accepts the `wisps-plane` value of `tier` rather than silently answering `invalid_value`, `issues.sweep.liveDependents`, which announces that the same operation accepts `protect_live_dependents` and answers `skipped.live_dependent` rather than silently answering `unknown_parameter`, `issues.sweep.limit`, which announces that it accepts `limit` and answers `remaining` rather than silently answering `unknown_parameter`, `issues.batchApply.depAddLineage`, which announces that a `dep_add` item on `POST /v0/beads/issues:batchApply` accepts `has_spawner` and `thread_id` (see `ApplyDepAddItem`) rather than a `400` naming the member unknown, and `issues.update.allowTemplate`, which announces that `PATCH /v0/beads/issues/{id}` accepts `allow_template` (see `UpdateIssueRequest`) rather than a `400` naming the member unknown, and `issues.create.defaultPriority`, which announces that a create (`POST /v0/beads/issues`, `issues:batchCreate` and `issues:batchApply` create items) with no `priority` member stores the default P2 rather than P0, and `issues.close.autoCloseMolecule`, which announces that `POST /v0/beads/issues/{id}:close` and `POST /v0/beads/issues:batchClose` accept `auto_close_molecule` and answer `auto_closed_molecule` and `molecule_auto_close_refusal` rather than a `400` naming the member unknown, `issues.list.search`, which announces that `GET /v0/beads/issues` accepts `q`, `bd search`'s free text (see that parameter), rather than silently answering `unknown_parameter`, and `issues.list.noAssignee`, `issues.list.title` and `issues.list.ids`, which announce that `GET /v0/beads/issues` accepts `no_assignee`, `title` and the repeatable `id` respectively (`bd list --no-assignee`, `--title` and `--id`; see those parameters) rather than answering `unknown_parameter`. One behavior token is CONDITIONAL rather than build-level: `policy.external_dependencies` announces that this server's ready, claim, claim-next, close, blocking and dependency-tree operations already apply bd's external-dependency policy (an issue blocked by an unsatisfied `external::` dependency is neither ready, claimable nor closable without force). A server advertises it only when it enforces that policy; a client that sees it must not apply the policy again, and a client that does not see it applies the policy itself. The list grows additively, and an operation never appears here unless it is fully implemented. This is how a client checks for an operation or a behavior — never the version string. + // Capabilities The tokens this server advertises: the OPERATIONS it implements, derived from its route table, and the server-wide BEHAVIORS it enforces. v0's operation vocabulary is `ready.list`, `ready.count`, `issues.list`, `issues.query`, `issues.count`, `issues.get`, `issues.related`, `issues.create`, `issues.addComment`, `issues.batchClose`, `issues.claim`, `issues.claimNext`, `issues.release`, `issues.close`, `issues.reopen`, `issues.update`, `issues.sweep`, `issues.delete`, `issues.batchGet`, `issues.reclaim`, `issues.batchCreate`, `issues.batchApply`, `stats.get`, `config.list`, `config.get`, `config.set`, `config.unset`, `dependencies.cycles`, `dependencies.list`, `dependencies.count`, `dependencies.blocking`, `dependencies.tree`, `dependencies.add`, `dependencies.remove`, `memories.list`, `memories.get`, `memories.remember`, `memories.forget`, `events.list`, `events.watch`, `issues.casMetadata`, `issues.advanceMolecule`; the behavior tokens are `project.enforce`, which announces that a `Bd-Project-Id` stamp for the wrong workspace is refused here rather than silently ignored, `issues.batchApplyLarge`, which announces that `POST /v0/beads/issues:batchApply` accepts the RAISED envelope — up to 1000 items (`ApplyBatchRequest.items.maxItems`), a 16 MiB body, and (for a request over 100 items) a run budget that EXTENDS to an operator-configured ceiling (`bd serve --large-apply-ceiling`, 5 minutes by default) — rather than the original 100-item, 4 MiB bound. The ceiling is a flat whole-run budget, not a value scaled by item count: a 101-item request and a 1000-item request both get the same extended budget. A request at or under 100 items is unaffected either way and keeps the server's ordinary deadline exactly as before. A client that checks for this token before sending a plan over 100 items learns whether THIS server accepts it without paying for a round trip an older server would refuse anyway, and `issues.list.sort`, which announces that `GET /v0/beads/issues` accepts the `sort` query parameter (two closed, pageable total orders — see that parameter) rather than silently answering `unknown_parameter`, and `issues.count.scope`, which announces that `GET /v0/beads/issues:count` accepts `parent`, `no_parent`, `exclude_type`, and `exclude_status` (see those parameters) rather than silently answering `unknown_parameter` for all four, `issues.sweep.wispsPlane`, which announces that `POST /v0/beads/issues:sweep` accepts the `wisps-plane` value of `tier` rather than silently answering `invalid_value`, `issues.sweep.liveDependents`, which announces that the same operation accepts `protect_live_dependents` and answers `skipped.live_dependent` rather than silently answering `unknown_parameter`, `issues.sweep.limit`, which announces that it accepts `limit` and answers `remaining` rather than silently answering `unknown_parameter`, `issues.batchApply.depAddLineage`, which announces that a `dep_add` item on `POST /v0/beads/issues:batchApply` accepts `has_spawner` and `thread_id` (see `ApplyDepAddItem`) rather than a `400` naming the member unknown, and `issues.update.allowTemplate`, which announces that `PATCH /v0/beads/issues/{id}` accepts `allow_template` (see `UpdateIssueRequest`) rather than a `400` naming the member unknown, and `issues.update.persistence`, which announces that `PATCH /v0/beads/issues/{id}` accepts a `persistence` member in its `patch` (see `IssuePatchBody`), the plane move behind `bd promote`, rather than a `400` naming the member unknown, and `issues.create.defaultPriority`, which announces that a create (`POST /v0/beads/issues`, `issues:batchCreate` and `issues:batchApply` create items) with no `priority` member stores the default P2 rather than P0, and `issues.close.autoCloseMolecule`, which announces that `POST /v0/beads/issues/{id}:close` and `POST /v0/beads/issues:batchClose` accept `auto_close_molecule` and answer `auto_closed_molecule` and `molecule_auto_close_refusal` rather than a `400` naming the member unknown, `issues.list.search`, which announces that `GET /v0/beads/issues` accepts `q`, `bd search`'s free text (see that parameter), rather than silently answering `unknown_parameter`, and `issues.list.noAssignee`, `issues.list.title` and `issues.list.ids`, which announce that `GET /v0/beads/issues` accepts `no_assignee`, `title` and the repeatable `id` respectively (`bd list --no-assignee`, `--title` and `--id`; see those parameters) rather than answering `unknown_parameter`. One behavior token is CONDITIONAL rather than build-level: `policy.external_dependencies` announces that this server's ready, claim, claim-next, close, blocking and dependency-tree operations already apply bd's external-dependency policy (an issue blocked by an unsatisfied `external::` dependency is neither ready, claimable nor closable without force). A server advertises it only when it enforces that policy; a client that sees it must not apply the policy again, and a client that does not see it applies the policy itself. The list grows additively, and an operation never appears here unless it is fully implemented. This is how a client checks for an operation or a behavior — never the version string. // // THIS LIST IS BUILD-LEVEL, NOT WORKSPACE-LEVEL, apart from the conditional `policy.external_dependencies` above, which depends on how this server composed its roles rather than on the build. It says which operations this binary serves, and for every entry but two that is the whole answer. `events.list` and `events.watch` are the exceptions: the durable events journal is a per-workspace setting that is OFF by default, so a server that advertises them may still refuse every request to both with 409 `events_journal_disabled` — correctly, because the operations exist and the workspace has no journal. A consumer of either MUST treat the capability as "this server speaks it" and the 409 as "not on this workspace", and must not read the capability as a promise that records will arrive. Capabilities []string `json:"capabilities"` @@ -1556,7 +1556,12 @@ type IssuePatchBody struct { // // IT IS A GRAPH EDIT, and it earns the graph's refusals: a new parent this workspace holds no row for is a `400`, a pair that already carries an edge of another type is `409 dependency_exists`, and a move under the issue's own descendant is `409 dependency_cycle` — the PLAIN one, carrying no `issue_id`/`blocker_id`/ `blocker_is_ancestor`, because the hierarchy refusal answers only to blocking edges and this member writes a `parent-child` edge. Naming the issue itself is a `400`. One call rather than a remove-then-add pair, which is the whole reason it is here: the two-call spelling leaves the issue parentless if the second call fails. ParentId *string `json:"parent_id,omitempty"` - Priority *int `json:"priority,omitempty"` + + // Persistence One of `persistent`, `ephemeral` or `no_history`; any other value is a `400` naming the member. Selects the issue's complete persistence state, moving the row between the durable and the wisp plane when the state changes plane. `persistent` promotes a wisp: the row keeps its id, and its labels, dependencies, events and comments move with it, all in this update's one transaction (`bd promote`, `bd update --persistent`). `ephemeral` and `no_history` select the wisp retention modes (`bd update --ephemeral` / `--no-history`); demoting a durable row that has retained snapshots is refused. The current mode is a no-op that reports `changed: false`. + // + // A PLANE MOVE IS AN AGGREGATE MIGRATION, not a field write, and it is applied LAST, after every other member of the patch, so the edit and the move commit together or not at all. Advertised by the `issues.update.persistence` capability token; a server that predates the member refuses it as an unknown parameter, and a client that does not see the token refuses the move before the dial rather than sending it. + Persistence *string `json:"persistence,omitempty"` + Priority *int `json:"priority,omitempty"` // RemoveLabels Labels to remove, applied AFTER `labels` and `add_labels`, so REMOVAL WINS over both. // diff --git a/internal/httpapi/routes.go b/internal/httpapi/routes.go index 6789f992a..a724540e1 100644 --- a/internal/httpapi/routes.go +++ b/internal/httpapi/routes.go @@ -221,6 +221,16 @@ const CapBatchApplyDepAddLineage = "issues.batchApply.depAddLineage" // still edits a template (bd-jkp9v3). const CapIssuesUpdateAllowTemplate = "issues.update.allowTemplate" +// CapIssuesUpdatePersistence is the behavior capability that advertises +// IssuePatchBody.persistence on updateIssue: the role's +// IssuePatch.Persistence, which moves the row between the durable and the wisp +// plane in the update's own transaction. It is what `bd promote` +// (issueops.Promote) and `bd update --persistent/--ephemeral/--no-history` +// send over http. An older server answers the member with `400 +// invalid_argument`/`unknown_parameter`; a client that does not see this token +// refuses the move before the dial, naming the token, rather than sending it. +const CapIssuesUpdatePersistence = "issues.update.persistence" + // CapIssuesCreateDefaultPriority is the behavior capability that advertises // that issues.create, issues.batchCreate and issues.batchApply's create items // store the create default priority (P2) for a request whose `priority` member @@ -1034,7 +1044,7 @@ var behaviorCapabilities = []string{ CapIssuesSweepWispsPlane, CapIssuesSweepLiveDependents, CapIssuesSweepLimit, CapBatchApplyDepAddLineage, CapIssuesUpdateAllowTemplate, CapIssuesCreateDefaultPriority, CapIssuesCloseAutoCloseMolecule, CapIssuesListSearch, - CapIssuesListNoAssignee, CapIssuesListTitle, CapListIDs, + CapIssuesListNoAssignee, CapIssuesListTitle, CapListIDs, CapIssuesUpdatePersistence, } // Capabilities lists what this build advertises in ContextResponse.capabilities: diff --git a/internal/httpapi/server_test.go b/internal/httpapi/server_test.go index d4a6b27f0..43e983b2e 100644 --- a/internal/httpapi/server_test.go +++ b/internal/httpapi/server_test.go @@ -639,7 +639,7 @@ func TestCapabilitiesAdvertiseEveryImplementedOperation(t *testing.T) { "issues.sweep.wispsPlane", "issues.sweep.liveDependents", "issues.sweep.limit", "issues.batchApply.depAddLineage", "issues.update.allowTemplate", "issues.create.defaultPriority", "issues.close.autoCloseMolecule", "issues.list.search", - "issues.list.noAssignee", "issues.list.title", "issues.list.ids") + "issues.list.noAssignee", "issues.list.title", "issues.list.ids", "issues.update.persistence") slices.Sort(want) if !slices.Equal(got, want) { t.Errorf("capabilities = %v, want %v", got, want) diff --git a/internal/httpapi/spec/openapi.v0.yaml b/internal/httpapi/spec/openapi.v0.yaml index de7f04b33..3556c5e99 100644 --- a/internal/httpapi/spec/openapi.v0.yaml +++ b/internal/httpapi/spec/openapi.v0.yaml @@ -2495,11 +2495,6 @@ paths: Nothing has asked for it. - `persistence` — a plane move is an atomic aggregate migration rather - than a field write, and moving a row between planes mid-patch is a - different act from editing it. - - `closed_by_session` and `close_reason` — written under first-close-wins by `{id}:close`, which a patch write would bypass. A `status` that crosses into the done category still answers to close POLICY here; it @@ -8287,6 +8282,11 @@ components: `PATCH /v0/beads/issues/{id}` accepts `allow_template` (see `UpdateIssueRequest`) rather than a `400` naming the member unknown, and + `issues.update.persistence`, which announces that + `PATCH /v0/beads/issues/{id}` accepts a `persistence` member in + its `patch` (see `IssuePatchBody`), the plane move behind + `bd promote`, rather + than a `400` naming the member unknown, and `issues.create.defaultPriority`, which announces that a create (`POST /v0/beads/issues`, `issues:batchCreate` and `issues:batchApply` create items) with no `priority` member stores @@ -10500,9 +10500,11 @@ components: one-edge-one-spelling rule: a parent is a `dep_add` item of type `parent-child`, so the order of every edge in the request stays total. The single patch has no ordering to express and publishes it directly. - `persistence` is absent from both — moving a row between planes mid-plan + `persistence` is absent here — moving a row between planes mid-plan is a different act from writing its fields, and nothing has asked for it - here. + here. The single patch publishes it (`IssuePatchBody.persistence`, + behind `issues.update.persistence`), where the move is the patch's last + step. properties: title: type: string @@ -12201,6 +12203,29 @@ components: description: 'RFC 3339. Explicit `null` CLEARS the deferral.' metadata: $ref: '#/components/schemas/ApplyMetadataPatch' + persistence: + type: string + maxLength: 255 + description: >- + One of `persistent`, `ephemeral` or `no_history`; any other value + is a `400` naming the member. Selects the issue's complete persistence state, moving the row + between the durable and the wisp plane when the state changes + plane. `persistent` promotes a wisp: the row keeps its id, and its + labels, dependencies, events and comments move with it, all in + this update's one transaction (`bd promote`, `bd update + --persistent`). `ephemeral` and `no_history` select the wisp + retention modes (`bd update --ephemeral` / `--no-history`); + demoting a durable row that has retained snapshots is refused. + The current mode is a no-op that reports `changed: false`. + + + A PLANE MOVE IS AN AGGREGATE MIGRATION, not a field write, and it + is applied LAST, after every other member of the patch, so the + edit and the move commit together or not at all. Advertised by the + `issues.update.persistence` capability token; a server that + predates the member refuses it as an unknown parameter, and a + client that does not see the token refuses the move before the + dial rather than sending it. UpdateIssueResponse: type: object diff --git a/internal/httpapi/update.go b/internal/httpapi/update.go index 64df715ce..2cf299943 100644 --- a/internal/httpapi/update.go +++ b/internal/httpapi/update.go @@ -46,7 +46,7 @@ var ( "title", "description", "design", "acceptance_criteria", "notes", "append_notes", "priority", "issue_type", "status", "assignee", "parent_id", "labels", "add_labels", "remove_labels", "metadata", - "estimated_minutes", "external_ref", "due_at", "defer_until", + "estimated_minutes", "external_ref", "due_at", "defer_until", "persistence", } // nullablePatchMembers is the closed set on which explicit `null` CLEARS // rather than refuses. They are exactly the members the role models as @@ -426,6 +426,18 @@ func (s *Server) issuePatch(w http.ResponseWriter, r *http.Request, id string, m } patch.ParentID = issueops.Field[string]{Set: true, Value: *wire.ParentId} } + if set("persistence") { + // The plane move (CapIssuesUpdatePersistence). The handler checks only + // that the value is one of the role's three modes, so an unknown one is + // a 400 naming the member rather than a translated storage error; the + // move itself, and every refusal it earns, is the role's. + mode := issueops.PersistenceMode(*wire.Persistence) + if !mode.IsValid() { + return refuse("persistence", fmt.Sprintf("`persistence` is %q; send %q, %q or %q", + *wire.Persistence, issueops.PersistenceModePersistent, issueops.PersistenceModeEphemeral, issueops.PersistenceModeNoHistory)) + } + patch.Persistence = issueops.Field[issueops.PersistenceMode]{Set: true, Value: mode} + } if set("metadata") { // applyMetadataPatch, unchanged and not respelled: the replace/merge/ // set/unset algebra is one definition, and a second copy here would be a diff --git a/internal/httpapi/update_test.go b/internal/httpapi/update_test.go index 8dd401a1b..a4fae26d5 100644 --- a/internal/httpapi/update_test.go +++ b/internal/httpapi/update_test.go @@ -305,7 +305,12 @@ func TestUpdateRejectsTheShapesTheDocumentRefuses(t *testing.T) { {"patch is not an object", `{"actor":"alice","patch":["title"]}`, "patch"}, {"empty patch", `{"actor":"alice","patch":{}}`, "patch"}, {"unknown request member", `{"actor":"alice","patch":{"title":"t"},"force":true}`, "force"}, - {"unknown patch member", `{"actor":"alice","patch":{"title":"t","persistence":"ephemeral"}}`, "patch.persistence"}, + {"unknown patch member", `{"actor":"alice","patch":{"title":"t","owner":"bob"}}`, "patch.owner"}, + // persistence is published (issues.update.persistence), but only as + // one of the three modes the role knows. + {"unknown persistence mode", `{"actor":"alice","patch":{"persistence":"durable"}}`, "patch.persistence"}, + {"blank persistence mode", `{"actor":"alice","patch":{"persistence":""}}`, "patch.persistence"}, + {"persistence is not a string", `{"actor":"alice","patch":{"persistence":true}}`, "patch"}, // The refusals the three policy members brought with them, all decided // at the edge because none of them needs to read a row. {"self parent", `{"actor":"alice","patch":{"parent_id":"bd-1"}}`, "patch.parent_id"}, @@ -1383,3 +1388,33 @@ func TestUpdateAnswersARefusedClaimAsTheClaimDoes(t *testing.T) { }) } } + +// TestUpdateForwardsThePersistenceMember is the plane move `bd promote` sends +// (issueops.Promote): patch.persistence reaches the role's +// IssuePatch.Persistence verbatim, for each of the three modes, and nothing +// else is set beside it. +func TestUpdateForwardsThePersistenceMember(t *testing.T) { + for _, mode := range []issueops.PersistenceMode{ + issueops.PersistenceModePersistent, issueops.PersistenceModeEphemeral, issueops.PersistenceModeNoHistory, + } { + t.Run(string(mode), func(t *testing.T) { + lifecycle := &roleLifecycle{updateResult: issueops.UpdateResult{Issue: updatedIssue("bd-1"), Changed: true}} + ts := newUpdateServer(t, lifecycle) + resp := ts.updateIssue(t, updatePath, `{"actor":"alice","patch":{"persistence":"`+string(mode)+`"}}`) + if resp.StatusCode != http.StatusOK { + t.Fatalf("status = %d, want 200: %s", resp.StatusCode, readAll(t, resp)) + } + got := lifecycle.updateRequests() + if len(got) != 1 { + t.Fatalf("the role was called %d times, want 1", len(got)) + } + p := got[0].Patch + if !p.Persistence.Set || p.Persistence.Value != mode { + t.Errorf("persistence = %+v, want a set %q", p.Persistence, mode) + } + if p.Title.Set || p.Status.Set || p.Assignee.Set || p.ParentID.Set { + t.Errorf("the handler set a member the body did not carry: %+v", p) + } + }) + } +} diff --git a/internal/httpapi/wireshape/testdata/golden.json b/internal/httpapi/wireshape/testdata/golden.json index 14fb03288..b136b13af 100644 --- a/internal/httpapi/wireshape/testdata/golden.json +++ b/internal/httpapi/wireshape/testdata/golden.json @@ -2917,6 +2917,12 @@ "type": "string", "required": false }, + { + "schema": "IssuePatchBody", + "member": "persistence", + "type": "string", + "required": false + }, { "schema": "IssuePatchBody", "member": "priority", diff --git a/internal/httpclient/BUILD.bazel b/internal/httpclient/BUILD.bazel index 6beb6b8ec..68803269c 100644 --- a/internal/httpclient/BUILD.bazel +++ b/internal/httpclient/BUILD.bazel @@ -170,6 +170,7 @@ go_test( "store_test.go", "target_test.go", "unlimited_read_test.go", + "update_persistence_test.go", "watch_test.go", "wave2b_roles_test.go", "wave2c_claimnext_test.go", diff --git a/internal/httpclient/batchapplier.go b/internal/httpclient/batchapplier.go index 1fd04b1be..e397f9f99 100644 --- a/internal/httpclient/batchapplier.go +++ b/internal/httpclient/batchapplier.go @@ -482,7 +482,7 @@ func applyRefBody(ref issueops.Ref) (apigen.Ref, error) { // applyPatchExcludedMembers is the refusal half of the apply patch's allowlist, // in the order encodeApplyPatch decides them. // -// THE ALLOWLIST IS NOT updateIssue's, and the two differences run in opposite +// THE ALLOWLIST IS NOT updateIssue's, and the differences run in opposite // directions, which is why this cannot share refuseExcludedPatchMembers: // // owner IS published here and refused there. ApplyPatchBody carries it; @@ -492,17 +492,22 @@ func applyRefBody(ref issueops.Ref) (apigen.Ref, error) { // a parent is a dep_add item of type parent-child, so the order of // every edge in a plan stays total and there is one spelling for // an edge. +// persistence is published THERE, behind issues.update.persistence, and +// absent here, also deliberately: moving a row between planes +// mid-plan is a different act from writing its fields. // -// The other three — spec_id, await_id, closed_by_session — and persistence are -// absent from both bodies. +// The other three — spec_id, await_id, closed_by_session — are absent from +// both bodies. var applyPatchExcludedMembers = []struct { member string ledger string set func(issueops.IssuePatch) bool }{ - // ParentID is this document's OWN exclusion and gets its own row; the other - // four are absent from both patch bodies, so they cite the rows that - // already refuse them rather than minting a second reason for one fact. + // ParentID is this document's OWN exclusion and gets its own row; SpecID, + // AwaitID and ClosedBySession are absent from both patch bodies, so they + // cite the rows that already refuse them rather than minting a second + // reason for one fact. Persistence cites W-IssuePatch.Persistence, the row + // that refuses it on this operation alone. {"ParentID", "W-ApplyPatch.ParentID", func(p issueops.IssuePatch) bool { return p.ParentID.Set }}, {"SpecID", "W-IssuePatch.SpecID", func(p issueops.IssuePatch) bool { return p.SpecID.Set }}, {"AwaitID", "W-IssuePatch.AwaitID", func(p issueops.IssuePatch) bool { return p.AwaitID.Set }}, diff --git a/internal/httpclient/encode/ledger.go b/internal/httpclient/encode/ledger.go index 970ca76de..8f6696f1d 100644 --- a/internal/httpclient/encode/ledger.go +++ b/internal/httpclient/encode/ledger.go @@ -719,8 +719,8 @@ func writeSideRows() []Row { patchRow("Owner", "an owner edit refuses ON updateIssue", "IssuePatchBody excludes owner — which the document itself calls an accident of order rather than a decision, since ApplyPatchBody DOES publish it and issues:batchApply's update item carries it"), patchRow("ClosedBySession", "a closed-by-session edit refuses", "neither IssuePatchBody nor ApplyPatchBody publishes closed_by_session"), - patchRow("Persistence", "a persistence-mode edit refuses", - "neither body publishes persistence: moving a row between planes mid-plan is a different act from writing its fields"), + patchRow("Persistence", "a persistence-mode edit refuses ON issues:batchApply", + "ApplyPatchBody excludes persistence: moving a row between planes mid-plan is a different act from writing its fields. IssuePatchBody publishes it behind issues.update.persistence, and updateIssue's encoder carries it (refusing before the dial against a server without that token)"), { ID: "W-IssuePatch.ParentID", Kind: KindRetired, What: "a parent re-hang through update used to refuse", diff --git a/internal/httpclient/lifecycle.go b/internal/httpclient/lifecycle.go index ea0df8554..9b98d3389 100644 --- a/internal/httpclient/lifecycle.go +++ b/internal/httpclient/lifecycle.go @@ -335,6 +335,9 @@ func (l *httpLifecycle) Update(ctx context.Context, req issueops.UpdateRequest) return issueops.UpdateResult{}, invalid("update names no field to write") } + if err := l.requirePersistenceMove(ctx, req); err != nil { + return issueops.UpdateResult{}, err + } req, err = l.applyTemplateGuardForServer(ctx, req) if err != nil { return issueops.UpdateResult{}, err @@ -417,6 +420,33 @@ func serverPredatesUpdateClaim(err error) bool { problem.Param == "claim" } +// requirePersistenceMove refuses, before anything is dialed, an update that +// moves the row between planes (IssuePatch.Persistence: `bd promote`, `bd +// update --persistent`) against a server that does not advertise +// wire.CapIssuesUpdatePersistence. Such a server refuses `patch.persistence` +// as an unknown parameter, and the move is one transaction on the server, so +// there is no client-side fallback: the refusal is the typed capability error +// naming the token (*wire.CapabilityError, which unwraps to +// *storage.ErrUnsupported with Capability set), never a dropped member and a +// "no change" answer. +func (l *httpLifecycle) requirePersistenceMove(ctx context.Context, req issueops.UpdateRequest) error { + if !req.Patch.Persistence.Set { + return nil + } + snap, err := l.store.snapshot(ctx) + if err != nil { + return err + } + if snap != nil && slices.Contains(snap.Capabilities, wire.CapIssuesUpdatePersistence) { + return nil + } + // The case-2 text names the server and the token, so `bd promote` + // against an older server says what to upgrade rather than only that the + // operation is unsupported. It unwraps to *storage.ErrUnsupported with + // Capability set, like every other capability refusal. + return wire.NewCapabilityError(wire.OpUpdateIssue, wire.CapIssuesUpdatePersistence, l.store.target.String(), snap) +} + // applyTemplateGuardForServer decides, BEFORE the dial and from the cached // handshake, how the template read-only guard (storage // issueops.AuthorizeTemplateUpdate) reaches the server this request goes to. @@ -779,6 +809,12 @@ func encodeIssuePatch(patch issueops.IssuePatch) (map[string]any, error) { } setString(out, "assignee", patch.Assignee) setString(out, "parent_id", patch.ParentID) + // The plane move (issues.update.persistence). Update has already refused + // it, before the dial, against a server that does not advertise the token; + // this only spells it. + if patch.Persistence.Set { + out["persistence"] = string(patch.Persistence.Value) + } if metadataPatched(patch.Metadata) { document, err := encodeMetadataPatch(patch.Metadata) if err != nil { @@ -910,8 +946,6 @@ func refuseExcludedPatchMembers(patch issueops.IssuePatch) error { return refuse(encode.OpUpdateIssue, "W-IssuePatch.SpecID") case patch.AwaitID.Set: return refuse(encode.OpUpdateIssue, "W-IssuePatch.AwaitID") - case patch.Persistence.Set: - return refuse(encode.OpUpdateIssue, "W-IssuePatch.Persistence") } return nil } diff --git a/internal/httpclient/served_claim_lifecycle_test.go b/internal/httpclient/served_claim_lifecycle_test.go index 08e5bc810..3362814c5 100644 --- a/internal/httpclient/served_claim_lifecycle_test.go +++ b/internal/httpclient/served_claim_lifecycle_test.go @@ -534,11 +534,12 @@ func TestServedLifecycleCloseExpectedVersionSingleWinnerUnderConcurrency(t *test // `force_notes_overwrite` before them. Their rows (W-UpdateRequest.Claim, // .ForceAssigneeTransfer, .ForceClosePolicy) are RETIRED. // -// What still parks after them is TWO members updateIssue publishes nothing for -// (W-IssuePatch.Persistence, W-UpdateRequest.Provenance), each named so the -// lock counts the contract rather than reading it as unwritten. Both refusals -// are themselves asserted by TestUpdateRefusesEveryMemberTheWireExcludes, which -// RUNS, so no park here stands in for an unpinned behavior. +// What still parks after them is ONE member updateIssue publishes nothing for +// (W-UpdateRequest.Provenance), named so the lock counts the contract rather +// than reading it as unwritten. W-IssuePatch.Persistence left the parks with +// issues.update.persistence (S21b). The remaining refusal is itself asserted by +// TestUpdateRefusesEveryMemberTheWireExcludes, which RUNS, so no park here +// stands in for an unpinned behavior. // TestServedLifecycleUpdateClaimIsAMutationWhenThePatchRestoresTheRow is the // claim folded into an update: a mutation even when the patch beside it restores @@ -808,18 +809,28 @@ func TestServedLifecycleUpdateClosePolicy(t *testing.T) { conformance.RunLifecycleUpdateClosePolicy(t, t.Context(), newServedUpdateFixture(t, "hlcp")) } -// TestServedLifecycleUpdatePersistentPreservesUnversionedClass parks on -// IssuePatch.Persistence, which neither IssuePatchBody nor ApplyPatchBody -// publishes: moving a row between planes mid-plan is a different act from -// writing its fields, and a dropped persistence mode would answer "no change" -// to a request that asked for one. +// TestServedLifecycleUpdatePersistentPreservesUnversionedClass RUNS since +// issues.update.persistence (S21b): IssuePatchBody publishes `persistence` and +// the client sends it, so the restatement is the server's own role call. func TestServedLifecycleUpdatePersistentPreservesUnversionedClass(t *testing.T) { - skipKnownDivergence(t, "W-IssuePatch.Persistence", parkBead, - "the case restates an unversioned row as persistent, and the wire publishes no persistence member "+ - "on either patch body; the client refuses it rather than reporting a no-op it did not ask the server for") conformance.RunLifecycleUpdatePersistentPreservesUnversionedClass(t, t.Context(), newServedUpdateFixture(t, "hlpu")) } +// TestServedLifecycleUpdateWispModesRefuseAnUnversionedRow is the role's +// refusal answered as a 400 the client maps back to ErrValidation; before the +// role classified it, the server answered a 500 `internal` and emitted +// `request_error` for a request the caller could have fixed. +func TestServedLifecycleUpdateWispModesRefuseAnUnversionedRow(t *testing.T) { + conformance.RunLifecycleUpdateWispModesRefuseAnUnversionedRow(t, t.Context(), newServedUpdateFixture(t, "hluw")) +} + +// TestServedLifecycleUpdatePersistentPromotesAWisp is the plane move `bd +// promote` sends over http (issues.update.persistence, S21b), served by the +// role the direct route runs. +func TestServedLifecycleUpdatePersistentPromotesAWisp(t *testing.T) { + conformance.RunLifecycleUpdatePersistentPromotesAWisp(t, t.Context(), newServedUpdateFixture(t, "hlpw")) +} + // TestServedLifecycleUpdateProvenanceLabelsHistory is the update-side twin of // the reopen park above: the whole purpose of the field is the LABEL on the // history entry, and the server writes its own, so dropping it would leave the diff --git a/internal/httpclient/update_persistence_test.go b/internal/httpclient/update_persistence_test.go new file mode 100644 index 000000000..f53dadd7a --- /dev/null +++ b/internal/httpclient/update_persistence_test.go @@ -0,0 +1,85 @@ +package httpclient + +import ( + "errors" + "strings" + "testing" + + "github.com/steveyegge/beads/internal/httpapi/apigen" + "github.com/steveyegge/beads/internal/httpclient/wire" + "github.com/steveyegge/beads/issueops" +) + +// TestUpdatePersistenceIsSentOnlyToAServerThatAdvertisesIt pins the plane +// move `bd promote` (issueops.Promote) sends. Against a server advertising +// issues.update.persistence it is one updateIssue carrying +// `patch.persistence`; against one that does not, it is the typed capability +// refusal naming the token, raised BEFORE the dial: the member is never +// dropped (the server would answer "no change" to a move it never saw) and +// never sent to a server that would refuse it as an unknown parameter. +func TestUpdatePersistenceIsSentOnlyToAServerThatAdvertisesIt(t *testing.T) { + promote := issueops.UpdateRequest{ + Actor: "alice", IssueID: "bd-w1", + Patch: issueops.IssuePatch{Persistence: set(issueops.PersistenceModePersistent)}, + } + + t.Run("advertised", func(t *testing.T) { + w := &stubWire{update: &apigen.UpdateIssueResponse{Revision: "7", Changed: true}} + lifecycle, err := New(testTarget(t), w, &apigen.ContextResponse{ + BdVersion: "1.2.3", + Capabilities: []string{wire.CapIssuesUpdateAllowTemplate, wire.CapIssuesUpdatePersistence}, + }).IssueLifecycle() + if err != nil { + t.Fatal(err) + } + res, err := lifecycle.Update(t.Context(), promote) + if err != nil { + t.Fatalf("Update: %v", err) + } + if !res.Changed { + t.Error("Changed = false, want the server's answer") + } + if len(w.calls) != 1 || w.calls[0] != "updateIssue:bd-w1" { + t.Fatalf("calls = %v, want one updateIssue", w.calls) + } + if got := w.lastPatch["persistence"]; got != "persistent" { + t.Errorf("patch.persistence = %v, want \"persistent\"; patch = %v", got, w.lastPatch) + } + if len(w.lastPatch) != 1 { + t.Errorf("patch = %v, want the persistence member alone", w.lastPatch) + } + }) + + t.Run("unadvertised", func(t *testing.T) { + w := &stubWire{update: &apigen.UpdateIssueResponse{Revision: "7"}} + lifecycle, err := stubStore(t, w).IssueLifecycle() + if err != nil { + t.Fatal(err) + } + _, err = lifecycle.Update(t.Context(), promote) + requireCapabilityRefusal(t, err, wire.CapIssuesUpdatePersistence, w) + if !errors.Is(err, wire.ErrCapabilityAbsent) { + t.Errorf("err = %v, want it to match wire.ErrCapabilityAbsent", err) + } + // The message names the token, so a user knows what the server lacks. + if !strings.Contains(err.Error(), wire.CapIssuesUpdatePersistence) { + t.Errorf("refusal %q does not name %s", err.Error(), wire.CapIssuesUpdatePersistence) + } + }) + + t.Run("an update without the move is unaffected", func(t *testing.T) { + w := &stubWire{update: &apigen.UpdateIssueResponse{Revision: "7"}} + lifecycle, err := stubStore(t, w).IssueLifecycle() + if err != nil { + t.Fatal(err) + } + if _, err := lifecycle.Update(t.Context(), issueops.UpdateRequest{ + Actor: "alice", IssueID: "bd-1", Patch: issueops.IssuePatch{Title: set("t")}, + }); err != nil { + t.Fatalf("Update: %v", err) + } + if _, sent := w.lastPatch["persistence"]; sent { + t.Errorf("patch = %v carries persistence nobody asked for", w.lastPatch) + } + }) +} diff --git a/internal/httpclient/wire/handshake.go b/internal/httpclient/wire/handshake.go index 5f7ee0131..bc395596c 100644 --- a/internal/httpclient/wire/handshake.go +++ b/internal/httpclient/wire/handshake.go @@ -249,6 +249,14 @@ const CapBatchApplyDepAddLineage = "issues.batchApply.depAddLineage" // (bd-jkp9v3). const CapIssuesUpdateAllowTemplate = "issues.update.allowTemplate" +// CapIssuesUpdatePersistence is the behavior capability announcing that +// updateIssue accepts `patch.persistence` (issueops.IssuePatch.Persistence, +// the plane move behind `bd promote`). lifecycle.go sends the member only to +// a server advertising it, and refuses the move before the dial otherwise: +// there is no client-side fallback, because the move is one transaction on +// the server. +const CapIssuesUpdatePersistence = "issues.update.persistence" + // CapIssuesCreateDefaultPriority is the behavior capability announcing that // the server stores the create default priority for an ABSENT `priority` // member on issues.create, issues.batchCreate and issues.batchApply create @@ -408,7 +416,7 @@ var behaviorCapabilities = []string{ CapSweepWispsPlane, CapSweepLiveDependents, CapSweepLimit, CapBatchApplyDepAddLineage, CapIssuesUpdateAllowTemplate, CapIssuesCreateDefaultPriority, CapCloseAutoCloseMolecule, CapListSearch, - CapListNoAssignee, CapListTitle, CapListIDs, + CapListNoAssignee, CapListTitle, CapListIDs, CapIssuesUpdatePersistence, } // CapabilityFor reports the capability token gating op, and whether op is on diff --git a/internal/httpclient/wire/vocabulary_test.go b/internal/httpclient/wire/vocabulary_test.go index aec04ef48..7dcbd2134 100644 --- a/internal/httpclient/wire/vocabulary_test.go +++ b/internal/httpclient/wire/vocabulary_test.go @@ -214,12 +214,12 @@ func TestTheProjectIdentityVocabularyMatchesTheServer(t *testing.T) { httpapi.CapIssuesSweepWispsPlane, httpapi.CapIssuesSweepLiveDependents, httpapi.CapIssuesSweepLimit, httpapi.CapBatchApplyDepAddLineage, httpapi.CapIssuesUpdateAllowTemplate, httpapi.CapIssuesCreateDefaultPriority, httpapi.CapIssuesCloseAutoCloseMolecule, httpapi.CapIssuesListSearch, - httpapi.CapIssuesListNoAssignee, httpapi.CapIssuesListTitle, httpapi.CapListIDs, + httpapi.CapIssuesListNoAssignee, httpapi.CapIssuesListTitle, httpapi.CapListIDs, httpapi.CapIssuesUpdatePersistence, }) { t.Errorf("behaviorCapabilities = %v, want the server's project.enforce, issues.batchApplyLarge, issues.list.sort, "+ "issues.count.scope, issues.sweep.wispsPlane, issues.sweep.liveDependents, issues.sweep.limit, "+ "issues.batchApply.depAddLineage, issues.update.allowTemplate, issues.create.defaultPriority, issues.close.autoCloseMolecule, issues.list.search, "+ - "issues.list.noAssignee, issues.list.title and issues.list.ids tokens", behaviorCapabilities) + "issues.list.noAssignee, issues.list.title, issues.list.ids and issues.update.persistence tokens", behaviorCapabilities) } } diff --git a/internal/httpclient/write_ledger_test.go b/internal/httpclient/write_ledger_test.go index 0532247bb..54ddf934f 100644 --- a/internal/httpclient/write_ledger_test.go +++ b/internal/httpclient/write_ledger_test.go @@ -318,6 +318,12 @@ func writeShapes() []writeShape { "Assignee": member("assignee"), "ParentID": member("parent_id"), "Metadata": member("metadata"), + // The plane move, carried since issues.update.persistence + // (S21b, `bd promote` over http). Only this shape: the batch + // item's ApplyPatchBody still excludes it, so + // W-IssuePatch.Persistence stays a refusal there — the Owner + // row's arrangement, the other way round. + "Persistence": member("persistence"), }, // NOTHING IS PENDING, and the set is empty rather than absent for the // reason the second list in accessors.go was: it held the two diff --git a/internal/httpclient/write_roles_test.go b/internal/httpclient/write_roles_test.go index f4645ef0a..b748bcb29 100644 --- a/internal/httpclient/write_roles_test.go +++ b/internal/httpclient/write_roles_test.go @@ -410,7 +410,9 @@ func TestUpdateRefusesEveryMemberTheWireExcludes(t *testing.T) { "Patch.ClosedBySession": {Patch: issueops.IssuePatch{ClosedBySession: set("s1")}}, "Patch.SpecID": {Patch: issueops.IssuePatch{SpecID: set("spec")}}, "Patch.AwaitID": {Patch: issueops.IssuePatch{AwaitID: set("await")}}, - "Patch.Persistence": {Patch: issueops.IssuePatch{Persistence: set(issueops.PersistenceModeEphemeral)}}, + // Patch.Persistence WAS here; issues.update.persistence publishes it + // (S21b). TestUpdatePersistenceIsSentOnlyToAServerThatAdvertisesIt + // is the positive assertion and the pre-dial capability refusal. // Patch.Labels.Add and Patch.Labels.Remove WERE here, and their absence // is the flip rather than an oversight: upstream #5510 published diff --git a/internal/storage/dolt/ephemeral_routing.go b/internal/storage/dolt/ephemeral_routing.go index d745aa427..8288bbb47 100644 --- a/internal/storage/dolt/ephemeral_routing.go +++ b/internal/storage/dolt/ephemeral_routing.go @@ -202,7 +202,8 @@ func (s *DoltStore) PartitionWispIDs(ctx context.Context, ids []string) (wispIDs } // PromoteFromEphemeral copies an issue from the wisps table to the issues table, -// clearing the Ephemeral flag. Used by bd promote and mol squash to crystallize wisps. +// clearing the Ephemeral flag. No bd command calls it: bd promote runs +// issueops.Promote, whose persistence move also carries the child counter. // // Uses direct SQL inserts to bypass IsEphemeralID routing, which would otherwise // redirect label/dependency/event writes back to wisp tables. diff --git a/internal/storage/dolt/issue_operations_persistence_test.go b/internal/storage/dolt/issue_operations_persistence_test.go index 3b4a8befe..a7c1ef504 100644 --- a/internal/storage/dolt/issue_operations_persistence_test.go +++ b/internal/storage/dolt/issue_operations_persistence_test.go @@ -3,8 +3,10 @@ package dolt import ( "context" "database/sql" + "errors" "testing" + "github.com/steveyegge/beads/internal/storage" "github.com/steveyegge/beads/internal/storage/issueops" "github.com/steveyegge/beads/internal/types" ) @@ -175,8 +177,39 @@ func TestMoveIssuePersistenceInTxRefusesUnversionedDemotion(t *testing.T) { _, err = issueops.MoveIssuePersistenceInTx(ctx, tx, current, types.PersistenceModeEphemeral, "test-actor") return err }) - if err == nil { - t.Fatal("unversioned demotion succeeded") + // The request is refused, not the row: ErrValidation is what makes this a + // 400 over http rather than a 500. + if !errors.Is(err, storage.ErrValidation) || !errors.Is(err, types.ErrUnversionedWispMove) { + t.Fatalf("unversioned demotion error = %v, want ErrValidation wrapping ErrUnversionedWispMove", err) + } + got, err := store.GetIssue(ctx, issue.ID) + if err != nil || got.Ephemeral || got.NoHistory { + t.Fatalf("refusal state = %#v, %v", got, err) + } +} + +func TestMoveIssuePersistenceInTxRefusesDemotionWithRetainedSnapshots(t *testing.T) { + store, cleanup := setupTestStore(t) + defer cleanup() + ctx := context.Background() + issue := &types.Issue{ID: "persist-snapshot", Title: "snapshot", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask} + if err := store.CreateIssue(ctx, issue, "tester"); err != nil { + t.Fatal(err) + } + // The snapshot tables have no default id since migration 0051. + if _, err := store.db.ExecContext(ctx, `INSERT INTO issue_snapshots (id, issue_id, snapshot_time, compaction_level, original_size, compressed_size, original_content) VALUES (?, ?, NOW(), 1, 1, 1, ?)`, "persist-snapshot-row", issue.ID, "snapshot"); err != nil { + t.Fatal(err) + } + err := store.withRetryTx(ctx, func(tx *sql.Tx) error { + current, err := issueops.GetIssueInTx(ctx, tx, issue.ID) + if err != nil { + return err + } + _, err = issueops.MoveIssuePersistenceInTx(ctx, tx, current, types.PersistenceModeEphemeral, "test-actor") + return err + }) + if !errors.Is(err, storage.ErrValidation) { + t.Fatalf("demotion with retained snapshots error = %v, want ErrValidation", err) } got, err := store.GetIssue(ctx, issue.ID) if err != nil || got.Ephemeral || got.NoHistory { diff --git a/internal/storage/dolt/lifecycle_update_contract_test.go b/internal/storage/dolt/lifecycle_update_contract_test.go index 2696c7834..0132cbd4f 100644 --- a/internal/storage/dolt/lifecycle_update_contract_test.go +++ b/internal/storage/dolt/lifecycle_update_contract_test.go @@ -87,6 +87,12 @@ func TestLifecycleUpdateContract(t *testing.T) { t.Run("PersistentPreservesUnversionedClass", func(t *testing.T) { conformance.RunLifecycleUpdatePersistentPreservesUnversionedClass(t, ctx, fixture) }) + t.Run("WispModesRefuseAnUnversionedRow", func(t *testing.T) { + conformance.RunLifecycleUpdateWispModesRefuseAnUnversionedRow(t, ctx, fixture) + }) + t.Run("PersistentPromotesAWisp", func(t *testing.T) { + conformance.RunLifecycleUpdatePersistentPromotesAWisp(t, ctx, fixture) + }) t.Run("ProvenanceLabelsHistory", func(t *testing.T) { conformance.RunLifecycleUpdateProvenanceLabelsHistory(t, ctx, fixture) }) diff --git a/internal/storage/domain/db/issue.go b/internal/storage/domain/db/issue.go index 8c78e1ff5..0d6064dde 100644 --- a/internal/storage/domain/db/issue.go +++ b/internal/storage/domain/db/issue.go @@ -114,11 +114,12 @@ func (r *issueSQLRepositoryImpl) InsertBatch(ctx context.Context, issues []*type // PromoteFromEphemeral promotes an active wisp into the Dolt-versioned issues // plane in place: same id, wisp_type retained, labels/dependencies/events/ // comments carried across to the permanent tables, inbound wisp-targeted -// dependency edges retargeted, and blocked state recomputed. It delegates to -// the exact issueops implementation the classic (direct/embedded) route runs, -// so the two modes cannot drift. The issueops error is returned unwrapped on -// purpose: the CLI surfaces it verbatim ("wisp not found"), and that -// text is part of the classic error contract. +// dependency edges retargeted, and blocked state recomputed. It runs the +// issueops implementation DoltStorage.PromoteFromEphemeral runs and returns +// its error unwrapped ("wisp not found"). `bd promote` no longer reaches +// it on any route: issueops.Promote makes the persistence move instead +// (MovePersistence below, on this layer), which also carries the child +// counter. func (r *issueSQLRepositoryImpl) PromoteFromEphemeral(ctx context.Context, id, actor string) error { if id == "" { return errors.New("db: PromoteFromEphemeral: id must not be empty") diff --git a/internal/storage/domain/issue.go b/internal/storage/domain/issue.go index 7f5ec7208..716810eca 100644 --- a/internal/storage/domain/issue.go +++ b/internal/storage/domain/issue.go @@ -863,8 +863,10 @@ func (u *issueUseCaseImpl) isWispID(ctx context.Context, id string) (bool, error // PromoteWisp moves an active wisp to the Dolt-versioned issues plane, // preserving its id, wisp_type, labels, dependencies, events, and comments. // One-way: the promoted row is no longer ephemeral, so purge won't reclaim -// it. The repository error passes through unwrapped — the CLI surfaces it -// verbatim and its text is part of the classic error contract. +// it. The repository error passes through unwrapped. `bd promote` does not +// call it: the proxied-server route runs issueops.Promote, whose move is +// ApplyUpdate's persistence branch (MovePersistence), which also carries the +// child counter. func (u *issueUseCaseImpl) PromoteWisp(ctx context.Context, id, actor string) error { if id == "" { return fmt.Errorf("promote wisp: id must not be empty") diff --git a/internal/storage/embeddeddolt/lifecycle_update_contract_test.go b/internal/storage/embeddeddolt/lifecycle_update_contract_test.go index 635c3ff13..93849a8ae 100644 --- a/internal/storage/embeddeddolt/lifecycle_update_contract_test.go +++ b/internal/storage/embeddeddolt/lifecycle_update_contract_test.go @@ -88,6 +88,12 @@ func TestLifecycleUpdateContract(t *testing.T) { t.Run("PersistentPreservesUnversionedClass", func(t *testing.T) { conformance.RunLifecycleUpdatePersistentPreservesUnversionedClass(t, ctx, fixture) }) + t.Run("WispModesRefuseAnUnversionedRow", func(t *testing.T) { + conformance.RunLifecycleUpdateWispModesRefuseAnUnversionedRow(t, ctx, fixture) + }) + t.Run("PersistentPromotesAWisp", func(t *testing.T) { + conformance.RunLifecycleUpdatePersistentPromotesAWisp(t, ctx, fixture) + }) t.Run("ProvenanceLabelsHistory", func(t *testing.T) { conformance.RunLifecycleUpdateProvenanceLabelsHistory(t, ctx, fixture) }) diff --git a/internal/storage/issueops/persistence.go b/internal/storage/issueops/persistence.go index 1d8a1e95b..6a395c75c 100644 --- a/internal/storage/issueops/persistence.go +++ b/internal/storage/issueops/persistence.go @@ -2,8 +2,10 @@ package issueops import ( "context" + "errors" "fmt" + "github.com/steveyegge/beads/internal/storage" "github.com/steveyegge/beads/internal/types" ) @@ -32,6 +34,14 @@ func moveIssuePersistenceInTx(ctx context.Context, tx DBTX, current *types.Issue } ephemeral, noHistory, storageClass, err := types.NormalizePersistenceMode(*current, mode) if err != nil { + // The unversioned refusal is the request's: the row is sound and the + // move it asks for is one its class never makes. The other errors + // describe a row that breaks its own persistence invariants, so they + // stay unclassified; an invalid mode is refused before any update + // path gets here (ValidateUpdateRequest). + if errors.Is(err, types.ErrUnversionedWispMove) { + return PersistenceMoveResult{}, fmt.Errorf("%w: %w", storage.ErrValidation, err) + } return PersistenceMoveResult{}, err } sourceWisp, err := isActiveWispForPersistenceMove(ctx, tx, current.ID) @@ -164,6 +174,9 @@ func persistenceIssueTable(wisp bool) string { return "issues" } +// rejectPersistenceDemotion refuses a durable-to-wisp move of a row that has +// retained snapshots. The refusal is the request's (ErrValidation); a failed +// count is not. func rejectPersistenceDemotion(ctx context.Context, tx DBTX, id string) error { for _, table := range []string{"issue_snapshots", "compaction_snapshots"} { var count int @@ -171,7 +184,7 @@ func rejectPersistenceDemotion(ctx context.Context, tx DBTX, id string) error { return fmt.Errorf("check retained snapshots in %s: %w", table, err) } if count > 0 { - return fmt.Errorf("cannot demote issue %s with retained snapshots", id) + return fmt.Errorf("%w: cannot demote issue %s with retained snapshots", storage.ErrValidation, id) } } return nil diff --git a/internal/storage/uow/lifecycle_update_contract_test.go b/internal/storage/uow/lifecycle_update_contract_test.go index 85983bf4f..4a1a0677d 100644 --- a/internal/storage/uow/lifecycle_update_contract_test.go +++ b/internal/storage/uow/lifecycle_update_contract_test.go @@ -89,6 +89,12 @@ func TestLifecycleUpdateContract(t *testing.T) { t.Run("PersistentPreservesUnversionedClass", func(t *testing.T) { conformance.RunLifecycleUpdatePersistentPreservesUnversionedClass(t, ctx, fixture) }) + t.Run("WispModesRefuseAnUnversionedRow", func(t *testing.T) { + conformance.RunLifecycleUpdateWispModesRefuseAnUnversionedRow(t, ctx, fixture) + }) + t.Run("PersistentPromotesAWisp", func(t *testing.T) { + conformance.RunLifecycleUpdatePersistentPromotesAWisp(t, ctx, fixture) + }) t.Run("ProvenanceLabelsHistory", func(t *testing.T) { conformance.RunLifecycleUpdateProvenanceLabelsHistory(t, ctx, fixture) }) diff --git a/internal/storage/uow/notifying.go b/internal/storage/uow/notifying.go index d0bafd710..1d9ee1e0f 100644 --- a/internal/storage/uow/notifying.go +++ b/internal/storage/uow/notifying.go @@ -31,8 +31,8 @@ // # Where this plumbing deliberately differs from the DoltStorage one // // Every per-verb firing rule below is matched 1:1 against the decorator that -// implements it (each override cites its twin). These five are the exceptions, -// and they are listed here rather than argued in five places: +// implements it (each override cites its twin). These four are the exceptions, +// and they are listed here rather than argued in four places: // // 1. LABEL MULTIPLICITY ON CREATE. The DoltStorage chain replays a legacy // sequence for a create that carries labels: on_create with the labels @@ -61,16 +61,7 @@ // that writes nothing; the DoltStorage plumbing passes the precondition // into the close. See specWrites. // -// 5. THE PROMOTION COMMENT. `bd promote` records an audit comment on the -// promoted issue, and this plumbing's one comment verb fires on_update for -// it. The DoltStorage route writes that comment through the legacy -// AddComment, which the decorator wraps only INSIDE a transaction -// (hookTrackingTransaction.AddComment) and not at the store level, where -// promote calls it — so an embedded promote fires nothing. One verb cannot -// tell which caller it is serving, and "a comment landed" is the on_update -// this vocabulary has. -// -// A sixth is not a divergence but is worth stating: a unit of work whose commit +// A fifth is not a divergence but is worth stating: a unit of work whose commit // message is empty is ROLLED BACK by RunTxResult, and a rolled-back attempt // fires nothing — so a write that lands nothing reports nothing, on both // plumbings. diff --git a/internal/storage/uow/notifying_parity_test.go b/internal/storage/uow/notifying_parity_test.go index 5114f2212..8626bf9d9 100644 --- a/internal/storage/uow/notifying_parity_test.go +++ b/internal/storage/uow/notifying_parity_test.go @@ -172,8 +172,9 @@ func TestRecordingIssueUseCaseCoversItsSurface(t *testing.T) { "ReclaimExpiredLeases": leases, "WakeExpiredDefers": "the deferred-work sweep is a clock crossing rather than a user's " + "mutation, and the DoltStorage plumbing fires nothing for it", - "PromoteWisp": "moves a row between planes without changing the bead; the DoltStorage " + - "plumbing has no promote hook either", + "PromoteWisp": "no route calls it: bd promote moves the row with ApplyUpdate's " + + "persistence spec, which records the update, and its DoltStorage twin, " + + "PromoteFromEphemeral, fires no hook either", }) } diff --git a/internal/types/storage_class_test.go b/internal/types/storage_class_test.go index d9d8dabcf..acaf36834 100644 --- a/internal/types/storage_class_test.go +++ b/internal/types/storage_class_test.go @@ -2,6 +2,8 @@ package types import ( "encoding/json" + "errors" + "fmt" "strings" "testing" "time" @@ -277,8 +279,16 @@ func TestNormalizePersistenceModeRejectsPlaneClassIncoherence(t *testing.T) { {"durable with explicit ephemeral", Issue{StorageClass: StorageClassEphemeral}, PersistenceModePersistent}, } for _, tc := range cases { - if _, _, _, err := NormalizePersistenceMode(tc.current, tc.target); err == nil { + _, _, _, err := NormalizePersistenceMode(tc.current, tc.target) + if err == nil { t.Errorf("%s: NormalizePersistenceMode succeeded, want error", tc.name) + continue + } + // A row that breaks its own invariants is not the request's refusal, + // even when its class is unversioned: callers classify only + // ErrUnversionedWispMove as validation. + if errors.Is(err, ErrUnversionedWispMove) { + t.Errorf("%s: NormalizePersistenceMode error %q matches ErrUnversionedWispMove, want the row-invariant error", tc.name, err) } } } @@ -294,8 +304,13 @@ func TestNormalizePersistenceModeRejectsUnsetAndUnknown(t *testing.T) { func TestNormalizePersistenceModeRejectsUnversionedDemotion(t *testing.T) { current := Issue{StorageClass: StorageClassUnversioned} for _, target := range []PersistenceMode{PersistenceModeEphemeral, PersistenceModeNoHistory} { - if _, _, _, err := NormalizePersistenceMode(current, target); err == nil { - t.Errorf("NormalizePersistenceMode(unversioned, %q) succeeded, want error", target) + _, _, _, err := NormalizePersistenceMode(current, target) + if !errors.Is(err, ErrUnversionedWispMove) { + t.Errorf("NormalizePersistenceMode(unversioned, %q) error = %v, want ErrUnversionedWispMove", target, err) + continue + } + if want := fmt.Sprintf("cannot move unversioned record to persistence mode %q", target); err.Error() != want { + t.Errorf("NormalizePersistenceMode(unversioned, %q) error = %q, want %q", target, err, want) } } } diff --git a/internal/types/types.go b/internal/types/types.go index 7a0edf045..b5461c910 100644 --- a/internal/types/types.go +++ b/internal/types/types.go @@ -1017,12 +1017,19 @@ func (m PersistenceMode) IsValid() bool { return slices.Contains(validPersistenceModes, m) } +// ErrUnversionedWispMove is NormalizePersistenceMode's refusal to move an +// unversioned record to a wisp mode. The record is sound and the requested +// move is what is refused, so callers can classify it apart from the +// row-invariant errors the function also returns. +var ErrUnversionedWispMove = errors.New("cannot move unversioned record") + // NormalizePersistenceMode maps a requested mode from current to its exact // persistence fields without mutating an issue. The returned values are // Ephemeral, NoHistory, and StorageClass, respectively. Plane and retention // changes preserve the create-selected class. Promotion clears an explicit // ephemeral class marker to select normalized versioned storage. An -// unversioned record may remain persistent but cannot move to a wisp mode. +// unversioned record may remain persistent but cannot move to a wisp mode +// (ErrUnversionedWispMove). func NormalizePersistenceMode(current Issue, mode PersistenceMode) (bool, bool, StorageClass, error) { if !mode.IsValid() { return false, false, "", fmt.Errorf("invalid persistence mode %q", mode) @@ -1041,7 +1048,7 @@ func NormalizePersistenceMode(current Issue, mode PersistenceMode) (bool, bool, return false, false, "", fmt.Errorf("storage class ephemeral requires ephemeral or no_history") } if current.StorageClass == StorageClassUnversioned && mode != PersistenceModePersistent { - return false, false, "", fmt.Errorf("cannot move unversioned record to persistence mode %q", mode) + return false, false, "", fmt.Errorf("%w to persistence mode %q", ErrUnversionedWispMove, mode) } if persistenceMode(current) == mode { return current.Ephemeral, current.NoHistory, current.StorageClass, nil diff --git a/issueops/BUILD.bazel b/issueops/BUILD.bazel index e23cdd54a..62fec725e 100644 --- a/issueops/BUILD.bazel +++ b/issueops/BUILD.bazel @@ -30,6 +30,7 @@ go_library( "molecule.go", "molecule_active.go", "moleculestepper.go", + "promote.go", "querier.go", "reader.go", "reader_ready_scope.go", @@ -63,6 +64,7 @@ go_test( "issueops_external_test.go", "molecule_internal_test.go", "molecule_test.go", + "promote_test.go", "search_test.go", ], embed = [":issueops"], diff --git a/issueops/promote.go b/issueops/promote.go new file mode 100644 index 000000000..d14d5bae0 --- /dev/null +++ b/issueops/promote.go @@ -0,0 +1,118 @@ +package issueops + +import ( + "context" + "fmt" +) + +// PromoteRequest describes one `bd promote`: move a wisp onto the durable +// issues plane and record why. +type PromoteRequest struct { + // Actor is the principal the move and the comment are attributed to. It + // must not be empty. + Actor string + // IssueID is the exact canonical id of the wisp. It must not be empty; + // fuzzy or prefix resolution is the caller's, for the reason + // GetRequest.ID gives. + IssueID string + // Reason is the optional text appended to the promotion comment. + Reason string + // Provenance labels the version-control history entry of the move, as + // UpdateRequest.Provenance describes. A remote backend labels its own + // entry, so a caller writing through one leaves it empty. + Provenance string +} + +// PromoteResult reports a promotion. +type PromoteResult struct { + // Issue is the promoted row as the move left it. + Issue *Issue + // CommentErr is set when the move succeeded but the promotion comment + // could not be written. The promotion stands: the comment is the audit + // note, not the act, and bd promote has always reported a failed comment + // as a warning rather than undoing the move. + CommentErr error +} + +// PromoteRoles are the three roles Promote composes. Every backend serves +// all three, so a promotion reads and writes the same way on every route. +type PromoteRoles struct { + Reader Reader + Lifecycle Lifecycle + Commenter Commenter +} + +// NotAWispError refuses a promotion of a row that is not an ephemeral wisp: +// it is already durable, or another writer promoted it first. A no-history +// wisp (NoHistory set, Ephemeral not) is refused with the same sentence, +// because the gate reads the Ephemeral flag as `bd promote` always has; +// `bd update --persistent` is the move for that row. +type NotAWispError struct { + ID string +} + +func (e *NotAWispError) Error() string { + return fmt.Sprintf("%s is not a wisp (already persistent)", e.ID) +} + +// PromotionComment is the audit comment a promotion records on the promoted +// row. Every route records exactly this text. +func PromotionComment(reason string) string { + comment := "Promoted from Level 0" + if reason != "" { + comment += ": " + reason + } + return comment +} + +// Promote is the one library entry for `bd promote`. It reads the row, +// refuses one that is not an ephemeral wisp (*NotAWispError), moves it to the +// durable plane with ONE Lifecycle.Update whose patch is the persistence move +// alone (Persistence = persistent: the row keeps its id, and its labels, +// dependencies, events and comments move with it, atomically, in the role's +// own transaction), and then records the promotion comment through the +// Commenter. +// +// A move that changed nothing lost a race to another promoter, and is +// reported as *NotAWispError without a second comment. Every refusal of the +// read or the move is returned unchanged, so a backend that cannot express +// the move (an http server without the issues.update.persistence capability) +// reaches the caller as its own typed refusal, before anything was written. +func Promote(ctx context.Context, roles PromoteRoles, req PromoteRequest) (PromoteResult, error) { + if req.Actor == "" { + return PromoteResult{}, fmt.Errorf("%w: promote: actor is required", ErrValidation) + } + if req.IssueID == "" { + return PromoteResult{}, fmt.Errorf("%w: promote: issue id is required", ErrValidation) + } + current, err := roles.Reader.Get(ctx, GetRequest{ID: req.IssueID}) + if err != nil { + return PromoteResult{}, err + } + if !current.Ephemeral { + return PromoteResult{}, &NotAWispError{ID: req.IssueID} + } + moved, err := roles.Lifecycle.Update(ctx, UpdateRequest{ + Actor: req.Actor, + IssueID: req.IssueID, + Patch: IssuePatch{ + Persistence: Field[PersistenceMode]{Set: true, Value: PersistenceModePersistent}, + }, + Provenance: req.Provenance, + }) + if err != nil { + return PromoteResult{}, err + } + if !moved.Changed { + return PromoteResult{}, &NotAWispError{ID: req.IssueID} + } + result := PromoteResult{Issue: moved.Issue} + if _, err := roles.Commenter.AddComment(ctx, AddCommentRequest{ + Author: req.Actor, + IssueID: req.IssueID, + Text: PromotionComment(req.Reason), + }); err != nil { + result.CommentErr = err + } + return result, nil +} diff --git a/issueops/promote_test.go b/issueops/promote_test.go new file mode 100644 index 000000000..28cb433cb --- /dev/null +++ b/issueops/promote_test.go @@ -0,0 +1,207 @@ +package issueops_test + +import ( + "context" + "errors" + "reflect" + "testing" + + "github.com/steveyegge/beads/issueops" +) + +// promoteFakes is the three roles issueops.Promote composes. Each embeds its +// interface so a method the entry must not call panics on the nil. +type promoteFakes struct { + issue *issueops.Issue + getErr error + updateErr error + unchanged bool + commentErr error + + updates []issueops.UpdateRequest + comments []issueops.AddCommentRequest +} + +type promoteReader struct { + issueops.Reader + f *promoteFakes +} + +func (r promoteReader) Get(_ context.Context, req issueops.GetRequest) (*issueops.IssueDetails, error) { + if r.f.getErr != nil { + return nil, r.f.getErr + } + if r.f.issue == nil || r.f.issue.ID != req.ID { + return nil, issueops.ErrNotFound + } + return &issueops.IssueDetails{Issue: *r.f.issue}, nil +} + +type promoteLifecycle struct { + issueops.Lifecycle + f *promoteFakes +} + +func (l promoteLifecycle) Update(_ context.Context, req issueops.UpdateRequest) (issueops.UpdateResult, error) { + l.f.updates = append(l.f.updates, req) + if l.f.updateErr != nil { + return issueops.UpdateResult{}, l.f.updateErr + } + promoted := *l.f.issue + promoted.Ephemeral = false + return issueops.UpdateResult{Issue: &promoted, Changed: !l.f.unchanged}, nil +} + +type promoteCommenter struct { + issueops.Commenter + f *promoteFakes +} + +func (c promoteCommenter) AddComment(_ context.Context, req issueops.AddCommentRequest) (issueops.AddCommentResult, error) { + c.f.comments = append(c.f.comments, req) + if c.f.commentErr != nil { + return issueops.AddCommentResult{}, c.f.commentErr + } + return issueops.AddCommentResult{Comment: &issueops.Comment{IssueID: req.IssueID, Author: req.Author, Text: req.Text}}, nil +} + +func (f *promoteFakes) roles() issueops.PromoteRoles { + return issueops.PromoteRoles{ + Reader: promoteReader{f: f}, + Lifecycle: promoteLifecycle{f: f}, + Commenter: promoteCommenter{f: f}, + } +} + +func wisp(id string) *issueops.Issue { + return &issueops.Issue{ID: id, Title: "a wisp", Ephemeral: true} +} + +func TestPromoteMovesTheWispThroughOnePersistenceUpdateThenComments(t *testing.T) { + f := &promoteFakes{issue: wisp("bd-w1")} + res, err := issueops.Promote(t.Context(), f.roles(), issueops.PromoteRequest{ + Actor: "alice", IssueID: "bd-w1", Reason: "keep it", Provenance: "bd: promote bd-w1", + }) + if err != nil { + t.Fatalf("Promote: %v", err) + } + if len(f.updates) != 1 { + t.Fatalf("updates = %d, want exactly one", len(f.updates)) + } + u := f.updates[0] + if u.Actor != "alice" || u.IssueID != "bd-w1" || u.Provenance != "bd: promote bd-w1" { + t.Errorf("update request = %+v, want actor alice, id bd-w1 and the caller's provenance", u) + } + if !u.Patch.Persistence.Set || u.Patch.Persistence.Value != issueops.PersistenceModePersistent { + t.Errorf("update patch persistence = %+v, want set to persistent", u.Patch.Persistence) + } + // The update is the plane move and nothing else. + only := issueops.IssuePatch{Persistence: u.Patch.Persistence} + if !reflect.DeepEqual(u.Patch, only) { + t.Errorf("update patch carries more than the persistence move: %+v", u.Patch) + } + if len(f.comments) != 1 { + t.Fatalf("comments = %d, want exactly one", len(f.comments)) + } + c := f.comments[0] + if c.Author != "alice" || c.IssueID != "bd-w1" || c.Text != "Promoted from Level 0: keep it" { + t.Errorf("comment = %+v, want alice's promotion comment with the reason", c) + } + if res.Issue == nil || res.Issue.Ephemeral || res.CommentErr != nil { + t.Errorf("result = %+v, want the promoted row and no comment error", res) + } +} + +func TestPromotionCommentWithoutAReason(t *testing.T) { + if got := issueops.PromotionComment(""); got != "Promoted from Level 0" { + t.Errorf("PromotionComment(\"\") = %q", got) + } +} + +func TestPromoteRefusesARowThatIsNotAWispBeforeWriting(t *testing.T) { + f := &promoteFakes{issue: &issueops.Issue{ID: "bd-1", Title: "durable"}} + _, err := issueops.Promote(t.Context(), f.roles(), issueops.PromoteRequest{Actor: "alice", IssueID: "bd-1"}) + var notWisp *issueops.NotAWispError + if !errors.As(err, ¬Wisp) || notWisp.ID != "bd-1" { + t.Fatalf("err = %v, want *NotAWispError for bd-1", err) + } + if err.Error() != "bd-1 is not a wisp (already persistent)" { + t.Errorf("message = %q, want the sentence bd promote always printed", err.Error()) + } + if len(f.updates) != 0 || len(f.comments) != 0 { + t.Errorf("wrote %d updates and %d comments, want none", len(f.updates), len(f.comments)) + } +} + +func TestPromoteReportsALostRaceAsNotAWisp(t *testing.T) { + // Another writer promoted the row between the read and the update: the + // update is a no-op, and no second promotion comment is written. + f := &promoteFakes{issue: wisp("bd-w2"), unchanged: true} + _, err := issueops.Promote(t.Context(), f.roles(), issueops.PromoteRequest{Actor: "alice", IssueID: "bd-w2"}) + var notWisp *issueops.NotAWispError + if !errors.As(err, ¬Wisp) { + t.Fatalf("err = %v, want *NotAWispError", err) + } + if len(f.comments) != 0 { + t.Errorf("wrote %d comments after a no-op promote, want none", len(f.comments)) + } +} + +func TestPromotePassesRefusalsThroughUnchanged(t *testing.T) { + refusal := &issueops.ErrUnsupported{Op: "Lifecycle.Update", Backend: "http", Capability: "issues.update.persistence"} + for name, f := range map[string]*promoteFakes{ + "missing": {}, + "get": {issue: wisp("bd-w3"), getErr: errors.New("boom")}, + "update": {issue: wisp("bd-w3"), updateErr: refusal}, + } { + t.Run(name, func(t *testing.T) { + _, err := issueops.Promote(t.Context(), f.roles(), issueops.PromoteRequest{Actor: "alice", IssueID: "bd-w3"}) + if err == nil { + t.Fatal("no error") + } + switch name { + case "missing": + if !errors.Is(err, issueops.ErrNotFound) { + t.Errorf("err = %v, want ErrNotFound", err) + } + case "update": + var unsup *issueops.ErrUnsupported + if !errors.As(err, &unsup) || unsup.Capability != "issues.update.persistence" { + t.Errorf("err = %v, want the capability refusal unchanged", err) + } + } + if len(f.comments) != 0 { + t.Errorf("commented after a failed promote") + } + }) + } +} + +func TestPromoteKeepsThePromotionWhenTheCommentFails(t *testing.T) { + f := &promoteFakes{issue: wisp("bd-w4"), commentErr: errors.New("comment down")} + res, err := issueops.Promote(t.Context(), f.roles(), issueops.PromoteRequest{Actor: "alice", IssueID: "bd-w4"}) + if err != nil { + t.Fatalf("Promote: %v, want the promotion to stand", err) + } + if res.CommentErr == nil || res.Issue == nil { + t.Errorf("result = %+v, want the promoted row and the comment error", res) + } +} + +func TestPromoteValidatesTheRequest(t *testing.T) { + for name, req := range map[string]issueops.PromoteRequest{ + "no actor": {IssueID: "bd-w5"}, + "no id": {Actor: "alice"}, + } { + t.Run(name, func(t *testing.T) { + f := &promoteFakes{issue: wisp("bd-w5")} + _, err := issueops.Promote(t.Context(), f.roles(), req) + if !errors.Is(err, issueops.ErrValidation) { + t.Errorf("err = %v, want ErrValidation", err) + } + if len(f.updates) != 0 { + t.Errorf("updated on an invalid request") + } + }) + } +} diff --git a/test/conformance/e2e_test.go b/test/conformance/e2e_test.go index dac3549d9..7ff80dc13 100644 --- a/test/conformance/e2e_test.go +++ b/test/conformance/e2e_test.go @@ -91,7 +91,7 @@ var corpus = []scenario{ {"create", "st", "--id", "cf-st1", "-t", "task"}, {"stale", "--days", "1", "--json"}, }}, - // Promote a wisp to a durable issue (PromoteFromEphemeral) — CLI-level differential + // Promote a wisp to a durable issue (issueops.Promote) — CLI-level differential // for one of the backfilled writes. {name: "promote", steps: [][]string{ {"create", "w", "--id", "cf-pw1", "-t", "task", "--ephemeral"},