beads/cmd/bd/mol_bond.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

1037 lines
39 KiB
Go

package main
import (
"context"
"errors"
"fmt"
"strings"
"github.com/spf13/cobra"
"github.com/steveyegge/beads/internal/formula"
"github.com/steveyegge/beads/internal/metrics"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/storage/externaldeps"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/internal/ui"
"github.com/steveyegge/beads/internal/utils"
)
var molBondCmd = &cobra.Command{
Use: "bond <A> <B>",
Aliases: []string{"fart"}, // Easter egg: molecules can produce gas
Short: "Bond two protos or molecules together",
Long: `Bond two protos or molecules to create a compound.
The bond command is polymorphic - it handles different operand types:
formula + formula → cook both, compound proto
formula + proto → cook formula, compound proto
formula + mol → cook formula, spawn and attach
proto + proto → compound proto (reusable template)
proto + mol → spawn proto, attach to molecule
mol + proto → spawn proto, attach to molecule
mol + mol → join into compound molecule
Formula names (e.g., mol-polecat-arm) are cooked inline as ephemeral protos.
This avoids needing pre-cooked proto beads in the database.
Bond types:
sequential (default) - B runs after A completes
parallel - B runs alongside A
conditional - B runs only if A fails
With --ref, the spawned proto arm is nested inside the molecule operand
rather than ordered against it - whichever side of the bond that is - so a
sequential --ref arm carries no ordering: it is ready as soon as it is
spawned. Ordering a nested arm against its own container is unsatisfiable
in both directions (the arm waits for the molecule to close; the molecule
cannot close while it holds an open arm). --ref is refused with --type
conditional, which has no safe degradation - omit --ref to bond a
conditional arm as a sibling.
Phase control:
By default, spawned protos follow the target's phase:
- Attaching to mol (Ephemeral=false) → spawns as persistent (Ephemeral=false)
- Attaching to ephemeral issue (Ephemeral=true) → spawns as ephemeral (Ephemeral=true)
Override with:
--pour Force spawn as liquid (persistent, Ephemeral=false)
--ephemeral Force spawn as vapor (ephemeral, Ephemeral=true, excluded from Dolt sync via dolt_ignore)
Dynamic bonding (Christmas Ornament pattern):
Use --ref to specify a custom child reference with variable substitution.
This creates IDs like "parent.child-ref" instead of random hashes.
Example:
bd mol bond mol-worker-arm bd-patrol --ref arm-{{worker_name}} --var worker_name=ace
# Creates: bd-patrol.arm-ace (and children like bd-patrol.arm-ace.capture)
Use cases:
- Found important bug during patrol? Use --pour to persist it
- Need ephemeral diagnostic on persistent feature? Use --ephemeral
- Spawning per-worker arms on a patrol? Use --ref for readable IDs
Examples:
bd mol bond mol-feature mol-deploy # Compound proto
bd mol bond mol-feature mol-deploy --type parallel # Run in parallel
bd mol bond mol-feature bd-abc123 # Attach proto to molecule
bd mol bond bd-abc123 bd-def456 # Join two molecules
bd mol bond mol-critical-bug wisp-patrol --pour # Persist found bug
bd mol bond mol-temp-check bd-feature --ephemeral # Ephemeral diagnostic
bd mol bond mol-arm bd-patrol --ref arm-{{name}} --var name=ace # Dynamic child ID`,
Args: cobra.ExactArgs(2),
SilenceUsage: true,
SilenceErrors: true,
RunE: runMolBond,
}
// BondResult holds the result of a bond operation
type BondResult struct {
ResultID string `json:"result_id"`
ResultType string `json:"result_type"` // "compound_proto" or "compound_molecule"
BondType string `json:"bond_type"`
Spawned int `json:"spawned,omitempty"` // Number of issues spawned (if proto was involved)
IDMapping map[string]string `json:"id_mapping,omitempty"` // Old ID -> new ID for spawned issues
}
func runMolBond(cmd *cobra.Command, args []string) error {
CheckReadonly("mol bond")
evt := metrics.NewCommandEvent("mol-bond")
defer func() {
if c := metrics.Global(); c != nil {
c.CloseEventAndAdd(evt)
}
}()
in, err := gatherMolBondInput(cmd, args)
if err != nil {
return HandleErrorRespectJSON("%v", err)
}
if usesProxiedServer() {
return runMolBondProxiedServer(rootCtx, in)
}
ctx := rootCtx
if store == nil {
return HandleErrorRespectJSON("no database connection")
}
plan, err := planMolBond(ctx, store, in)
if err != nil {
return HandleErrorRespectJSON("%v", err)
}
defer plan.Close()
// Dry-run uses the exact same read-only discovery and store-policy
// validation as execution. It stops before writable reopen or formula cook.
if in.dryRun {
renderMolBondDryRun(in, plan.a.issue, plan.a.formula, plan.b.issue, plan.b.formula)
return nil
}
// Close foreign read handles before opening the one accepted target home
// writable. Rejected cross-store bonds therefore never writable-open a
// foreign rig (and cannot trigger its open-time migrations).
plan.Close()
activeStore, closeActiveStore, err := openMolBondHome(ctx, store, plan)
if err != nil {
return HandleErrorRespectJSON("%v", err)
}
defer closeActiveStore()
opA, opB, err := materializeMolBondOperands(ctx, activeStore, plan, in.vars)
if err != nil {
return HandleErrorRespectJSON("%v", err)
}
result, err := bondMolBondOperands(ctx, activeStore, opA, opB, in)
if err != nil {
return HandleErrorRespectJSON("bonding: %v", err)
}
return renderMolBondResult(result, opA.subgraph.Root.ID, opB.subgraph.Root.ID, in.ephemeral, in.pour)
}
// molBondPlan is a bond that passed read-only validation: both operands'
// discoveries, and the issue and logical store that pin the mutation.
type molBondPlan struct {
a, b *molBondDiscovery
targetID string
targetStoreKey string
}
// Close releases the discoveries' read-only handles. It is idempotent.
func (p *molBondPlan) Close() {
p.a.Close()
p.b.Close()
}
// planMolBond discovers both operands and validates their store homes, all
// through read-only handles, so a rejected bond never opens a foreign rig
// writable.
func planMolBond(ctx context.Context, localStore storage.DoltStorage, in molBondInput) (*molBondPlan, error) {
discA, err := discoverMolBondOperand(ctx, localStore, in.argA, in.vars)
if err != nil {
return nil, err
}
discB, err := discoverMolBondOperand(ctx, localStore, in.argB, in.vars)
if err != nil {
discA.Close()
return nil, err
}
plan := &molBondPlan{a: discA, b: discB}
plan.targetID, plan.targetStoreKey, err = validateMolBondHomes(localStore, discA, discB)
if err != nil {
plan.Close()
return nil, err
}
return plan, nil
}
// openMolBondHome opens the bond's validated home for writing: the local store,
// or the routed target reopened writable. A routed home gets the
// external-dependency policy and nothing else, as wireExternalDependencyPolicy
// asks of routed stores: the bond writes into another rig, so the launching
// workspace's hooks and telemetry do not apply to it. An auto-route arrives
// with the policy already applied.
func openMolBondHome(ctx context.Context, localStore storage.DoltStorage, plan *molBondPlan) (storage.DoltStorage, func(), error) {
if plan.targetID == "" || plan.targetStoreKey == dependencyStoreKey(localStore) {
return localStore, func() {}, nil
}
rr, err := resolveAndGetIssueForMutation(ctx, localStore, plan.targetID)
if err != nil {
return nil, nil, err
}
if err := verifyMolBondWritableHome(rr, plan.targetStoreKey); err != nil {
rr.Close()
return nil, nil, err
}
home := rr.Store
if !externaldeps.Applied(home) {
home = wireExternalDependencyPolicy(home)
}
return home, rr.Close, nil
}
// materializeMolBondOperands re-reads both operands in the bond's home and
// cooks any formula operand in memory.
func materializeMolBondOperands(ctx context.Context, activeStore storage.DoltStorage, plan *molBondPlan, vars map[string]string) (*molBondOperand, *molBondOperand, error) {
opA, err := materializeMolBondOperand(ctx, activeStore, plan.a, vars)
if err != nil {
return nil, nil, err
}
opB, err := materializeMolBondOperand(ctx, activeStore, plan.b, vars)
if err != nil {
return nil, nil, err
}
return opA, opB, nil
}
// bondMolBondOperands runs the bond operation the two operand types select.
func bondMolBondOperands(ctx context.Context, activeStore storage.DoltStorage, opA, opB *molBondOperand, in molBondInput) (*BondResult, error) {
issueA, issueB := opA.subgraph.Root, opB.subgraph.Root
aIsProto, bIsProto := opA.bondsAsProto(), opB.bondsAsProto()
// Dispatch based on operand types
// All operations use activeStore; phase flags determine ephemeral vs persistent.
switch {
case aIsProto && bIsProto:
// Compound protos are templates - always persistent
// Note: Proto+proto bonding from formulas is a DB operation, not in-memory
return bondProtoProto(ctx, activeStore, issueA, issueB, in.bondType, in.customTitle, currentActor())
case aIsProto:
if opA.cooked {
return bondProtoMolWithSubgraph(ctx, activeStore, opA.subgraph, issueA, issueB, in.bondType, in.vars, in.childRef, currentActor(), in.ephemeral, in.pour)
}
return bondProtoMol(ctx, activeStore, issueA, issueB, in.bondType, in.vars, in.childRef, currentActor(), in.ephemeral, in.pour)
case bIsProto:
if opB.cooked {
return bondProtoMolWithSubgraph(ctx, activeStore, opB.subgraph, issueB, issueA, in.bondType, in.vars, in.childRef, currentActor(), in.ephemeral, in.pour)
}
return bondMolProto(ctx, activeStore, issueA, issueB, in.bondType, in.vars, in.childRef, currentActor(), in.ephemeral, in.pour)
default:
return bondMolMol(ctx, activeStore, issueA, issueB, in.bondType, currentActor())
}
}
type molBondInput struct {
argA string
argB string
bondType string
customTitle string
dryRun bool
vars map[string]string
ephemeral bool
pour bool
childRef string
}
func gatherMolBondInput(cmd *cobra.Command, args []string) (molBondInput, error) {
in := molBondInput{argA: args[0], argB: args[1]}
in.bondType, _ = cmd.Flags().GetString("type")
in.customTitle, _ = cmd.Flags().GetString("as")
in.dryRun, _ = cmd.Flags().GetBool("dry-run")
in.ephemeral, _ = cmd.Flags().GetBool("ephemeral")
in.pour, _ = cmd.Flags().GetBool("pour")
in.childRef, _ = cmd.Flags().GetString("ref")
if in.ephemeral && in.pour {
return in, fmt.Errorf("cannot use both --ephemeral and --pour")
}
if in.bondType != types.BondTypeSequential && in.bondType != types.BondTypeParallel && in.bondType != types.BondTypeConditional {
return in, fmt.Errorf("invalid bond type '%s', must be: sequential, parallel, or conditional", in.bondType)
}
if err := refuseConditionalRefArm(in.bondType, in.childRef); err != nil {
return in, err
}
varFlags, _ := cmd.Flags().GetStringArray("var")
vars, err := parseVarFlags(varFlags)
if err != nil {
return in, err
}
in.vars = vars
return in, nil
}
func renderMolBondDryRun(in molBondInput, issueA *types.Issue, formulaA string, issueB *types.Issue, formulaB string) {
idA := in.argA
idB := in.argB
aIsProto := false
bIsProto := false
if issueA != nil {
idA = issueA.ID
aIsProto = isProto(issueA)
}
if issueB != nil {
idB = issueB.ID
bIsProto = isProto(issueB)
}
if formulaA != "" {
aIsProto = true
}
if formulaB != "" {
bIsProto = true
}
fmt.Printf("\nDry run: bond %s + %s\n", idA, idB)
if formulaA != "" {
fmt.Printf(" A: %s (formula → will cook as proto)\n", formulaA)
} else if issueA != nil {
fmt.Printf(" A: %s (%s)\n", issueA.Title, operandType(aIsProto))
}
if formulaB != "" {
fmt.Printf(" B: %s (formula → will cook as proto)\n", formulaB)
} else if issueB != nil {
fmt.Printf(" B: %s (%s)\n", issueB.Title, operandType(bIsProto))
}
fmt.Printf(" Bond type: %s\n", in.bondType)
if in.ephemeral {
fmt.Printf(" Phase override: vapor (--ephemeral)\n")
} else if in.pour {
fmt.Printf(" Phase override: liquid (--pour)\n")
}
if in.childRef != "" {
resolvedRef := substituteVariables(in.childRef, in.vars)
fmt.Printf(" Child ref: %s (resolved: %s)\n", in.childRef, resolvedRef)
}
if aIsProto && bIsProto {
fmt.Printf(" Result: compound proto\n")
if in.customTitle != "" {
fmt.Printf(" Custom title: %s\n", in.customTitle)
}
} else if aIsProto || bIsProto {
fmt.Printf(" Result: spawn proto, attach to molecule\n")
} else {
fmt.Printf(" Result: compound molecule\n")
}
if formulaA != "" || formulaB != "" {
fmt.Printf("\n Note: Cooked formulas are ephemeral and deleted after bonding.\n")
}
}
func renderMolBondResult(result *BondResult, idA, idB string, ephemeral, pour bool) error {
if jsonOutput {
return outputJSON(result)
}
fmt.Printf("%s Bonded: %s + %s\n", ui.RenderPass("✓"), idA, idB)
fmt.Printf(" Result: %s (%s)\n", result.ResultID, result.ResultType)
if result.Spawned > 0 {
fmt.Printf(" Spawned: %d issues\n", result.Spawned)
}
if ephemeral {
fmt.Printf(" Phase: vapor (ephemeral, Ephemeral=true)\n")
} else if pour {
fmt.Printf(" Phase: liquid (persistent, Ephemeral=false)\n")
}
return nil
}
// isProto checks if an issue is a proto (has the template label)
func isProto(issue *types.Issue) bool {
for _, label := range issue.Labels {
if label == MoleculeLabel {
return true
}
}
return false
}
// operandType returns a human-readable type string
func operandType(isProtoIssue bool) string {
if isProtoIssue {
return "proto"
}
return "molecule"
}
// bondProtoProto bonds two protos to create a compound proto
func bondProtoProto(ctx context.Context, s storage.DoltStorage, protoA, protoB *types.Issue, bondType, customTitle, actorName string) (*BondResult, error) {
var result *BondResult
err := transact(ctx, s, fmt.Sprintf("bd: bond protos %s + %s", protoA.ID, protoB.ID), func(tx storage.Transaction) error {
r, err := bondProtoProtoInto(ctx, storeMolWriter{DoltStorage: s, tx: tx}, protoA, protoB, bondType, customTitle, actorName)
if err != nil {
return err
}
result = r
return nil
})
if err != nil {
return nil, err
}
return result, nil
}
func bondProtoProtoInto(ctx context.Context, w molWriter, protoA, protoB *types.Issue, bondType, customTitle, actorName string) (*BondResult, error) {
// Create compound proto: a new root that references both protos as children
// The compound root will be a new issue that ties them together
compoundTitle := fmt.Sprintf("Compound: %s + %s", protoA.Title, protoB.Title)
if customTitle != "" {
compoundTitle = customTitle
}
// Create compound root issue. The molecule label travels IN the create
// rather than in a write of its own: a create decides which table the row
// goes to, and carrying the labels with it means one decision places both.
// The separate write this replaces was made through molWriter.AddLabel,
// whose two implementations each resolved the plane again by a different
// predicate, so the row and its label were free to disagree.
compound := &types.Issue{
Title: compoundTitle,
Description: fmt.Sprintf("Compound proto bonding %s and %s", protoA.ID, protoB.ID),
Status: types.StatusOpen,
Priority: minPriority(protoA.Priority, protoB.Priority),
IssueType: types.TypeEpic,
Labels: []string{MoleculeLabel},
BondedFrom: []types.BondRef{
{SourceID: protoA.ID, BondType: bondType, BondPoint: ""},
{SourceID: protoB.ID, BondType: bondType, BondPoint: ""},
},
}
if err := w.CreateIssue(ctx, compound, actorName); err != nil {
return nil, fmt.Errorf("creating compound: %w", err)
}
compoundID := compound.ID
// Add parent-child dependencies from compound to both proto roots
depA := &types.Dependency{
IssueID: protoA.ID,
DependsOnID: compoundID,
Type: types.DepParentChild,
}
if err := w.AddDependency(ctx, depA, actorName); err != nil {
return nil, fmt.Errorf("linking proto A: %w", err)
}
depB := &types.Dependency{
IssueID: protoB.ID,
DependsOnID: compoundID,
Type: types.DepParentChild,
}
if err := w.AddDependency(ctx, depB, actorName); err != nil {
return nil, fmt.Errorf("linking proto B: %w", err)
}
// For sequential/conditional bonding, add blocking dependency: B blocks on A
// Sequential: B runs after A completes (any outcome)
// Conditional: B runs only if A fails
if bondType == types.BondTypeSequential || bondType == types.BondTypeConditional {
depType := types.DepBlocks
if bondType == types.BondTypeConditional {
depType = types.DepConditionalBlocks
}
seqDep := &types.Dependency{
IssueID: protoB.ID,
DependsOnID: protoA.ID,
Type: depType,
}
if err := w.AddDependency(ctx, seqDep, actorName); err != nil {
return nil, fmt.Errorf("adding sequence dep: %w", err)
}
}
return &BondResult{
ResultID: compoundID,
ResultType: "compound_proto",
BondType: bondType,
Spawned: 0,
}, nil
}
// bondProtoMol bonds a proto to an existing molecule by spawning the proto.
// If childRef is provided, generates custom IDs like "parent.childref" (dynamic bonding).
// protoSubgraph can be nil if proto is from DB (will be loaded), or pre-loaded for formulas.
func bondProtoMol(ctx context.Context, s storage.DoltStorage, proto, mol *types.Issue, bondType string, vars map[string]string, childRef string, actorName string, ephemeralFlag, pourFlag bool) (*BondResult, error) {
return bondProtoMolWithSubgraph(ctx, s, nil, proto, mol, bondType, vars, childRef, actorName, ephemeralFlag, pourFlag)
}
// bondProtoMolWithSubgraph is the internal implementation that accepts a pre-loaded subgraph.
func bondProtoMolWithSubgraph(ctx context.Context, s storage.DoltStorage, protoSubgraph *TemplateSubgraph, proto, mol *types.Issue, bondType string, vars map[string]string, childRef string, actorName string, ephemeralFlag, pourFlag bool) (*BondResult, error) {
if protoSubgraph == nil {
var err error
protoSubgraph, err = loadTemplateSubgraph(ctx, s, proto.ID)
if err != nil {
return nil, fmt.Errorf("loading proto: %w", err)
}
}
opts, err := buildAttachCloneOpts(protoSubgraph, mol, bondType, vars, childRef, actorName, ephemeralFlag, pourFlag)
if err != nil {
return nil, err
}
spawnResult, err := cloneSubgraph(ctx, s, protoSubgraph, opts)
if err != nil {
return nil, fmt.Errorf("spawning and attaching proto: %w", err)
}
return &BondResult{
ResultID: mol.ID,
ResultType: "compound_molecule",
BondType: bondType,
Spawned: spawnResult.Created,
IDMapping: spawnResult.IDMapping,
}, nil
}
// bondProtoMolAttachInto is bondProtoMolWithSubgraph's counterpart for
// callers that already have an open molWriter (the proxied-server duals),
// so spawn + attach happen inside the caller's own transaction.
func bondProtoMolAttachInto(ctx context.Context, w molWriter, protoSubgraph *TemplateSubgraph, proto, mol *types.Issue, bondType string, vars map[string]string, childRef string, actorName string, ephemeralFlag, pourFlag bool) (*BondResult, error) {
if protoSubgraph == nil {
var err error
protoSubgraph, err = loadTemplateSubgraph(ctx, w, proto.ID)
if err != nil {
return nil, fmt.Errorf("loading proto: %w", err)
}
}
opts, err := buildAttachCloneOpts(protoSubgraph, mol, bondType, vars, childRef, actorName, ephemeralFlag, pourFlag)
if err != nil {
return nil, err
}
spawnResult, err := cloneSubgraphInto(ctx, w, protoSubgraph, opts)
if err != nil {
return nil, fmt.Errorf("spawning and attaching proto: %w", err)
}
return &BondResult{
ResultID: mol.ID,
ResultType: "compound_molecule",
BondType: bondType,
Spawned: spawnResult.Created,
IDMapping: spawnResult.IDMapping,
}, nil
}
// refuseConditionalRefArm rejects --ref combined with --type conditional.
//
// A --ref arm is nested inside its target, so an ordering edge onto that
// target can never be satisfied (see buildAttachCloneOpts). A sequential bond
// degrades gracefully: the edge is dropped and the arm carries no ordering. A
// conditional edge means "run only if the target fails", so dropping it would
// turn an arm that should almost never run into one that always runs - a
// silent false dispatch, which is worse than the deadlock it replaced. There
// is no reading of the two flags together that is both safe and useful, so
// refuse rather than guess.
//
// Both gatherMolBondInput (which also covers --dry-run and the proxied route)
// and buildAttachCloneOpts consult this, so a caller that skips flag
// validation cannot construct the arm either.
//
// The message has to read correctly for every operand shape, not just the
// nesting ones. gatherMolBondInput runs before operands are resolved, so this
// also refuses mol+mol and proto+proto - shapes that never receive a childRef
// at all, where --ref is inert and nothing nests. It is therefore phrased as
// what --ref does where it applies rather than as a claim about the bond in
// front of the user. Keep it that way if you reword it.
func refuseConditionalRefArm(bondType, childRef string) error {
if childRef == "" || bondType != types.BondTypeConditional {
return nil
}
return fmt.Errorf("--ref cannot be combined with --type conditional: where --ref nests an arm, a conditional edge onto the arm's own container cannot be satisfied, and dropping that edge would run the arm unconditionally instead of only on failure. Omit --ref to bond a conditional arm as a sibling, or use --type sequential or --type parallel with --ref")
}
func buildAttachCloneOpts(subgraph *TemplateSubgraph, mol *types.Issue, bondType string, vars map[string]string, childRef string, actorName string, ephemeralFlag, pourFlag bool) (CloneOptions, error) {
if err := refuseConditionalRefArm(bondType, childRef); err != nil {
return CloneOptions{}, err
}
// Resolve variables the way pour (cmd/bd/pour.go) and wisp (cmd/bd/wisp.go)
// do: fill declared defaults first, then demand only the declared vars that
// have none. Demanding every handlebar the subgraph mentions would fail the
// bond on a proto's documentation placeholders and on declared vars that
// carry only a default - and widening the scanned field set (assignee,
// labels, metadata) would have widened that refusal too.
// extractRequiredVariables returns the unfiltered list when VarDefs is nil,
// so a legacy template still requires every var it mentions.
vars = applyVariableDefaults(vars, subgraph)
var missingVars []string
for _, v := range extractRequiredVariables(subgraph) {
if _, ok := vars[v]; !ok {
missingVars = append(missingVars, v)
}
}
if len(missingVars) > 0 {
return CloneOptions{}, fmt.Errorf("missing required variables: %s (use --var)", strings.Join(missingVars, ", "))
}
makeEphemeral := mol.Ephemeral
if ephemeralFlag {
makeEphemeral = true
} else if pourFlag {
makeEphemeral = false
}
var depType types.DependencyType
switch bondType {
case types.BondTypeSequential:
depType = types.DepBlocks
case types.BondTypeConditional:
depType = types.DepConditionalBlocks
default:
depType = types.DepParentChild
}
opts := CloneOptions{
Vars: vars,
Actor: actorName,
Ephemeral: makeEphemeral,
AttachToID: mol.ID,
AttachDepType: depType,
}
if childRef != "" {
opts.ParentID = mol.ID
opts.ChildRef = childRef
// A --ref arm is nested INSIDE mol, and its ID already records that.
// Blocking it on mol as well is unsatisfiable in both directions: the
// arm waits for mol to close, and mol cannot close while it holds an
// open arm. Nesting carries the attachment, so the blocking edge is
// dropped rather than deadlocking the molecule it was bonded into.
//
// The arm therefore carries NO ordering relative to mol - it is ready
// as soon as it is spawned. That is a real loss of the "B runs after A
// completes" promise, documented in the place that makes it: this
// command's long help. docs/cli-reference/mol.md is generated from the
// release named in docs/cli-docs.pin, so it will carry the same text
// once that pin advances past this change - do not hand-write it there.
// The loss is the deliberate trade: a nested arm's only satisfiable
// relationship to its container is containment.
//
// Only DepBlocks is dropped. DepConditionalBlocks never arrives here -
// refuseConditionalRefArm above rejects it - and keeping the check
// narrow means a future bond type that does reach this point is not
// silently stripped of its edge as well.
if depType == types.DepBlocks {
opts.AttachToID = ""
opts.AttachDepType = ""
}
// A parallel arm keeps its DepParentChild edge on top of the ParentID
// nesting. The two say the same thing, so the edge is redundant rather
// than wrong - but it is what `bd dep list` reports for every parallel
// arm bonded so far, and it is satisfiable, so it stays.
}
return opts, nil
}
// bondMolProto bonds a molecule to a proto (symmetric with bondProtoMol)
func bondMolProto(ctx context.Context, s storage.DoltStorage, mol, proto *types.Issue, bondType string, vars map[string]string, childRef string, actorName string, ephemeralFlag, pourFlag bool) (*BondResult, error) {
// Same as bondProtoMol but with arguments swapped
return bondProtoMol(ctx, s, proto, mol, bondType, vars, childRef, actorName, ephemeralFlag, pourFlag)
}
// wouldCreateCycle checks whether adding an edge (newDepID depends on newDependsOnID)
// would create a cycle in the dependency graph. It does a BFS from newDependsOnID
// following "depends on" edges; if newDepID is reachable, a cycle would be formed.
// Returns (hasCycle, cyclePath) where cyclePath shows the chain if found.
func wouldCreateCycle(ctx context.Context, s molReader, newDepID, newDependsOnID string) (bool, []string) {
visited := map[string]bool{newDependsOnID: true}
// parent tracks how we reached each node, for path reconstruction.
parent := map[string]string{newDependsOnID: ""}
queue := []string{newDependsOnID}
for len(queue) > 0 {
current := queue[0]
queue = queue[1:]
deps, err := s.GetDependencyRecords(ctx, current)
if err != nil {
// If we can't query deps for a node, skip it rather than failing.
continue
}
for _, dep := range deps {
next := dep.DependsOnID
if next == newDepID {
// Found the cycle. Reconstruct the path.
path := []string{newDepID}
for node := current; node != ""; node = parent[node] {
path = append(path, node)
}
// Reverse to get forward direction.
for i, j := 0, len(path)-1; i < j; i, j = i+1, j-1 {
path[i], path[j] = path[j], path[i]
}
// Append newDepID again to show the cycle closing.
path = append(path, newDepID)
return true, path
}
if !visited[next] {
visited[next] = true
parent[next] = current
queue = append(queue, next)
}
}
}
return false, nil
}
// bondMolMol bonds two molecules together.
// It checks for transitive cycles in the dependency graph (GH#2719).
func bondMolMol(ctx context.Context, s storage.DoltStorage, molA, molB *types.Issue, bondType, actorName string) (*BondResult, error) {
if hasCycle, cyclePath := wouldCreateCycle(ctx, s, molB.ID, molA.ID); hasCycle {
return nil, fmt.Errorf("cannot bond %s → %s: would create a transitive dependency cycle: %s",
molA.ID, molB.ID, strings.Join(cyclePath, " → "))
}
var result *BondResult
err := transact(ctx, s, fmt.Sprintf("bd: bond molecules %s + %s", molA.ID, molB.ID), func(tx storage.Transaction) error {
r, err := bondMolMolInto(ctx, storeMolWriter{DoltStorage: s, tx: tx}, molA, molB, bondType, actorName)
if err != nil {
return err
}
result = r
return nil
})
if err != nil {
return nil, fmt.Errorf("linking molecules: %w", err)
}
return result, nil
}
func bondMolMolInto(ctx context.Context, w molWriter, molA, molB *types.Issue, bondType, actorName string) (*BondResult, error) {
// Add dependency: B links to A
// Sequential: use blocks (B runs after A completes)
// Conditional: use conditional-blocks (B runs only if A fails)
// Parallel: use parent-child (organizational, no blocking)
// Note: Schema only allows one dependency per (issue_id, target) pair (target = typed column)
var depType types.DependencyType
switch bondType {
case types.BondTypeSequential:
depType = types.DepBlocks
case types.BondTypeConditional:
depType = types.DepConditionalBlocks
default:
depType = types.DepParentChild
}
dep := &types.Dependency{
IssueID: molB.ID,
DependsOnID: molA.ID,
Type: depType,
}
if err := w.AddDependency(ctx, dep, actorName); err != nil {
return nil, fmt.Errorf("linking molecules: %w", err)
}
// Note: bonded_from field tracking is not yet supported by storage layer.
// The dependency relationship captures the bonding semantics.
return &BondResult{
ResultID: molA.ID,
ResultType: "compound_molecule",
BondType: bondType,
}, nil
}
// minPriority returns the higher priority (lower number)
func minPriority(a, b int) int {
if a < b {
return a
}
return b
}
type molBondOperand struct {
subgraph *TemplateSubgraph
cooked bool
}
// bondsAsProto reports whether the operand bonds as a proto: a template issue,
// or a formula cooked in memory.
func (o *molBondOperand) bondsAsProto() bool {
return o.subgraph.Root.IsTemplate || o.cooked
}
// molBondDiscovery is the read-only phase of operand resolution. Existing
// issues retain their logical store home; formulas remain storeless.
type molBondDiscovery struct {
operand string
issue *types.Issue
formula string
store storage.DoltStorage
storeKey string
closeFn func()
}
func (d *molBondDiscovery) Close() {
if d != nil && d.closeFn != nil {
d.closeFn()
d.closeFn = nil
}
}
// discoverMolBondOperand resolves issue-first through read-only routing. This
// lets store-policy validation finish before any routed database is opened
// writable. Formula fallback remains unconditional: the parser decides whether
// an operand names a formula (#3874).
func discoverMolBondOperand(ctx context.Context, localStore storage.DoltStorage, operand string, vars map[string]string) (*molBondDiscovery, error) {
rr, err := resolveAndGetIssueWithRouting(ctx, localStore, operand)
if err == nil {
return &molBondDiscovery{
operand: operand,
issue: rr.Issue,
store: rr.Store,
storeKey: dependencyStoreKey(rr.Store),
closeFn: rr.Close,
}, nil
}
parser := formula.NewParser()
f, loadErr := parser.LoadByName(operand)
if loadErr == nil {
// Discovery must fail the same way materialization would, and
// materialization (resolveAndCookFormulaWithVars) resolves inheritance
// before it validates anything: parser.Resolve is what runs
// Formula.Validate, which LoadByName never does (#5761). Validating
// --var values against the resolved formula also checks a var
// declared only in a parent. An enum/pattern/provided-empty violation
// fails the cook, so surfacing it here makes --dry-run and execution
// reject the bond identically, before any writable reopen (#5253).
// Both are wrapped the way the cook wraps them, so the messages match.
resolved, resolveErr := parser.Resolve(f)
if resolveErr != nil {
return nil, fmt.Errorf("resolving formula %q: %w", operand, resolveErr)
}
if err := formula.ValidateProvidedVars(resolved, vars); err != nil {
return nil, fmt.Errorf("formula %q: %w", operand, err)
}
return &molBondDiscovery{operand: operand, formula: resolved.Formula}, nil
}
if !isNotFoundErr(err) {
return nil, err
}
return nil, fmt.Errorf("'%s' not found as issue or formula: %w", operand, loadErr)
}
// validateMolBondHomes returns the issue and logical store that pin the
// mutation. Formula-only bonds stay local. All checks use read-only handles.
func validateMolBondHomes(localStore storage.DoltStorage, discoveries ...*molBondDiscovery) (string, string, error) {
var targetID, targetKey string
var targetStore storage.DoltStorage
for _, d := range discoveries {
if d == nil || d.issue == nil {
continue
}
if targetStore == nil {
targetID, targetKey, targetStore = d.issue.ID, d.storeKey, d.store
continue
}
if !sameBondStore(targetStore, d.store) {
return "", "", fmt.Errorf("cannot bond %s and %s: they live in different stores/rigs; run the bond from the rig that owns them", targetID, d.issue.ID)
}
}
if targetStore == nil {
return "", dependencyStoreKey(localStore), nil
}
return targetID, targetKey, nil
}
// verifyMolBondWritableHome closes the TOCTOU gap between read-only discovery
// and writable reopen. Routing or local contents may change between phases; a
// bond must never mutate a logical store that was not the validated home.
func verifyMolBondWritableHome(rr *RoutedResult, expectedStoreKey string) error {
if rr == nil || rr.Store == nil {
return fmt.Errorf("routed bond target reopened without a store")
}
if actual := dependencyStoreKey(rr.Store); actual != expectedStoreKey {
return fmt.Errorf("routed bond target changed between discovery and writable reopen (expected %s, got %s); retry the command", expectedStoreKey, actual)
}
return nil
}
// sameBondStore reports whether two store handles refer to the same underlying
// database. dependencyStoreKey unwraps decorators before consulting
// StoreLocator, so a HookFiringStore and a separately opened raw route handle
// onto the same database compare equal.
func sameBondStore(a, b storage.DoltStorage) bool {
if a == b {
return true
}
return dependencyStoreKey(a) == dependencyStoreKey(b)
}
// materializeMolBondOperand is the writable phase. After validation selects one
// store home, existing issues are re-read there and formulas are cooked in
// memory for the bond operation.
func materializeMolBondOperand(ctx context.Context, activeStore storage.DoltStorage, d *molBondDiscovery, vars map[string]string) (*molBondOperand, error) {
if d == nil {
return nil, fmt.Errorf("missing mol bond operand")
}
if d.issue == nil {
subgraph, err := resolveAndCookFormulaWithVars(d.operand, nil, vars)
if err != nil {
if errors.Is(err, formula.ErrVarValidation) || errors.Is(err, formula.ErrValidation) {
// Don't double-wrap: operand IS a formula that either does not
// validate or was given --var values failing its enum/pattern/
// required-empty constraints, both distinct from "not found".
return nil, err
}
return nil, fmt.Errorf("'%s' not found as issue or formula: %w", d.operand, err)
}
return &molBondOperand{subgraph: subgraph, cooked: true}, nil
}
rr, err := resolveAndGetFromStore(ctx, activeStore, d.issue.ID, false)
if err != nil {
return nil, err
}
issue := rr.Issue
if isProto(issue) {
subgraph, err := loadTemplateSubgraph(ctx, activeStore, issue.ID)
if err != nil {
return nil, fmt.Errorf("loading proto subgraph '%s': %w", issue.ID, err)
}
return &molBondOperand{subgraph: subgraph}, nil
}
return &molBondOperand{
subgraph: &TemplateSubgraph{
Root: issue,
Issues: []*types.Issue{issue},
IssueMap: map[string]*types.Issue{issue.ID: issue},
},
}, nil
}
// resolveOrDescribe checks if an operand is an issue or formula without cooking.
// Used by proxied-server dry-run mode. Returns (issue, formulaName, error).
func resolveOrDescribe(ctx context.Context, s molReader, operand string, vars map[string]string) (*types.Issue, string, error) {
id, err := utils.ResolvePartialID(ctx, s, operand)
if err == nil {
issue, err := s.GetIssue(ctx, id)
if err == nil {
return issue, "", nil
}
}
parser := formula.NewParser()
f, err := parser.LoadByName(operand)
if err != nil {
return nil, "", fmt.Errorf("'%s' not found as issue or formula: %w", operand, err)
}
// A dry-run must fail the same way the real bond would, and the real bond
// (resolveAndCookFormulaWithVars) resolves inheritance BEFORE it validates
// anything. parser.Resolve is what calls Formula.Validate - LoadByName ->
// loadFormula -> ParseFile never does - so skipping it here previewed a
// successful bond for a formula the real bond rejects, including the
// unspawnable waits_for gate this PR adds. Resolving first also means the
// --var check runs against the merged formula rather than the unmerged
// one, so a var declared only in a parent is checked too.
resolved, err := parser.Resolve(f)
if err != nil {
return nil, "", fmt.Errorf("resolving formula %q: %w", operand, err)
}
// An enum/pattern/provided-empty violation in --var values fails
// resolveOrCookToSubgraph, so reporting "will be cooked" here would be a
// false preview. Wrapped the same way the real path wraps it, so the two
// produce the same message rather than merely the same exit code.
if err := formula.ValidateProvidedVars(resolved, vars); err != nil {
return nil, "", fmt.Errorf("formula %q: %w", operand, err)
}
return nil, resolved.Formula, nil
}
// resolveOrCookToSubgraph tries to resolve an operand as an issue ID or formula.
// If it's an issue, loads the subgraph from DB. If it's a formula, cooks inline to subgraph.
// Returns the subgraph, whether it was cooked from formula, and any error.
//
// The vars parameter is used for step condition filtering (bd-7zka.1).
// This implements gt-4v1eo: formulas are cooked to in-memory subgraphs (no DB storage).
func resolveOrCookToSubgraph(ctx context.Context, s molReader, operand string, vars map[string]string) (*TemplateSubgraph, bool, error) {
// First, try to resolve as an existing issue
id, err := utils.ResolvePartialID(ctx, s, operand)
if err == nil {
issue, err := s.GetIssue(ctx, id)
if err == nil {
// Check if it's a proto (template)
if isProto(issue) {
subgraph, err := loadTemplateSubgraph(ctx, s, id)
if err != nil {
return nil, false, fmt.Errorf("loading proto subgraph '%s': %w", id, err)
}
return subgraph, false, nil
}
// It's a molecule, not a proto - wrap it as a single-issue subgraph
return &TemplateSubgraph{
Root: issue,
Issues: []*types.Issue{issue},
IssueMap: map[string]*types.Issue{issue.ID: issue},
}, false, nil
}
}
// Not found as issue — fall through to the formula registry. Same rationale
// as resolveOrDescribe above: let the parser decide. Pass vars for step
// condition filtering (bd-7zka.1).
subgraph, err := resolveAndCookFormulaWithVars(operand, nil, vars)
if err != nil {
if errors.Is(err, formula.ErrVarValidation) || errors.Is(err, formula.ErrValidation) {
// Don't double-wrap: operand IS a formula that either does not
// validate or was given --var values failing its enum/pattern/
// required-empty constraints, both distinct from "not found".
return nil, false, err
}
return nil, false, fmt.Errorf("'%s' not found as issue or formula: %w", operand, err)
}
return subgraph, true, nil
}
// registerMolBondFlags declares bond's flags on cmd. It exists so a test can
// build an isolated command with the real flag set rather than mutating the
// package-level molBondCmd, whose flag values would then leak between tests.
func registerMolBondFlags(cmd *cobra.Command) {
cmd.Flags().String("type", types.BondTypeSequential, "Bond type: sequential, parallel, or conditional")
cmd.Flags().String("as", "", "Custom title for compound proto (proto+proto only)")
cmd.Flags().Bool("dry-run", false, "Preview what would be created")
cmd.Flags().StringArray("var", []string{}, "Variable substitution for spawned protos (key=value)")
cmd.Flags().Bool("ephemeral", false, "Force spawn as vapor (ephemeral, Ephemeral=true)")
cmd.Flags().Bool("pour", false, "Force spawn as liquid (persistent, Ephemeral=false)")
cmd.Flags().String("ref", "", "Custom child reference with {{var}} substitution (e.g., arm-{{polecat_name}})")
}
func init() {
registerMolBondFlags(molBondCmd)
molCmd.AddCommand(molBondCmd)
}