From 6d27a4f96e7fb74e2db516d7be9c80475f59dbef Mon Sep 17 00:00:00 2001 From: Julian Knutsen Date: Fri, 9 Oct 2026 18:30:42 +0000 Subject: [PATCH] fix(issueops): enforce the close guards on every close leg (#7425) * fix(issueops): enforce the close guards on every close leg The template read-only guard, the pin guard and the assignee authority fence (be-035) lived only in cmd/bd (validateIssueClosable), so a close through bd serve, issues:batchClose, a batch:apply close item or a library caller of Lifecycle.Close / BatchCloser / BatchApplier closed what bd close refused. They now run inside the close's own transaction in CloseIssueCheckedInTx (enforceCloseGuardsInTx), the body every checked close shares (dolt, embedded, uow, and the server behind httpapi), for a target that is not already closed: - a template refuses with *issueops.TemplateReadOnlyError (no bypass); - unless Force (CloseRequest, CloseBatchRequest, CloseItem) is set, a pinned issue refuses with *issueops.PinnedError and another actor's bead with *issueops.CloseNotAssigneeError (matches ErrNotOwner). Wire: 409 template_read_only, issue_pinned and not_assignee (holder in `assignee`, also on a batch-close outcome); the client rebuilds the typed errors. The decision is one exported pure rule over the pre-image, issueops.CheckClosable (internal/storage/issueops), which the in-tx guard calls; bd close's direct and proxied preflights call it too, ahead of gate satisfaction under the same already-closed skip, so bd close output, refusal order and exit codes are unchanged (validateIssueClosable is gone). bd close --if-revision now applies the guards too. Conformance: RunLifecycleCloseEnforcesTheCloseGuards, RunBatchCloserItemsAnswerToTheCloseGuards and RunBatchApplyCloseItemsAnswerToTheCloseGuards on dolt, embedded, uow and http, plus handler mapping tests, a CheckClosable table test, and a cmd/bd test pinning that the guards outrank gate satisfaction. Co-Authored-By: Claude Opus 5.5 * fix(httpclient): send force on the raw close; scope the close guards Review fixes for #7425 (adopt-pr bd-0h0ao4, iterations 1 and 2). The raw close keeps parity over http. httpclient.Store.CloseIssue maps the off-role raw close onto the role's closeIssue op and sent force=false. With the guards in the role, a pinned or claimed target then refused (409 issue_pinned / not_assignee) on http only: dolt, embedded and proxied run the raw close as issueops.CloseIssueInTx, which applies neither the guards nor close policy. The molecule auto-close, `bd gate resolve`, `bd todo done` and `bd human dismiss` all make that call, and its signature carries no force a caller could pass. It now sends force. Over http that also stops applying close policy to the raw close, which it did at base and no other backend does; parity is the point, so that goes too. The template guard has no bypass on the wire, so a template still refuses the raw close over http where the other backends close it; no raw caller is known to close one. TestServedRawCloseKeepsParityWithTheOtherBackends closes both pin spellings, a held bead and a parent with an open child through Store.CloseIssue and requires the template refusal; with force back to false it fails on 409 issue_pinned. The close guards stay on the close verbs. A status update that crosses into the done category (`bd update -s closed`, PATCH, a batchApply update item) still answers to close policy only, so it closes a pinned issue or another actor's bead on every backend, as it did before this PR. Guarding it changes what the update legs admit and needs its own refusal mapping on PATCH and batchApply, so it is left for a follow-up; the update.go and domain/db comments now say the exclusion is deliberate. CHANGELOG: the entry moves from Fixed to Changed as BREAKING, is scoped to the close operations, names the two paths the guards do not cover, and adds a Migration line (send force or reclaim; templates are never closable). Docs: the OpBatchCloseIssues item codes, the CloseIssueChecked and CloseIssueOptions.Force docs (storage, dolt, embeddeddolt), the oracle-a scenario strings that named the retired validateIssueClosable, and the TestCloseCheckOne_CloseGuardsOutrankGateSatisfaction doc, which claimed a proxied route it does not drive. Iteration 2: the wire contract says what force waives. The OpenAPI `force` members of CloseIssueRequest, BatchCloseRequest and ApplyCloseItem said force bypasses close policy "and nothing else"; it also waives the pin and the assignee guard, and never the template guard. The batchClose "only two answers" paragraph now says the same, and types.gen.go is regenerated (`make api-gen`). "Close guards" names the close operations instead of "every route to a close" and adds that a status update into the done category is not one, and the PATCH done-crossing paragraph says a patch is never refused `issue_pinned` or `not_assignee`. The conformance comments that quoted the old Force sentence (batch_apply_contract.go, batch_closer_contract.go, lifecycle_close_reopen_contract.go) quote the current docs, and the batch_apply failure message no longer says Force does nothing else. CHANGELOG: a `close` line of `bd batch` is named among the raw closes, and "a template is never closable" becomes "the close operations never close a template, forced or not". The storage interface CloseIssue gains a doc that states its HTTP exception. TestCloseGuardRefusalsPrintTheGuardSentenceOnEveryRoute pins the sentence `bd close` prints for each guard (template, pin, assignee) through each printer (closeDirectRefusal, closeDirectTypedRefusal, closeProxiedRefusal, closeProxiedTypedRefusal), with the refusal bare, wrapped by the use case and the SQL repository, or inside a served problem envelope. One pinned refusal also goes through closeProxiedOutcomes and closeProxiedFailures, where the stderr line and the `--json` error field must both be the sentence. Six overlay mutants fail it: closeGuardRefusal recognizing no guard, or not the pin, and each of the four printers skipping its call to closeGuardRefusal. Not done here: a CLI test that `--if-revision` exits 1 on a guard refusal, not ExitGuardMismatch. External PR #7372 carries per-id fence tests for that route (6 of 7 pass at this head); they are better absorbed with credit than rewritten. Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Gas City Adopt-PR Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- .../scripts/embedded-storage-test-shards.txt | 1 + CHANGELOG.md | 28 +++ backend/conformance/batch_apply_contract.go | 104 +++++++++- backend/conformance/batch_closer_contract.go | 100 ++++++++- .../lifecycle_close_reopen_contract.go | 196 +++++++++++++++++- backend/conformance/role_bundle_cases.go | 3 + cmd/bd/close.go | 2 +- cmd/bd/close_direct.go | 76 +++++-- cmd/bd/close_failure_report_test.go | 106 ++++++++++ cmd/bd/close_gate_test.go | 80 +++++++ cmd/bd/close_proxied_server.go | 18 +- cmd/bd/show_unit_helpers.go | 16 -- cmd/bd/show_unit_helpers_test.go | 59 ------ internal/httpapi/BUILD.bazel | 1 + internal/httpapi/apigen/types.gen.go | 15 +- internal/httpapi/batch_apply.go | 7 +- internal/httpapi/batch_close.go | 11 + internal/httpapi/close_guards_test.go | 163 +++++++++++++++ internal/httpapi/problem.go | 55 ++++- internal/httpapi/spec/openapi.v0.yaml | 111 +++++++--- .../httpapi/wireshape/testdata/golden.json | 6 + internal/httpclient/batchcloser.go | 34 ++- internal/httpclient/lifecycle.go | 18 +- .../httpclient/served_batch_apply_test.go | 4 + .../httpclient/served_batch_close_test.go | 7 + .../httpclient/served_claim_lifecycle_test.go | 69 ++++++ internal/httpclient/wire/client.go | 6 +- internal/httpclient/wire/problem.go | 17 +- internal/httpclient/wire/writes.go | 4 +- .../storage/dolt/batch_apply_contract_test.go | 5 + .../dolt/batch_closer_contract_test.go | 6 + internal/storage/dolt/issues.go | 6 +- .../lifecycle_close_reopen_contract_test.go | 3 + internal/storage/domain/db/issue.go | 8 +- .../embeddeddolt/batch_apply_contract_test.go | 3 + .../batch_closer_contract_test.go | 6 + internal/storage/embeddeddolt/issues.go | 6 +- .../lifecycle_close_reopen_contract_test.go | 3 + internal/storage/issueops/BUILD.bazel | 2 + internal/storage/issueops/close.go | 14 ++ internal/storage/issueops/close_guard.go | 112 ++++++++++ internal/storage/issueops/close_guard_test.go | 55 +++++ internal/storage/issueops/update.go | 15 +- internal/storage/storage.go | 18 +- .../storage/uow/batch_apply_contract_test.go | 3 + .../storage/uow/batch_closer_contract_test.go | 1 + .../lifecycle_close_reopen_contract_test.go | 3 + internal/validation/issue.go | 4 +- issueops/batchapplier.go | 3 +- issueops/batchcloser.go | 12 +- issueops/errors.go | 45 ++++ issueops/issueops.go | 20 +- issueops/template_errors.go | 5 +- .../harness/scenarios/enumerated.json | 4 +- 54 files changed, 1464 insertions(+), 215 deletions(-) create mode 100644 internal/httpapi/close_guards_test.go create mode 100644 internal/storage/issueops/close_guard.go create mode 100644 internal/storage/issueops/close_guard_test.go diff --git a/.github/scripts/embedded-storage-test-shards.txt b/.github/scripts/embedded-storage-test-shards.txt index da78fa452..0b2f4d259 100644 --- a/.github/scripts/embedded-storage-test-shards.txt +++ b/.github/scripts/embedded-storage-test-shards.txt @@ -417,6 +417,7 @@ 20 15 TestCreateBatchFastPathsMatchPerRowLarge_Embedded 20 15 TestDoltCommitResponseLossIsIndeterminate 20 15 TestEmbeddedBatchCloserAllIdempotentBatchLandsNothing +20 15 TestEmbeddedBatchCloserItemsAnswerToTheCloseGuards 20 15 TestEmbeddedDependencyEditorRecordsOneHistoryEntryPerLandedRequest 20 15 TestEmbeddedDependencyEditorRefusesACycleThroughAParentChildHop 20 15 TestEmbeddedDependencyEditorRefusesBlockingEdgeAcrossAWispHierarchy diff --git a/CHANGELOG.md b/CHANGELOG.md index 77b8fc52d..230391fdc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -202,6 +202,34 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 amendment to a released migration must land as a new migration (0070+, or ignored 0028+, as of this change) so installed schemas and freshly-migrated ones cannot fork. +- **BREAKING: the close guards now hold for every close operation, not only + `bd close`.** The template read-only guard, the pin guard and the assignee + authority fence (be-035) used to be a pre-read in `cmd/bd`, so a close + through `bd serve` (`POST /v0/beads/issues/{id}:close`), `issues:batchClose`, + a `close` item of `issues:batchApply`, or a library caller of + `issueops.Lifecycle.Close`, `BatchCloser` or `BatchApplier` closed a + template, a pinned issue, or a bead another actor holds that `bd close` + refused. They now live in the role, inside the close's own transaction, on + every backend: a template refuses with `*issueops.TemplateReadOnlyError` (no + bypass), and unless `Force` is set a pinned issue refuses with + `*issueops.PinnedError` and another actor's bead with + `*issueops.CloseNotAssigneeError` (matching `ErrNotOwner`). Over HTTP they + are `409` `template_read_only`, `issue_pinned` and `not_assignee` (the + holder in `assignee`, also on a batch-close outcome), and the client + rebuilds the same typed errors. `bd close` prints the same lines and exits + as before, and `bd close --if-revision`, which skipped the guards, now + applies them too. Two paths stay outside the guards. The raw storage + `CloseIssue`, which the molecule auto-close, a `close` line of `bd batch` + and the other closes `cmd/bd` makes outside `bd close` use, runs neither the + guards nor close policy on dolt, embedded or proxied; over HTTP it now sends + `force`, so there it also stops applying close policy, and only a template + refuses. A status update into the done category (`bd update -s closed`, a + `PATCH` whose `status` is done, an `update` item of `issues:batchApply`) + answers to close policy only, as before, so it still closes a pinned issue + or another actor's bead. Migration: HTTP and library callers that close + pinned issues or beads another actor holds must send `force` (`Force` on the + request), or reclaim the bead first; the close operations never close a + template, forced or not (pour it instead). ### Fixed - **An update of a template is now refused for every caller, not only diff --git a/backend/conformance/batch_apply_contract.go b/backend/conformance/batch_apply_contract.go index 6da619b21..c2ac269d9 100644 --- a/backend/conformance/batch_apply_contract.go +++ b/backend/conformance/batch_apply_contract.go @@ -882,9 +882,12 @@ func RunBatchApplyEvaluatesExpectedAssigneeAsModified(t *testing.T, ctx context. // close it. The refusal is the assertion; the rollback of the parent it created // is what says the refusal took the request with it. // -// POSITIVE HALF: the identical request with Force lands, which is the whole of -// what Force does ("bypasses blocker and open-child close policy, and nothing -// else") and the proof that the refusal was the policy rather than the shape. +// POSITIVE HALF: the identical request with Force lands, and that is the proof +// the refusal was the policy rather than the shape. Force "bypasses blocker and +// open-child close policy, the pin and the assignee fence, and never the +// template guard" (batchapplier.go), and the parent trips no guard — the +// unforced half reached the policy, which the guards run before — so the +// policy is the only refusal Force had to waive. func RunBatchApplyClosePolicyEvaluatesAtTheCloseItem(t *testing.T, ctx context.Context, fixture BatchApplyFixture) { t.Helper() parent := fixture.IssuePrefix + "-closepolicy-parent" @@ -924,7 +927,7 @@ func RunBatchApplyClosePolicyEvaluatesAtTheCloseItem(t *testing.T, ctx context.C t.Errorf("%s status = %q under Force, want %q", parent, got, types.StatusClosed) } if got := batchApplyColumn(t, ctx, fixture, "status", child); got != string(types.StatusOpen) { - t.Errorf("%s status = %q, want %q: Force bypasses the close policy and nothing else", child, got, types.StatusOpen) + t.Errorf("%s status = %q, want %q: Force waives the parent's close policy, it does not close the child", child, got, types.StatusOpen) } assertBatchApplyTypedEdgeCount(t, ctx, fixture, child, parent, string(publicops.DepParentChild), 1) } @@ -2561,3 +2564,96 @@ func RunBatchApplySplicesTheMetadataOfATemplateItCreates(t *testing.T, ctx conte t.Errorf("%s carries no gc.self key: the splice that finishes a template's own create must land", created) } } + +// RunBatchApplyCloseItemsAnswerToTheCloseGuards pins that a close item answers +// to the close guards Lifecycle.Close states, under CloseRequest's rules: a +// template refuses forced or not, a pin and another actor's bead refuse unless +// the item's Force is set. A refusal is the item's *ItemError carrying the +// guard's typed error, and the request is all or nothing, so the create item +// ahead of it does not land. +// +// The assignee case is AS-MODIFIED: the holder is set by an update item of the +// same request, so a guard that read the row before the request began — or not +// at all — closes it. +func RunBatchApplyCloseItemsAnswerToTheCloseGuards(t *testing.T, ctx context.Context, fixture BatchApplyFixture) { + t.Helper() + template := fixture.IssuePrefix + "-closeguard-template" + pinned := fixture.IssuePrefix + "-closeguard-pinned" + held := fixture.IssuePrefix + "-closeguard-held" + bystander := fixture.IssuePrefix + "-closeguard-bystander" + for _, issue := range []*types.Issue{ + {ID: template, IsTemplate: true}, + {ID: pinned, Pinned: true}, + {ID: held}, + } { + issue.Title, issue.Status, issue.Priority, issue.IssueType = issue.ID, types.StatusOpen, 2, types.TypeTask + if err := fixture.CreateIssue(ctx, issue, "seed"); err != nil { + t.Fatalf("seed %s: %v", issue.ID, err) + } + } + + plan := func(target string, force bool, extra ...publicops.ApplyItem) publicops.ApplyBatchRequest { + closeItem := batchApplyClose(publicops.Ref{ID: target}) + closeItem.Close.Force = force + items := []publicops.ApplyItem{batchApplyCreate("bystander", batchApplyIssue(bystander, "must not land beside a refusal"))} + items = append(items, extra...) + return publicops.ApplyBatchRequest{Actor: "apply-closer", ForceIDPrefix: true, Items: append(items, closeItem)} + } + refused := func(label string, request publicops.ApplyBatchRequest, check func(error)) { + t.Helper() + _, err := fixture.BatchApplier.ApplyBatch(ctx, request) + var itemErr *publicops.ItemError + if !errors.As(err, &itemErr) { + t.Fatalf("%s: error = %v, want an *ItemError", label, err) + } + if itemErr.Kind != publicops.ItemClose || itemErr.Index != len(request.Items)-1 { + t.Errorf("%s: ItemError = %#v, want the close item at index %d", label, itemErr, len(request.Items)-1) + } + check(err) + assertBatchApplyRowCount(t, ctx, fixture, "issues", bystander, 0) + } + + for _, force := range []bool{false, true} { + refused("template close item", plan(template, force), func(err error) { + var refusal *publicops.TemplateReadOnlyError + if !errors.As(err, &refusal) || refusal.IssueID != template { + t.Errorf("template close item (force=%v) = %v, want *TemplateReadOnlyError naming %s", force, err, template) + } + }) + } + refused("pinned close item", plan(pinned, false), func(err error) { + var refusal *publicops.PinnedError + if !errors.As(err, &refusal) || refusal.IssueID != pinned { + t.Errorf("pinned close item = %v, want *PinnedError naming %s", err, pinned) + } + }) + assign := batchApplyUpdate(publicops.Ref{ID: held}, publicops.IssuePatch{Assignee: publicops.Field[string]{Set: true, Value: "holder"}}) + refused("held close item", plan(held, false, assign), func(err error) { + var refusal *publicops.CloseNotAssigneeError + if !errors.As(err, &refusal) { + t.Errorf("close item on a bead an earlier item assigned away = %v, want *CloseNotAssigneeError", err) + return + } + if refusal.IssueID != held || refusal.Assignee != "holder" || refusal.Actor != "apply-closer" { + t.Errorf("assignee refusal = %#v, want IssueID %q, Assignee holder, Actor apply-closer", refusal, held) + } + }) + for _, id := range []string{template, pinned, held} { + if got := batchApplyColumn(t, ctx, fixture, "status", id); got != string(types.StatusOpen) { + t.Errorf("%s status after the refusals = %q, want it still open", id, got) + } + } + + // The item's Force waives the pin and the assignee fence. + forcedPin := plan(pinned, true) + forcedPin.Items = forcedPin.Items[1:] + batchApplyMust(t, ctx, fixture, forcedPin) + forcedHeld := plan(held, true, assign) + forcedHeld.Items = forcedHeld.Items[1:] + batchApplyMust(t, ctx, fixture, forcedHeld) + for _, id := range []string{pinned, held} { + if got := batchApplyColumn(t, ctx, fixture, "status", id); got != string(types.StatusClosed) { + t.Errorf("%s status under the item's Force = %q, want %q", id, got, types.StatusClosed) + } + } +} diff --git a/backend/conformance/batch_closer_contract.go b/backend/conformance/batch_closer_contract.go index fde364126..a62b7a667 100644 --- a/backend/conformance/batch_closer_contract.go +++ b/backend/conformance/batch_closer_contract.go @@ -39,9 +39,10 @@ import ( // still reports OpenChildren (batchcloser.go:81-86); a duplicated id is one // of those at its own index, and the first occurrence's reason is what the // row keeps (batchcloser.go:28-33). -// - Force is request-wide and bypasses only blocker and open-child policy; -// the per-item precondition its clause also names is a category the request -// type keeps EMPTY (batchcloser.go:43-53). +// - Force is request-wide and bypasses blocker and open-child policy, the +// pin and the assignee fence, never the template guard; the per-item +// precondition its clause also names is a category the request type keeps +// EMPTY (batchcloser.go:43-55). // - ClaimNext runs after the closes, inside the same transaction, and only // when at least one item closed (batchcloser.go:55-70, 100-103, 143-146). // - LANDED means CHANGED: an all-idempotent batch earns no claim and records @@ -1397,3 +1398,96 @@ func requireBatchCloserWisps(t *testing.T, fixture BatchCloserFixture) { t.Skipf("fixture has no CreateWisp: this backend cannot seed the ephemeral plane, so the ephemeral rules are UNPINNED here") } } + +// RunBatchCloserItemsAnswerToTheCloseGuards pins that every item of a batch +// answers to the close guards Lifecycle.Close states — template, pin, assignee +// — as a PER-ITEM refusal carrying the same typed error, while the survivors +// still commit; and that the request-wide Force waives the pin and the +// assignee fence and never the template. +// +// The guarded items sit between two plain ones, so an implementation that +// aborted the batch on a guard, or skipped the guard for items after the +// first, fails here rather than in `bd close a b c`. +func RunBatchCloserItemsAnswerToTheCloseGuards(t *testing.T, ctx context.Context, fixture BatchCloserFixture) { + t.Helper() + first := fixture.IssuePrefix + "-guard-first" + template := fixture.IssuePrefix + "-guard-template" + pinned := fixture.IssuePrefix + "-guard-pinned" + held := fixture.IssuePrefix + "-guard-held" + last := fixture.IssuePrefix + "-guard-last" + seedBatchCloserIssue(t, ctx, fixture, first) + seedBatchCloserIssue(t, ctx, fixture, last) + for _, issue := range []*types.Issue{ + {ID: template, IsTemplate: true}, + {ID: pinned, Status: types.StatusPinned}, + {ID: held, Assignee: "holder"}, + } { + issue.Title, issue.Priority, issue.IssueType = issue.ID, 2, types.TypeTask + if issue.Status == "" { + issue.Status = types.StatusOpen + } + if err := fixture.CreateIssue(ctx, issue, "seed"); err != nil { + t.Fatalf("seed %s: %v", issue.ID, err) + } + } + + result, err := fixture.Closer.CloseBatch(ctx, publicops.CloseBatchRequest{ + Actor: "closer", + Items: []publicops.BatchCloseItem{{IssueID: first}, {IssueID: template}, {IssueID: pinned}, {IssueID: held}, {IssueID: last}}, + }) + if err != nil { + t.Fatalf("CloseBatch over guarded items: %v, want per-item refusals", err) + } + if len(result.Outcomes) != 5 { + t.Fatalf("outcomes = %d, want 5", len(result.Outcomes)) + } + for _, i := range []int{0, 4} { + if result.Outcomes[i].Err != nil || !result.Outcomes[i].Changed { + t.Errorf("outcome %d (%s) = %+v, want the plain item to land", i, result.Outcomes[i].IssueID, result.Outcomes[i]) + } + } + var templateRefusal *publicops.TemplateReadOnlyError + if !errors.As(result.Outcomes[1].Err, &templateRefusal) || templateRefusal.IssueID != template { + t.Errorf("template item = %v, want *TemplateReadOnlyError naming %s", result.Outcomes[1].Err, template) + } + var pinRefusal *publicops.PinnedError + if !errors.As(result.Outcomes[2].Err, &pinRefusal) || pinRefusal.IssueID != pinned { + t.Errorf("pinned item = %v, want *PinnedError naming %s", result.Outcomes[2].Err, pinned) + } + var assigneeRefusal *publicops.CloseNotAssigneeError + if !errors.As(result.Outcomes[3].Err, &assigneeRefusal) { + t.Errorf("held item = %v, want *CloseNotAssigneeError", result.Outcomes[3].Err) + } else if assigneeRefusal.IssueID != held || assigneeRefusal.Assignee != "holder" || assigneeRefusal.Actor != "closer" { + t.Errorf("held item refusal = %#v, want IssueID %q, Assignee holder, Actor closer", assigneeRefusal, held) + } + for _, i := range []int{1, 2, 3} { + if result.Outcomes[i].Issue != nil { + t.Errorf("refused outcome %d carries an Issue snapshot, want nil beside Err", i) + } + } + assertBatchCloserStatus(t, ctx, fixture, first, types.StatusClosed) + assertBatchCloserStatus(t, ctx, fixture, last, types.StatusClosed) + assertBatchCloserStatus(t, ctx, fixture, template, types.StatusOpen) + assertBatchCloserStatus(t, ctx, fixture, pinned, types.StatusPinned) + assertBatchCloserStatus(t, ctx, fixture, held, types.StatusOpen) + + forced, err := fixture.Closer.CloseBatch(ctx, publicops.CloseBatchRequest{ + Actor: "closer", + Items: []publicops.BatchCloseItem{{IssueID: template}, {IssueID: pinned}, {IssueID: held}}, + Force: true, + }) + if err != nil { + t.Fatalf("forced CloseBatch over guarded items: %v", err) + } + if !errors.Is(forced.Outcomes[0].Err, publicops.ErrTemplateReadOnly) { + t.Errorf("forced template item = %v, want ErrTemplateReadOnly: force never waives read-only", forced.Outcomes[0].Err) + } + for _, i := range []int{1, 2} { + if forced.Outcomes[i].Err != nil || !forced.Outcomes[i].Changed { + t.Errorf("forced outcome %d (%s) = %+v, want force to bypass the guard", i, forced.Outcomes[i].IssueID, forced.Outcomes[i]) + } + } + assertBatchCloserStatus(t, ctx, fixture, template, types.StatusOpen) + assertBatchCloserStatus(t, ctx, fixture, pinned, types.StatusClosed) + assertBatchCloserStatus(t, ctx, fixture, held, types.StatusClosed) +} diff --git a/backend/conformance/lifecycle_close_reopen_contract.go b/backend/conformance/lifecycle_close_reopen_contract.go index 2395cfa3c..c11556181 100644 --- a/backend/conformance/lifecycle_close_reopen_contract.go +++ b/backend/conformance/lifecycle_close_reopen_contract.go @@ -846,11 +846,12 @@ func RunLifecycleCloseAndReopenSpanTheConfiguredDoneCategory(t *testing.T, ctx c // RunLifecycleExpectedVersionIsCheckedBeforeTheNoOps pins the ORDERING clause // both requests spell out. CloseRequest.ExpectedVersion "requires the current -// row version to match and is checked before an idempotent close" -// (issueops/issueops.go:295-300); ReopenRequest.ExpectedVersion is "checked -// before a non-done no-op" (:272-275); and Close's own doc adds "ExpectedVersion +// row version to match, and is checked BEFORE the idempotent close" +// (issueops/issueops.go:362-373); ReopenRequest.ExpectedVersion is "checked +// before a non-done no-op" (:390-391); and Close's own doc adds "ExpectedVersion // is checked first, including for an idempotent close", with Force bypassing -// "blocker and open-child policy" and nothing else (:364-365). +// "the pin, the assignee fence, and blocker and open-child policy" and nothing +// else (:485-498). // // The dangerous shape is not a stale version on a live mutation — it is a stale // version on the request that would have done nothing anyway. An implementation @@ -1383,13 +1384,14 @@ func RunLifecycleCloseSettlesItsTransitiveAndCrossPlaneDependers(t *testing.T, c // RunLifecycleCloseAdmitsATransitivelyBlockedTarget uses clears the first and // not the second, and closing the child to clear the second would take the // second subject with it, since a closed row cannot be blocked and so has -// nothing left to flip. Force waives close policy and nothing else — -// CloseRequest.Force "bypasses only blocker and open-child close policy" and -// "never bypasses validation, ExpectedVersion, or lifecycle rules" -// (issueops/issueops.go:310-311) — so it is the shape that keeps both subjects -// observable, and it is not exotic: it is the same forced close of a -// blocked issue that RunLifecycleCloseIsIdempotentOnAClosedRowThatStillLooksBlocked -// is built on. +// nothing left to flip. Force waives close policy, the pin and the assignee +// fence, and nothing else — CloseRequest.Force "bypasses blocker and +// open-child close policy and the two close guards a force has always waived +// in bd" and "never bypasses the template guard, validation, ExpectedVersion, +// or lifecycle rules" (issueops/issueops.go:357-360) — so it is the shape that +// keeps both subjects observable, and it is not exotic: it is the same forced +// close of a blocked issue that +// RunLifecycleCloseIsIdempotentOnAClosedRowThatStillLooksBlocked is built on. // // All three legs reach ONE body here (internal/storage/issueops.closeIssueInTx), // so this is a wrapper and engine check rather than a third vote, exactly as @@ -1822,3 +1824,175 @@ func (c *lifecycleCloseReopenEventCounter) assertNoneAdded(t *testing.T, label s } c.total = total } + +// RunLifecycleCloseEnforcesTheCloseGuards pins the three close guards +// issueops.Lifecycle.Close states before close policy — template read-only, +// the pin, and the assignee authority fence (be-035) — on the role itself, so +// every caller of it is held to them and not only `bd close`, which used to +// apply them as a CLI pre-read the served and library routes skipped. +// +// Each refusal is asserted at the level a caller acts on: the typed error with +// its fields, its sentinel, and the sentence bd prints — read off the typed +// error, because a served refusal wraps it in the problem envelope — plus the +// row and the event stream left untouched. Force is asserted as the bypass for +// exactly the two guards it has always waived, and NOT for the template. +// +// The controls are load-bearing too: an unassigned issue and one held by the +// closing actor under a different spelling both close unforced, so a guard +// that refused every assigned row, or compared verbatim, fails here. A wisp +// case proves the guard reads the plane the close writes. A pinned issue with +// an open child reads the PIN's refusal, pinning the order (guards before +// policy). And a forced close of a boolean-pinned issue leaves the pin set, so +// the plain retry must stay the idempotent no-op (ga-ktn9pe.4.8) rather than +// refuse on the residue. +func RunLifecycleCloseEnforcesTheCloseGuards(t *testing.T, ctx context.Context, fixture LifecycleCloseReopenFixture) { + t.Helper() + + template := fixture.IssuePrefix + "-lcg-template" + statusPinned := fixture.IssuePrefix + "-lcg-status-pinned" + flagPinned := fixture.IssuePrefix + "-lcg-flag-pinned" + held := fixture.IssuePrefix + "-lcg-held" + respelled := fixture.IssuePrefix + "-lcg-respelled" + unassigned := fixture.IssuePrefix + "-lcg-unassigned" + pinnedParent := fixture.IssuePrefix + "-lcg-pinned-parent" + pinnedChild := fixture.IssuePrefix + "-lcg-pinned-child" + wisp := fixture.IssuePrefix + "-lcg-wisp-held" + + seed := func(issue *types.Issue) { + t.Helper() + issue.Title, issue.Priority, issue.IssueType = issue.ID, 2, types.TypeTask + if issue.Status == "" { + issue.Status = types.StatusOpen + } + if err := fixture.CreateIssue(ctx, issue, "seed"); err != nil { + t.Fatalf("seed %s: %v", issue.ID, err) + } + } + seed(&types.Issue{ID: template, IsTemplate: true}) + seed(&types.Issue{ID: statusPinned, Status: types.StatusPinned}) + seed(&types.Issue{ID: flagPinned, Pinned: true}) + seed(&types.Issue{ID: held, Assignee: "holder"}) + seed(&types.Issue{ID: respelled, Assignee: "gastown.closer"}) + seed(&types.Issue{ID: unassigned}) + seed(&types.Issue{ID: pinnedParent, Pinned: true}) + seed(&types.Issue{ID: pinnedChild}) + lifecycleCloseReopenSeedEdge(t, ctx, fixture, pinnedChild, pinnedParent, types.DepParentChild) + + refuses := func(id string, force bool, label string, check func(error)) { + t.Helper() + before := lifecycleCloseReopenReadRow(t, ctx, fixture, id) + events := newLifecycleCloseReopenEventCounter(t, ctx, fixture, id) + _, err := fixture.Lifecycle.Close(ctx, publicops.CloseRequest{Actor: "closer", IssueID: id, Force: force}) + check(err) + lifecycleCloseReopenAssertRow(t, ctx, fixture, id, "after the "+label+" refusal", before) + events.assertNoneAdded(t, label+" refusal") + } + + // The template refuses, forced or not: no flag waives read-only. + for _, force := range []bool{false, true} { + refuses(template, force, "template", func(err error) { + var refusal *publicops.TemplateReadOnlyError + if !errors.As(err, &refusal) { + t.Fatalf("close of template %s (force=%v): err = %v, want *TemplateReadOnlyError", template, force, err) + } + if refusal.IssueID != template || !errors.Is(err, publicops.ErrTemplateReadOnly) { + t.Errorf("template refusal = %#v (%v), want IssueID %q matching ErrTemplateReadOnly", refusal, err, template) + } + want := "cannot modify template " + template + ": templates are read-only; use 'bd mol pour' to create a work item" + if refusal.Error() != want { + t.Errorf("template refusal reads %q, want %q", refusal.Error(), want) + } + }) + } + + // Both pin spellings refuse unforced (ga-z3vht). + for _, id := range []string{statusPinned, flagPinned} { + refuses(id, false, "pin", func(err error) { + var refusal *publicops.PinnedError + if !errors.As(err, &refusal) { + t.Fatalf("unforced close of pinned %s: err = %v, want *PinnedError", id, err) + } + if refusal.IssueID != id || !errors.Is(err, publicops.ErrPinned) { + t.Errorf("pin refusal = %#v (%v), want IssueID %q matching ErrPinned", refusal, err, id) + } + if want := "cannot modify pinned issue " + id + " (use --force to override)"; refusal.Error() != want { + t.Errorf("pin refusal reads %q, want %q", refusal.Error(), want) + } + }) + } + + // Another actor's bead refuses unforced, naming holder and actor. + refuses(held, false, "assignee", func(err error) { + var refusal *publicops.CloseNotAssigneeError + if !errors.As(err, &refusal) { + t.Fatalf("unforced close of %s held by another actor: err = %v, want *CloseNotAssigneeError", held, err) + } + if refusal.IssueID != held || refusal.Assignee != "holder" || refusal.Actor != "closer" { + t.Errorf("assignee refusal = %#v, want IssueID %q, Assignee holder, Actor closer", refusal, held) + } + if !errors.Is(err, publicops.ErrNotOwner) { + t.Errorf("assignee refusal %v does not match ErrNotOwner", err) + } + if want := `cannot close ` + held + `: assignee is "holder", actor is "closer"; reclaim or use --force to override`; refusal.Error() != want { + t.Errorf("assignee refusal reads %q, want %q", refusal.Error(), want) + } + }) + + // The guard runs before close policy: a pinned parent with an open child + // reads the pin, not the open children. + refuses(pinnedParent, false, "pin-before-policy", func(err error) { + if !errors.Is(err, publicops.ErrPinned) { + t.Fatalf("unforced close of pinned parent %s with an open child: err = %v, want ErrPinned first", pinnedParent, err) + } + }) + + // The controls: an unassigned bead and the actor's own bead under another + // spelling of its identity close unforced. + for _, tc := range []struct{ id, actor string }{{unassigned, "closer"}, {respelled, "gastown_closer"}} { + result, err := fixture.Lifecycle.Close(ctx, publicops.CloseRequest{Actor: tc.actor, IssueID: tc.id}) + if err != nil { + t.Fatalf("unforced close of %s by %s: %v, want it to land", tc.id, tc.actor, err) + } + if !result.Changed || result.Issue.Status != types.StatusClosed { + t.Errorf("unforced close of %s = %#v, want a committed close", tc.id, result) + } + } + + // Force bypasses the pin and the assignee fence. + for _, id := range []string{statusPinned, flagPinned, held} { + result, err := fixture.Lifecycle.Close(ctx, publicops.CloseRequest{Actor: "closer", IssueID: id, Force: true}) + if err != nil { + t.Fatalf("forced close of %s: %v, want force to bypass the guard", id, err) + } + if !result.Changed || result.Issue.Status != types.StatusClosed { + t.Errorf("forced close of %s = %#v, want a committed close", id, result) + } + } + + // The forced close left pinned=true on the flag-pinned row; the plain retry + // is the idempotent re-close, not a pin refusal. + retry, err := fixture.Lifecycle.Close(ctx, publicops.CloseRequest{Actor: "closer", IssueID: flagPinned}) + if err != nil { + t.Fatalf("plain re-close of the already-closed, still-pinned %s: %v, want the idempotent no-op", flagPinned, err) + } + if retry.Changed { + t.Errorf("plain re-close of %s reported Changed = true, want the no-op", flagPinned) + } + + // The guard reads the plane the close writes. + if err := fixture.CreateWisp(ctx, &types.Issue{ + ID: wisp, Title: wisp, Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, Assignee: "holder", Ephemeral: true, + }, "seed"); err != nil { + t.Fatalf("seed wisp %s: %v", wisp, err) + } + if _, err := fixture.Lifecycle.Close(ctx, publicops.CloseRequest{Actor: "closer", IssueID: wisp}); !errors.As(err, new(*publicops.CloseNotAssigneeError)) { + t.Fatalf("unforced close of wisp %s held by another actor: err = %v, want *CloseNotAssigneeError", wisp, err) + } + var status string + if err := fixture.QueryScalar(ctx, "SELECT status FROM wisps WHERE id = ?", []any{wisp}, &status); err != nil { + t.Fatalf("read wisp %s status: %v", wisp, err) + } + if types.Status(status) != types.StatusOpen { + t.Errorf("wisp %s status after the refusal = %q, want it still open", wisp, status) + } +} diff --git a/backend/conformance/role_bundle_cases.go b/backend/conformance/role_bundle_cases.go index 059a50056..27f0d762f 100644 --- a/backend/conformance/role_bundle_cases.go +++ b/backend/conformance/role_bundle_cases.go @@ -60,6 +60,7 @@ var roleContractCases = []roleContract{ RunBatchApplyRefusesAnUnusableRequest, RunBatchApplyUpdateItemsRefuseATemplate, RunBatchApplySplicesTheMetadataOfATemplateItCreates, + RunBatchApplyCloseItemsAnswerToTheCloseGuards, ), roleCases("BatchCloser", "BatchCloser()", oncePerRole, @@ -84,6 +85,7 @@ var roleContractCases = []roleContract{ RunBatchCloserAllRefusedBatchRecordsNoHistory, RunBatchCloserDoesNotMutateTheCallerRequest, RunBatchCloserSettlesTheDependersOfWhatItClosed, + RunBatchCloserItemsAnswerToTheCloseGuards, ), roleCases("BatchCreator", "BatchCreator()", oncePerRole, @@ -442,6 +444,7 @@ var roleContractCases = []roleContract{ RunLifecycleCloseSettlesTheClosedRowItselfAndItsChild, RunLifecycleCloseOnASpawnersLastChildSatisfiesAWaitsForGate, RunLifecycleReopenReblocksItsDependers, + RunLifecycleCloseEnforcesTheCloseGuards, ), // The accessor-reachable half of Lifecycle.Create, moved out of the staging diff --git a/cmd/bd/close.go b/cmd/bd/close.go index 5a28910a2..07eec5fa2 100644 --- a/cmd/bd/close.go +++ b/cmd/bd/close.go @@ -185,7 +185,7 @@ the flags appear in the command line.`, // The typed error, not the decorated display line: the --force // hint closeDirectRefusal appends is advice for a human reader, // and the id already has its own field. - failures = append(failures, closeIDFailure{ID: id, Error: res.Err.Error()}) + failures = append(failures, closeIDFailure{ID: id, Error: closeDirectTypedRefusal(res.Err)}) continue } diff --git a/cmd/bd/close_direct.go b/cmd/bd/close_direct.go index 47890945e..79a91c59a 100644 --- a/cmd/bd/close_direct.go +++ b/cmd/bd/close_direct.go @@ -6,6 +6,7 @@ import ( "fmt" "github.com/steveyegge/beads/internal/storage" + storeissueops "github.com/steveyegge/beads/internal/storage/issueops" "github.com/steveyegge/beads/internal/types" "github.com/steveyegge/beads/issueops" ) @@ -36,12 +37,16 @@ type closeDirectPlan struct { // closeDirectPreflight applies `bd close`'s own close policy to every resolved // argument, and hands the batch only the items that survived. // -// Neither check is library policy — the template/pin/assignee fence and gate -// satisfaction read the issue and nothing else, and the role has no vocabulary -// for either — which is why they stay in cmd/bd. It is closeProxiedRunPreflight's +// The one check left here is gate satisfaction. It is closeProxiedRunPreflight's // job on this route. // -// The open-children guard is NOT here, and that is the point: the engine +// The close guards — template, pin, assignee — are NOT here: they are the +// role's (issueops.Lifecycle.Close), enforced inside the close's own +// transaction on every route to a close, and they come back as the item's +// typed refusal, which closeDirectRefusal prints as the sentence this route +// always printed. +// +// The open-children guard is NOT here either, and that is the point: the engine // enforces it inside the close's own transaction, refusing with a // CloseOpenChildrenError whose message is the one this route used to compose // by hand. Keeping a copy here would be a second implementation of a rule the @@ -67,21 +72,16 @@ func closeDirectPreflight(results []*RoutedResult, resolvedIDs, reasons []string // closeDirectCheckOne returns one argument's refusal, or "" when it may go to // the batch. st is the store that owns the issue. func closeDirectCheckOne(id string, issue *types.Issue, st storage.DoltStorage, force bool) string { - // Close validation guards a state change; a row already at literal - // StatusClosed has none to guard, so skip it and let the re-close reach the - // engine as the idempotent no-op it has always been (ga-ktn9pe.4.8). - // Without this, a forced close of a boolean-pinned bead leaves pinned=true - // (the close write never touches the column — deliberately, it is the - // deletion-protection flag bd gc/purge/cleanup honor) and the plain retry - // hits NotPinned and exits nonzero, which strands the molecule auto-close - // the unchanged branch re-drives. Only a literal closed status qualifies: - // reaching a configured done status is still a real close, mirroring the - // engine's isClosedInTx. The snapshot only decides whether validation runs, - // never what is written — the engine's in-transaction `status != closed` - // guard remains the authority on whether the close is a no-op, so a - // concurrent close still converges. Mirrored in closeProxiedCheckOne. + // The close guards' own rule (storeissueops.CheckClosable), applied to the + // resolved pre-image ahead of gate satisfaction so a refusal that trips both + // reads the guard's sentence, as it always has. The role applies the same + // rule inside the close transaction, which stays the authority. A row + // already at literal StatusClosed has no state change to guard: the re-close + // reaches the engine as the idempotent no-op it has always been + // (ga-ktn9pe.4.8) — a forced close of a pinned bead leaves pinned=true, and + // the plain retry must not then refuse. Mirrored in closeProxiedCheckOne. if issue == nil || issue.Status != types.StatusClosed { - if err := validateIssueClosable(id, issue, currentActor(), force); err != nil { + if err := storeissueops.CheckClosable(id, issue, currentActor(), force); err != nil { return err.Error() } } @@ -210,6 +210,9 @@ func closeDirectCloseBatch(ctx context.Context, st storage.DoltStorage, request // line this route used to compose before the guard moved into the transaction. // Everything else is an unexpected failure and is reported against the id. func closeDirectRefusal(id string, err error) string { + if guard, ok := closeGuardRefusal(err); ok { + return guard + } switch { case errors.Is(err, storage.ErrCloseBlocked): return fmt.Sprintf("%v (use --force to override)", err) @@ -219,3 +222,40 @@ func closeDirectRefusal(id string, err error) string { return fmt.Sprintf("Error closing %s: %v", id, err) } } + +// closeGuardRefusal returns a close guard's own sentence when err is one of the +// three refusals the role raises before close policy — a template, a pin, or a +// bead someone else holds — and reports whether it was. +// +// The sentence is the typed error's, found with errors.As rather than taken +// from err itself, because err may have traveled: the unit-of-work route wraps +// it in the use case's and repository's prefixes, and a served one in the +// problem envelope. Each guard's message already names its subject and its +// --force hint, so it prints bare — the line `bd close` printed when the guard +// was a CLI pre-read, on every route. +func closeGuardRefusal(err error) (string, bool) { + var ( + template *issueops.TemplateReadOnlyError + pinned *issueops.PinnedError + notAssignee *issueops.CloseNotAssigneeError + ) + switch { + case errors.As(err, &template): + return template.Error(), true + case errors.As(err, &pinned): + return pinned.Error(), true + case errors.As(err, ¬Assignee): + return notAssignee.Error(), true + } + return "", false +} + +// closeDirectTypedRefusal is the reason a --json consumer reads for one refused +// id on this route: the typed error, with a close guard's sentence taken from +// the guard itself so a served refusal reads as a local one does. +func closeDirectTypedRefusal(err error) string { + if guard, ok := closeGuardRefusal(err); ok { + return guard + } + return err.Error() +} diff --git a/cmd/bd/close_failure_report_test.go b/cmd/bd/close_failure_report_test.go index cb05c024e..58879c84d 100644 --- a/cmd/bd/close_failure_report_test.go +++ b/cmd/bd/close_failure_report_test.go @@ -279,3 +279,109 @@ func TestCloseProxiedFailuresKeepPolicyRefusalsAndTypedOrder(t *testing.T) { t.Errorf("failures[0].Error = %q, want the display line %q as the fallback", got[0].Error, policyRefusal) } } + +// closeGuardServedEnvelope stands in for the problem envelope a served refusal +// arrives in (wire.ProblemError): a message of its own that never repeats the +// guard's sentence, with the typed refusal reachable only through Unwrap. +type closeGuardServedEnvelope struct{ inner error } + +func (e closeGuardServedEnvelope) Error() string { + return "closeIssue: bd serve at http://127.0.0.1:1 answered 409 issue_pinned: this issue is pinned" +} + +func (e closeGuardServedEnvelope) Unwrap() error { return e.inner } + +// The close guards are the role's now, so they reach the CLI as typed refusals +// — and the line a person reads, and the failed[].error a --json consumer +// reads, must still be the sentence `bd close` printed when they were a CLI +// pre-read: on both routes, and however far the refusal traveled. Each guard's +// message already names its subject and its --force hint, so every printer +// hands it back BARE, with no "Error closing :" prefix and no second hint. +// +// The "want" column is transcribed from the pre-read's validators +// (validation.NotTemplate, NotPinned, AssigneeMatches before the move), so the +// sentences themselves are pinned, not only their relationship to the typed +// errors. The bare rows catch the decorating printers; the wrapped rows are +// the ones that catch the typed printers, which would otherwise hand back the +// whole chain. +func TestCloseGuardRefusalsPrintTheGuardSentenceOnEveryRoute(t *testing.T) { + guards := []struct { + name string + err error + want string + }{ + { + name: "template", + err: &issueops.TemplateReadOnlyError{IssueID: "gr-1"}, + want: "cannot modify template gr-1: templates are read-only; use 'bd mol pour' to create a work item", + }, + { + name: "pinned", + err: &issueops.PinnedError{IssueID: "gr-1"}, + want: "cannot modify pinned issue gr-1 (use --force to override)", + }, + { + name: "not assignee", + err: &issueops.CloseNotAssigneeError{IssueID: "gr-1", Assignee: "alice", Actor: "bob"}, + want: `cannot close gr-1: assignee is "alice", actor is "bob"; reclaim or use --force to override`, + }, + } + // How the refusal reaches the printer: as the engine minted it (the direct + // route), wrapped by the use case and the SQL repository (the proxied route; + // see TestCloseProxiedTypedRefusalUnwrapsTheRoleWrappers), or inside a + // served problem envelope. + travels := []struct { + name string + wrap func(error) error + }{ + {name: "bare", wrap: func(err error) error { return err }}, + {name: "wrapped by the role", wrap: func(err error) error { + return fmt.Errorf("close gr-1: %w", fmt.Errorf("db: IssueSQLRepository.CloseChecked gr-1: %w", err)) + }}, + {name: "in a served envelope", wrap: func(err error) error { return closeGuardServedEnvelope{inner: err} }}, + } + printers := []struct { + name string + print func(error) string + }{ + {name: "closeDirectRefusal", print: func(err error) string { return closeDirectRefusal("gr-1", err) }}, + {name: "closeDirectTypedRefusal", print: closeDirectTypedRefusal}, + {name: "closeProxiedRefusal", print: func(err error) string { return closeProxiedRefusal("gr-1", err) }}, + {name: "closeProxiedTypedRefusal", print: closeProxiedTypedRefusal}, + } + + for _, g := range guards { + for _, tr := range travels { + for _, p := range printers { + t.Run(g.name+"/"+tr.name+"/"+p.name, func(t *testing.T) { + if got := p.print(tr.wrap(g.err)); got != g.want { + t.Errorf("%s = %q, want the guard's own sentence %q", p.name, got, g.want) + } + }) + } + } + } + + // And through the proxied route's own bookkeeping, which is where the two + // printers meet: the stderr line and failed[].error are the same sentence, + // because the hint a guard needs is already in it. + pinned := guards[1] + args := []string{"gr-1"} + pre := closeProxiedPreflight{ + items: []issueops.BatchCloseItem{{IssueID: "gr-1", Reason: "done"}}, + itemArgs: []int{0}, + before: map[string]*types.Issue{}, + errors: make([]string, len(args)), + failureErrors: make([]string, len(args)), + } + closeProxiedOutcomes(&pre, issueops.CloseBatchResult{ + Outcomes: []issueops.CloseOutcome{{IssueID: "gr-1", Err: travels[1].wrap(pinned.err)}}, + }) + failures := closeProxiedFailures(&pre, args) + if len(failures) != 1 || failures[0].Error != pinned.want { + t.Errorf("failures = %+v, want one entry whose error is %q", failures, pinned.want) + } + if pre.errors[0] != pinned.want { + t.Errorf("stderr line = %q, want %q", pre.errors[0], pinned.want) + } +} diff --git a/cmd/bd/close_gate_test.go b/cmd/bd/close_gate_test.go index f935de4d3..542fa7ec2 100644 --- a/cmd/bd/close_gate_test.go +++ b/cmd/bd/close_gate_test.go @@ -6,6 +6,7 @@ import ( "errors" "strings" "testing" + "time" "github.com/steveyegge/beads/internal/storage" "github.com/steveyegge/beads/internal/types" @@ -350,3 +351,82 @@ func TestCloseBeadGateGetter_RouteSelection(t *testing.T) { t.Error("direct mode: the getter does not read the gate's own store") } } + +// TestCloseCheckOne_CloseGuardsOutrankGateSatisfaction pins `bd close`'s +// refusal order on the direct preflight route (closeDirectCheckOne): the close +// guards (storeissueops.CheckClosable, the role's own rule) answer before gate +// satisfaction, so a pinned, held or template gate whose condition is unmet +// prints the guard's sentence, as it always has. Force waives the pin and the +// holder (and the gate check with them) but never the template, and a row +// already closed skips the guards (ga-ktn9pe.4.8). closeProxiedCheckOne makes +// the same call in the same order; it resolves the row through a unit of work, +// so this test does not drive it. +func TestCloseCheckOne_CloseGuardsOutrankGateSatisfaction(t *testing.T) { + actorMu.Lock() + savedActor, savedPending := actor, actorGitFallbackPending + actor, actorGitFallbackPending = "alice", false + actorMu.Unlock() + t.Cleanup(func() { + actorMu.Lock() + actor, actorGitFallbackPending = savedActor, savedPending + actorMu.Unlock() + }) + + // An unexpired timer gate: checkGateSatisfaction refuses it unforced. + gate := func(mut func(*types.Issue)) *types.Issue { + issue := &types.Issue{ + ID: "bd-g1", + IssueType: "gate", + AwaitType: "timer", + Status: types.StatusOpen, + CreatedAt: time.Now(), + Timeout: time.Hour, + } + mut(issue) + return issue + } + const gateRefusal = "cannot close bd-g1: gate condition not satisfied" + cases := []struct { + name string + issue *types.Issue + force bool + want string + }{ + {"pinned", gate(func(i *types.Issue) { i.Pinned = true }), false, + "cannot modify pinned issue bd-g1 (use --force to override)"}, + {"pinned status", gate(func(i *types.Issue) { i.Status = types.StatusPinned }), false, + "cannot modify pinned issue bd-g1 (use --force to override)"}, + {"template", gate(func(i *types.Issue) { i.IsTemplate = true }), false, + "cannot modify template bd-g1: templates are read-only; use 'bd mol pour' to create a work item"}, + {"forced template", gate(func(i *types.Issue) { i.IsTemplate = true }), true, + "cannot modify template bd-g1: templates are read-only; use 'bd mol pour' to create a work item"}, + {"held", gate(func(i *types.Issue) { i.Assignee = "bob" }), false, + `cannot close bd-g1: assignee is "bob", actor is "alice"; reclaim or use --force to override`}, + {"unguarded gate", gate(func(*types.Issue) {}), false, gateRefusal}, + {"forced pin", gate(func(i *types.Issue) { i.Pinned = true; i.Assignee = "bob" }), true, ""}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + check := func(route, got string) { + t.Helper() + if tc.want == gateRefusal { + if !strings.HasPrefix(got, gateRefusal) { + t.Fatalf("%s refusal = %q, want the gate refusal", route, got) + } + return + } + if got != tc.want { + t.Fatalf("%s refusal = %q, want %q", route, got, tc.want) + } + } + check("direct", closeDirectCheckOne("bd-g1", tc.issue, nil, tc.force)) + }) + } + + // The already-closed skip: a forced close leaves pinned=true behind, and + // the plain re-close must reach the engine as the idempotent no-op. + residue := &types.Issue{ID: "bd-c1", Status: types.StatusClosed, Pinned: true, Assignee: "bob"} + if got := closeDirectCheckOne("bd-c1", residue, nil, false); got != "" { + t.Fatalf("closed residue refusal = %q, want none", got) + } +} diff --git a/cmd/bd/close_proxied_server.go b/cmd/bd/close_proxied_server.go index e7a791d4f..cf94bba83 100644 --- a/cmd/bd/close_proxied_server.go +++ b/cmd/bd/close_proxied_server.go @@ -12,6 +12,7 @@ import ( "github.com/steveyegge/beads/internal/audit" "github.com/steveyegge/beads/internal/storage" "github.com/steveyegge/beads/internal/storage/domain" + storeissueops "github.com/steveyegge/beads/internal/storage/issueops" "github.com/steveyegge/beads/internal/storage/uow" "github.com/steveyegge/beads/internal/types" "github.com/steveyegge/beads/internal/ui" @@ -294,13 +295,12 @@ func closeProxiedCheckOne(ctx context.Context, uw uow.UnitOfWork, id string, in return fmt.Sprintf("Error resolving %s: %v", id, err), nil } - // Mirrors the ordering in closeDirectCheckOne (ga-ktn9pe.4.8): a row already at - // literal StatusClosed has no state change for close validation to guard, so - // the re-close skips it and reaches the engine as the idempotent no-op it has - // always been. Both close paths must agree here — diverging is the defect - // class #5217 closed. + // The close guards' own rule, ahead of gate satisfaction and under the same + // already-closed skip as closeDirectCheckOne (ga-ktn9pe.4.8); both close + // paths must agree here (#5217). The role re-applies it inside the close + // transaction, which stays the authority. if current.Status != types.StatusClosed { - if err := validateIssueClosable(id, current, currentActor(), in.force); err != nil { + if err := storeissueops.CheckClosable(id, current, currentActor(), in.force); err != nil { return err.Error(), nil } } @@ -419,6 +419,9 @@ func closeProxiedFailures(pre *closeProxiedPreflight, args []string) []closeIDFa // not noise, it is the only thing that says where an unexpected failure came // from, and there is no engine sentence to converge on. func closeProxiedTypedRefusal(err error) string { + if guard, ok := closeGuardRefusal(err); ok { + return guard + } for _, sentinel := range []error{storage.ErrCloseBlocked, storage.ErrCloseOpenChildren} { if !errors.Is(err, sentinel) { continue @@ -445,6 +448,9 @@ func closeProxiedTypedRefusal(err error) string { // reading the message, which is the point of the outcome carrying a typed // error at all. func closeProxiedRefusal(id string, err error) string { + if guard, ok := closeGuardRefusal(err); ok { + return guard + } switch { case errors.Is(err, storage.ErrCloseBlocked): return fmt.Sprintf("%v (use --force to override)", err) diff --git a/cmd/bd/show_unit_helpers.go b/cmd/bd/show_unit_helpers.go index 74c0e9705..c866d8672 100644 --- a/cmd/bd/show_unit_helpers.go +++ b/cmd/bd/show_unit_helpers.go @@ -25,22 +25,6 @@ func validateIssueUpdatable(id string, issue *types.Issue) error { return validation.NotTemplate()(id, issue) } -// validateIssueClosable checks if an issue can be closed. -// Uses the centralized validation package for consistency. -// -// actor is the current actor identity (may be empty in early-init contexts); -// AssigneeMatches refuses the close when the bead is assigned to someone else -// unless force is true. This is the authority guard for be-035. -func validateIssueClosable(id string, issue *types.Issue, actor string, force bool) error { - // Note: We use individual validators instead of ForClose() to maintain - // backward compatibility - the original didn't check for nil issues. - return validation.Chain( - validation.NotTemplate(), - validation.NotPinned(force), - validation.AssigneeMatches(actor, force), - )(id, issue) -} - // validateIssueReassignable checks whether an assignee update may proceed: // plain `bd update -a` / `bd assign` must not silently overwrite another // actor's live in_progress claim (bd-98s5c) — it was the last unfenced diff --git a/cmd/bd/show_unit_helpers_test.go b/cmd/bd/show_unit_helpers_test.go index 0d956e135..02dfd6bdf 100644 --- a/cmd/bd/show_unit_helpers_test.go +++ b/cmd/bd/show_unit_helpers_test.go @@ -22,65 +22,6 @@ func TestValidateIssueUpdatable(t *testing.T) { } } -func TestValidateIssueClosable(t *testing.T) { - if err := validateIssueClosable("x", nil, "alice", false); err != nil { - t.Fatalf("expected nil error, got %v", err) - } - if err := validateIssueClosable("bd-1", &types.Issue{IsTemplate: true}, "alice", false); err == nil { - t.Fatalf("expected template close error") - } - if err := validateIssueClosable("bd-2", &types.Issue{Status: types.StatusPinned}, "alice", false); err == nil { - t.Fatalf("expected pinned close error") - } - if err := validateIssueClosable("bd-2", &types.Issue{Status: types.StatusPinned}, "alice", true); err != nil { - t.Fatalf("expected pinned close to succeed with force, got %v", err) - } - - // ga-z3vht: pinned=true protects the bead independently of status, so - // `bd close` refuses it without --force on both the direct and proxied path. - booleanPinned := &types.Issue{Status: types.StatusOpen, Pinned: true} - if err := validateIssueClosable("bd-6", booleanPinned, "alice", false); err == nil { - t.Fatalf("expected boolean-pinned close error") - } - if err := validateIssueClosable("bd-6", booleanPinned, "alice", true); err != nil { - t.Fatalf("expected boolean-pinned close to succeed with force, got %v", err) - } - - // ga-ktn9pe.4.8: a closed row carrying pinned=true is the residue left by a - // forced close, and this guard still refuses it — closed status earns no - // exemption from the boolean trigger. Idempotent re-close was restored by - // ORDERING instead: cmd/bd/close.go and close_proxied_server.go skip close - // validation entirely for a row already closed at resolve time, so this guard - // is never reached on the no-op retry. Do not "simplify" it by exempting - // closed here — that would also disarm the guard on live status transitions. - closedPinnedResidue := &types.Issue{Status: types.StatusClosed, Pinned: true} - if err := validateIssueClosable("bd-7", closedPinnedResidue, "alice", false); err == nil { - t.Fatalf("expected closed+pinned residue to refuse a plain close") - } - if err := validateIssueClosable("bd-7", closedPinnedResidue, "alice", true); err != nil { - t.Fatalf("expected closed+pinned residue close to succeed with force, got %v", err) - } - - // be-035: actor != assignee must be refused without --force. - mismatched := &types.Issue{Assignee: "bob"} - if err := validateIssueClosable("bd-3", mismatched, "alice", false); err == nil { - t.Fatalf("expected actor/assignee mismatch error") - } - // --force overrides the authority check. - if err := validateIssueClosable("bd-3", mismatched, "alice", true); err != nil { - t.Fatalf("expected close to succeed with force despite mismatch, got %v", err) - } - // Same-actor close is allowed. - if err := validateIssueClosable("bd-4", &types.Issue{Assignee: "alice"}, "alice", false); err != nil { - t.Fatalf("expected matching-assignee close to succeed, got %v", err) - } - // Unassigned beads can be closed by anyone (lots of bd's flow involves - // closing beads nobody claimed). - if err := validateIssueClosable("bd-5", &types.Issue{Assignee: ""}, "alice", false); err != nil { - t.Fatalf("expected unassigned close to succeed, got %v", err) - } -} - func TestFindRepliesToAndReplies_WorksWithDoltStorage(t *testing.T) { ctx := context.Background() st := newTestStoreWithPrefix(t, filepath.Join(t.TempDir(), "test.db"), "test") diff --git a/internal/httpapi/BUILD.bazel b/internal/httpapi/BUILD.bazel index fab98a6f5..2cc93e90c 100644 --- a/internal/httpapi/BUILD.bazel +++ b/internal/httpapi/BUILD.bazel @@ -72,6 +72,7 @@ go_test( "brief_projection_test.go", "claim_next_test.go", "claim_test.go", + "close_guards_test.go", "close_test.go", "comments_test.go", "context_test.go", diff --git a/internal/httpapi/apigen/types.gen.go b/internal/httpapi/apigen/types.gen.go index b09477c7c..1d12b9fa7 100644 --- a/internal/httpapi/apigen/types.gen.go +++ b/internal/httpapi/apigen/types.gen.go @@ -393,7 +393,7 @@ type ApplyCloseItem struct { // IT IS A STRING, and it must be the `revision` string a response carried, verbatim. A JSON number — or any other type — is a `400` naming this member. The token spans the FULL 64-bit range, so a number would be rounded past 2^53 by an IEEE-754-double parser and the guard would miss a row nothing else touched; a string round-trips exactly in every consumer. ExpectedVersion *string `json:"expected_version,omitempty"` - // Force Bypasses close policy — the open-children refusal and the live-blocker refusal — and nothing else. + // Force Bypasses close policy — the open-children refusal and the live-blocker refusal — and the pin and the assignee guard, and nothing else: never the template guard. // // CLOSE POLICY EVALUATES AT THIS ITEM, against the row as this request has already changed it. A LATER item that gives a closed parent an open child is NOT refused: the policy is a gate on the closing act, not an invariant the store maintains. Force *bool `json:"force,omitempty"` @@ -764,7 +764,7 @@ type BatchCloseRequest struct { // Actor Who is closing. `ClaimRequest.actor`'s rules exactly, and the value is recorded against every item. Actor string `json:"actor"` - // Force Bypass close policy — the open-children refusal and the live-blocker refusal — for EVERY item, and nothing else. It never bypasses validation and it never bypasses existence: an id that names nothing refuses whether or not this is set. It is request-wide because the flag that spells it is. + // Force Bypass close policy — the open-children refusal and the live-blocker refusal — and the pin and the assignee guard for EVERY item, and nothing else. It never bypasses the template guard or validation, and it never bypasses existence: an id that names nothing refuses whether or not this is set. It is request-wide because the flag that spells it is. Force *bool `json:"force,omitempty"` // Items The issues to close, in the order the caller asked for them. Every item appears in `outcomes` at the same index. @@ -929,7 +929,7 @@ type CloseIssueRequest struct { // IT IS A STRING, and it must be the `revision` string a response carried, verbatim. A JSON number — or any other type — is a `400` naming this member. The token spans the FULL 64-bit range, so a number would be rounded past 2^53 by an IEEE-754-double parser and the guard would miss a row nothing else touched; a string round-trips exactly in every consumer. ExpectedVersion *string `json:"expected_version,omitempty"` - // Force Bypass close policy — the open-children refusal and the live-blocker refusal — and nothing else. The refusals are the ROLE's, so this endpoint cannot skip a guard by forgetting one exists. A forced close still reports `open_children`. + // Force Bypass close policy — the open-children refusal and the live-blocker refusal — and the pin and the assignee guard, and nothing else: never the template guard (see "Close guards" on `POST /v0/beads/issues/{id}:close`). The refusals are the ROLE's, so this endpoint cannot skip a guard by forgetting one exists. A forced close still reports `open_children`. // // IT BYPASSES POLICY, NEVER A PRECONDITION. `expected_version` is still checked with it set, for the reason `issueops.CloseRequest.Force` gives: a caller saying "close it anyway" has said nothing about whether the row is still the one it read. Force *bool `json:"force,omitempty"` @@ -969,10 +969,13 @@ type CloseOutcome struct { // A BATCH WHOSE ITEMS ARE ALL `true` LANDED NOTHING, and records no history entry: a per-item success that changed nothing is not work the caller did. AlreadyClosed *bool `json:"already_closed,omitempty"` + // Assignee With `not_assignee`: the issue's assignee the refusing transaction observed, exactly as `Problem.assignee` carries it for the single close. Absent on a successful item and on every other refusal. + Assignee *string `json:"assignee,omitempty"` + // Blockers With `not_closable` on the live-blocker refusal: the blockers that refused THIS item, exactly as `Problem.blockers` carries them for the single close, and optional for the same reason. Absent on a successful item and on every other refusal. Blockers *[]Blocker `json:"blockers,omitempty"` - // Code This item's refusal, from `Problem.code`'s vocabulary and restricted to `not_found` (the id names no row in either plane) and `not_closable` (close policy refused it: open children, or a live blocker — see `open_children`). ABSENT means the item succeeded. + // Code This item's refusal, from `Problem.code`'s vocabulary and restricted to `not_found` (the id names no row in either plane), `not_closable` (close policy refused it: open children, or a live blocker — see `open_children`), and the close guards `template_read_only`, `issue_pinned` and `not_assignee` (see `assignee`), exactly as the single close answers them. ABSENT means the item succeeded. // // It is the problem vocabulary rather than a second one because an item refusal and a request refusal are the same question asked at two scopes, and a client that had to learn two vocabularies to classify one condition would be classifying the SCOPE rather than the condition. Code *string `json:"code,omitempty"` @@ -1586,7 +1589,7 @@ type Problem struct { // IT IS A STRING, and it must be the `revision` string a response carried, verbatim. A JSON number — or any other type — is a `400` naming this member. The token spans the FULL 64-bit range, so a number would be rounded past 2^53 by an IEEE-754-double parser and the guard would miss a row nothing else touched; a string round-trips exactly in every consumer. ActualVersion *string `json:"actual_version,omitempty"` - // Assignee With `already_claimed`: the actor currently holding the issue, read inside the transaction that refused. + // Assignee With `already_claimed`: the actor currently holding the issue, read inside the transaction that refused. With `not_assignee`: the issue's assignee the refusing close observed — always present on that code. // // IT IS OPTIONAL ON EVERY OPERATION BUT THE CLAIM. `POST /v0/beads/issues/{id}:claim` always carries it, because its conflict path reads the row it lost to. `PATCH /v0/beads/issues/{id}` and `POST /v0/beads/issues:batchApply` carry it only when the refusing transaction reported a holder, and `POST /v0/beads/issues/{id}:release` never does — the ownership fence refuses without naming anyone. An absent member means "this refusal could not name the holder", never "nobody holds it"; re-read the row. Assignee *string `json:"assignee,omitempty"` @@ -1607,7 +1610,7 @@ type Problem struct { // IT IS OPTIONAL. A refusal that could not name its blockers omits it and keeps the generic `detail`; absence means "this refusal did not name them", never "nothing blocks it". Re-read the issue's dependencies then. Blockers *[]Blocker `json:"blockers,omitempty"` - // Code The stable machine-readable reason, and the ONLY member a client may dispatch on. v0's vocabulary: `invalid_argument` (400, also emitted by the Host-header middleware on any route), `invalid_cursor` (400), `unauthenticated` (401, only on a server configured with a token file), `not_found` (404), `already_claimed` (409), `not_claimable` (409), `not_closable` (409), `not_releasable` (409), `template_read_only` (409), `dependency_cycle` (409), `dependency_exists` (409), `already_exists` (409), `precondition_failed` (409), `events_journal_disabled` (409), `events_journal_truncated` (410), `busy` (503), `db_unavailable` (503), `events_watch_saturated` (503), `internal` (500). Renaming or removing a status+code pair is a breaking change; ADDING one is not, so clients MUST default-branch on unknown values and fall back to the status class (unknown 4xx → client bug, fail loud; unknown 503 → retry per `Retry-After`; other unknown 5xx → server fault). + // Code The stable machine-readable reason, and the ONLY member a client may dispatch on. v0's vocabulary: `invalid_argument` (400, also emitted by the Host-header middleware on any route), `invalid_cursor` (400), `unauthenticated` (401, only on a server configured with a token file), `not_found` (404), `already_claimed` (409), `not_claimable` (409), `not_closable` (409), `not_releasable` (409), `template_read_only` (409), `issue_pinned` (409), `not_assignee` (409), `dependency_cycle` (409), `dependency_exists` (409), `already_exists` (409), `precondition_failed` (409), `events_journal_disabled` (409), `events_journal_truncated` (410), `busy` (503), `db_unavailable` (503), `events_watch_saturated` (503), `internal` (500). Renaming or removing a status+code pair is a breaking change; ADDING one is not, so clients MUST default-branch on unknown values and fall back to the status class (unknown 4xx → client bug, fail loud; unknown 503 → retry per `Retry-After`; other unknown 5xx → server fault). Code string `json:"code"` // DeclaredLater With `invalid_argument` on a batch operation whose items may name each other: whether the unresolvable key IS declared by the request, at a LATER index. diff --git a/internal/httpapi/batch_apply.go b/internal/httpapi/batch_apply.go index 8b2e3fcba..a1cfa73f0 100644 --- a/internal/httpapi/batch_apply.go +++ b/internal/httpapi/batch_apply.go @@ -1054,9 +1054,12 @@ func (s *Server) failApplyBatch(w http.ResponseWriter, r *http.Request, request s.fail(w, r, at(closeBlockedResult(err, "an item closes a blocked issue", "clear the blocker, or send the item's force flag"), "")) - // An update item naming a template: the shared mapping plus the item + // An update item naming a template, or the close guards on a close item: + // the shared mapping, carrying the holder for not_assignee, plus the item // members. - case errors.Is(err, issueops.ErrTemplateReadOnly): + case errors.Is(err, issueops.ErrTemplateReadOnly), + errors.Is(err, issueops.ErrPinned), + errors.As(err, new(*issueops.CloseNotAssigneeError)): s.fail(w, r, at(ClassifyError(err), "")) case errors.Is(err, storage.ErrAlreadyClaimed): diff --git a/internal/httpapi/batch_close.go b/internal/httpapi/batch_close.go index 9fb4cc02b..d28bea778 100644 --- a/internal/httpapi/batch_close.go +++ b/internal/httpapi/batch_close.go @@ -118,6 +118,7 @@ func closeOutcome(outcome issueops.CloseOutcome) apigen.CloseOutcome { } var openChildren *issueops.CloseOpenChildrenError + var notAssignee *issueops.CloseNotAssigneeError var ( code Code detail string @@ -135,6 +136,16 @@ func closeOutcome(outcome issueops.CloseOutcome) apigen.CloseOutcome { code = CodeNotClosable detail, wire.Blockers = closeBlocked(outcome.Err, "this issue is blocked", "clear the blocker, or send `force`") + // The close guards answer per item exactly as the single close answers + // them — the shared mapping's code and detail — with the holder on the + // outcome's own `assignee` member. + case errors.Is(outcome.Err, issueops.ErrTemplateReadOnly), + errors.Is(outcome.Err, issueops.ErrPinned), + errors.As(outcome.Err, ¬Assignee): + res := ClassifyError(outcome.Err) + code, detail = Code(res.Problem.Code), derefString(res.Problem.Detail) + wire.Assignee = res.Problem.Assignee + case errors.Is(outcome.Err, storage.ErrNotFound): code, detail = CodeNotFound, "no issue with this id in either plane" diff --git a/internal/httpapi/close_guards_test.go b/internal/httpapi/close_guards_test.go new file mode 100644 index 000000000..fb7a0e0ef --- /dev/null +++ b/internal/httpapi/close_guards_test.go @@ -0,0 +1,163 @@ +package httpapi + +import ( + "fmt" + "net/http" + "strings" + "testing" + + "github.com/steveyegge/beads/issueops" +) + +// The close guards — template read-only, the pin, the assignee fence — are the +// ROLE's (issueops.Lifecycle.Close and the batch roles that share its body), so +// these cases drive a fake role that refuses the way the real one does and pin +// what the wire makes of it on each of the three close routes. The real role +// behind a real server is the served leg of the conformance contracts +// (internal/httpclient: TestServedLifecycleCloseEnforcesTheCloseGuards and its +// batch siblings), which also proves the client rebuilds the typed error. + +// closeGuardCases are the three refusals as a unit-of-work backend returns +// them: wrapped by the use case and the repository, so the mapping has to find +// them by type rather than by being handed the bare value. +var closeGuardCases = []struct { + name string + err error + code Code + assignee any +}{ + { + name: "template", + err: &issueops.TemplateReadOnlyError{IssueID: "bd-1"}, + code: CodeTemplateReadOnly, + }, + { + name: "pinned", + err: &issueops.PinnedError{IssueID: "bd-1"}, + code: CodeIssuePinned, + }, + { + name: "not assignee", + err: &issueops.CloseNotAssigneeError{IssueID: "bd-1", Assignee: "bob", Actor: "alice"}, + code: CodeNotAssignee, + assignee: "bob", + }, +} + +func wrapAsUOW(err error) error { + return fmt.Errorf("close bd-1: db: IssueSQLRepository.CloseChecked bd-1: %w", err) +} + +// assertNoRoleProse checks a detail is this server's own words: the role's +// sentence names the actor the caller sent and the holder, and a refusal's +// detail is not where a client reads either. +func assertNoRoleProse(t *testing.T, where string, detail any) { + t.Helper() + text, _ := detail.(string) + if text == "" { + t.Errorf("%s detail = %v, want this server's own sentence", where, detail) + } + for _, leaked := range []string{"cannot modify", "cannot close", "IssueSQLRepository"} { + if strings.Contains(text, leaked) { + t.Errorf("%s detail %q carries the role's prose (%q)", where, text, leaked) + } + } +} + +func TestCloseGuardsAreTypedConflicts(t *testing.T) { + for _, tc := range closeGuardCases { + t.Run(tc.name, func(t *testing.T) { + lifecycle := &roleLifecycle{closeErr: wrapAsUOW(tc.err)} + ts := newCloseServer(t, lifecycle) + + resp := ts.closeIssue(t, closePath, `{"actor":"alice"}`) + if resp.StatusCode != http.StatusConflict { + t.Fatalf("status = %d, want 409: %s", resp.StatusCode, readAll(t, resp)) + } + body := decodeBody(t, resp) + if body["code"] != string(tc.code) { + t.Errorf("code = %v, want %s", body["code"], tc.code) + } + if body["assignee"] != tc.assignee { + t.Errorf("assignee = %v, want %v", body["assignee"], tc.assignee) + } + if _, ok := body["open_children"]; ok { + t.Errorf("a close guard carries open_children, which would read as close policy") + } + assertNoRoleProse(t, "close", body["detail"]) + }) + } +} + +// TestCloseForwardsForceToTheGuards pins that the handler hands `force` to the +// role and decides nothing itself: whether a guard is waived is the role's call. +func TestCloseForwardsForceToTheGuards(t *testing.T) { + lifecycle := &roleLifecycle{closeErr: wrapAsUOW(&issueops.TemplateReadOnlyError{IssueID: "bd-1"})} + ts := newCloseServer(t, lifecycle) + + resp := ts.closeIssue(t, closePath, `{"actor":"alice","force":true}`) + if resp.StatusCode != http.StatusConflict { + t.Fatalf("status = %d, want the role's 409 under force: %s", resp.StatusCode, readAll(t, resp)) + } + if got := lifecycle.closeRequests(); len(got) != 1 || !got[0].Force { + t.Fatalf("the role received %+v, want one request carrying Force", got) + } +} + +func TestBatchCloseItemsCarryTheCloseGuards(t *testing.T) { + outcomes := []issueops.CloseOutcome{{IssueID: "bd-0", Issue: closedIssue("bd-0"), Changed: true}} + for _, tc := range closeGuardCases { + outcomes = append(outcomes, issueops.CloseOutcome{IssueID: "bd-1", Err: wrapAsUOW(tc.err)}) + } + ts := newBatchCloseServer(t, &roleBatchCloser{result: issueops.CloseBatchResult{Outcomes: outcomes}}) + + resp := ts.batchClose(t, `{"actor":"alice","items":[{"id":"bd-0"},{"id":"bd-1"},{"id":"bd-1"},{"id":"bd-1"}]}`) + if resp.StatusCode != http.StatusOK { + t.Fatalf("status = %d, want 200 carrying per-item refusals: %s", resp.StatusCode, readAll(t, resp)) + } + got := outcomesOf(t, resp) + if len(got) != 4 { + t.Fatalf("outcomes = %d, want 4", len(got)) + } + if _, refused := got[0]["code"]; refused { + t.Errorf("outcome 0 = %v, want the plain item's success", got[0]) + } + for i, tc := range closeGuardCases { + item := got[i+1] + if item["code"] != string(tc.code) { + t.Errorf("%s item code = %v, want %s", tc.name, item["code"], tc.code) + } + if item["assignee"] != tc.assignee { + t.Errorf("%s item assignee = %v, want %v", tc.name, item["assignee"], tc.assignee) + } + if _, ok := item["issue"]; ok { + t.Errorf("%s item carries an issue snapshot beside its refusal", tc.name) + } + assertNoRoleProse(t, tc.name+" item", item["detail"]) + } +} + +func TestApplyBatchCloseItemGuardsAreTypedConflicts(t *testing.T) { + for _, tc := range closeGuardCases { + t.Run(tc.name, func(t *testing.T) { + applier := &roleBatchApplier{err: itemErr(1, issueops.ItemClose, "", "bd-1", wrapAsUOW(tc.err))} + ts := newApplyBatchServer(t, applier) + + resp := ts.claim(t, batchApplyPath, `{"actor":"alice","items":[{"kind":"create","create":{"title":"one"}}]}`) + if resp.StatusCode != http.StatusConflict { + t.Fatalf("status = %d, want 409: %s", resp.StatusCode, readAll(t, resp)) + } + body := decodeBody(t, resp) + if body["code"] != string(tc.code) { + t.Errorf("code = %v, want %s", body["code"], tc.code) + } + if body["assignee"] != tc.assignee { + t.Errorf("assignee = %v, want %v", body["assignee"], tc.assignee) + } + if body["item_index"] != float64(1) || body["item_kind"] != "close" || body["item_issue_id"] != "bd-1" { + t.Errorf("item members = %v/%v/%v, want 1/close/bd-1", body["item_index"], body["item_kind"], body["item_issue_id"]) + } + assertNoRoleProse(t, "applyBatch", body["detail"]) + }) + } +} diff --git a/internal/httpapi/problem.go b/internal/httpapi/problem.go index a7694e09a..2bad156a1 100644 --- a/internal/httpapi/problem.go +++ b/internal/httpapi/problem.go @@ -146,6 +146,23 @@ const ( // A 409 for CodeNotClosable's reason: the body is well-formed and the // STATE of the named row refuses it. CodeTemplateReadOnly Code = "template_read_only" + // CodeIssuePinned is an unforced close of a pinned issue, by either of the + // two spellings bd pins with (the `pinned` flag or the `pinned` status). + // `force` is the bypass. It is its own code rather than a third + // `not_closable` because that code's member-presence discriminator already + // reads "no `open_children`" as a live blocker, and a pin is not one. + CodeIssuePinned Code = "issue_pinned" + // CodeNotAssignee is an unforced close by an actor who is not the issue's + // assignee (be-035): an unassigned issue is closable by anyone, an + // assigned one by its holder, compared separator-insensitively. `force` is + // the bypass. The holder the refusing transaction observed travels in the + // `assignee` member, so a client names it without reading `detail`; the + // closing actor is the one the request sent. + // + // It is minted rather than folded into CodeAlreadyClaimed, which a client + // maps to a lost CLAIM: answering it for a close would have the client + // read the operation, rather than the code, to decide what was refused. + CodeNotAssignee Code = "not_assignee" // CodeDependencyCycle covers BOTH never-makes-progress refusals a requested // edge set can earn: a scheduling cycle, and a blocking edge against the // issue's own ancestor or descendant. They are one code because they have @@ -273,6 +290,8 @@ var codeStatus = map[Code]int{ CodeNotClosable: http.StatusConflict, CodeNotesOverwrite: http.StatusConflict, CodeTemplateReadOnly: http.StatusConflict, + CodeIssuePinned: http.StatusConflict, + CodeNotAssignee: http.StatusConflict, CodeNotReleasable: http.StatusConflict, CodeDependencyCycle: http.StatusConflict, CodeDependencyExists: http.StatusConflict, @@ -823,7 +842,8 @@ var operationCodes = map[string][]Code{ // The NARROWEST write vocabulary on this surface, and the narrowness is the // contract rather than an oversight. A problem document from this operation // means the batch never ran; every refusal an ITEM can earn — not_found for - // an id naming no row, not_closable for close policy — travels in that + // an id naming no row, not_closable for close policy, template_read_only, + // issue_pinned and not_assignee for the close guards — travels in that // item's outcome inside a 200. A 404 here would say the operation went to // the wrong place, and a 409 would say the whole batch was refused, and // neither is ever true of a per-item refusal. @@ -856,14 +876,18 @@ var operationCodes = map[string][]Code{ CodeAlreadyClaimed, CodeNotReleasable, CodePreconditionFailed, CodeBusy, CodeDBUnavailable, CodeInternal, }, - // TWO 409s, and they answer different questions with `code` as the only - // discriminator a client needs. + // Several 409s, and they answer different questions with `code` as the + // only discriminator a client needs. // // not_closable is close POLICY: an unforced close refused for open children - // or for a live blocker. There is no already_claimed here — closing work - // somebody else holds is not a refusal on this surface — and the idempotent - // re-close is a 200 carrying `already_closed`, the claim's answer to the - // same question. + // or for a live blocker. The idempotent re-close is a 200 carrying + // `already_closed`, the claim's answer to the same question. + // + // template_read_only, issue_pinned and not_assignee are the CLOSE GUARDS + // the role applies before policy, in that order: a template (no bypass), a + // pin and closing work somebody else holds (both bypassed by `force`). + // There is no already_claimed: that code is a lost claim, and not_assignee + // carries the holder in `assignee` itself. // // precondition_failed is `expected_version`'s, in the 409 form for the // reason that code documents, and it is CHECKED FIRST — before policy and @@ -872,6 +896,7 @@ var operationCodes = map[string][]Code{ // members make unrelated claims. OpCloseIssue: { CodeInvalidArgument, CodeUnauthenticated, CodeNotFound, CodeNotClosable, CodePreconditionFailed, + CodeTemplateReadOnly, CodeIssuePinned, CodeNotAssignee, CodeBusy, CodeDBUnavailable, CodeInternal, }, // ONE 409, and it is a PRECONDITION rather than a policy. Close has a policy @@ -978,7 +1003,7 @@ var operationCodes = map[string][]Code{ OpApplyBatch: { CodeInvalidArgument, CodeUnauthenticated, CodeNotFound, CodePreconditionFailed, CodeNotClosable, CodeAlreadyClaimed, CodeNotesOverwrite, CodeAlreadyExists, - CodeTemplateReadOnly, + CodeTemplateReadOnly, CodeIssuePinned, CodeNotAssignee, CodeDependencyCycle, CodeDependencyExists, CodeBusy, CodeDBUnavailable, CodeInternal, }, @@ -1525,6 +1550,7 @@ func ClassifyError(err error) Result { // `if` away from a pruned-past checkpoint arriving as a generic 500 on // whichever arm forgot it. var truncated *storage.EventsJournalTruncatedError + var notAssignee *issueops.CloseNotAssigneeError switch { case err == nil: @@ -1560,11 +1586,20 @@ func ClassifyError(err error) Result { case errors.Is(err, issueops.ErrCloseBlocked): return closeBlockedResult(err, "issue is blocked", "clear the blocker or close with force") - // The detail is this server's own words rather than the role's message, - // for the reason Problem.detail gives. + // The close guards; the first, template read-only, is every update's guard + // too. Each detail is this server's own words rather than the role's + // message, for the reason Problem.detail gives; the typed members are what + // a client reconstructs the refusal from. case errors.Is(err, issueops.ErrTemplateReadOnly): return newResult(CodeTemplateReadOnly, "this issue is a template, and templates are read-only; pour it to create work") + case errors.Is(err, issueops.ErrPinned): + return newResult(CodeIssuePinned, "this issue is pinned; close with force to override") + + case errors.As(err, ¬Assignee): + return newResult(CodeNotAssignee, + "this issue is assigned to another actor; reclaim it, or close with force").WithAssignee(notAssignee.Assignee) + case errors.Is(err, ErrBusy): res := newResult(CodeBusy, "") res.RetryAfterSeconds = retryAfterSaturation diff --git a/internal/httpapi/spec/openapi.v0.yaml b/internal/httpapi/spec/openapi.v0.yaml index 6d9c5b354..f62181bf3 100644 --- a/internal/httpapi/spec/openapi.v0.yaml +++ b/internal/httpapi/spec/openapi.v0.yaml @@ -2420,8 +2420,10 @@ paths: `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 - does not acquire the close's semantics, which is why `{id}:close` - remains the operation to reach for when what you mean is "close this". + does not acquire the close's semantics, and that includes its close + guards: a patch is never refused `issue_pinned` or `not_assignee`. + That is why `{id}:close` remains the operation to reach for when what + you mean is "close this". `created_at`, `created_by` — `POST /v0/beads/issues` withholds them for @@ -3202,8 +3204,33 @@ paths: the blockers themselves travel in `blockers`). The MEMBER'S PRESENCE is the discriminator, so telling the two apart never requires reading `detail`. Both refusals are the ROLE's, so `force` - bypasses those two and nothing else — this endpoint cannot skip a guard - by forgetting one exists. + bypasses those two — this endpoint cannot skip a guard by forgetting + one exists. + + + ## Close guards + + + Before close policy, a close of an issue that is not already closed + answers to three guards, in this order. A template refuses with + `409` / `template_read_only` and has no bypass. A pinned issue (the + `pinned` flag or the `pinned` status) refuses with `409` / + `issue_pinned`. An issue assigned to someone other than `actor` + (compared separator-insensitively; an unassigned issue is closable by + anyone) refuses with `409` / `not_assignee`, carrying the holder in + `assignee`. `force` bypasses the pin and the assignee guard. They are + the guards `bd close` applies, and they are the ROLE's, so every close + operation — this one, `POST /v0/beads/issues:batchClose` and a + `close` item of `POST /v0/beads/issues:batchApply` — applies them + alike. An idempotent re-close is not guarded: it changes nothing. + + + The guards gate the close operations, not the closed state. A status + update that crosses into the done category — a `PATCH` of + `/v0/beads/issues/{id}` or an `update` item of + `POST /v0/beads/issues:batchApply` — is not a close operation and + answers to close policy only, so it still closes a pinned issue or one + another actor holds. ## The guard @@ -3297,8 +3324,13 @@ paths: bypass both. `force` does NOT bypass the guard above. - Nothing was written in either case. - x-bd-codes: [not_closable, precondition_failed] + `template_read_only`, `issue_pinned` and `not_assignee`: a close + guard refused (see "Close guards"). `not_assignee` carries the + holder in `assignee`. `force` bypasses the latter two. + + + Nothing was written in any case. + x-bd-codes: [issue_pinned, not_assignee, not_closable, precondition_failed, template_read_only] content: application/problem+json: schema: @@ -4338,9 +4370,16 @@ paths: per-item bypasses, and a forced item never earns this. - `template_read_only` is an `update` item whose target is a - template, exactly as `PATCH /v0/beads/issues/{id}` answers it; no - item member bypasses it. + `template_read_only` is an `update` or a `close` item whose target + is a template, exactly as `PATCH /v0/beads/issues/{id}` and + `POST /v0/beads/issues/{id}:close` answer it; no item member + bypasses it. + + + `issue_pinned` and `not_assignee` are the other two close guards + refusing a `close` item, exactly as + `POST /v0/beads/issues/{id}:close` answers them; `not_assignee` + carries the holder in `assignee`. `close.force` bypasses both. `already_claimed` is the assignee fence: an `update` whose @@ -4372,8 +4411,8 @@ paths: a malformed request. x-bd-codes: [already_claimed, already_exists, dependency_cycle, - dependency_exists, not_closable, notes_overwrite_refused, precondition_failed, - template_read_only] + dependency_exists, issue_pinned, not_assignee, not_closable, + notes_overwrite_refused, precondition_failed, template_read_only] content: application/problem+json: schema: @@ -4421,8 +4460,9 @@ paths: contract: a refusal OF THE REQUEST is a problem document, and a refusal OF AN ITEM is a member of that item's outcome. `code` on an outcome is the same vocabulary `Problem.code` publishes, restricted to - `not_found` and `not_closable`, so a client classifies an item exactly - as it classifies a request. + `not_found`, `not_closable` and the three close guards + (`template_read_only`, `issue_pinned`, `not_assignee`), so a client + classifies an item exactly as it classifies a request. WHAT IS ATOMIC IS EVERYTHING THAT LANDS: one transaction, at most one @@ -4466,8 +4506,9 @@ paths: NO PER-ITEM PRECONDITION. There is no counterpart here to a compare-and-set guard, matching the role, so `force` is a question with - only two answers: it bypasses blocker and open-child close policy for - every item, and it never bypasses validation or existence. + only two answers: it bypasses blocker and open-child close policy, the + pin and the assignee guard for every item, and it never bypasses the + template guard, validation or existence. ## Hooks and auto-commit @@ -10452,7 +10493,8 @@ components: default: false description: >- Bypasses close policy — the open-children refusal and the - live-blocker refusal — and nothing else. + live-blocker refusal — and the pin and the assignee guard, and + nothing else: never the template guard. CLOSE POLICY EVALUATES AT THIS ITEM, against the row as this request @@ -11065,10 +11107,11 @@ components: default: false description: >- Bypass close policy — the open-children refusal and the live-blocker - refusal — for EVERY item, and nothing else. It never bypasses - validation and it never bypasses existence: an id that names nothing - refuses whether or not this is set. It is request-wide because the - flag that spells it is. + refusal — and the pin and the assignee guard for EVERY item, and + nothing else. It never bypasses the template guard or validation, + and it never bypasses existence: an id that names nothing refuses + whether or not this is set. It is request-wide because the flag + that spells it is. BatchCloseItem: type: object @@ -11161,13 +11204,22 @@ components: refused THIS item, exactly as `Problem.blockers` carries them for the single close, and optional for the same reason. Absent on a successful item and on every other refusal. + assignee: + type: string + description: >- + With `not_assignee`: the issue's assignee the refusing transaction + observed, exactly as `Problem.assignee` carries it for the single + close. Absent on a successful item and on every other refusal. code: type: string description: >- This item's refusal, from `Problem.code`'s vocabulary and restricted - to `not_found` (the id names no row in either plane) and + to `not_found` (the id names no row in either plane), `not_closable` (close policy refused it: open children, or a live - blocker — see `open_children`). ABSENT means the item succeeded. + blocker — see `open_children`), and the close guards + `template_read_only`, `issue_pinned` and `not_assignee` (see + `assignee`), exactly as the single close answers them. ABSENT means + the item succeeded. It is the problem vocabulary rather than a second one because an @@ -11246,9 +11298,11 @@ components: default: false description: >- Bypass close policy — the open-children refusal and the - live-blocker refusal — and nothing else. The refusals are the - ROLE's, so this endpoint cannot skip a guard by forgetting one - exists. A forced close still reports `open_children`. + live-blocker refusal — and the pin and the assignee guard, and + nothing else: never the template guard (see "Close guards" on + `POST /v0/beads/issues/{id}:close`). The refusals are the ROLE's, + so this endpoint cannot skip a guard by forgetting one exists. A + forced close still reports `open_children`. IT BYPASSES POLICY, NEVER A PRECONDITION. `expected_version` is @@ -12185,7 +12239,8 @@ components: configured with a token file), `not_found` (404), `already_claimed` (409), `not_claimable` (409), `not_closable` (409), `not_releasable` (409), - `template_read_only` (409), + `template_read_only` (409), `issue_pinned` (409), + `not_assignee` (409), `dependency_cycle` (409), `dependency_exists` (409), `already_exists` (409), `precondition_failed` (409), `events_journal_disabled` (409), `events_journal_truncated` (410), @@ -12245,7 +12300,9 @@ components: type: string description: >- With `already_claimed`: the actor currently holding the issue, read - inside the transaction that refused. + inside the transaction that refused. With `not_assignee`: the + issue's assignee the refusing close observed — always present on + that code. IT IS OPTIONAL ON EVERY OPERATION BUT THE CLAIM. `POST diff --git a/internal/httpapi/wireshape/testdata/golden.json b/internal/httpapi/wireshape/testdata/golden.json index 89c866bab..02a66f58c 100644 --- a/internal/httpapi/wireshape/testdata/golden.json +++ b/internal/httpapi/wireshape/testdata/golden.json @@ -1220,6 +1220,12 @@ "type": "boolean", "required": false }, + { + "schema": "CloseOutcome", + "member": "assignee", + "type": "string", + "required": false + }, { "schema": "CloseOutcome", "member": "blockers", diff --git a/internal/httpclient/batchcloser.go b/internal/httpclient/batchcloser.go index a9d231e3c..d7257186a 100644 --- a/internal/httpclient/batchcloser.go +++ b/internal/httpclient/batchcloser.go @@ -239,7 +239,7 @@ func decodeBatchCloseResult(req issueops.CloseBatchRequest, resp *apigen.BatchCl } outcomes := make([]issueops.CloseOutcome, len(resp.Outcomes)) for i := range resp.Outcomes { - outcomes[i] = decodeBatchCloseOutcome(resp.Outcomes[i]) + outcomes[i] = decodeBatchCloseOutcome(req.Actor, resp.Outcomes[i]) } return issueops.CloseBatchResult{Outcomes: outcomes}, nil } @@ -252,10 +252,10 @@ func decodeBatchCloseResult(req issueops.CloseBatchRequest, resp *apigen.BatchCl // members are FLAT on the outcome rather than nested under an error object, so // `open_children` is read from the same field in both branches and means two // different things depending on which one — see the schema. -func decodeBatchCloseOutcome(item apigen.CloseOutcome) issueops.CloseOutcome { +func decodeBatchCloseOutcome(actor string, item apigen.CloseOutcome) issueops.CloseOutcome { out := issueops.CloseOutcome{IssueID: item.IssueId} if item.Code != nil { - out.Err = perItemCloseError(item.IssueId, item) + out.Err = perItemCloseError(item.IssueId, actor, item) return out } // A successful outcome carries the snapshot; already_closed is the idempotent @@ -276,6 +276,10 @@ func decodeBatchCloseOutcome(item apigen.CloseOutcome) issueops.CloseOutcome { // not_found -> issueops.ErrNotFound // not_closable + open_children -> *issueops.CloseOpenChildrenError // not_closable -> issueops.ErrCloseBlocked +// template_read_only -> *issueops.TemplateReadOnlyError +// issue_pinned -> *issueops.PinnedError +// not_assignee + assignee -> *issueops.CloseNotAssigneeError (the +// closing actor is the request's own) // an unknown code -> *wire.UnknownItemCodeError (the generic // typed per-item error, so version skew lands // as a typed refusal rather than a silent gap) @@ -285,7 +289,7 @@ func decodeBatchCloseOutcome(item apigen.CloseOutcome) issueops.CloseOutcome { // // It is only ever called with a refused outcome — Code non-nil — which the one // caller above guarantees. -func perItemCloseError(issueID string, item apigen.CloseOutcome) error { +func perItemCloseError(issueID, actor string, item apigen.CloseOutcome) error { var code string if item.Code != nil { code = *item.Code @@ -298,6 +302,16 @@ func perItemCloseError(issueID string, item apigen.CloseOutcome) error { return &issueops.CloseOpenChildrenError{IssueID: issueID, OpenChildren: *item.OpenChildren} } return issueops.ErrCloseBlocked + case codeTemplateReadOnly: + return &issueops.TemplateReadOnlyError{IssueID: issueID} + case codeIssuePinned: + return &issueops.PinnedError{IssueID: issueID} + case codeNotAssignee: + var assignee string + if item.Assignee != nil { + assignee = stripItemControlRunes(*item.Assignee) + } + return &issueops.CloseNotAssigneeError{IssueID: issueID, Assignee: assignee, Actor: actor} default: var detail string if item.Detail != nil { @@ -311,12 +325,15 @@ func perItemCloseError(issueID string, item apigen.CloseOutcome) error { } } -// The two per-item refusal codes this outcome can carry. They are the +// The per-item refusal codes this outcome can carry. They are the // `Problem.code` spellings, restated here rather than imported because // importing the server package would drag the storage engine into a client. const ( - codeNotFound = "not_found" - codeNotClosable = "not_closable" + codeNotFound = "not_found" + codeNotClosable = "not_closable" + codeTemplateReadOnly = "template_read_only" + codeIssuePinned = "issue_pinned" + codeNotAssignee = "not_assignee" ) // stripItemControlRunes removes control runes from a server-controlled per-item @@ -363,6 +380,9 @@ func perItemCloseRefusal(issueID string, err error) (issueops.CloseOutcome, bool case errors.As(err, &openChildren): case errors.Is(err, issueops.ErrNotFound): case errors.Is(err, issueops.ErrCloseBlocked): + case errors.Is(err, issueops.ErrTemplateReadOnly): + case errors.Is(err, issueops.ErrPinned): + case errors.As(err, new(*issueops.CloseNotAssigneeError)): default: return issueops.CloseOutcome{}, false } diff --git a/internal/httpclient/lifecycle.go b/internal/httpclient/lifecycle.go index 1bad6d62c..409be20d3 100644 --- a/internal/httpclient/lifecycle.go +++ b/internal/httpclient/lifecycle.go @@ -936,11 +936,17 @@ func setNullableTime(out map[string]any, member string, field issueops.Field[*ti // operation the Lifecycle role uses (design D8's off-role list, extended by the // `bd close` decision). // -// Its one caller at tip is the molecule auto-close, which closes a parent whose -// children have all finished and discards nothing about the outcome. Routing it -// onto the role's operation rather than refusing it is what keeps that path -// working over http; it carries no reason-per-item and no force, so the mapping -// is total. +// Routing it onto the role's operation rather than refusing it is what keeps +// the molecule auto-close (which closes a parent whose children have all +// finished) and the other raw closes cmd/bd makes outside `bd close` working +// over http. It sends force because the raw close is the unguarded one +// everywhere else: dolt, embedded and proxied run it as +// issueops.CloseIssueInTx, which applies neither the close guards nor close +// policy, and its signature carries no force a caller could use to waive a +// refusal those backends never make. Sent unforced, a pinned or claimed root +// would stop closing over http and nowhere else. The template guard has no +// bypass on the wire, so a template still refuses here where the other +// backends close it; no raw caller is known to close one. func (s *Store) CloseIssue(ctx context.Context, id, reason, actor, session string) error { w, err := s.roleWire("CloseIssue") if err != nil { @@ -952,6 +958,6 @@ func (s *Store) CloseIssue(ctx context.Context, id, reason, actor, session strin if err := requireID("issue id", id); err != nil { return err } - _, err = w.CloseIssue(ctx, id, closeBody(actor, reason, session, false)) + _, err = w.CloseIssue(ctx, id, closeBody(actor, reason, session, true)) return err } diff --git a/internal/httpclient/served_batch_apply_test.go b/internal/httpclient/served_batch_apply_test.go index fa21e6b0c..1117c51b8 100644 --- a/internal/httpclient/served_batch_apply_test.go +++ b/internal/httpclient/served_batch_apply_test.go @@ -261,6 +261,10 @@ func TestServedBatchApplySplicesTheMetadataOfATemplateItCreates(t *testing.T) { conformance.RunBatchApplySplicesTheMetadataOfATemplateItCreates(t, t.Context(), newServedBatchApplyFixture(t, "hbats")) } +func TestServedBatchApplyCloseItemsAnswerToTheCloseGuards(t *testing.T) { + conformance.RunBatchApplyCloseItemsAnswerToTheCloseGuards(t, t.Context(), newServedBatchApplyFixture(t, "hbacg")) +} + // TestServedBatchApplyStampsSpawnerIDOnlyWhenNamed wires the dep_add // HasSpawner/ThreadID lineage conformance case onto the http leg (S5): a // served default Config always advertises CapBatchApplyDepAddLineage (it is diff --git a/internal/httpclient/served_batch_close_test.go b/internal/httpclient/served_batch_close_test.go index 11b9a5145..9c3911ef4 100644 --- a/internal/httpclient/served_batch_close_test.go +++ b/internal/httpclient/served_batch_close_test.go @@ -168,3 +168,10 @@ func TestServedBatchCloserDoesNotMutateTheCallerRequest(t *testing.T) { func TestServedBatchCloserSettlesTheDependersOfWhatItClosed(t *testing.T) { conformance.RunBatchCloserSettlesTheDependersOfWhatItClosed(t, t.Context(), newServedBatchCloserFixture(t, "hbcbs")) } + +// TestServedBatchCloserItemsAnswerToTheCloseGuards is the served leg of the +// close guards: each guarded item travels back as its outcome's code (and +// `assignee`) and is rebuilt into the same typed error a local batch returns. +func TestServedBatchCloserItemsAnswerToTheCloseGuards(t *testing.T) { + conformance.RunBatchCloserItemsAnswerToTheCloseGuards(t, t.Context(), newServedBatchCloserFixture(t, "hbcgd")) +} diff --git a/internal/httpclient/served_claim_lifecycle_test.go b/internal/httpclient/served_claim_lifecycle_test.go index 9f8033046..08e5bc810 100644 --- a/internal/httpclient/served_claim_lifecycle_test.go +++ b/internal/httpclient/served_claim_lifecycle_test.go @@ -309,6 +309,75 @@ func TestServedLifecycleReopenReblocksItsDependers(t *testing.T) { conformance.RunLifecycleReopenReblocksItsDependers(t, t.Context(), newServedCloseReopenFixture(t, "hlbr")) } +// TestServedLifecycleCloseEnforcesTheCloseGuards is the served leg of the close +// guards: bd serve refuses with template_read_only, issue_pinned and +// not_assignee, and the client rebuilds the typed error — sentence included — +// the embedded store returns. +func TestServedLifecycleCloseEnforcesTheCloseGuards(t *testing.T) { + conformance.RunLifecycleCloseEnforcesTheCloseGuards(t, t.Context(), newServedCloseReopenFixture(t, "hlcg")) +} + +// TestServedRawCloseKeepsParityWithTheOtherBackends is the off-role half of the +// guards: Store.CloseIssue must close what the raw close closes on dolt, +// embedded and proxied, where issueops.CloseIssueInTx runs neither the guards +// nor close policy. A pin of either spelling, another actor's claim and an open +// child each refuse the Lifecycle close above; the raw close sends force, so a +// molecule auto-close of such a root still lands over http. The template is the +// one refusal left, because read-only has no bypass on the wire. +func TestServedRawCloseKeepsParityWithTheOtherBackends(t *testing.T) { + ctx := t.Context() + env := newServedEnv(t, "hrc") + + const ( + flagPinned = "hrc-flag-pinned" + statusPinned = "hrc-status-pinned" + held = "hrc-held" + parent = "hrc-parent" + child = "hrc-child" + template = "hrc-template" + ) + for _, issue := range []*types.Issue{ + {ID: flagPinned, Status: types.StatusOpen, Pinned: true}, + {ID: statusPinned, Status: types.StatusPinned}, + {ID: held, Status: types.StatusInProgress, Assignee: "holder"}, + {ID: parent, Status: types.StatusOpen}, + {ID: child, Status: types.StatusOpen}, + {ID: template, Status: types.StatusOpen, IsTemplate: true}, + } { + issue.Title, issue.Priority, issue.IssueType = issue.ID, 2, types.TypeTask + if err := env.createIssue(ctx, issue, "seed"); err != nil { + t.Fatalf("seed %s: %v", issue.ID, err) + } + } + if err := env.addDependency(ctx, &types.Dependency{IssueID: child, DependsOnID: parent, Type: types.DepParentChild}, "seed"); err != nil { + t.Fatalf("seed %s as a child of %s: %v", child, parent, err) + } + + assertStatus := func(id string, want types.Status) { + t.Helper() + got, err := env.getIssue(ctx, id) + if err != nil { + t.Fatalf("read back %s: %v", id, err) + } + if got.Status != want { + t.Errorf("%s has status %q after the raw close, want %q", id, got.Status, want) + } + } + + for _, id := range []string{flagPinned, statusPinned, held, parent} { + if err := env.subject.CloseIssue(ctx, id, "all steps complete", "closer", ""); err != nil { + t.Fatalf("raw close of %s over http: %v, want it to land as the raw close does on every other backend", id, err) + } + assertStatus(id, types.StatusClosed) + } + + err := env.subject.CloseIssue(ctx, template, "all steps complete", "closer", "") + if !errors.As(err, new(*issueops.TemplateReadOnlyError)) { + t.Fatalf("raw close of template %s over http: err = %v, want *TemplateReadOnlyError", template, err) + } + assertStatus(template, types.StatusOpen) +} + func TestServedLifecycleReopenLeavesNonDoneStatusesUnchanged(t *testing.T) { conformance.RunLifecycleReopenLeavesNonDoneStatusesUnchanged(t, t.Context(), newServedCloseReopenFixture(t, "hlrn")) } diff --git a/internal/httpclient/wire/client.go b/internal/httpclient/wire/client.go index 2c6fd6263..76955f51f 100644 --- a/internal/httpclient/wire/client.go +++ b/internal/httpclient/wire/client.go @@ -208,6 +208,10 @@ type Request struct { IssueID string DependsOnID string + // Actor is the acting identity the body carries, for a refusal whose typed + // error names it — the close's not_assignee — when the wire does not + // repeat what the request already said. + Actor string } // Do issues r and decodes a 2xx body into out, which may be nil for a response @@ -292,7 +296,7 @@ func (c *Client) Do(ctx context.Context, r Request, out any) error { } func (c *Client) target(r Request) target { - return target{op: r.Op, serverURL: c.base.Redacted(), issueID: r.IssueID, dependsOnID: r.DependsOnID, expectID: c.expectID} + return target{op: r.Op, serverURL: c.base.Redacted(), issueID: r.IssueID, dependsOnID: r.DependsOnID, actor: r.Actor, expectID: c.expectID} } // credentialSourceReporter is the optional half of a CredentialProvider: a diff --git a/internal/httpclient/wire/problem.go b/internal/httpclient/wire/problem.go index a02dc3d34..106cfea73 100644 --- a/internal/httpclient/wire/problem.go +++ b/internal/httpclient/wire/problem.go @@ -346,6 +346,9 @@ type target struct { serverURL string issueID string dependsOnID string + // actor is the request's acting identity (Request.Actor), which the + // not_assignee refusal names and the wire does not repeat. + actor string // expectID is the workspace's own pinned project id (Client.expectID), which // the wire never carries — it is a client-side fact. A project_mismatch // refusal names the server's own id in server_project_id; pairing it with this @@ -638,12 +641,20 @@ var codeSentinel = map[string]func(*ProblemError, target) error{ // sentinel callers already switch on locally.] "notes_overwrite_refused": func(*ProblemError, target) error { return issueops.ErrNotesOverwrite }, - // The template guard, rebuilt whole so a caller reads the same typed error - // — and the same message — the embedded store returns. The row comes from - // the request or, on a batch, from `item_issue_id`. + // The close guards (the first, template read-only, is every update's guard + // too), rebuilt whole so a caller reads the same typed error — and the same + // message — the embedded store returns. The row comes from the request or, + // on a batch, from `item_issue_id`; the holder from `assignee`; the closing + // actor from the request, which the wire does not repeat. "template_read_only": func(e *ProblemError, t target) error { return &issueops.TemplateReadOnlyError{IssueID: refusedIssueID(e, t)} }, + "issue_pinned": func(e *ProblemError, t target) error { + return &issueops.PinnedError{IssueID: refusedIssueID(e, t)} + }, + "not_assignee": func(e *ProblemError, t target) error { + return &issueops.CloseNotAssigneeError{IssueID: refusedIssueID(e, t), Assignee: deref(e.Assignee), Actor: t.actor} + }, // The same rule again: `issue_id` present means the edge named the issue's // own ancestor or descendant, absent means a plain scheduling cycle. The diff --git a/internal/httpclient/wire/writes.go b/internal/httpclient/wire/writes.go index c9557f1b1..c367198b1 100644 --- a/internal/httpclient/wire/writes.go +++ b/internal/httpclient/wire/writes.go @@ -160,7 +160,7 @@ func (c *Client) CloseIssue(ctx context.Context, id string, body apigen.CloseIss return nil, err } var out apigen.CloseIssueResponse - r := Request{Op: OpCloseIssue, Method: http.MethodPost, Path: path, Body: body, IssueID: id} + r := Request{Op: OpCloseIssue, Method: http.MethodPost, Path: path, Body: body, IssueID: id, Actor: body.Actor} if err := c.dispatch(ctx, r, &out); err != nil { return nil, err } @@ -539,7 +539,7 @@ func (c *Client) ApplyBatch(ctx context.Context, body ApplyBatchRequest) (*apige } var out apigen.ApplyBatchResponse - r := Request{Op: OpApplyBatch, Method: http.MethodPost, Path: PathIssuesBatchApply, Body: body} + r := Request{Op: OpApplyBatch, Method: http.MethodPost, Path: PathIssuesBatchApply, Body: body, Actor: body.Actor} if err := c.dispatch(ctx, r, &out); err != nil { return nil, err } diff --git a/internal/storage/dolt/batch_apply_contract_test.go b/internal/storage/dolt/batch_apply_contract_test.go index 480150703..8ead3a15b 100644 --- a/internal/storage/dolt/batch_apply_contract_test.go +++ b/internal/storage/dolt/batch_apply_contract_test.go @@ -265,6 +265,11 @@ func TestBatchApplyContract(t *testing.T) { defer cancel() conformance.RunBatchApplySplicesTheMetadataOfATemplateItCreates(t, ctx, fixture) }) + t.Run("CloseItemsAnswerToTheCloseGuards", func(t *testing.T) { + ctx, cancel := testContext(t) + defer cancel() + conformance.RunBatchApplyCloseItemsAnswerToTheCloseGuards(t, ctx, fixture) + }) } // newDoltBatchApplyFixture composes the frozen role kit with this backend's diff --git a/internal/storage/dolt/batch_closer_contract_test.go b/internal/storage/dolt/batch_closer_contract_test.go index 82337b90c..360ef1347 100644 --- a/internal/storage/dolt/batch_closer_contract_test.go +++ b/internal/storage/dolt/batch_closer_contract_test.go @@ -131,6 +131,12 @@ func TestBatchCloserSettlesTheDependersOfWhatItClosed(t *testing.T) { conformance.RunBatchCloserSettlesTheDependersOfWhatItClosed(t, ctx, fixture) } +func TestBatchCloserItemsAnswerToTheCloseGuards(t *testing.T) { + fixture, ctx, cleanup := newDoltBatchCloserFixture(t, "bcguard") + defer cleanup() + conformance.RunBatchCloserItemsAnswerToTheCloseGuards(t, ctx, fixture) +} + func newDoltBatchCloserFixture(t *testing.T, prefix string) (conformance.BatchCloserFixture, context.Context, func()) { t.Helper() store, storeCleanup := setupTestStore(t) diff --git a/internal/storage/dolt/issues.go b/internal/storage/dolt/issues.go index 3efcde47c..b6a8362b6 100644 --- a/internal/storage/dolt/issues.go +++ b/internal/storage/dolt/issues.go @@ -606,8 +606,10 @@ func (s *DoltStore) closeIssue(ctx context.Context, id string, reason string, ac // when it has a live direct blocker unless opts.Force is set, and — when // opts.ExpectedVersion is non-nil — with storage.ErrVersionMismatch when the // row's current RowVersion no longer matches (an orthogonal CAS that Force does -// not bypass). Both checks and the close share one transaction, so they are -// atomic (no TOCTOU). Mirrors CloseIssue's Dolt-specific concerns (wisp routing, +// not bypass). The close guards (template, pin, assignee; see +// issueops.CloseIssueCheckedInTx) refuse first, the template whatever Force +// says. Every check and the close share one transaction, so they are atomic +// (no TOCTOU). Mirrors CloseIssue's Dolt-specific concerns (wisp routing, // DOLT_ADD/COMMIT). func (s *DoltStore) CloseIssueChecked(ctx context.Context, id string, actor string, opts storage.CloseIssueOptions) (storage.CloseIssueResult, error) { var result storage.CloseIssueResult diff --git a/internal/storage/dolt/lifecycle_close_reopen_contract_test.go b/internal/storage/dolt/lifecycle_close_reopen_contract_test.go index 5fab44fa9..236909c36 100644 --- a/internal/storage/dolt/lifecycle_close_reopen_contract_test.go +++ b/internal/storage/dolt/lifecycle_close_reopen_contract_test.go @@ -80,6 +80,9 @@ func TestLifecycleCloseReopenContract(t *testing.T) { t.Run("ReopenReblocksItsDependers", func(t *testing.T) { conformance.RunLifecycleReopenReblocksItsDependers(t, ctx, fixture) }) + t.Run("CloseEnforcesTheCloseGuards", func(t *testing.T) { + conformance.RunLifecycleCloseEnforcesTheCloseGuards(t, ctx, fixture) + }) } func newDoltLifecycleCloseReopenFixture(t *testing.T, prefix string) (conformance.LifecycleCloseReopenFixture, context.Context, func()) { diff --git a/internal/storage/domain/db/issue.go b/internal/storage/domain/db/issue.go index 4a1282e25..8c78e1ff5 100644 --- a/internal/storage/domain/db/issue.go +++ b/internal/storage/domain/db/issue.go @@ -223,9 +223,11 @@ func (r *issueSQLRepositoryImpl) Update(ctx context.Context, id string, updates // Close-policy parity with issueops.updateIssueInTx: a status that crosses // into the done category is a close by another name and answers to close - // policy. A refusal returns before any write and aborts the caller's unit of - // work. The wrap keeps the sentinels matchable, so a caller distinguishes - // these refusals here exactly as it does on the close path. + // policy, and, as there, to close policy only: the pin and assignee close + // guards stay on the close verbs (see updateIssueInTx for why). A refusal + // returns before any write and aborts the caller's unit of work. The wrap + // keeps the sentinels matchable, so a caller distinguishes these refusals + // here exactly as it does on the close path. if statusChanging { crossing, err := issueops.CrossesIntoDoneCategoryInTx(ctx, r.runner, oldIssue.Status, updates) if err != nil { diff --git a/internal/storage/embeddeddolt/batch_apply_contract_test.go b/internal/storage/embeddeddolt/batch_apply_contract_test.go index 5bf1afbaa..9280f9acb 100644 --- a/internal/storage/embeddeddolt/batch_apply_contract_test.go +++ b/internal/storage/embeddeddolt/batch_apply_contract_test.go @@ -193,6 +193,9 @@ func TestBatchApplyContract(t *testing.T) { t.Run("SplicesTheMetadataOfATemplateItCreates", func(t *testing.T) { conformance.RunBatchApplySplicesTheMetadataOfATemplateItCreates(t, ctx, fixture) }) + t.Run("CloseItemsAnswerToTheCloseGuards", func(t *testing.T) { + conformance.RunBatchApplyCloseItemsAnswerToTheCloseGuards(t, ctx, fixture) + }) } // newEmbeddedBatchApplyFixture composes the frozen role kit with this backend's diff --git a/internal/storage/embeddeddolt/batch_closer_contract_test.go b/internal/storage/embeddeddolt/batch_closer_contract_test.go index bb18d6b1d..8131d5fc8 100644 --- a/internal/storage/embeddeddolt/batch_closer_contract_test.go +++ b/internal/storage/embeddeddolt/batch_closer_contract_test.go @@ -133,6 +133,12 @@ func TestEmbeddedBatchCloserSettlesTheDependersOfWhatItClosed(t *testing.T) { conformance.RunBatchCloserSettlesTheDependersOfWhatItClosed(t, ctx, newEmbeddedBatchCloserFixture(t, "bcblocked")) } +func TestEmbeddedBatchCloserItemsAnswerToTheCloseGuards(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunBatchCloserItemsAnswerToTheCloseGuards(t, ctx, newEmbeddedBatchCloserFixture(t, "bcguard")) +} + func newEmbeddedBatchCloserFixture(t *testing.T, prefix string) conformance.BatchCloserFixture { t.Helper() te := newTestEnv(t, prefix) diff --git a/internal/storage/embeddeddolt/issues.go b/internal/storage/embeddeddolt/issues.go index 7e1140204..bd67df66c 100644 --- a/internal/storage/embeddeddolt/issues.go +++ b/internal/storage/embeddeddolt/issues.go @@ -165,8 +165,10 @@ func (s *EmbeddedDoltStore) CloseIssue(ctx context.Context, id string, reason st // when it has a live direct blocker unless opts.Force is set, and — when // opts.ExpectedVersion is non-nil — with storage.ErrVersionMismatch when the // row's current RowVersion no longer matches (an orthogonal CAS that Force does -// not bypass). Both checks and the close share one transaction, so they are -// atomic (no TOCTOU). Delegates SQL work to issueops; EmbeddedDolt auto-commits +// not bypass). The close guards (template, pin, assignee; see +// issueops.CloseIssueCheckedInTx) refuse first, the template whatever Force +// says. Every check and the close share one transaction, so they are atomic +// (no TOCTOU). Delegates SQL work to issueops; EmbeddedDolt auto-commits // the transaction. func (s *EmbeddedDoltStore) CloseIssueChecked(ctx context.Context, id string, actor string, opts storage.CloseIssueOptions) (storage.CloseIssueResult, error) { var result storage.CloseIssueResult diff --git a/internal/storage/embeddeddolt/lifecycle_close_reopen_contract_test.go b/internal/storage/embeddeddolt/lifecycle_close_reopen_contract_test.go index 153b33232..c8fef9004 100644 --- a/internal/storage/embeddeddolt/lifecycle_close_reopen_contract_test.go +++ b/internal/storage/embeddeddolt/lifecycle_close_reopen_contract_test.go @@ -83,6 +83,9 @@ func TestLifecycleCloseReopenContract(t *testing.T) { t.Run("ReopenReblocksItsDependers", func(t *testing.T) { conformance.RunLifecycleReopenReblocksItsDependers(t, ctx, fixture) }) + t.Run("CloseEnforcesTheCloseGuards", func(t *testing.T) { + conformance.RunLifecycleCloseEnforcesTheCloseGuards(t, ctx, fixture) + }) } func newEmbeddedLifecycleCloseReopenFixture(t *testing.T, te *testEnv, prefix string) conformance.LifecycleCloseReopenFixture { diff --git a/internal/storage/issueops/BUILD.bazel b/internal/storage/issueops/BUILD.bazel index be4703360..3d7ab0898 100644 --- a/internal/storage/issueops/BUILD.bazel +++ b/internal/storage/issueops/BUILD.bazel @@ -22,6 +22,7 @@ go_library( "claim_next.go", "close.go", "close_batch.go", + "close_guard.go", "commenter.go", "comments.go", "commit_pending.go", @@ -136,6 +137,7 @@ go_test( "blocked_recheck_test.go", "blocked_state_result_test.go", "blocked_state_template_test.go", + "close_guard_test.go", "close_test.go", "config_helpers_test.go", "config_prefix_test.go", diff --git a/internal/storage/issueops/close.go b/internal/storage/issueops/close.go index 188c704c1..03f9fbb94 100644 --- a/internal/storage/issueops/close.go +++ b/internal/storage/issueops/close.go @@ -54,6 +54,12 @@ func CloseIssueWithoutEventInTx(ctx context.Context, tx DBTX, id string, reason, // is_blocked column whose direct blockers have since closed. Reading the live // blocker list self-heals against a stale column instead of acting on it. // +// Before close policy it applies the close guards (enforceCloseGuardsInTx) to a +// target that is not already closed: a template refuses with +// *TemplateReadOnlyError whatever force says, and unless force is set a pinned +// issue refuses with *PinnedError and one assigned to someone other than actor +// with *CloseNotAssigneeError. +// // When expectedVersion is non-nil it adds an ORTHOGONAL optimistic-concurrency // precondition: the row's current RowVersion (row_lock) must still equal // *expectedVersion or the close refuses with storage.ErrVersionMismatch. This @@ -80,6 +86,14 @@ func CloseIssueCheckedInTx(ctx context.Context, tx DBTX, id, reason, actor, sess if !found { return nil, fmt.Errorf("%w: issue %s", storage.ErrNotFound, id) } + // The close guards run before close policy, so a target that trips both + // reads the guard's refusal, as `bd close` always printed it. They only + // read, so they need no savepoint. + if !closed { + if err := enforceCloseGuardsInTx(ctx, tx, id, targetColumn, actor, force); err != nil { + return nil, err + } + } // domain/db also supplies a *sql.DB Runner, whose independently pooled // statements cannot retain a savepoint. The shared UOW uses a pinned // *sql.Conn after START TRANSACTION, while embedded callers use *sql.Tx. diff --git a/internal/storage/issueops/close_guard.go b/internal/storage/issueops/close_guard.go new file mode 100644 index 000000000..9c715d89f --- /dev/null +++ b/internal/storage/issueops/close_guard.go @@ -0,0 +1,112 @@ +package issueops + +import ( + "context" + "database/sql" + "fmt" + + "github.com/steveyegge/beads/internal/types" + publicops "github.com/steveyegge/beads/issueops" +) + +// closeGuardRow is the slice of the close target the close guards read. +type closeGuardRow struct { + isTemplate bool + pinned bool + status types.Status + assignee string +} + +// enforceCloseGuardsInTx applies the close guards — template read-only, the +// pin, and the assignee authority fence (be-035) — to an open target whose +// dependency routing the caller already read from this transaction. +// +// They are the guards `bd close` used to run as a pre-read in cmd/bd, which +// left every other caller of the role (bd serve, BatchCloser, BatchApplier +// close items, a library embedder) closing what bd refused. Living here, they +// read the row the close is about to write, inside the same transaction, so +// there is no read-then-write window either. +// +// Order is the historical one: template first (no bypass), then the pin, then +// the assignee — so a request that trips more than one reads the refusal bd +// always printed for it. force bypasses the pin and the assignee and nothing +// else. +// +// The caller runs this only for a target that is not already literally closed: +// a re-close has no state change to guard, and it stays the idempotent no-op it +// has always been (ga-ktn9pe.4.8) — a forced close of a pinned bead leaves the +// pin set, and the plain retry must not then refuse. +func enforceCloseGuardsInTx(ctx context.Context, tx DBTX, id, targetColumn, actor string, force bool) error { + row, err := readCloseGuardRowInTx(ctx, tx, id, targetColumn) + if err != nil { + return err + } + return CheckClosable(id, &types.Issue{ + IsTemplate: row.isTemplate, + Pinned: row.pinned, + Status: row.status, + Assignee: row.assignee, + }, actor, force) +} + +// CheckClosable is the close guards' one decision over an issue's pre-image: +// template read-only (*TemplateReadOnlyError, no bypass), then — unless force — +// the pin (*PinnedError, either spelling) and the assignee authority fence +// (*CloseNotAssigneeError; an unassigned issue is closable by anyone). A nil +// issue passes. It is pure: enforceCloseGuardsInTx applies it to the row the +// close is about to write, inside the close transaction, which is the +// authority; `bd close` also applies it to its resolved pre-image ahead of its +// own gate-satisfaction check, so a refusal that trips both reads the guard's +// sentence, as it always has. +// +// The caller decides whether to guard at all: an already-closed target is an +// idempotent re-close with no state change to guard (ga-ktn9pe.4.8). +func CheckClosable(id string, issue *types.Issue, actor string, force bool) error { + if issue == nil { + return nil + } + if issue.IsTemplate { + return &publicops.TemplateReadOnlyError{IssueID: id} + } + if force { + return nil + } + // Both pin spellings are load-bearing (ga-z3vht): Gas Town pins by + // status, Gas City by the column. See validation.NotPinned. + if issue.Pinned || issue.Status == types.StatusPinned { + return &publicops.PinnedError{IssueID: id} + } + if issue.Assignee != "" && !actorMatches(issue.Assignee, actor) { + return &publicops.CloseNotAssigneeError{IssueID: id, Assignee: issue.Assignee, Actor: actor} + } + return nil +} + +//nolint:gosec // G201: table is one of two hardcoded identifiers chosen from targetColumn. +func readCloseGuardRowInTx(ctx context.Context, tx DBTX, id, targetColumn string) (closeGuardRow, error) { + table := "issues" + switch targetColumn { + case "depends_on_issue_id": + case "depends_on_wisp_id": + table = "wisps" + default: + return closeGuardRow{}, fmt.Errorf("close guard: unsupported target column %q", targetColumn) + } + var ( + row closeGuardRow + template sql.NullBool + pinned sql.NullBool + status string + assignee sql.NullString + ) + if err := tx.QueryRowContext(ctx, + "SELECT is_template, pinned, status, assignee FROM "+table+" WHERE id = ?", id, + ).Scan(&template, &pinned, &status, &assignee); err != nil { + return closeGuardRow{}, fmt.Errorf("read close guard state for %s from %s: %w", id, table, err) + } + row.isTemplate = template.Valid && template.Bool + row.pinned = pinned.Valid && pinned.Bool + row.status = types.Status(status) + row.assignee = assignee.String + return row, nil +} diff --git a/internal/storage/issueops/close_guard_test.go b/internal/storage/issueops/close_guard_test.go new file mode 100644 index 000000000..9fa419d5b --- /dev/null +++ b/internal/storage/issueops/close_guard_test.go @@ -0,0 +1,55 @@ +package issueops + +import ( + "errors" + "testing" + + "github.com/steveyegge/beads/internal/types" + publicops "github.com/steveyegge/beads/issueops" +) + +// TestCheckClosable pins the close guards' one decision: template first (no +// bypass), then — unless force — the pin (both spellings) and the assignee +// fence (separator-insensitive; unassigned is anyone's). +func TestCheckClosable(t *testing.T) { + cases := []struct { + name string + issue *types.Issue + actor string + force bool + want error + }{ + {"nil", nil, "alice", false, nil}, + {"plain", &types.Issue{Status: types.StatusOpen}, "alice", false, nil}, + {"template", &types.Issue{IsTemplate: true}, "alice", false, publicops.ErrTemplateReadOnly}, + {"forced template", &types.Issue{IsTemplate: true}, "alice", true, publicops.ErrTemplateReadOnly}, + {"template outranks pin", &types.Issue{IsTemplate: true, Pinned: true}, "alice", false, publicops.ErrTemplateReadOnly}, + {"pinned column", &types.Issue{Pinned: true}, "alice", false, publicops.ErrPinned}, + {"pinned status", &types.Issue{Status: types.StatusPinned}, "alice", false, publicops.ErrPinned}, + {"forced pin", &types.Issue{Pinned: true}, "alice", true, nil}, + {"pin outranks holder", &types.Issue{Pinned: true, Assignee: "bob"}, "alice", false, publicops.ErrPinned}, + {"held", &types.Issue{Assignee: "bob"}, "alice", false, publicops.ErrNotOwner}, + {"forced held", &types.Issue{Assignee: "bob"}, "alice", true, nil}, + {"own", &types.Issue{Assignee: "alice"}, "alice", false, nil}, + {"unassigned", &types.Issue{}, "alice", false, nil}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + err := CheckClosable("bd-1", tc.issue, tc.actor, tc.force) + if tc.want == nil { + if err != nil { + t.Fatalf("CheckClosable = %v, want nil", err) + } + return + } + if !errors.Is(err, tc.want) { + t.Fatalf("CheckClosable = %v, want %v", err, tc.want) + } + }) + } + var held *publicops.CloseNotAssigneeError + if err := CheckClosable("bd-1", &types.Issue{Assignee: "bob"}, "alice", false); !errors.As(err, &held) || + held.IssueID != "bd-1" || held.Assignee != "bob" || held.Actor != "alice" { + t.Fatalf("held refusal = %#v", err) + } +} diff --git a/internal/storage/issueops/update.go b/internal/storage/issueops/update.go index 44add0cea..ee77833ba 100644 --- a/internal/storage/issueops/update.go +++ b/internal/storage/issueops/update.go @@ -406,10 +406,17 @@ func updateIssueInTx(ctx context.Context, tx DBTX, id string, updates map[string // A status update that crosses into the done category is a close by another // name, so it answers to close policy. Running after the no-op filter keeps // a done-to-done restatement policy-free, and running after the callers' - // version and assignee preconditions keeps force away from those: it - // bypasses the two close refusals and nothing else, exactly as it does for - // `bd close`. A refusal returns here, before any write, and aborts the - // caller's transaction. + // version and assignee preconditions keeps force away from those: here it + // bypasses the two close-policy refusals and nothing else. A refusal + // returns here, before any write, and aborts the caller's transaction. + // + // Close policy is ALL it answers to. The pin guard and the assignee + // authority fence, which CloseIssueCheckedInTx applies to the close verbs, + // are deliberately not run here: a crossing still closes a pinned issue or + // a bead another actor holds on every update leg (`bd update -s closed`, + // PATCH, batchApply), as it always has. Refusing those would change what + // the update legs admit, which is its own decision and not part of putting + // the close verbs' guards in the role. crossing, err := CrossesIntoDoneCategoryInTx(ctx, tx, oldIssue.Status, updates) if err != nil { return nil, err diff --git a/internal/storage/storage.go b/internal/storage/storage.go index 66553307f..61f80cde0 100644 --- a/internal/storage/storage.go +++ b/internal/storage/storage.go @@ -407,6 +407,9 @@ type Storage interface { // when the current assignee differs. UnclaimIssueIfAssignee(ctx context.Context, id string, actor string, expectedAssignee string) error UpdateIssueType(ctx context.Context, id string, issueType string, actor string) error + // CloseIssue is the raw close: it applies neither the close guards nor + // close policy, except over HTTP, where it closes with force and a template + // — the one guard force never bypasses — still refuses. CloseIssue(ctx context.Context, id string, reason string, actor string, session string) error // CloseIssueChecked closes an issue, but refuses with ErrCloseOpenChildren // when it has open parent-child dependents, or ErrCloseBlocked when it has a @@ -418,9 +421,16 @@ type Storage interface { // (no TOCTOU). When opts.ExpectedVersion is non-nil it adds an orthogonal // optimistic-concurrency precondition: the close proceeds only if the issue's // current RowVersion still equals *opts.ExpectedVersion, else it refuses with - // ErrVersionMismatch atomically (Force does NOT bypass this check). Already- - // closed is an idempotent success with Unchanged=true; a missing issue returns - // ErrNotFound. + // ErrVersionMismatch atomically (Force does NOT bypass this check). After + // the version check and before the child and blocker policy it applies the + // close guards in the same transaction: a template refuses with + // *issueops.TemplateReadOnlyError whatever Force says, and unless Force is + // set a pinned issue refuses with *issueops.PinnedError and one assigned to + // someone other than actor with *issueops.CloseNotAssigneeError. Already- + // closed is an idempotent success with Unchanged=true and skips the guards; + // a missing issue returns ErrNotFound. CloseIssue above is the raw close and + // applies neither the guards nor the policy, except that over HTTP, where + // the template guard has no bypass on the wire, a template still refuses. CloseIssueChecked(ctx context.Context, id string, actor string, opts CloseIssueOptions) (CloseIssueResult, error) DeleteIssue(ctx context.Context, id string) error SearchIssues(ctx context.Context, query string, filter types.IssueFilter) ([]*types.Issue, error) @@ -647,7 +657,7 @@ type Storage interface { type CloseIssueOptions struct { Reason string Session string - Force bool // bypass the is_blocked guard (mirrors `bd close --force`) + Force bool // bypass close policy and the pin and assignee guards, never the template (mirrors `bd close --force`) // ExpectedVersion, when non-nil, gates the close on an optimistic-concurrency // check: the close proceeds only if the issue's current RowVersion (the // row_lock token) equals *ExpectedVersion, otherwise it refuses with diff --git a/internal/storage/uow/batch_apply_contract_test.go b/internal/storage/uow/batch_apply_contract_test.go index 9bb82d3e9..2d8b4673d 100644 --- a/internal/storage/uow/batch_apply_contract_test.go +++ b/internal/storage/uow/batch_apply_contract_test.go @@ -163,6 +163,9 @@ func TestBatchApplyContract(t *testing.T) { t.Run("SplicesTheMetadataOfATemplateItCreates", func(t *testing.T) { conformance.RunBatchApplySplicesTheMetadataOfATemplateItCreates(t, ctx, fixture) }) + t.Run("CloseItemsAnswerToTheCloseGuards", func(t *testing.T) { + conformance.RunBatchApplyCloseItemsAnswerToTheCloseGuards(t, ctx, fixture) + }) } func newUOWBatchApplyFixture(t *testing.T, ctx context.Context, prefix string) conformance.BatchApplyFixture { diff --git a/internal/storage/uow/batch_closer_contract_test.go b/internal/storage/uow/batch_closer_contract_test.go index 43640e738..4ca8d2b4e 100644 --- a/internal/storage/uow/batch_closer_contract_test.go +++ b/internal/storage/uow/batch_closer_contract_test.go @@ -47,6 +47,7 @@ func TestBatchCloserContract(t *testing.T) { {name: "AllRefusedBatchRecordsNoHistory", prefix: "bc-nohistory", run: conformance.RunBatchCloserAllRefusedBatchRecordsNoHistory}, {name: "DoesNotMutateTheCallerRequest", prefix: "bc-snapshot", run: conformance.RunBatchCloserDoesNotMutateTheCallerRequest}, {name: "SettlesTheDependersOfWhatItClosed", prefix: "bc-blocked", run: conformance.RunBatchCloserSettlesTheDependersOfWhatItClosed}, + {name: "ItemsAnswerToTheCloseGuards", prefix: "bc-guard", run: conformance.RunBatchCloserItemsAnswerToTheCloseGuards}, } { t.Run(test.name, func(t *testing.T) { test.run(t, ctx, newUOWBatchCloserFixture(t, provider, test.prefix)) diff --git a/internal/storage/uow/lifecycle_close_reopen_contract_test.go b/internal/storage/uow/lifecycle_close_reopen_contract_test.go index c495de06a..9a77a7f95 100644 --- a/internal/storage/uow/lifecycle_close_reopen_contract_test.go +++ b/internal/storage/uow/lifecycle_close_reopen_contract_test.go @@ -81,6 +81,9 @@ func TestLifecycleCloseReopenContract(t *testing.T) { t.Run("ReopenReblocksItsDependers", func(t *testing.T) { conformance.RunLifecycleReopenReblocksItsDependers(t, ctx, fixture) }) + t.Run("CloseEnforcesTheCloseGuards", func(t *testing.T) { + conformance.RunLifecycleCloseEnforcesTheCloseGuards(t, ctx, fixture) + }) } func newUOWLifecycleCloseReopenFixture(t *testing.T, ctx context.Context, prefix string) conformance.LifecycleCloseReopenFixture { diff --git a/internal/validation/issue.go b/internal/validation/issue.go index bde847ec3..bad1fc61a 100644 --- a/internal/validation/issue.go +++ b/internal/validation/issue.go @@ -66,7 +66,7 @@ func NotPinned(force bool) IssueValidator { return nil // Let Exists() handle nil check if needed } if !force && (issue.Pinned || issue.Status == types.StatusPinned) { - return fmt.Errorf("cannot modify pinned issue %s (use --force to override)", id) + return &issueops.PinnedError{IssueID: id} } return nil } @@ -171,7 +171,7 @@ func AssigneeMatches(actor string, force bool) IssueValidator { if issue.Assignee == "" || ActorMatches(issue.Assignee, actor) { return nil } - return fmt.Errorf("cannot close %s: assignee is %q, actor is %q; reclaim or use --force to override", id, issue.Assignee, actor) + return &issueops.CloseNotAssigneeError{IssueID: id, Assignee: issue.Assignee, Actor: actor} } } diff --git a/issueops/batchapplier.go b/issueops/batchapplier.go index 76d301234..7b3634a08 100644 --- a/issueops/batchapplier.go +++ b/issueops/batchapplier.go @@ -167,7 +167,8 @@ type CloseItem struct { // Reason and Session are CloseRequest's, under its first-close-wins rule. Reason string Session string - // Force bypasses blocker and open-child close policy, and nothing else. + // Force is CloseRequest.Force: it bypasses blocker and open-child close + // policy, the pin and the assignee fence, and never the template guard. // // CLOSE POLICY EVALUATES AT THIS ITEM, against the row as this request has // already changed it — the same as-modified rule the update guards take. A diff --git a/issueops/batchcloser.go b/issueops/batchcloser.go index f557a791b..bd2861bb1 100644 --- a/issueops/batchcloser.go +++ b/issueops/batchcloser.go @@ -40,10 +40,11 @@ type CloseBatchRequest struct { Items []BatchCloseItem // Session records the closing session against every item. Session string - // Force bypasses only blocker and open-child close policy, for every item. - // It never bypasses validation, and it never bypasses existence: an id that - // names nothing refuses whether or not force is set. It is request-wide - // because the flag that spells it is. + // Force bypasses blocker and open-child close policy, the pin and the + // assignee fence, for every item — exactly CloseRequest.Force. It never + // bypasses the template guard or validation, and it never bypasses + // existence: an id that names nothing refuses whether or not force is set. + // It is request-wide because the flag that spells it is. // // It would not bypass a per-item LIFECYCLE PRECONDITION either, but no // batch item carries one: there is no counterpart here to the @@ -86,7 +87,8 @@ type CloseOutcome struct { OpenChildren int // Err is this item's refusal, and NEVER aborts the rest of the batch. It // carries the same typed close vocabulary Lifecycle.Close returns — - // ErrNotFound, ErrCloseBlocked, *CloseOpenChildrenError — so a caller + // ErrNotFound, ErrCloseBlocked, *CloseOpenChildrenError, + // *TemplateReadOnlyError, *PinnedError, *CloseNotAssigneeError — so a caller // classifies it with errors.Is and errors.As rather than by reading prose. Err error } diff --git a/issueops/errors.go b/issueops/errors.go index 7db6159ed..6a1dfe921 100644 --- a/issueops/errors.go +++ b/issueops/errors.go @@ -242,6 +242,51 @@ func (e *CloseOpenChildrenError) Unwrap() error { return ErrCloseOpenChildren } +// ErrPinned is returned when an unforced close names a pinned issue — pinned by +// either of the two spellings bd uses, the Pinned column or the pinned status. +// Force (CloseRequest.Force, CloseBatchRequest.Force, CloseItem.Force) bypasses +// it. +var ErrPinned = errors.New("issue is pinned") + +// PinnedError reports the pinned issue an unforced close was refused for. Its +// message is the sentence `bd close` has always printed for the refusal. +type PinnedError struct { + // IssueID names the pinned issue. + IssueID string +} + +func (e *PinnedError) Error() string { + return fmt.Sprintf("cannot modify pinned issue %s (use --force to override)", e.IssueID) +} + +// Unwrap makes PinnedError match ErrPinned. +func (e *PinnedError) Unwrap() error { return ErrPinned } + +// CloseNotAssigneeError reports an unforced close refused because the issue is +// assigned to someone other than the closing actor (be-035): storage would +// accept the id-only close, so without the guard actor A silently closes the +// bead actor B holds. Authority is identity-by-string under the same +// separator-insensitive comparison every assignee guard uses; an unassigned +// issue is closable by anyone. Force bypasses it. +// +// It matches ErrNotOwner — the ownership refusal a release earns for the same +// situation — and its message is the sentence `bd close` has always printed. +type CloseNotAssigneeError struct { + // IssueID names the issue that refused the close. + IssueID string + // Assignee is the holder observed inside the refusing transaction. + Assignee string + // Actor is the closing actor the request named. + Actor string +} + +func (e *CloseNotAssigneeError) Error() string { + return fmt.Sprintf("cannot close %s: assignee is %q, actor is %q; reclaim or use --force to override", e.IssueID, e.Assignee, e.Actor) +} + +// Unwrap makes CloseNotAssigneeError match ErrNotOwner. +func (e *CloseNotAssigneeError) Unwrap() error { return ErrNotOwner } + // ErrAlreadyExists is returned when a create operation is given an ID that is // already occupied. The issue and wisp tables share one ID space. var ErrAlreadyExists = errors.New("issue already exists") diff --git a/issueops/issueops.go b/issueops/issueops.go index 69c8a20a1..3d5588e2b 100644 --- a/issueops/issueops.go +++ b/issueops/issueops.go @@ -362,8 +362,10 @@ type CloseRequest struct { // and read back on CloseResult.Issue.ClosedBySession, under the same // first-close-wins rule as Reason. Session string - // Force bypasses only blocker and open-child close policy. It never bypasses - // validation, ExpectedVersion, or lifecycle rules. + // Force bypasses blocker and open-child close policy and the two close + // guards a force has always waived in bd: the pin, and the assignee + // authority fence. It never bypasses the template guard, validation, + // ExpectedVersion, or lifecycle rules. Force bool // ExpectedVersion requires the current row version to match, and is checked // BEFORE the idempotent close — so a re-close of an already-closed issue @@ -496,10 +498,16 @@ type Lifecycle interface { // Close validates guards and commits the complete request as one atomic // mutation. It moves the issue to literal StatusClosed, including from a // configured done status. ExpectedVersion is checked first, including for an - // idempotent close. An unforced close with open children returns - // CloseOpenChildrenError without mutation. Force bypasses blocker and - // open-child policy and reports OpenChildren, including for an idempotent - // re-close. A refusal or validation error leaves persistent state unchanged. + // idempotent close. A close of an issue that is not already closed answers + // to the close guards before close policy: a template returns + // *TemplateReadOnlyError, forced or not; unforced, a pinned issue returns + // *PinnedError and one assigned to someone other than Actor (compared + // separator-insensitively) returns *CloseNotAssigneeError, matching + // ErrNotOwner. An unforced close with open children returns + // CloseOpenChildrenError without mutation. Force bypasses the pin, the + // assignee fence, and blocker and open-child policy, and reports + // OpenChildren, including for an idempotent re-close. A refusal or + // validation error leaves persistent state unchanged. Close(context.Context, CloseRequest) (CloseResult, error) // Reopen validates guards and commits the complete request as one atomic // mutation. It moves literal StatusClosed and configured done statuses to diff --git a/issueops/template_errors.go b/issueops/template_errors.go index 8997324c3..73dc50501 100644 --- a/issueops/template_errors.go +++ b/issueops/template_errors.go @@ -6,8 +6,9 @@ import ( ) // ErrTemplateReadOnly is returned when a mutation that guards templates names -// one. Every update does (Lifecycle.Update, a BatchApplier update item); not -// every verb does yet (bd-jkp9v3). Templates are read-only: the way to get +// one. Every update does (Lifecycle.Update, a BatchApplier update item), and so +// does every close (Lifecycle.Close, BatchCloser, a BatchApplier close item); +// not every verb does yet (bd-jkp9v3). Templates are read-only: the way to get // work out of one is to pour it (`bd mol pour`), which creates new issues and // leaves the template untouched. There is no force bypass — no Force flag // waives it; only an update that sets UpdateRequest.AllowTemplate (bd label, diff --git a/tests/oracle-a/harness/scenarios/enumerated.json b/tests/oracle-a/harness/scenarios/enumerated.json index 242e11e03..3135e819e 100644 --- a/tests/oracle-a/harness/scenarios/enumerated.json +++ b/tests/oracle-a/harness/scenarios/enumerated.json @@ -67,7 +67,7 @@ "--json" ] ], - "pins": "close.go has no already-closed guard in validateIssueClosable (only NotTemplate+NotPinned); second close re-runs CloseIssue; pins idempotency/event behavior of the storage layer.", + "pins": "the close guards (storeissueops.CheckClosable: template, pin, assignee) skip a row already at literal closed (ga-ktn9pe.4.8), so the second close reaches the role as its idempotent re-close (Changed=false, exit 0); pins idempotency/event behavior of the storage layer.", "deterministic": true }, { @@ -598,7 +598,7 @@ "--json" ] ], - "pins": "validateIssueClosable NotPinned(force): without force stderr 'cannot modify pinned issue clp-1 (use --force to override)' + SilentExit; with --force closes.", + "pins": "the pin close guard (storeissueops.CheckClosable, waived by force; the role applies it again inside the close transaction): without force stderr 'cannot modify pinned issue clp-1 (use --force to override)' + SilentExit; with --force closes.", "deterministic": true }, {