beads/cmd/bd/show_unit_helpers.go
Julian Knutsen 6d27a4f96e
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 <noreply@anthropic.com>

* 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 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 18:30:42 +00:00

95 lines
4.6 KiB
Go

package main
import (
"context"
"github.com/steveyegge/beads/internal/storage"
"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/validation"
)
// validateIssueUpdatable checks if an issue can be updated.
//
// It is the CLI-only template guard that bd comment, bd note, bd priority and
// bd tag (and the proxied comment and mutate routes) still run as a pre-read:
// their writes do not go through issueops.Lifecycle.Update, whose role rule
// (storage issueops.AuthorizeTemplateUpdate) guards bd update and bd assign on
// every route. Until those commands move onto the role, this is their only
// guard.
// Uses the centralized validation package for consistency.
func validateIssueUpdatable(id string, issue *types.Issue) error {
// Note: We use NotTemplate() directly instead of ForUpdate() to maintain
// backward compatibility - the original didn't check for nil issues.
return validation.NotTemplate()(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
// cross-actor takeover path after --claim, unclaim, and close were fenced.
//
// Call it only when the update actually carries an assignee change;
// newAssignee may be "" (unassign), which is fenced the same way. Do NOT call
// it when the caller passed an explicit --if-assignee guard: that CAS names
// the holder, so nothing about it is silent, and it is how sanctioned X→Y
// transfers (park) work without needing the fence bypass (under
// --if-assignee, --force never arms the assignee half).
func validateIssueReassignable(id string, issue *types.Issue, actor, newAssignee string, poolAliases func() []string, force bool) error {
return validation.AssigneeNotStolen(actor, newAssignee, poolAliases, force)(id, issue)
}
// ifRevisionAlreadyStale reports whether issue's own already-read RowVersion
// no longer matches ifRevision — that is, whether this pre-write read already
// knows the write is a foregone --if-revision precondition failure. Every
// validateIssueReassignable call site that also honors --if-revision
// (mc-zndi7.74) checks this FIRST and skips the fence when it is true.
//
// Why: --if-revision's correctness comes from the atomic compare-and-set
// inside the guarded write itself, which already orders its own version check
// ahead of the assignee-transfer fence (ExecuteUpdate checks ExpectedVersion
// before calling AuthorizeAssigneeTransfer; the uow leg's
// updatePreconditionsHold stands the fence down the same way before
// ApplyUpdate's own version check runs). validateIssueReassignable's callers
// above, though, read the issue in their OWN earlier, separately-timed
// request — not inside that write's transaction — so a racing winner's commit
// can land in the gap and leave this read already showing the winner's new
// assignee. Without this check the loser's pre-read trips the live-claim
// fence and reports the plain "already claimed" policy refusal (exit 1)
// before ever reaching the guarded write that would have reported
// precondition_failed (exit 13) — the wrong outcome for a caller whose whole
// point in passing --if-revision was to get a crisp, retryable signal that it
// lost a race rather than an ordinary policy refusal.
//
// ifRevision == nil (no active guard) always returns false, leaving every
// unguarded caller's behavior exactly as before.
func ifRevisionAlreadyStale(issue *types.Issue, ifRevision *int64) bool {
return ifRevision != nil && issue.RowVersion != *ifRevision
}
// storeClaimPoolAliases returns a lazy claim.pools reader against a direct
// store, for the reassign fence's pool-alias carve-out. Config read errors
// yield no aliases — the fence fails closed (refuses) rather than allowing a
// takeover it can't verify.
func storeClaimPoolAliases(ctx context.Context, st storage.DoltStorage) func() []string {
return func() []string {
raw, err := st.GetConfig(ctx, "claim.pools")
if err != nil {
return nil
}
return issueops.ParseClaimPools(raw)
}
}
// uowClaimPoolAliases is storeClaimPoolAliases' proxied-server sibling: the
// same lazy claim.pools read through the unit of work's transaction.
func uowClaimPoolAliases(ctx context.Context, uw uow.UnitOfWork) func() []string {
return func() []string {
raw, err := uw.ConfigUseCase().GetConfig(ctx, "claim.pools")
if err != nil {
return nil
}
return issueops.ParseClaimPools(raw)
}
}