beads/cmd/bd/close.go
Julian Knutsen 37acca96db
feat(cli): add --if-revision compare-and-swap guard to update/close/assign/delete (#7203)
* feat(cli): add --if-revision compare-and-swap guard to update/close/assign/delete

Adds --if-revision <int64> to `bd update`, `bd close`, `bd assign` and
`bd delete`, reusing the existing opaque row_lock token published as
IssueDetails.Revision and the library's own ExpectedVersion compare-and-swap
support. A mismatch writes nothing and exits 13 (ExitGuardMismatch); with
--json the stderr envelope carries integer expected_revision/current_revision
fields deployed callers decode directly, never a quoted string. An
unsupported backend reports conditional_write_unsupported and exits 1
instead of silently dropping the guard. The guard composes with
--if-assignee/--if-status (every guard must hold) and is refused alongside
label or parent edits and alongside more than one id, matching the existing
--if-assignee rules. `bd assign` is newly routed through the checked
Lifecycle path to gain CAS support it previously had none of at all.

Implements Item 4 (compare-and-swap through the CLI, gastownhall/beads#4682)
from the BEADS-JOURNAL-PLAN.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* chore(bazel): regenerate cmd/bd BUILD.bazel for if_revision/close_if_revision

gazelle hadn't picked up if_revision.go, close_if_revision.go,
if_revision_test.go, and if_revision_embedded_test.go, so Bazel's bd_lib
and bd_test targets failed to build with "undefined: parseIfRevisionFlag"
and friends while plain `go build`/`go test` worked fine. Ran `make
bazel-sync` (bazel run //:gazelle; go_srcs.py; bazel mod tidy) to pick up
the new files; only cmd/bd/BUILD.bazel's srcs lists changed.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* test(cli): update update-guard parity strings for --if-revision

TestParityUpdateGuardsRequireFieldUpdate and TestParityUpdateGuardsRejectClaim
pinned the exact stderr text of update.go's pre-write guard short-circuits.
Adding --if-revision to those guard messages (update.go/update_input.go)
changed "--if-assignee/--if-status" to "--if-assignee/--if-status/--if-revision"
in both, which this PR's own change to the guard text had not updated here —
caught by CI's dolt-server tier, not by the targeted if_revision* test runs.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-04 13:38:01 -07:00

886 lines
33 KiB
Go

package main
import (
"context"
"encoding/json"
"fmt"
"os"
"strings"
"time"
"github.com/spf13/cobra"
"github.com/steveyegge/beads/internal/audit"
"github.com/steveyegge/beads/internal/config"
"github.com/steveyegge/beads/internal/debug"
"github.com/steveyegge/beads/internal/metrics"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/internal/ui"
"github.com/steveyegge/beads/internal/validation"
"github.com/steveyegge/beads/issueops"
)
var closeCmd = &cobra.Command{
Use: "close [id...]",
Aliases: []string{"done"},
GroupID: "issues",
Short: "Close one or more issues",
Long: `Close one or more issues.
If no issue ID is provided, closes the last touched issue (from most recent
create, update, show, or close operation). This fallback only applies in
interactive sessions (stdin is a terminal); in scripts and agent sessions a
missing ID is an error, so a command built from an empty variable cannot
silently close an unrelated issue. Set BD_LAST_TOUCHED_FALLBACK=1 to allow
the fallback anywhere, or =0 to disable it entirely.
When closing multiple issues, provide one --reason for all IDs or repeat
--reason once per ID. Reasons map positionally: the first --reason applies
to the first ID, the second --reason to the second ID, regardless of where
the flags appear in the command line.`,
// Refuse a missing ID in argument validation, before root's
// PersistentPreRunE can open the store, migrate, or auto-import
// (bd-m00pb); see updateCmd for the full rationale.
Args: func(cmd *cobra.Command, args []string) error {
if len(args) == 0 && !AllowLastTouchedFallback() {
return HandleErrorRespectJSON("no issue ID provided (the last-touched fallback only applies in interactive sessions; pass an explicit issue ID or set BD_LAST_TOUCHED_FALLBACK=1)")
}
return nil
},
SilenceUsage: true,
SilenceErrors: true,
RunE: func(cmd *cobra.Command, args []string) error {
CheckReadonly("close") // also covers the migration freeze check (dc-6jaq)
evt := metrics.NewCommandEvent("close")
defer func() {
if c := metrics.Global(); c != nil {
c.CloseEventAndAdd(evt)
}
}()
if usesProxiedServer() {
return runCloseProxiedServer(cmd, rootCtx, args)
}
// If no IDs provided, use last touched issue (interactive only;
// the non-interactive case was already refused in Args validation)
if len(args) == 0 {
lastTouched := GetLastTouchedID()
if lastTouched == "" {
return HandleErrorRespectJSON("no issue ID provided and no last touched issue")
}
args = []string{lastTouched}
}
reasons, updatedArgs, err := resolveCloseReasons(cmd, args)
if err != nil {
return HandleErrorRespectJSON("%v", err)
}
args = updatedArgs
if err := validateCloseReasons(reasons); err != nil {
return HandleErrorRespectJSON("%v", err)
}
force, _ := cmd.Flags().GetBool("force")
continueFlag, _ := cmd.Flags().GetBool("continue")
noAuto, _ := cmd.Flags().GetBool("no-auto")
suggestNext, _ := cmd.Flags().GetBool("suggest-next")
claimNext, _ := cmd.Flags().GetBool("claim-next")
session, _ := cmd.Flags().GetString("session")
if session == "" {
session = os.Getenv("CLAUDE_SESSION_ID")
}
ctx := rootCtx
// A8 (beads#4682): a single-id compare-and-swap close bypasses the
// batch below entirely -- see close_if_revision.go for why
// BatchCloseItem cannot carry this guard.
ifRevision, err := parseIfRevisionFlag(cmd)
if err != nil {
return err
}
if err := requireSingleIfRevisionID(ifRevision, args); err != nil {
return err
}
if ifRevision != nil {
// The bypass below never looks at these three post-close flags, so
// honoring them would mean silently dropping what the caller asked
// for. Refuse instead of guessing, the same way --continue and
// --suggest-next already refuse a multi-id batch below.
if continueFlag || suggestNext || claimNext {
return HandleErrorRespectJSON("--if-revision does not support --continue, --suggest-next, or --claim-next")
}
return runCloseDirectIfRevision(ctx, args[0], reasonForCloseIndex(reasons, 0), force, session, *ifRevision)
}
opsCtx, err := issueOpsContext(ctx)
if err != nil {
return HandleErrorRespectJSON("%v", err)
}
if continueFlag && len(args) > 1 {
return HandleErrorRespectJSON("--continue only works when closing a single issue")
}
if suggestNext && len(args) > 1 {
return HandleErrorRespectJSON("--suggest-next only works when closing a single issue")
}
results, cleanup, resolveErr := resolveCloseTargets(ctx, store, args)
defer cleanup()
if resolveErr != nil {
return HandleErrorRespectJSON("%v", resolveErr)
}
resolvedIDs := make([]string, 0, len(results))
for _, r := range results {
resolvedIDs = append(resolvedIDs, r.ResolvedID)
}
// Track which stores were mutated so routed closes can commit before
// cleanup closes the routed handle. Deduped by pointer.
mutatedStores := map[storage.DoltStorage][]string{}
// Pick a store for post-close work (--suggest-next, --continue, --claim-next).
// All three flags are documented as single-issue paths; for the multi-id case
// we use the first resolved ID's store, which matches the common case where
// every ID routes to the same place.
postCloseStore := store
if len(results) > 0 && results[0].Store != nil {
postCloseStore = results[0].Store
}
// THE BATCH. The CLI's own close policy runs first and read-only, then
// every id it passed goes to the BatchCloser role as one request per
// store: one transaction, one Dolt commit over N ids, and an id the
// batch refuses skipped while the survivors commit. --claim-next rides
// inside that transaction, and the engine's own is_blocked guard runs
// there too (GH#962), so there is no read-then-write TOCTOU window
// between the check and the close.
plan := closeDirectPreflight(results, resolvedIDs, reasons, force)
outcomes, claimedNext := closeDirectRun(opsCtx, closeDirectBatches(plan.items), len(resolvedIDs),
session, force, postCloseStore, closeClaimNextRequest(claimNext, continueFlag))
// Report and follow up on every argument, in the order it was typed.
closedIssues := []*types.Issue{}
closedCount := 0
alreadyClosed := 0
var failures []closeIDFailure
firstSettledID := ""
for i, id := range resolvedIDs {
res := outcomes[i]
if res == nil {
// The CLI's own close policy refused this argument, so the
// batch never saw it.
fmt.Fprintln(os.Stderr, plan.refusals[i])
failures = append(failures, closeIDFailure{ID: id, Error: plan.refusals[i]})
continue
}
if res.Err != nil {
fmt.Fprintln(os.Stderr, closeDirectRefusal(id, res.Err))
// 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()})
continue
}
// Open children only survive to here when --force waived the
// engine's refusal. Say so, so orphaned children are never silent.
if res.OpenChildren > 0 {
fmt.Fprintf(os.Stderr, "warning: closing %s with %d open child issue(s) still active\n", id, res.OpenChildren)
}
activeStore := results[i].Store
reason := reasonForCloseIndex(reasons, i)
// Pre-close snapshot, for the audit entry's old status and the
// success line's title.
issue := results[i].Issue
if !res.Changed {
// Already closed: an idempotent no-op on the step's stored state. The
// old CloseIssue path also returned nil here and still reported the
// (already-closed) issue, so keep OUTPUT parity via the shared display
// block below — the issue stays in --json output and the text report
// exactly as before. Suppress the step's own real-state-change side
// effects (the audit entry, so no spurious closed→closed; the
// closedCount bump; step-level pending-commit tracking, since the step
// write itself is a no-op), but still count the command as a successful
// close for its retry-safe post-close contracts (last-touched,
// --continue, --suggest-next, --claim-next) via alreadyClosed below.
// Exit stays 0.
alreadyClosed++
// Molecule auto-close is itself a retry-safe, fully state-derived
// post-close contract, so it must replay on an already-closed re-close
// just like the contracts above. If the final step's real close
// persisted but its molecule auto-close did not (a crash between the two
// commits, or the root CloseIssue failing with only a warning), this
// idempotent re-close is the ONLY thing that re-drives it — otherwise the
// molecule root is stranded open forever. autoCloseCompletedMolecule
// early-returns unless the root is genuinely open, auto-close-eligible,
// and complete, so it heals only that case and reintroduces none of the
// suppressed real-close side effects (no audit, no closed→closed on the
// step). Register the store when it actually closed the root so the
// pending-commit sweep persists it — closedCount==0 would not commit.
if molID := autoCloseCompletedMolecule(ctx, activeStore, id, actor, session); molID != "" {
mutatedStores[activeStore] = append(mutatedStores[activeStore], molID)
}
} else {
mutatedStores[activeStore] = append(mutatedStores[activeStore], id)
// Audit log the close (survives Dolt GC flatten)
oldStatus := "open"
if issue != nil {
oldStatus = string(issue.Status)
}
audit.LogFieldChange(id, "status", oldStatus, "closed", actor, reason)
closedCount++
// Auto-close parent molecule if all steps are now complete.
// Runs against the same store the step was closed in.
autoCloseCompletedMolecule(ctx, activeStore, id, actor, session)
}
// First id this command settled as closed — a real close or an
// already-closed no-op both "touch" it. Drives the retry-safe last-touched
// contract below so a re-close still points default-target commands at it.
if firstSettledID == "" {
firstSettledID = id
}
// The operation's own post-state snapshot is what gets reported. A
// real close and an idempotent no-op both report the closed issue
// here, matching the historical output shape. Dependency records are
// dropped from it because `bd close` has never printed them: the
// re-read this replaced did not hydrate them either.
closedIssue := res.Issue
if closedIssue != nil {
closedIssue.Dependencies = nil
}
if jsonOutput {
if closedIssue != nil {
closedIssues = append(closedIssues, closedIssue)
}
} else {
debug.PrintNormal("%s Closed %s: %s\n", ui.RenderPass("✓"), formatFeedbackID(id, issueTitleOrEmpty(issue)), reason)
}
}
// A close command "succeeds" for its user-facing, retry-safe contracts when it
// settled the target as closed — whether it performed the real state change
// (closedCount) or confirmed an already-closed idempotent no-op
// (alreadyClosed). last-touched, --continue, --suggest-next, and --claim-next
// all re-derive their result from current state, so they must replay on an
// already-closed retry; `bd close --continue` in particular is a workflow-
// advancement trigger a crash/retry has to be able to re-drive. The real
// close-mutation side effects (audit, event, molecule auto-close) stay
// suppressed for an already-closed no-op via the `else` branch above; the
// pending-commit sweep is gated on mutatedStores, which a post-close claim
// also populates.
closedForCommand := closedCount > 0 || alreadyClosed > 0
// Record the closed issue as last-touched so `bd close` honors its own
// documented contract (the "last touched issue ... from create, update,
// show, or close" behavior) and downstream write-marker consumers see the
// close (GH#3965). Mirrors bd update's firstUpdatedID pattern. A later
// --claim-next overwrites this with the claimed issue (the newer touch).
if closedForCommand {
SetLastTouchedID(firstSettledID)
}
if suggestNext && len(resolvedIDs) == 1 && closedForCommand {
unblocked, err := postCloseStore.GetNewlyUnblockedByClose(ctx, resolvedIDs[0])
if err == nil && len(unblocked) > 0 {
if jsonOutput {
return outputJSON(map[string]interface{}{
"closed": closedIssues,
"unblocked": unblocked,
})
}
fmt.Printf("\nNewly unblocked:\n")
for _, issue := range unblocked {
fmt.Printf(" • %s (P%d)\n", formatFeedbackID(issue.ID, issue.Title), issue.Priority)
}
}
}
if continueFlag && len(resolvedIDs) == 1 && closedForCommand {
autoClaim := !noAuto
result, err := AdvanceToNextStep(ctx, newStandaloneStoreMolWriter(postCloseStore), resolvedIDs[0], autoClaim, actor)
if err != nil {
fmt.Fprintf(os.Stderr, "Warning: could not advance to next step: %v\n", err)
} else if result != nil {
// Mirror --claim-next: when AdvanceToNextStep auto-claims the
// next step, update .beads/last-touched so subsequent default-
// target commands (e.g. bare `bd update`, `bd close`) target
// it. Without this, last-touched stays pointed at the just-
// closed step. See gastownhall/beads#3769.
if result.AutoAdvanced && result.NextStep != nil {
SetLastTouchedID(result.NextStep.ID)
// The auto-claim mutated postCloseStore's working set. Register it
// so the pending-commit sweep below persists the advance — parity
// with --claim-next, and required when the close itself was an
// already-closed no-op (closedCount==0 wouldn't otherwise commit).
// Same-pointer key dedupes with the closed store on a real close.
mutatedStores[postCloseStore] = append(mutatedStores[postCloseStore], result.NextStep.ID)
}
if jsonOutput {
return outputJSON(map[string]interface{}{
"closed": closedIssues,
"continue": result,
})
}
PrintContinueResult(result)
}
}
// Report --claim-next. The claim itself already happened, inside the
// batch's own transaction and only when something landed, so what is
// left here is the report and the last-touched hand-off. Register the
// claimed store anyway: the batch committed the claim, but the sweep
// below still has to name it if a molecule auto-close made the store
// dirty again.
//
// A batch that also REFUSED an id still reports its claim here, and
// that is deliberate (#6648). The claim landed inside the batch's
// transaction alongside the survivors and a sibling's refusal does not
// roll it back, so suppressing the report would not un-claim anything —
// it would only leave an issue assigned to this actor with nothing on
// stdout or stderr saying so. The claim is announced here and named
// again in reportCloseFailures' summary, so a caller that exits on the
// nonzero status can still see what it owns. Retrying the same command
// does not stack claims: the survivor is already closed the second time
// round, nothing lands, and an empty batch earns no claim.
var claimedNextIssue *types.Issue
if claimNext && closedForCommand && !continueFlag {
if claimedNext != nil {
claimedNextIssue = claimedNext.Issue
mutatedStores[postCloseStore] = append(mutatedStores[postCloseStore], claimedNextIssue.ID)
if !jsonOutput {
debug.PrintNormal("%s Auto-claimed next ready issue: %s (P%d)\n", ui.RenderPass("✓"), formatFeedbackID(claimedNextIssue.ID, claimedNextIssue.Title), claimedNextIssue.Priority)
}
SetLastTouchedID(claimedNextIssue.ID)
} else if !jsonOutput {
debug.PrintNormal("\n%s No ready issues available to claim.\n", ui.RenderWarn("✨"))
}
}
if jsonOutput && len(closedIssues) > 0 {
if claimedNextIssue != nil {
if err := outputJSON(map[string]interface{}{
"closed": closedIssues,
"claimed": claimedNextIssue,
}); err != nil {
return err
}
} else {
if err := outputJSON(closedIssues); err != nil {
return err
}
}
}
// Commit whenever a store was actually mutated — a real close, an auto-claimed
// --continue advance, or a --claim-next claim. Gating on mutatedStores rather
// than closedCount matters for an already-closed re-close that still advanced
// or claimed via a retry-safe post-close flag: the mutation lives in the
// working set and must be persisted, not left for a later write to sweep. For
// existing paths this is equivalent to closedCount>0 (only real closes and
// post-close claims populate mutatedStores). Commit is a no-op if there is
// genuinely nothing pending.
if len(mutatedStores) > 0 {
for s, ids := range mutatedStores {
if s == nil {
continue
}
if err := commitPendingIfEmbedded(ctx, s, actor, doltAutoCommitParams{
Command: "close",
IssueIDs: ids,
}); err != nil {
return HandleErrorRespectJSON("failed to commit: %v", err)
}
}
}
totalAttempted := len(resolvedIDs)
if len(failures) > 0 {
return reportCloseFailures(failures, totalAttempted, closeClaimedID(claimedNextIssue), jsonOutput)
}
if totalAttempted > 0 && closedCount == 0 && alreadyClosed == 0 {
return SilentExit()
}
return nil
},
}
// closeIDFailure records one issue id a batch close refused, and why. It
// mirrors updateIDFailure (update.go) on purpose: `bd close` and `bd update`
// are the two write verbs that take a list of ids, so a caller that learned to
// read one partial-failure report should not have to learn a second shape.
type closeIDFailure struct {
ID string `json:"id"`
Error string `json:"error"`
}
// closeClaimedID names the issue --claim-next claimed on this run, or "" when
// the run claimed nothing.
func closeClaimedID(claimed *types.Issue) string {
if claimed == nil {
return ""
}
return claimed.ID
}
// reportCloseFailures emits the partial-failure summary both close routes end
// on and returns the nonzero exit that #6648 added. Every refusal has already
// been printed inline, in the order the ids were typed; this is the summary
// that says how much of the batch was left open.
//
// Both routes report through here so the wording and the JSON shape are stated
// once instead of hand-rolled per route. Each route still passes its own
// denominator, because only it knows what it attempted — the direct route
// counts resolved ids, the proxied one counts arguments.
//
// The summary is suppressed for a single-id batch deliberately: one inline
// refusal is already unambiguous about which id failed, and suppressing it
// keeps single-id stderr byte-identical to what it was before close learned to
// fail a partial batch.
//
// In --json mode the summary is one compact JSON line on stderr — the shape
// reportUpdateFailures established — so a consumer that sees exit 1 can read
// WHICH ids failed instead of scraping English prose, while stdout keeps the
// plain closed-issues array a successful close emits. claimedNextID names the
// issue --claim-next claimed on this run, if any: that claim is committed
// inside the batch's own transaction and a sibling's refusal does not roll it
// back, so the report names it rather than pretending it did not happen.
func reportCloseFailures(failures []closeIDFailure, total int, claimedNextID string, jsonOut bool) error {
if total <= 1 {
return SilentExit()
}
msg := fmt.Sprintf("%d of %d issues failed to close", len(failures), total)
if !jsonOut {
fmt.Fprintf(os.Stderr, "Error: %s\n", msg)
if claimedNextID != "" {
fmt.Fprintf(os.Stderr, "Note: --claim-next already claimed %s; it stays assigned to you.\n", claimedNextID)
}
return SilentExit()
}
inner := map[string]interface{}{
"error": msg,
"failed": failures,
}
if claimedNextID != "" {
inner["claimed"] = claimedNextID
}
var payload interface{}
if jsonEnvelopeEnabled() {
payload = map[string]interface{}{
"schema_version": JSONSchemaVersion,
"data": inner,
}
} else {
inner["schema_version"] = JSONSchemaVersion
payload = inner
}
data, err := json.Marshal(payload)
if err != nil {
// Marshaling flat strings cannot realistically fail; fall back to the
// text summary rather than exiting with nothing said at all.
fmt.Fprintf(os.Stderr, "Error: %s\n", msg)
} else {
fmt.Fprintln(os.Stderr, string(data))
}
return SilentExit()
}
func init() {
registerCloseReasonFlag(closeCmd)
closeCmd.Flags().String("resolution", "", "Alias for --reason (Jira CLI convention)")
_ = closeCmd.Flags().MarkHidden("resolution") // Hidden alias for agent/CLI ergonomics
closeCmd.Flags().StringP("message", "m", "", "Alias for --reason (git commit convention)")
_ = closeCmd.Flags().MarkHidden("message") // Hidden alias for agent/CLI ergonomics
closeCmd.Flags().String("comment", "", "Alias for --reason")
_ = closeCmd.Flags().MarkHidden("comment") // Hidden alias for agent/CLI ergonomics
closeCmd.Flags().String("reason-file", "", "Read close reason from file (use - for stdin)")
closeCmd.Flags().BoolP("force", "f", false, "Force close pinned issues or unsatisfied gates")
closeCmd.Flags().Bool("continue", false, "Auto-advance to next step in molecule")
closeCmd.Flags().Bool("no-auto", false, "With --continue, show next step but don't claim it")
closeCmd.Flags().Bool("suggest-next", false, "Show newly unblocked issues after closing")
closeCmd.Flags().Bool("claim-next", false, "Automatically claim the next highest priority available issue")
closeCmd.Flags().String("session", "", "Claude Code session ID (or set CLAUDE_SESSION_ID env var)")
// A8 (beads#4682): bypasses the N-id batch above for a single guarded close.
closeCmd.Flags().String("if-revision", "", ifRevisionFlagHelp)
closeCmd.ValidArgsFunction = issueIDCompletion
rootCmd.AddCommand(closeCmd)
}
type closeReasonFlagValue struct {
values []string
}
func registerCloseReasonFlag(cmd *cobra.Command) {
cmd.Flags().VarP(&closeReasonFlagValue{}, "reason", "r", "Reason for closing")
}
func (v *closeReasonFlagValue) Set(s string) error {
v.values = append(v.values, s)
return nil
}
func (v *closeReasonFlagValue) String() string {
if len(v.values) == 0 {
return ""
}
return v.values[len(v.values)-1]
}
func (v *closeReasonFlagValue) Type() string {
return "string"
}
func (v *closeReasonFlagValue) Values() []string {
out := make([]string, len(v.values))
copy(out, v.values)
return out
}
func resolveCloseReasons(cmd *cobra.Command, args []string) ([]string, []string, error) {
reasons, err := collectCloseReasonFlags(cmd)
if err != nil {
return nil, args, err
}
if fileReason, ok, err := resolveReasonFile(cmd, len(reasons) > 0); err != nil {
return nil, args, err
} else if ok {
reasons = []string{fileReason}
}
// Desire-path: "bd done <id> <message>" treats last positional arg as reason
// when no reason flag was explicitly provided (hq-pe8ce)
if len(reasons) == 0 && cmd.CalledAs() == "done" && len(args) >= 2 {
reasons = []string{args[len(args)-1]}
args = args[:len(args)-1]
}
if len(reasons) == 0 {
reasons = []string{"Closed"}
}
if len(reasons) > 1 && len(reasons) != len(args) {
return nil, args, fmt.Errorf("got %d close reasons for %d issue IDs; provide exactly one shared reason or one reason per issue", len(reasons), len(args))
}
return reasons, args, nil
}
func collectCloseReasonFlags(cmd *cobra.Command) ([]string, error) {
if flag := cmd.Flags().Lookup("reason"); flag != nil {
if v, ok := flag.Value.(interface{ Values() []string }); ok {
if reasons := nonEmptyCloseReasons(v.Values()); len(reasons) > 0 {
return reasons, nil
}
}
}
for _, name := range []string{"resolution", "message", "comment"} {
reason, err := cmd.Flags().GetString(name)
if err != nil {
return nil, err
}
if reason != "" {
return []string{reason}, nil
}
}
return nil, nil
}
func nonEmptyCloseReasons(reasons []string) []string {
out := make([]string, 0, len(reasons))
for _, reason := range reasons {
if reason != "" {
out = append(out, reason)
}
}
return out
}
func reasonForCloseIndex(reasons []string, i int) string {
if len(reasons) == 1 {
return reasons[0]
}
return reasons[i]
}
// closeClaimNextRequest is --claim-next as the batch expresses it. BOTH of
// `bd close`'s routes build it here, so the claim asks one question no matter
// which door it came through.
//
// The role runs it inside the closes' transaction and only when at least one
// item landed, which is the rule each route used to enforce by hand; --continue
// still wins, because the two flags have always been mutually exclusive here.
//
// It asks for priority order and no limit. The old two-step read the single top
// ready row and warned if that one row happened to be taken; the role's claim
// walks the ready order and takes the first row it can win, so a race with
// another agent now claims the next candidate instead of claiming nothing.
func closeClaimNextRequest(claimNext, continueOn bool) *issueops.ReadyRequest {
if !claimNext || continueOn {
return nil
}
return &issueops.ReadyRequest{Sort: string(types.SortPolicyPriority)}
}
func validateCloseReasons(reasons []string) error {
closeValidation := config.GetString("validation.on-close")
if closeValidation != "error" && closeValidation != "warn" {
return nil
}
for _, reason := range reasons {
if err := validation.ValidateCloseReason(reason); err != nil {
if closeValidation == "error" {
return err
}
// warn mode: print warning but proceed
fmt.Fprintf(os.Stderr, "%s %v\n", ui.RenderWarn("⚠"), err)
}
}
return nil
}
// isMachineCheckableGate returns true if the issue is a gate with a machine-checkable await type.
func isMachineCheckableGate(issue *types.Issue) bool {
if issue == nil || issue.IssueType != "gate" {
return false
}
switch {
case strings.HasPrefix(issue.AwaitType, "gh:pr"):
return true
case strings.HasPrefix(issue.AwaitType, "gh:run"):
return true
case issue.AwaitType == "timer":
return true
case issue.AwaitType == "bead":
return true
default:
return false
}
}
// checkGateSatisfaction checks whether a gate issue's condition is satisfied.
// Returns nil if the gate is satisfied (or not a machine-checkable gate), or an error describing why it cannot be closed.
func checkGateSatisfaction(issue *types.Issue) error {
if !isMachineCheckableGate(issue) {
return nil
}
var resolved bool
var escalated bool
var reason string
var err error
switch {
case strings.HasPrefix(issue.AwaitType, "gh:run"):
resolved, escalated, reason, err = checkGHRun(issue, func(gateID, runID string) error { return updateGateAwaitIDFunc(nil, gateID, runID) })
case strings.HasPrefix(issue.AwaitType, "gh:pr"):
resolved, escalated, reason, err = checkGHPR(issue)
case issue.AwaitType == "timer":
resolved, escalated, reason, err = checkTimer(issue, time.Now())
case issue.AwaitType == "bead":
resolved, reason = checkBeadGate(rootCtx, routedBeadGateGetter{localStore: store}, issue.AwaitID)
if resolved {
return nil
}
return fmt.Errorf("gate condition not satisfied: %s (use --force to override)", reason)
}
if err != nil {
// If we can't check the condition, allow close with a warning
fmt.Fprintf(os.Stderr, "Warning: could not evaluate gate condition: %v\n", err)
return nil
}
if resolved {
return nil
}
if escalated {
return fmt.Errorf("gate condition not satisfied: %s (use --force to override)", reason)
}
return fmt.Errorf("gate condition not satisfied: %s (use --force to override)", reason)
}
// autoCloseCompletedMolecule checks if closing a step completed an auto-closing
// parent molecule, and if so, closes the molecule root. Ordinary epics remain
// open when all children finish so they can become explicitly close-eligible
// instead of being closed as a side effect of the final child close. It returns
// the molecule root ID when it actually closed the root (and "" otherwise) so a
// caller that did not otherwise mutate the store — an already-closed re-close in
// particular — can register the store for the pending-commit sweep. The check is
// fully state-derived and idempotent: it early-returns unless the root is open,
// auto-close-eligible, and has all steps complete, so re-invoking it never
// double-closes or reintroduces side effects.
func autoCloseCompletedMolecule(ctx context.Context, s storage.DoltStorage, closedStepID, actorName, session string) string {
moleculeID := findParentMolecule(ctx, s, closedStepID)
if moleculeID == "" {
return "" // Not part of a molecule
}
// Check if molecule root is already closed
root, err := s.GetIssue(ctx, moleculeID)
if err != nil || root == nil || root.Status == types.StatusClosed || !shouldAutoCloseCompletedRoot(root) {
return ""
}
// Load progress to check completion
progress, err := getMoleculeProgress(ctx, s, moleculeID)
if err != nil {
return "" // Best effort — don't fail the close
}
if progress.Completed < progress.Total {
return "" // Not all steps complete yet
}
// All steps complete — auto-close the molecule root
if err := s.CloseIssue(ctx, moleculeID, "all steps complete", actorName, session); err != nil {
fmt.Fprintf(os.Stderr, "Warning: could not auto-close completed molecule %s: %v\n", moleculeID, err)
return ""
}
if !jsonOutput {
debug.PrintNormal("%s Auto-closed completed molecule %s\n", ui.RenderPass("✓"), formatFeedbackID(moleculeID, root.Title))
}
return moleculeID
}
// shouldAutoCloseCompletedRoot returns true for molecule roots that should
// auto-close when their final step closes. Regular epics stay open and become
// explicit close-eligible work, while ephemeral wisps, template-driven
// molecules, and molecule-type coordination roots keep their cleanup behavior.
func shouldAutoCloseCompletedRoot(root *types.Issue) bool {
if root == nil {
return false
}
if root.IssueType == types.TypeMolecule || root.Ephemeral {
return true
}
if root.IssueType != types.TypeEpic {
return false
}
for _, label := range root.Labels {
if label == BeadsTemplateLabel {
return true
}
}
return false
}
// resolveReasonFile resolves the --reason-file flag for `bd close`.
// Returns (content, true, nil) when --reason-file was set and read successfully.
// Returns (_, false, nil) when --reason-file was not set.
// Returns an error on conflict with an existing reason, file read failure, or empty content.
// Mirrors the --body-file pattern from `bd create` so agents can pass structured close
// templates without shell-escaping hell.
func resolveReasonFile(cmd *cobra.Command, hasExistingReason bool) (string, bool, error) {
if !cmd.Flags().Changed("reason-file") {
return "", false, nil
}
if hasExistingReason {
return "", false, fmt.Errorf("cannot specify both --reason-file and --reason/--resolution/--message/--comment")
}
path, _ := cmd.Flags().GetString("reason-file")
content, err := readBodyFile(path)
if err != nil {
return "", false, fmt.Errorf("reading reason file %q: %w", path, err)
}
if strings.TrimSpace(content) == "" {
return "", false, fmt.Errorf("--reason-file %q is empty; close reason is required", path)
}
return content, true, nil
}
// resolveCloseTargets resolves a batch of partial issue IDs for `bd close`,
// preserving input order. For each ID it tries the local store first, then
// explicit prefix routing via routes.jsonl, then a shared contributor-routed
// store. This matches resolveAndGetIssueWithRouting's routing precedence.
//
// The contributor-routed handle is shared across the batch so bulk close does
// not repeatedly open the same planning store and every result has a clear store
// owner for subsequent close-time checks and writes.
//
// Each returned RoutedResult.Store points to whichever store actually owns the
// issue. The caller invokes cleanup() once when done; per-result Close() is a
// no-op for routed-via-shared-handle entries because they don't own the handle.
func resolveCloseTargets(ctx context.Context, localStore storage.DoltStorage, ids []string) ([]*RoutedResult, func(), error) {
results := make([]*RoutedResult, 0, len(ids))
var sharedRouted storage.DoltStorage
var sharedRoutedTried bool
cleanup := func() {
for _, r := range results {
r.Close()
}
if sharedRouted != nil {
_ = sharedRouted.Close()
}
}
ensureShared := func() (storage.DoltStorage, error) {
if sharedRouted != nil {
return sharedRouted, nil
}
if sharedRoutedTried {
return nil, fmt.Errorf("no auto-routed store available")
}
sharedRoutedTried = true
rs, routed, _, err := openRoutedReadStore(ctx, localStore)
if err != nil {
return nil, err
}
if !routed {
return nil, fmt.Errorf("no auto-routed store available")
}
sharedRouted = rs
return rs, nil
}
for _, id := range ids {
// Local first.
if r, err := resolveAndGetFromStore(ctx, localStore, id, false); err == nil {
results = append(results, r)
continue
} else if !isNotFoundErr(err) {
cleanup()
return nil, func() {}, fmt.Errorf("resolving ID %s: %w", id, err)
}
// Write-intent: a prefix-routed target opens writable so the close
// commits on the target head (#4141). Contributor auto-routing below
// stays read-only: it hydrates foreign projects that must not be mutated.
if r, err := resolveViaPrefixRoutingWithAccess(ctx, id, true, false); err == nil {
results = append(results, r)
continue
}
// Contributor auto-routing uses one shared store for the whole batch.
if rs, rerr := ensureShared(); rerr == nil {
if r, err := resolveAndGetFromStore(ctx, rs, id, true); err == nil {
// Per-id RoutedResult does not own the shared handle; cleanup() does.
results = append(results, r)
continue
}
}
cleanup()
return nil, func() {}, fmt.Errorf("resolving ID %s: no issue found matching %q", id, id)
}
return results, cleanup, nil
}