beads/cmd/bd/close.go
gascity-eddie[bot] 91a72ef7b5
fix(mol): route bond operand resolution like show/update/close (closes #4714) (follow-up to #4720) (#7622)
* fix(mol): route bond operand resolution like show/update/close (closes #4714)

bd mol bond resolved operands with utils.ResolvePartialID against the local
store only, so a bead that lived in a routed store failed with
"'<id>' not found (not an issue ID or formula name)" — even though bd show
resolved the same ID. This broke `gt sling <bead> <rig>`, which cooks the
default formula and bonds it to a rig-routed bead.

- Resolve operands through resolveAndGetIssueForMutation, the same routing
  fallback bd show/update/close use (local, then prefix-routed rig via
  routes.jsonl, then contributor auto-routing). Write-intent so a prefix-routed
  target opens writable and the bond commits where the bead lives.
- Run the bond mutation against the store that owns the resolved issue instead
  of the global local store; reject a bond whose two operands resolve to
  different stores rather than writing to the wrong database.
- Route the --dry-run preview read-only so it previews routed operands too.
- Add TestResolveMolBondOperandRouting covering local and routed resolution.

Same routing-parity fix as #3608/#3609 for bd close.

* fix(mol): fail fast on read-only routed stores, share same-rig bond handles

Address the two structural issues from the #4720 review beyond the rebase
itself (the rebase already preserves main's unconditional formula fallback
from #3874 instead of reintroducing the looksLikeFormulaName gate):

- Routed operands resolve but couldn't be bonded: contributor auto-routing
  deliberately opens stores read-only (they hydrate foreign projects that
  must never be mutated), yet the bond selected that store and dispatched
  mutations that only failed at the store layer. Operand resolution now
  mirrors resolveCloseTargets explicitly (local, then prefix-routed
  write-intent, then the shared auto-routed read-only handle) and records
  writability per operand; pickBondStore rejects a bond pinned to a
  read-only store with a clear message before any mutation is attempted.
  TestMolBondPrefixRoutedWriteThrough now verifies the actual dependency
  write commits in the routed database, not just resolution, and
  TestMolBondAutoRoutedReadOnlyFailsFast covers the fail-fast path.

- Same routed database compared as two different stores: pickBondStore
  compared Go handle identity, but each route-open constructs a fresh store
  in server mode, so two operands in the same routed rig were wrongly
  rejected as cross-store. Both operands of a bond now share one routed
  handle (an already-opened routed store is tried before opening another),
  and sameBondStore falls back to StoreLocator identity (CLIDir pins the
  concrete database) for separately-opened handles onto the same database.
  TestSameBondStoreSeparateHandles covers the two-handle case directly.

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

* fix(mol): validate routed bond homes before mutation

Discover bond operands read-only, enforce dry-run parity and cross-store policy before writable reopen, unwrap decorated store identities, preserve actionable route failures, and verify the accepted home after reopen.

Co-authored-by: Johan Snyman <johan.snyman@orange.com>

Agent-Signature: codex-gpt-5.6-sol-high on behalf of matt wilkie

* fix(mol): reconcile routed bond discovery with #5253 var validation

The rebase onto current main carried two silent regressions the Aug 16
review named: the discovery-based resolution (which replaced
resolveOrDescribe on the direct-store path) never validated --var values,
so `bd mol bond --dry-run <formula> <x> --var bad=...` previewed success
for a bond execution refuses — exactly the false preview #5253 fixed —
and materializeMolBondOperand wrapped every cook error as
"'%s' not found as issue or formula", re-introducing the ErrVarValidation
double-wrap #5253 removed from resolveOrCookToSubgraph.

discoverMolBondOperand now takes the provided vars and runs
formula.ValidateProvidedVars on its formula fallback, so --dry-run and
execution reject the bond identically, before any writable reopen.
materializeMolBondOperand passes formula.ErrVarValidation through
unwrapped, matching resolveOrCookToSubgraph and pour/wisp.

Agent-Signature: claude-fable-5 on behalf of R0SEWT

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

* fix(mol): review polish — fs.ErrNotExist, hook-isolated test repos, auto-route coverage

Three non-blocking notes from the Aug 16 review:

- routed.go: errors.Is(err, fs.ErrNotExist) instead of the legacy
  os.IsNotExist, so the not-found check keeps working if loadPrefixRoutes
  ever starts wrapping its open error.
- mol_bond_routing_test.go: pin core.hooksPath to .git/hooks after each
  git init (the initGitRepoAt convention), so a developer or CI box with a
  global hooksPath override never runs foreign hooks inside test repos.
- The widened openAutoRoutedStore behavior (maintainer/default auto-routes
  open writable for any validated write-intent resolver, not just mol bond)
  now has both the CHANGELOG sentence and a write-through test:
  TestMaintainerAutoRouteMutationWritesThrough drives
  resolveAndGetIssueForMutation — the bd update resolver — through a
  maintainer auto-route, commits a real update there, and re-reads it via a
  fresh routed read.

Agent-Signature: claude-fable-5 on behalf of R0SEWT

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

* fix(mol): carry main's #5761 formula validation into routed bond discovery

Rebase adaptation for #4720 onto main b303d494df. The PR moved the direct
(non-proxied) `bd mol bond` path off resolveOrDescribe and
resolveOrCookToSubgraph onto discoverMolBondOperand and
materializeMolBondOperand. Main's #5761 meanwhile fixed the old pair so a
--dry-run fails on exactly what the real bond fails on; the new pair did not
have that fix:

- discoverMolBondOperand loaded the formula with parser.LoadByName, which
  never runs Formula.Validate, so a --dry-run previewed a successful bond for
  a formula the cook rejects (e.g. a waits_for gate with no spawner). It also
  validated --var values against the unmerged formula, so a var whose enum is
  declared only in a parent went unchecked. Discovery now resolves the
  formula with parser.Resolve first, the way resolveAndCookFormulaWithVars
  does, and wraps both failures the way the cook does, so --dry-run and
  execution report the same message.
- materializeMolBondOperand passed only formula.ErrVarValidation through
  unwrapped. A formula that fails validation was reported as "not found as
  issue or formula". formula.ErrValidation now passes through too, as in
  main's resolveOrCookToSubgraph.

TestDiscoverMolBondOperandRejectsWhatMaterializeRejects and
TestDiscoverMolBondOperandValidatesVarsAgainstTheMergedFormula assert the two
phases against each other, like main's TestBondDryRun* pair does for the
proxied route.

Also:
- The PR's routing tests now pass the `exact` argument that main's #5393
  added to resolveViaPrefixRoutingWithAccess. They pass false, which keeps
  the partial-ID resolution the tests were written against.
- The PR's three new cgo test files are added to the bd_test srcs. This is
  `make bazel-sync` output on the merged tree, and it touches nothing else.

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: Rody Vilchez <102562850+R0SEWT@users.noreply.github.com>

* test(mol): rebuild the RepoContext cache in the PR's role-routing tests

Rebase adaptation for #4720 onto main b303d494df. Main's #5243 moved
auto-routing role detection onto beads.GetRepoContext(), which caches the
repo context once per process; before it, role detection ran
routing.DetectUserRole(".") on every call. The PR's auto-routing tests chdir
into a fresh repo and set beads.role there, so after the rebase they read
the context an earlier test built for its own, now-deleted repo. There
beads.role is unset, and the remote-URL fallback finds no origin and answers
maintainer:

- TestMolBondAutoRoutedReadOnlyFailsFast fails whenever a role-routing test
  ran before it in the same binary (reproducible alone with -count=2):
  discovery looks for the contributor operand in the local store and reports
  it not found.
- TestDiscoverMolBondOperandRouting/maintainer_routed_issue and
  TestMaintainerAutoRouteMutationWritesThrough still pass, but only because
  that fallback is also maintainer; they never read the beads.role they
  configure.

Each test now calls resetRepoContextCachesForTest after its chdir, as #5243
did for main's own role-routing tests (TestResolveCloseTargets, which
TestDiscoverMolBondOperandRouting mirrors, and the routing_read tests).

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: Rody Vilchez <102562850+R0SEWT@users.noreply.github.com>

* fix(routing): open maintainer auto-routes writable for exact-match writes

#5393 landed after this PR was written. It moved `bd comment` and
`bd comments add` off resolveAndGetIssueForMutation onto a new
resolveAndGetIssueForMutationExact. This PR widens the former's auto-route
tier for write intent: a maintainer/default target opens writable, while a
contributor target stays read-only and MutationForbidden. On the PR's
original base that widening covered comment writes. After the rebase the
exact resolver still opened every auto-route read-only, so comment writes
lost it and the CHANGELOG's "any validated write-intent resolver" no longer
held.

The exact resolver is meant to keep the mutation resolver's routing
fallbacks and only tighten matching (#5393: it "keeps the existing
cross-rig prefix-routing and contributor auto-routing fallbacks intact").
Its auto tier now takes the same write-intent path. Matching stays exact,
and the abbreviation-refusal precedence is unchanged.

TestMaintainerAutoRouteExactMutationWritesThrough pins the change: the
routed store must not be read-only, and a comment written through it must
commit in the planning database. Without this change the read-only check
fails. The write itself still succeeds, because a server-mode read-only
open does not refuse it.

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: Rody Vilchez <102562850+R0SEWT@users.noreply.github.com>

* fix(routing): harden routed writes and surface routing failures

Review fixes for #4720.

bd close resolved its batch's shared auto-route through
openRoutedReadStore, so the route opened read-only even though every
other write-intent resolver opened it writable. The shared handle now
opens through openAutoRoutedStore with write intent, so the close commits
where the issue lives.

A contributor auto-route now opens writable for write-intent callers, as
maintainer and default routes do. The refusal the previous revision added
(errContributorRouteMutationForbidden, contributorRouteRefusal,
RoutedResult.MutationForbidden) is gone. A contributor's route target is
their own planning repository, the one bd create writes to:
docs/multi-agent/multi-repo-migration.md and
examples/contributor-workflow/README.md have the contributor claim and
close planning issues from the fork, and GH#2345, beads-0km and GH#3608
made bd show, update and close reach those issues. The read-only rule
came from #4389's review fixes (e8ae7a291a), which kept "contributor
auto-routing" read-only to preserve the bd-6dnrw.32/GH#3231 guarantee
that "routed reads never mutate a foreign project's history". That
guarantee is about reads, and the planning repository is not a foreign
project. Base therefore split by backend: a server-mode bd update, close
or comment of a planning issue committed, because a read-only server
store accepts the write, while the embedded store refused it with "store
is read-only". Refusing in every resolver would have broken the
documented workflow on both backends. bd mol bond was the only command
that checked MutationForbidden, so its check goes too, and a bond of
planning issues commits in the planning repository like any other routed
write. Reads through every route stay read-only. This reverses the
previous revision's stance and is flagged here as a maintainer call.

bd unclaim now resolves its issue through resolveAndGetIssueForMutation,
as bd update --claim does, so a routed issue opens writable; with the
read resolver an embedded routed target refused the release with "store
is read-only". Like bd close, it commits a routed change itself
(commitPendingIfEmbedded), since the post-run auto-commit covers only the
local store. bd human respond and dismiss already opened their target
writable but never committed it, so on an embedded workspace the close
sat uncommitted in the routed repository's working set; they now commit
it the same way. resolveAndGetIssueWithRoutingAccess's
writablePrefixRoute parameter is renamed writable, since it now governs
auto routes too.

A routed commit that fails no longer looks like success, and a retry
commits it. bd unclaim printed "Unclaimed" (or listed the issue in its
--json output) even when the release's routed commit failed; it now
reports the commit error and leaves the issue out. The failed commit
leaves the release, or the close human respond and dismiss make, in the
routed repository's working set. There a retry finds the issue
unassigned or already closed and refuses before it reaches its commit,
and nothing else commits a routed target. On that refusal unclaim,
respond and dismiss now commit the pending write before reporting it,
through commitRoutedWrite, which their success paths share.

A routed write never creates the target's database. The routed open runs
before the lookup it serves, so an embedded open of a repository that had
not been bootstrapped yet created an empty database that outlived an id
that missed; bd bootstrap then took it for the real one and skipped the
clone from sync.remote. openRoutedTargetStore's writable branch now opens
through newExistingDoltStoreFromConfig, which refuses an embedded
workspace without a database (embeddeddolt.HasRepository) before the
sanitize migration can rewrite anything there. A server-mode open already
never creates one.

resolveAndGetIssueForMutation already returned a routing failure (an
unreadable routes.jsonl, a routed store that fails to open) as itself. The
exact resolver and bd close still fell through to "no issue found
matching", which misstates why the lookup missed. All of them now share
isRoutingFailure. The exact resolver checks its abbreviation refusal first,
so the auto tier still gets its chance at an exact match. A prefix route
whose target has no usable metadata.json now names the route and the file
and says why the file could not be used.

An auto-routed store now opens the target's own dolt_database, as a prefix
route already did. Otherwise BEADS_DOLT_SERVER_DATABASE, which names the
launching workspace's database, would point a server-mode open at the wrong
database on a shared server. openRoutedTargetStore holds that override for
both route kinds. A write refuses a target whose metadata.json cannot be
read or parsed or names no dolt_database (autoRouteTargetDatabase) instead
of falling back to that variable. A target with no metadata.json at all
opens, read or written, the only embedded database it holds
(embeddeddolt.Databases), or the default database
(configfile.DefaultDoltDatabase) when it holds none or several.
Contributor setup leaves the planning repository without one until the
first routed bd create writes it, and names its database the way any
workspace without metadata.json does, BEADS_DOLT_SERVER_DATABASE first.
The open would otherwise resolve that name again from the launcher's
variable, so when the two differed a read that missed failed with
"database not found" and a write that missed created a database beside
the one setup created. A server-mode target holds no embedded database,
so with the variable set such a route now opens the default database
rather than the launcher's, which is what it opens without the variable.
A read of a target whose metadata.json is unreadable or names no
database keeps the lenient lookup it had.

bd mol bond's routed home now gets the external-dependency policy and
nothing else, as wireExternalDependencyPolicy asks of routed stores. The
launching workspace's hooks and telemetry no longer wrap writes into
another rig. runMolBond's tail is split into planMolBond, openMolBondHome,
materializeMolBondOperands and bondMolBondOperands, which takes it from
cyclomatic 26 down to 10 or less per function. getIssueWithRouting and the
resolveViaAutoRouting wrapper had no callers left and are removed.

Tests:
- TestMaintainerAutoRouteMutationWritesThrough now checks that the routed
  store is writable. Without that check it passes even against a read-only
  open, because a server-mode read-only store accepts the write.
- TestAutoRouteCloseTargetWriteIntent covers bd close's write intent for a
  maintainer route.
- TestContributorAutoRouteWritesThrough replaces
  TestContributorAutoRouteRefusesWriteIntent: an update, a comment and a
  close through a contributor route each open the target writable and
  commit, a read through the same route stays read-only, and a missing id
  stays a plain not-found.
- TestEmbeddedContributorRoutedWritesCommitInPlanning runs bd update
  --claim, unclaim, comment, close, human respond and human dismiss
  through the bd binary in a contributor checkout. Each advances the
  planning database's HEAD, and the issues end up closed there and absent
  from the fork's database. The embedded shard manifest gains the test.
- TestMolBondContributorAutoRoutedWriteThrough replaces
  TestMolBondAutoRoutedReadOnlyFailsFast: bd mol bond's pipeline bonds two
  planning issues through a contributor route, and a fresh routed read
  sees the dependency; setupAutoRoute now seeds extra planning issues for
  it. TestDiscoverMolBondOperandRouting's contributor case now expects the
  writable reopen.
- TestResolveCloseTargets keeps base's contributor cases (beads-0km); the
  previous revision had moved them to routing.maintainer.
- TestRoutedWriteDoesNotCreateTargetDatabase (in-process) and
  TestEmbeddedRoutedWriteMissDoesNotCreateTargetDatabase (the bd binary)
  check that a missed write through a prefix route and through a
  maintainer auto-route leaves an embedded target that has not been
  bootstrapped without an embeddeddolt directory. The embedded shard
  manifest gains the test.
- TestRoutedMutationResolversReportRoutingFailures runs each write-intent
  resolver against an auto route whose store fails to open, an auto route
  whose target's metadata.json names no dolt_database while
  BEADS_DOLT_SERVER_DATABASE names the launcher's, and a prefix route
  whose target cannot load.
- TestAutoRouteTargetDatabase covers a write and a read of a target whose
  metadata.json names a database, is missing, names none, or cannot be
  parsed; a missing one yields the target's only embedded database, or
  the default database when it holds none or several, either way.
  TestDatabases covers the listing, which applies HasRepository's .dolt
  marker probe to each database.
- TestAutoRouteMissWithoutMetadataIgnoresEnv runs a missed read and a
  missed write through an auto-route to a target that has one database
  but no metadata.json: the default database while
  BEADS_DOLT_SERVER_DATABASE names the launcher's, and a database named
  after the launcher's with the variable set and unset at use. Each miss
  must report not found and leave the target holding only its database.
- TestRoutedWriteRetryCommitsFailedCommit fails the routed commit of bd
  unclaim (text and --json), human respond and human dismiss with an
  invalid --dolt-auto-commit. The run must fail with nothing on stdout and
  leave the routed repository's HEAD as it was; a retry must report its
  refusal and commit the write there.
- TestAutoRouteOpensTargetDatabaseDespiteEnv checks the target-database
  change.
- The auto-routing tests clear BEADS_ROUTING_MODE and BD_ROUTING_MODE
  through neutralizeRoutingModeEnv. Viper ranks them above the
  routing.mode the tests write, so a host that exports either var never
  routes. bdEnv, which builds the bd binary's environment in the
  embedded tests, now drops BD_ROUTING_MODE as it drops BEADS_*; agent
  hosts export it, and TestEmbeddedContributorRoutedWritesCommitInPlanning
  failed on such a host.
  TestEmbeddedRoutedWriteMissDoesNotCreateTargetDatabase no longer needs
  its own envWithout.
- Reverting each fix turns its test red: the contributor read-only clamp
  (the contributor tests above), unclaim's resolver or commit and the
  respond and dismiss commits (the matching step of the embedded test),
  and each autoRouteTargetDatabase rule. So does dropping unclaim's,
  respond's or dismiss's retry commit, or unclaim's skip of a release
  whose commit failed (TestRoutedWriteRetryCommitsFailedCommit); either
  earlier no-metadata.json rule, the variable, which leaves the stray
  database the review reported, or a fixed default database, which fails
  the read of a target setup named after the variable
  (TestAutoRouteMissWithoutMetadataIgnoresEnv and
  TestAutoRouteTargetDatabase), and taking the first of several databases
  (TestAutoRouteTargetDatabase); and bdEnv's BD_ROUTING_MODE drop, on a
  host that exports BD_ROUTING_MODE=off (both embedded tests).

The CHANGELOG entry now records that every auto-route opens writable for
the commands that change an existing issue, the unclaim and human
respond/dismiss commits, that a routed write never creates the target's
database, and the target-database and routing-failure changes.
docs/multi-agent/routing.md says that write commands follow every route,
contributor, maintainer and default alike, never create the routed
repository's database, and refuse a target whose metadata.json is
unreadable or names no dolt_database. Both say that an auto-route opens
a target with no metadata.json at the one embedded database it holds, or
its default database when it holds none or several, while a prefix route
always needs the target's dolt_database. That page documents
behavior that is not in a release yet, which the docs release-pin
decision (engdocs/decisions/2026-07-17-docs-release-pin.md §1) would
leave undocumented. The review asked for docs that match the behavior,
as feature PRs #6508, #5855, #5997 and #5092 also did, so it is flagged
here as a maintainer call.

Open, and not changed here. bd close has the same retry gap on base: a
re-close of an issue that a failed routed commit left closed counts as
already closed and never commits that store (mutatedStores).
commitPendingIfEmbedded gates on the launcher's mode (isEmbeddedMode),
not the routed store's, so a server-mode launcher that opens an embedded
routed repository would leave the write uncommitted there. That gate is
shared by every routed write command and is not exercised here.

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: Rody Vilchez <102562850+R0SEWT@users.noreply.github.com>

* ci(shards): list TestDatabases in the 40-shard embedded storage manifest

The routed-write hardening added TestDatabases to
internal/storage/embeddeddolt/detection_test.go without a slot in the
Bazel-only 40-shard block of .github/scripts/embedded-storage-test-shards.txt,
so gen_embedded_storage_shard_manifest.py 40 --weights=duration --check
reported it missing and TestStorageEmbeddedShardManifestGeneratorNotStale
(go test ./scripts) failed.

Regenerated with the repository command
(gen_embedded_storage_shard_manifest.py 40 --weights=duration --write);
the incremental pack adds exactly one line, on shard 25.

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: Rody Vilchez <102562850+R0SEWT@users.noreply.github.com>

---------

Co-authored-by: Rody Vilchez <102562850+R0SEWT@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Co-authored-by: matt wilkie <maphew@gmail.com>
Co-authored-by: Eddie the Engineer <julianknutsen@users.noreply.github.com>
Co-authored-by: Eddie the Engineer <338826946+gascity-eddie[bot]@users.noreply.github.com>
2026-10-16 21:10:12 +00:00

977 lines
38 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.
Closing a molecule's last open step also closes the molecule's root, with
the reason "all steps complete", when the root is a poured molecule, a wisp,
or an epic labeled "template"; any other epic stays open as close-eligible
work. A root that would refuse its own close (an open blocker, a pin, another
assignee) stays open with a warning, and the step's close stands. Under
--json, the step's entry names the closed root (auto_closed_molecule) or the
refusal (molecule_auto_close_refusal). --continue claims the next ready step
in the molecule for you; add --no-auto to only show it.`,
// 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
}
// --continue is a second operation after the close commits. Against a
// server that cannot run it (no issues.advanceMolecule), or whose
// handshake cannot be read, refuse BEFORE closing: refusing only at the
// advance would leave the step closed and the next step unclaimed, the
// half-done state --continue exists to avoid.
if continueFlag {
served, err := storage.ServesMoleculeAdvance(ctx, postCloseStore)
if err != nil {
return HandleErrorRespectJSON("--continue could not read whether the server serves issues.advanceMolecule: %v; nothing was closed", err)
}
if !served {
return HandleErrorRespectJSON("--continue needs the server's issues.advanceMolecule operation, which this server does not advertise; nothing was closed (close without --continue, then claim the next step with bd update --claim)")
}
}
// 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 := []closedIssueJSON{}
closedCount := 0
alreadyClosed := 0
var failures []closeIDFailure
firstSettledID := ""
// The roots noticeUnservedMoleculeAutoClose already named, so a batch
// that closes several steps of one molecule names it once.
unservedRoots := map[string]bool{}
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: closeDirectTypedRefusal(res.Err)})
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++
// The molecule auto-close is state-derived, so the library
// replays it on an already-closed re-close too (healing a root a
// crash left open); reportMoleculeAutoClose below covers both arms.
} 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", currentActor(), reason)
closedCount++
}
// The molecule root this close completed, closed by the library in
// the batch's own transaction. Register its store so the
// pending-commit sweep persists it even when the step itself was
// an already-closed no-op.
if molID := reportMoleculeAutoClose(res.AutoClosedMolecule, res.MoleculeAutoCloseRefusal); molID != "" {
mutatedStores[activeStore] = append(mutatedStores[activeStore], molID)
}
noticeUnservedMoleculeAutoClose(ctx, activeStore, id, unservedRoots)
// 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, newClosedIssueJSON(closedIssue, res.AutoClosedMolecule, res.MoleculeAutoCloseRefusal))
}
} 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 := advanceMoleculeDirect(ctx, postCloseStore, resolvedIDs[0], autoClaim)
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 the molecule advance 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, currentActor(), 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.
// gateStore is the store that owns the gate (nil on the proxied-server route);
// see closeBeadGateGetter.
// 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, gateStore storage.DoltStorage) 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":
// bd gate check's rule, without recording a sighting: a missing
// bead no check ever saw does not satisfy the gate.
resolved, reason, err = evaluateBeadGate(rootCtx, issue, closeBeadGateGetter(gateStore), nil)
if err != nil {
// Unlike the gh:* and timer arms above, a bead gate whose store
// cannot be read stays closed: the close would need that same
// store, and "could not read" must not pass as "satisfied".
return fmt.Errorf("gate condition not satisfied: could not check bead gate: %v (use --force to override)", err)
}
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)
}
// closeBeadGateGetter picks the bead-gate lookup the current route can serve.
// The direct and embedded routes look the awaited bead up from gateStore, the
// store that owns the gate, as bd gate check in that rig would: for a gate
// reached through a route, the launcher's store can report an open bead as
// missing. The proxied-server route never opens a local store, so it reads
// through the same fresh-read getter bd gate check uses there (#5861).
func closeBeadGateGetter(gateStore storage.DoltStorage) issueGetter {
if usesProxiedServer() {
return proxiedFreshReadGetter{}
}
return routedBeadGateGetter{localStore: gateStore}
}
// reportMoleculeAutoClose presents what the library's molecule auto-close did
// for one close (issueops.CloseRequest.AutoCloseMolecule): the root it closed,
// or why a completed root stayed open. It returns the closed root's id, or "".
func reportMoleculeAutoClose(root *types.Issue, refusal string) string {
if refusal != "" {
fmt.Fprintf(os.Stderr, "Warning: could not auto-close completed molecule: %s\n", refusal)
}
if root == nil {
return ""
}
if !jsonOutput {
debug.PrintNormal("%s Auto-closed completed molecule %s\n", ui.RenderPass("✓"), formatFeedbackID(root.ID, root.Title))
}
return root.ID
}
// closedIssueJSON is one entry of `bd close --json`'s list of closed issues:
// the closed issue's own members, and beside them what its close did to the
// molecule it completed (issueops.CloseResult.AutoClosedMolecule and
// MoleculeAutoCloseRefusal, under the HTTP API's BatchCloseOutcome names).
// Beside, not around: every entry still decodes as the issue it always was,
// and both members are absent unless the close completed a molecule. A batch
// reports each root once, on the first entry under it.
type closedIssueJSON struct {
*types.Issue
AutoClosedMolecule *types.Issue `json:"auto_closed_molecule,omitempty"`
MoleculeAutoCloseRefusal string `json:"molecule_auto_close_refusal,omitempty"`
}
// newClosedIssueJSON is closed's entry. The auto-closed root drops its
// dependency records, as the closed issue does: `bd close` never prints them.
func newClosedIssueJSON(closed, autoClosedMolecule *types.Issue, refusal string) closedIssueJSON {
if autoClosedMolecule != nil {
autoClosedMolecule.Dependencies = nil
}
return closedIssueJSON{Issue: closed, AutoClosedMolecule: autoClosedMolecule, MoleculeAutoCloseRefusal: refusal}
}
// noticeUnservedMoleculeAutoClose names, on stderr, the molecule a close left
// complete but could not ask to auto-close. Against a server that does not
// advertise issues.close.autoCloseMolecule (an older bd serve, or one whose
// orchestrator owns the molecule lifecycle) the close goes out without the
// request (storage.ServesMoleculeAutoClose), so a close after which
// issueops.CompletedMolecule answers a root must say so: the root's auto-close
// is that server's to run, never silently skipped. A step under an ordinary
// epic, under a molecule with a step still open, or under a root already
// closed prints nothing. An already-closed step whose molecule is complete
// with its root open names the root again, as the served route replays its
// auto-close. noted, when not nil, holds the roots this command already
// named, so a batch names each once. A store that serves the auto-close prints
// nothing.
func noticeUnservedMoleculeAutoClose(ctx context.Context, s storage.DoltStorage, stepID string, noted map[string]bool) {
if s == nil || storage.ServesMoleculeAutoClose(ctx, s) {
return
}
const token = "issues.close.autoCloseMolecule"
reader, err := issueops.NewMoleculeReader(s)
var root *types.Issue
if err == nil {
root, err = issueops.CompletedMolecule(ctx, reader, stepID)
}
if err != nil {
fmt.Fprintf(os.Stderr, "note: %s was closed without its molecule auto-close (the server does not advertise %s), and its molecule could not be read: %v\n", stepID, token, err)
return
}
if root == nil || noted[root.ID] {
return
}
if noted != nil {
noted[root.ID] = true
}
fmt.Fprintf(os.Stderr, "note: closing %s completed molecule %s, which this close did not auto-close: the server does not advertise %s, so the molecule's auto-close is the server's to run (bd close %s closes it)\n", stepID, root.ID, token, root.ID)
}
// advanceMoleculeDirect runs `bd close --continue` on the direct route through
// the store's MoleculeStepper role.
func advanceMoleculeDirect(ctx context.Context, s storage.DoltStorage, closedStepID string, autoClaim bool) (*ContinueResult, error) {
roles, err := directMoleculeRoles(s)
if err != nil {
return nil, err
}
return advanceMolecule(ctx, roles, closedStepID, autoClaim)
}
// 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 auto-routed store.
// This matches resolveAndGetIssueForMutation's routing precedence and write
// intent, and like it returns a routing failure (an unreadable routes.jsonl, a
// routed store that fails to open) as itself rather than as a not-found.
//
// The auto-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))
shared := &closeAutoRoute{localStore: localStore}
cleanup := func() {
for _, r := range results {
r.Close()
}
shared.Close()
}
for _, id := range ids {
r, err := resolveCloseTarget(ctx, localStore, shared, id)
if err != nil {
cleanup()
return nil, func() {}, err
}
results = append(results, r)
}
return results, cleanup, nil
}
// resolveCloseTarget resolves one ID of a bd close batch: the local store,
// then a prefix route, then the batch's shared auto-routed store.
func resolveCloseTarget(ctx context.Context, localStore storage.DoltStorage, shared *closeAutoRoute, id string) (*RoutedResult, error) {
// Local first.
r, err := resolveAndGetFromStore(ctx, localStore, id, false)
if err == nil {
return r, nil
}
if !isNotFoundErr(err) {
return nil, 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).
r, err = resolveViaPrefixRoutingWithAccess(ctx, id, true, false)
if err == nil {
return r, nil
}
if isRoutingFailure(err) {
return nil, fmt.Errorf("resolving ID %s: %w", id, err)
}
r, err = shared.resolve(ctx, id)
if err == nil {
return r, nil
}
if isRoutingFailure(err) {
return nil, fmt.Errorf("resolving ID %s: %w", id, err)
}
return nil, fmt.Errorf("resolving ID %s: no issue found matching %q", id, id)
}
// closeAutoRoute is the auto-routed store a bd close batch shares. It opens on
// first use and is closed once, by the batch's cleanup.
type closeAutoRoute struct {
localStore storage.DoltStorage
store storage.DoltStorage
err error
tried bool
}
// resolve looks id up in the shared auto-routed store, opening it on the first
// call with write intent, as resolveAndGetIssueForMutation does: the target
// opens writable, whichever rule selected it, so the close commits where the
// issue lives. The outcome of that open, failure included, holds for the rest
// of the batch.
func (a *closeAutoRoute) resolve(ctx context.Context, id string) (*RoutedResult, error) {
if !a.tried {
a.tried = true
rs, routed, _, err := openAutoRoutedStore(ctx, a.localStore, true)
switch {
case err != nil:
a.err = err
case !routed:
a.err = fmt.Errorf("%w: no auto-routed store available", errRoutingUnavailable)
default:
a.store = rs
}
}
if a.err != nil {
return nil, a.err
}
// Per-id RoutedResult does not own the shared handle; Close does.
return resolveAndGetFromStore(ctx, a.store, id, true)
}
// Close closes the shared auto-routed store, if one was opened.
func (a *closeAutoRoute) Close() {
if a.store != nil {
_ = a.store.Close()
a.store = nil
}
}