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

185 lines
6.2 KiB
Go

//go:build cgo
package main
import (
"context"
"os"
"path/filepath"
"testing"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/types"
)
// TestResolveCloseTargets is the regression test for beads-0km: bd close
// failed for issues that lived only in the routed contributor planning store,
// while bd show / bd update succeeded for the same IDs because they routed via
// resolveAndGetIssueWithRouting and close did not. The fix uses
// resolveCloseTargets, which performs the same routing fallback and shares one
// routed-store handle across IDs when multiple IDs route to the same target.
//
// The cases cover:
// - maintainer-mode local resolution (no routing involved)
// - contributor-mode batch where every ID lives in the planning store
// (must share one routed-store handle)
// - contributor-mode mixed batch with one local ID and one routed ID
// (validates the per-result store routing and the mutatedStores fan-out)
func TestResolveCloseTargets(t *testing.T) {
cases := []struct {
name string
role string // git config beads.role value
enableRouting bool // set routing.mode=auto + routing.contributor=<planningDir>
localSeed []string // IDs to create in the primary (local) store
planningSeed []string // IDs to create in the planning store; non-nil also creates the dir
inputIDs []string // argument to resolveCloseTargets
wantRoutedFlag []bool // expected RoutedResult.Routed per result
wantStoreOrigin []string // per result: "local" (== primaryStore) or "planning" (routed handle)
}{
{
name: "maintainer_local_only",
role: "maintainer",
enableRouting: false,
localSeed: []string{"shared-local"},
inputIDs: []string{"shared-local"},
wantRoutedFlag: []bool{false},
wantStoreOrigin: []string{"local"},
},
{
name: "contributor_batch_all_routed_shares_one_handle",
role: "contributor",
enableRouting: true,
planningSeed: []string{"shared-aaa", "shared-bbb"},
inputIDs: []string{"shared-aaa", "shared-bbb"},
wantRoutedFlag: []bool{true, true},
wantStoreOrigin: []string{"planning", "planning"},
},
{
name: "contributor_mixed_local_and_routed",
role: "contributor",
enableRouting: true,
localSeed: []string{"shared-here"},
planningSeed: []string{"shared-there"},
inputIDs: []string{"shared-here", "shared-there"},
wantRoutedFlag: []bool{false, true},
wantStoreOrigin: []string{"local", "planning"},
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
initConfigForTest(t)
neutralizeRoutingModeEnv(t)
tmpDir := t.TempDir()
repoDir := filepath.Join(tmpDir, "repo")
planningDir := filepath.Join(tmpDir, "planning")
runCmd(t, tmpDir, "git", "init", repoDir)
runCmd(t, repoDir, "git", "config", "beads.role", tc.role)
primaryStore := newTestStoreIsolatedDB(t, filepath.Join(repoDir, ".beads", "beads.db"), "shared")
ctx := context.Background()
if tc.enableRouting {
if err := primaryStore.SetConfig(ctx, "routing.mode", "auto"); err != nil {
t.Fatalf("set routing.mode: %v", err)
}
if err := primaryStore.SetConfig(ctx, "routing.contributor", planningDir); err != nil {
t.Fatalf("set routing.contributor: %v", err)
}
}
for _, id := range tc.localSeed {
seedIssue(t, ctx, primaryStore, id)
}
if len(tc.planningSeed) > 0 {
planningStore := newTestStoreIsolatedDB(t, filepath.Join(planningDir, ".beads", "beads.db"), "shared")
for _, id := range tc.planningSeed {
seedIssue(t, ctx, planningStore, id)
}
// Release the planning store so resolveCloseTargets can open
// the routed store through the normal command path.
if err := planningStore.Close(); err != nil {
t.Fatalf("close planning store: %v", err)
}
}
oldWD, err := os.Getwd()
if err != nil {
t.Fatalf("getwd: %v", err)
}
t.Cleanup(func() { _ = os.Chdir(oldWD) })
if err := os.Chdir(repoDir); err != nil {
t.Fatalf("chdir repoDir: %v", err)
}
// Role detection reads the process-wide RepoContext cache, which the
// previous case built for its own, now-deleted repo. Rebuild it from
// repoDir.
resetRepoContextCachesForTest(t)
results, cleanup, err := resolveCloseTargets(ctx, primaryStore, tc.inputIDs)
if err != nil {
t.Fatalf("resolveCloseTargets: %v", err)
}
defer cleanup()
if len(results) != len(tc.inputIDs) {
t.Fatalf("got %d results, want %d", len(results), len(tc.inputIDs))
}
// Track the first routed-store handle we see so every subsequent
// routed result reuses the same batch handle.
var sharedRoutedStore storage.DoltStorage
for i, r := range results {
if r == nil || r.Issue == nil {
t.Fatalf("result[%d] missing Issue", i)
}
if r.ResolvedID != tc.inputIDs[i] {
t.Errorf("result[%d].ResolvedID = %q, want %q", i, r.ResolvedID, tc.inputIDs[i])
}
if r.Routed != tc.wantRoutedFlag[i] {
t.Errorf("result[%d].Routed = %v, want %v", i, r.Routed, tc.wantRoutedFlag[i])
}
switch tc.wantStoreOrigin[i] {
case "local":
if r.Store != primaryStore {
t.Errorf("result[%d].Store should be the local primary store", i)
}
case "planning":
if r.Store == nil {
t.Errorf("result[%d].Store is nil", i)
}
if r.Store == primaryStore {
t.Errorf("result[%d].Store should be the routed planning store, not the local one", i)
}
if sharedRoutedStore == nil {
sharedRoutedStore = r.Store
} else if r.Store != sharedRoutedStore {
t.Errorf("result[%d].Store: routed handles should be deduped to one shared handle", i)
}
default:
t.Fatalf("unknown wantStoreOrigin[%d] = %q", i, tc.wantStoreOrigin[i])
}
}
})
}
}
// seedIssue creates a minimal open task in the given store for test fixtures.
func seedIssue(t *testing.T, ctx context.Context, s storage.DoltStorage, id string) {
t.Helper()
issue := &types.Issue{
ID: id,
Title: "test issue " + id,
Status: types.StatusOpen,
Priority: 2,
IssueType: types.TypeTask,
}
if err := s.CreateIssue(ctx, issue, "test"); err != nil {
t.Fatalf("seed issue %s: %v", id, err)
}
}