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

540 lines
21 KiB
Go

package main
import (
"bufio"
"context"
"encoding/json"
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
"strings"
"github.com/steveyegge/beads/internal/beads"
"github.com/steveyegge/beads/internal/configfile"
"github.com/steveyegge/beads/internal/debug"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/storage/embeddeddolt"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/internal/utils"
)
var errRoutingUnavailable = errors.New("routing unavailable")
// isNotFoundErr returns true if the error indicates the issue was not found.
// This covers both storage.ErrNotFound (from GetIssue) and the plain error
// from ResolvePartialID which doesn't wrap the sentinel.
func isNotFoundErr(err error) bool {
if errors.Is(err, storage.ErrNotFound) {
return true
}
if err != nil && strings.Contains(err.Error(), "no issue found matching") {
return true
}
return false
}
// isRoutingFailure reports whether a routed tier's error must reach the caller
// instead of falling through to the next tier: anything but "this tier has no
// route" (errRoutingUnavailable) or a plain not-found. An unreadable
// routes.jsonl or a routed store that fails to open is why the lookup missed,
// and returning the local not-found in its place would misstate the cause.
func isRoutingFailure(err error) bool {
return err != nil && !errors.Is(err, errRoutingUnavailable) && !isNotFoundErr(err)
}
// RoutedResult contains the result of a routed issue lookup
type RoutedResult struct {
Issue *types.Issue
Store storage.DoltStorage // The store that contains this issue (may be routed)
Routed bool // true if the issue was found via routing
ResolvedID string // The resolved (full) issue ID
closeFn func() // Function to close routed storage (if any)
}
// Close closes any routed storage. Safe to call if Routed is false.
func (r *RoutedResult) Close() {
if r.closeFn != nil {
r.closeFn()
r.closeFn = nil
}
}
// commitRoutedWrite commits what command wrote through result when result is
// routed. The post-run auto-commit covers only the local store, so a command
// that writes to a routed target commits that write itself, as bd update and
// bd close do. An unrouted result is left to the post-run auto-commit.
func commitRoutedWrite(ctx context.Context, result *RoutedResult, command string) error {
if !result.Routed {
return nil
}
return commitPendingIfEmbedded(ctx, result.Store, currentActor(), doltAutoCommitParams{
Command: command,
IssueIDs: []string{result.ResolvedID},
})
}
// resolveAndGetIssueWithRouting resolves a partial ID and gets the issue.
// Tries the local store first, then prefix-based routing via routes.jsonl,
// then falls back to auto-routing (routing.mode=auto). A routing failure, such
// as an unreadable routes.jsonl or a routed store that fails to open, is
// returned as itself rather than as the local not-found.
//
// Returns a RoutedResult containing the issue, resolved ID, and the store to use.
// The caller MUST call result.Close() when done to release any routed storage.
//
// Routed target stores, prefix and auto alike, are opened read-only; mutating
// commands must use resolveAndGetIssueForMutation instead so a routed read can
// never write migrations or other open-time mutations into a foreign project
// (GH#3231, #4141).
func resolveAndGetIssueWithRouting(ctx context.Context, localStore storage.DoltStorage, id string) (*RoutedResult, error) {
return resolveAndGetIssueWithRoutingAccess(ctx, localStore, id, false)
}
// resolveAndGetIssueForMutation resolves an issue like
// resolveAndGetIssueWithRouting, but opens the routed target store writable so
// mutation commands commit to the repository that holds the issue: a
// prefix-routed rig, or the target of any auto-route, a contributor's planning
// repository included (openAutoRoutedStore).
func resolveAndGetIssueForMutation(ctx context.Context, localStore storage.DoltStorage, id string) (*RoutedResult, error) {
return resolveAndGetIssueWithRoutingAccess(ctx, localStore, id, true)
}
func resolveAndGetIssueWithRoutingAccess(ctx context.Context, localStore storage.DoltStorage, id string, writable bool) (*RoutedResult, error) {
// Try local store first.
result, err := resolveAndGetFromStore(ctx, localStore, id, false)
if err == nil {
return result, nil
}
// If not found locally, try prefix-based routing via routes.jsonl.
// This handles cross-rig lookups where the ID's prefix maps to a different
// database (e.g., hr-8wn.1 routes to the herald rig's database).
if isNotFoundErr(err) {
if prefixResult, prefixErr := resolveViaPrefixRoutingWithAccess(ctx, id, writable, false); prefixErr == nil {
return prefixResult, nil
} else if isRoutingFailure(prefixErr) {
return nil, prefixErr
}
}
// If not found via prefix routing, try auto-routing as fallback (GH#2345).
// The target reopens writable when the caller has write intent.
if isNotFoundErr(err) {
if autoResult, autoErr := resolveViaAutoRoutingWithAccess(ctx, localStore, id, writable, false); autoErr == nil {
return autoResult, nil
} else if isRoutingFailure(autoErr) {
return nil, autoErr
}
}
return nil, err
}
// idResolverFor is the store id resolution should ask. A backend that can only
// look ids up exactly (utils.ExactIDLookupStore, the http backend) sits under
// the decorator chain, which does not forward that capability, so the
// resolver is handed the backend itself: resolution is a pure read, and the
// decorators (hooks, the external-dependency policy, telemetry) decide
// nothing about it. Every other store is resolved through s unchanged.
func idResolverFor(s storage.DoltStorage) utils.PartialIDResolverStore {
if s == nil {
return s
}
if raw := storage.UnwrapStore(s); raw != nil {
if exact, ok := raw.(utils.ExactIDLookupStore); ok && exact.ExactIDLookupOnly() {
return raw
}
}
return s
}
// resolveAndGetFromStore resolves a partial ID and gets the issue from a specific store.
func resolveAndGetFromStore(ctx context.Context, s storage.DoltStorage, id string, routed bool) (*RoutedResult, error) {
// First, resolve the partial ID
resolvedID, err := utils.ResolvePartialID(ctx, idResolverFor(s), id)
if err != nil {
return nil, err
}
// Then get the issue
issue, err := s.GetIssue(ctx, resolvedID)
if err != nil {
return nil, err
}
return &RoutedResult{
Issue: issue,
Store: s,
Routed: routed,
ResolvedID: resolvedID,
}, nil
}
// resolveAndGetFromStoreExact is resolveAndGetFromStore's exact-match sibling:
// it requires utils.ResolvePartialIDExact instead of the default abbreviation-
// tolerant resolver, so a non-exact candidate (e.g. a reserved word that
// happens to be a leading-prefix abbreviation of some issue's hash) is
// reported as "not found" rather than silently resolved.
func resolveAndGetFromStoreExact(ctx context.Context, s storage.DoltStorage, id string, routed bool) (*RoutedResult, error) {
resolvedID, err := utils.ResolvePartialIDExact(ctx, idResolverFor(s), id)
if err != nil {
return nil, err
}
issue, err := s.GetIssue(ctx, resolvedID)
if err != nil {
return nil, err
}
return &RoutedResult{
Issue: issue,
Store: s,
Routed: routed,
ResolvedID: resolvedID,
}, nil
}
// resolveAndGetIssueForMutationExact resolves an issue like
// resolveAndGetIssueForMutation, but requires an EXACT id match against each
// store it tries (no leading-prefix abbreviation matching) — see
// utils.ResolvePartialIDExact. Cross-rig prefix routing and auto-routing are
// still attempted as fallbacks exactly as before if the local store doesn't
// have the issue at all; only the per-store resolution within each tier is
// tightened. Used by write paths where an id argument
// that doesn't exactly name a real issue must error out instead of silently
// mutating whatever it fuzzy-matches (`bd comment list <id>`, a typo for
// `bd comments list`, was silently resolving "list" to a wisp whose hash
// happened to start with "list"). A routing failure is returned as itself, as
// resolveAndGetIssueForMutation returns it.
func resolveAndGetIssueForMutationExact(ctx context.Context, localStore storage.DoltStorage, id string) (*RoutedResult, error) {
result, err := resolveAndGetFromStoreExact(ctx, localStore, id, false)
if err == nil {
return result, nil
}
if !isNotFoundErr(err) {
return nil, err
}
// The routed tiers resolve with utils.ResolvePartialIDExact too, so each
// can mint utils.ErrAbbreviatedIDNotAllowed of its own — the abbreviation
// names a real issue in the routed rig rather than here — and both
// wrappers hand that error back unwrapped. Keep the first such refusal:
// the local error is only a plain not-found, and returning it would tell
// the caller no issue matches an id a routed store demonstrably holds,
// which is exactly the falsehood the sentinel exists to prevent. The
// refusal is checked before isRoutingFailure, which it would also satisfy,
// so the auto tier still gets its chance at an exact match.
var abbrevErr error
prefixResult, prefixErr := resolveViaPrefixRoutingWithAccess(ctx, id, true, true)
switch {
case prefixErr == nil:
return prefixResult, nil
case errors.Is(prefixErr, utils.ErrAbbreviatedIDNotAllowed):
abbrevErr = prefixErr
case isRoutingFailure(prefixErr):
return nil, prefixErr
}
// Write intent, as in resolveAndGetIssueForMutation: the auto-route opens
// writable so the write commits where the issue lives. The auto tier's own
// abbreviation refusal is a routing failure here, and is returned as one.
autoResult, autoErr := resolveViaAutoRoutingWithAccess(ctx, localStore, id, true, true)
switch {
case autoErr == nil:
return autoResult, nil
case abbrevErr != nil:
return nil, abbrevErr
case isRoutingFailure(autoErr):
return nil, autoErr
}
return nil, err
}
// resolveViaAutoRoutingWithAccess attempts to find an issue using auto-routing.
// This is the fallback when the local store doesn't have the issue (GH#2345).
// Returns a RoutedResult if the issue is found in the auto-routed store.
//
// writable is the caller's write intent: the target opens writable for it,
// whichever rule selected the target (openAutoRoutedStore).
//
// exact selects utils.ResolvePartialIDExact over the default abbreviation-
// tolerant resolver for the auto-routed store lookup, mirroring the local-store
// distinction in resolveAndGetFromStore vs resolveAndGetFromStoreExact.
func resolveViaAutoRoutingWithAccess(ctx context.Context, localStore storage.DoltStorage, id string, writable bool, exact bool) (*RoutedResult, error) {
routedStore, routed, _, err := openAutoRoutedStore(ctx, localStore, writable)
if err != nil {
return nil, err
}
if !routed {
return nil, fmt.Errorf("%w: no auto-routed store available", errRoutingUnavailable)
}
var result *RoutedResult
if exact {
result, err = resolveAndGetFromStoreExact(ctx, routedStore, id, true)
} else {
result, err = resolveAndGetFromStore(ctx, routedStore, id, true)
}
if err != nil {
_ = routedStore.Close()
return nil, err
}
result.closeFn = func() { _ = routedStore.Close() }
return result, nil
}
// prefixRoute represents a prefix-to-path routing rule from routes.jsonl.
type prefixRoute struct {
Prefix string `json:"prefix"` // Issue ID prefix (e.g., "hr-")
Path string `json:"path"` // Relative path to rig directory from town root
}
// resolveViaPrefixRouting attempts to find an issue by looking up its prefix
// in routes.jsonl and opening the target rig's database read-only.
//
// This enables cross-rig lookups: when running from a redirected .beads directory
// (e.g., crew/beercan → town/.beads with database "hq"), a bead ID like "hr-8wn.1"
// can be resolved by following the "hr-" route to the herald rig's .beads directory,
// which declares dolt_database="herald".
//
// The read-only open guarantees a routed read cannot mutate the target; mutation
// commands must route through resolveViaPrefixRoutingWithAccess with writable=true.
func resolveViaPrefixRouting(ctx context.Context, id string) (*RoutedResult, error) {
return resolveViaPrefixRoutingWithAccess(ctx, id, false, false)
}
// resolveViaPrefixRoutingWithAccess is the shared implementation that selects the
// store-open mode. writable opens the routed target writable, behaving like running
// the command inside that rig; false keeps the read-only open that guarantees a
// routed read cannot mutate the target (bd-6dnrw.32). exact selects
// utils.ResolvePartialIDExact over the default abbreviation-tolerant resolver for
// the routed store lookup, mirroring resolveAndGetFromStore vs
// resolveAndGetFromStoreExact.
func resolveViaPrefixRoutingWithAccess(ctx context.Context, id string, writable bool, exact bool) (*RoutedResult, error) {
matchedRoute, targetBeadsDir, err := lookupPrefixRoute(id)
if err != nil {
return nil, err
}
// Check that the target has a different dolt_database
targetDB, err := loadDoltDatabase(targetBeadsDir)
if err == nil && targetDB == "" {
err = fmt.Errorf("%s has no dolt_database field", filepath.Join(targetBeadsDir, "metadata.json"))
}
if err != nil {
return nil, fmt.Errorf("prefix route %q to %s: target rig has no dolt_database configured: %w", matchedRoute.Prefix, matchedRoute.Path, err)
}
debug.Logf("[routing] Prefix %q matched route to %s (database: %s)\n", matchedRoute.Prefix, matchedRoute.Path, targetDB)
targetStore, err := openRoutedTargetStore(ctx, targetBeadsDir, targetDB, writable)
if err != nil {
return nil, fmt.Errorf("opening routed store for %s: %w", matchedRoute.Path, err)
}
var result *RoutedResult
if exact {
result, err = resolveAndGetFromStoreExact(ctx, targetStore, id, true)
} else {
result, err = resolveAndGetFromStore(ctx, targetStore, id, true)
}
if err != nil {
_ = targetStore.Close()
return nil, err
}
result.closeFn = func() { _ = targetStore.Close() }
if os.Getenv("BD_DEBUG_ROUTING") != "" {
fmt.Fprintf(os.Stderr, "[routing] Resolved %s via prefix route to %s (database: %s)\n", id, matchedRoute.Path, targetDB)
}
return result, nil
}
// lookupPrefixRoute finds the routes.jsonl route for id and returns it with
// the target rig's .beads directory. Having no route to follow (no prefix in
// the ID, no beads directory, no routes, no matching route, or a route back to
// the current database) wraps errRoutingUnavailable; an unreadable routes.jsonl
// does not, so callers report it instead of falling through.
func lookupPrefixRoute(id string) (*prefixRoute, string, error) {
if strings.Index(id, "-") <= 0 {
return nil, "", fmt.Errorf("%w: no prefix in ID %q", errRoutingUnavailable, id)
}
// Find the resolved beads directory (where routes.jsonl lives)
currentBeadsDir := resolveCommandBeadsDir(dbPath)
if currentBeadsDir == "" {
return nil, "", fmt.Errorf("%w: no beads directory available", errRoutingUnavailable)
}
// Load routes from routes.jsonl
routes, err := loadPrefixRoutes(currentBeadsDir)
if err != nil {
if errors.Is(err, fs.ErrNotExist) {
return nil, "", fmt.Errorf("%w: no routes available", errRoutingUnavailable)
}
return nil, "", fmt.Errorf("loading routes: %w", err)
}
if len(routes) == 0 {
return nil, "", fmt.Errorf("%w: no routes available", errRoutingUnavailable)
}
// Find the most specific route for this ID
matchedRoute := matchPrefixRoute(routes, id)
if matchedRoute == nil {
return nil, "", fmt.Errorf("%w: no route for ID %q", errRoutingUnavailable, id)
}
// Skip if the route points to current directory (town-level, already checked)
if matchedRoute.Path == "." {
return nil, "", fmt.Errorf("%w: route points to current database", errRoutingUnavailable)
}
// Derive the town root from the current beads dir.
// currentBeadsDir is typically <town_root>/.beads
townRoot := filepath.Dir(currentBeadsDir)
// Resolve the target rig's .beads directory
rigDir := filepath.Join(townRoot, matchedRoute.Path)
return matchedRoute, beads.FollowRedirect(filepath.Join(rigDir, ".beads")), nil
}
// openRoutedTargetStore opens the store of a routed target, prefix or auto,
// writable or read-only. BEADS_DOLT_SERVER_DATABASE outranks the target's
// metadata.json when a store resolves its database name, and it names the
// launching workspace's database (set by the user, or by
// preserveRedirectSourceDatabase after a redirect), so while the target opens
// it is pointed at database, the target's own dolt_database. Otherwise a
// server-mode open would connect to the launcher's database on the shared
// server, and an embedded writable open would create or migrate a wrongly
// named database under the target. An empty database leaves the environment
// as it is: the target names no database of its own to prefer.
//
// A writable open never creates the target's database
// (newExistingDoltStoreFromConfig): the open runs before the lookup it serves,
// so an id that misses must leave a repository that has not been bootstrapped
// yet as it found it. A target that has been bootstrapped does run its
// open-time schema migrations on such a miss, as any bd command run in that
// repository would; they bring it to the schema this bd writes, not to
// anything the missed id asked for.
func openRoutedTargetStore(ctx context.Context, beadsDir, database string, writable bool) (storage.DoltStorage, error) {
if database != "" {
origDB := os.Getenv("BEADS_DOLT_SERVER_DATABASE")
_ = os.Setenv("BEADS_DOLT_SERVER_DATABASE", database)
defer func() {
// Restore the original env var
if origDB != "" {
_ = os.Setenv("BEADS_DOLT_SERVER_DATABASE", origDB)
} else {
_ = os.Unsetenv("BEADS_DOLT_SERVER_DATABASE")
}
}()
}
if writable {
return newExistingDoltStoreFromConfig(ctx, beadsDir)
}
return newReadOnlyStoreFromConfig(ctx, beadsDir)
}
// matchPrefixRoute returns the route whose prefix is the longest leading match
// for beadID, or nil if none matches. Route prefixes end in "-", so a
// multi-hyphen prefix such as "claude-os-" matches "claude-os-76l", and with
// both "hq-" and "hq-cv-" configured, "hq-cv-abc" takes the "hq-cv-" route
// (GH#5048).
func matchPrefixRoute(routes []prefixRoute, beadID string) *prefixRoute {
var best *prefixRoute
for i, r := range routes {
if !strings.HasSuffix(r.Prefix, "-") || !strings.HasPrefix(beadID, r.Prefix) {
continue
}
if best == nil || len(r.Prefix) > len(best.Prefix) {
best = &routes[i]
}
}
return best
}
// loadPrefixRoutes loads prefix-to-path routes from routes.jsonl in the beads directory.
func loadPrefixRoutes(beadsDir string) ([]prefixRoute, error) {
routesPath := filepath.Join(beadsDir, "routes.jsonl")
file, err := os.Open(routesPath) //nolint:gosec // G304: path is constructed from trusted beads directory
if err != nil {
return nil, err
}
defer file.Close()
var routes []prefixRoute
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if line == "" || strings.HasPrefix(line, "#") {
continue
}
var route prefixRoute
if err := json.Unmarshal([]byte(line), &route); err != nil {
continue
}
if route.Prefix != "" && route.Path != "" {
routes = append(routes, route)
}
}
return routes, scanner.Err()
}
// loadDoltDatabase reads the dolt_database field from a .beads/metadata.json
// file, and reports a metadata.json it cannot read or parse; a file without the
// field returns "" and no error.
func loadDoltDatabase(beadsDir string) (string, error) {
metadataPath := filepath.Join(beadsDir, "metadata.json")
data, err := os.ReadFile(metadataPath) //nolint:gosec // G304: path is constructed from trusted beads directory
if err != nil {
return "", err
}
var meta struct {
DoltDatabase string `json:"dolt_database"`
}
if err := json.Unmarshal(data, &meta); err != nil {
return "", fmt.Errorf("parsing %s: %w", metadataPath, err)
}
return meta.DoltDatabase, nil
}
// autoRouteTargetDatabase is the dolt_database an auto-routed open points its
// target at (openRoutedTargetStore). A read stays tolerant: a metadata.json
// that is unreadable or names no database yields "", and the target's own open
// decides. A write refuses both, as a prefix route does,
// because the launcher's BEADS_DOLT_SERVER_DATABASE would then pick the
// database, and an embedded writable open creates the database it is given
// when the target holds any other (newExistingDoltStoreFromConfig refuses only
// a target that holds none).
//
// A target with no metadata.json at all is still opened, read or written. That
// is the planning repository contributor setup creates (runContributorWizard,
// autoConfigureForkContributor) until the first routed bd create writes one
// (ensureBeadsDirForPath). Setup names its database as any workspace without
// metadata.json does, after the variable when it is set and the default
// database otherwise, so the open is pointed at the only embedded database the
// target holds, or at the default database when it holds none or several.
// Resolving the name again at use would follow the launcher's variable, which
// need not be the one setup ran with: a read would then miss the database
// setup created, and a write would create another beside it.
func autoRouteTargetDatabase(beadsDir string, writable bool) (string, error) {
database, err := loadDoltDatabase(beadsDir)
switch {
case errors.Is(err, fs.ErrNotExist):
if databases := embeddeddolt.Databases(beadsDir); len(databases) == 1 {
return databases[0], nil
}
return configfile.DefaultDoltDatabase, nil
case !writable:
return database, nil
case err != nil:
return "", err
case database == "":
return "", fmt.Errorf("%s has no dolt_database field", filepath.Join(beadsDir, "metadata.json"))
}
return database, nil
}