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 mainb303d494df. 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 mainb303d494df. 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>
This commit is contained in:
parent
babf8d7ed7
commit
91a72ef7b5
25 changed files with 2471 additions and 240 deletions
2
.github/scripts/embedded-cmd-test-shards.txt
vendored
2
.github/scripts/embedded-cmd-test-shards.txt
vendored
|
|
@ -143,7 +143,9 @@
|
|||
100 59 TestEmbeddedDeferAutoWake
|
||||
|
||||
100 60 TestEmbeddedCommentsCLI
|
||||
100 60 TestEmbeddedRoutedWriteMissDoesNotCreateTargetDatabase
|
||||
|
||||
100 61 TestEmbeddedContributorRoutedWritesCommitInPlanning
|
||||
100 61 TestEmbeddedUpdateRoutedStoreCommitsTargetHead
|
||||
|
||||
100 62 TestEmbeddedGateCheckSkipsTemplateGates
|
||||
|
|
|
|||
|
|
@ -388,6 +388,7 @@
|
|||
40 24 TestReopenIssue
|
||||
|
||||
40 25 TestBatchGetterContract
|
||||
40 25 TestDatabases
|
||||
40 25 TestDualWriteFixtureKitIsWired
|
||||
40 25 TestEmbeddedBatchCloserClaimNextIsNilWhenNothingClosed
|
||||
40 25 TestEmbeddedIssueOperationsUpdateClaimHonorsConfiguredActiveStatuses
|
||||
|
|
|
|||
40
CHANGELOG.md
40
CHANGELOG.md
|
|
@ -557,6 +557,46 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|||
|
||||
### Fixed
|
||||
|
||||
- **`bd mol bond <A> <B>` ignored prefix routing** — operand resolution now uses
|
||||
the same routing fallback as `bd show`/`bd update`/`bd close`, so a bead that
|
||||
lives in a routed store (a prefix-routed rig via `routes.jsonl`, or the
|
||||
contributor planning store) resolves instead of failing with `'<id>' not found
|
||||
as issue or formula`. Previously `bd mol bond` resolved operands
|
||||
against the local store only, so `gt sling <bead> <rig>` — which cooks the
|
||||
default formula and bonds it to a rig-routed bead — died at `bd mol bond` even
|
||||
though `bd show <bead>` resolved the same ID. Resolution is write-intent: the
|
||||
routed target opens writable and the bond commits where the bead lives. Two
|
||||
operands that live in the same routed rig share one store handle and bond
|
||||
normally; only a bond whose operands resolve to genuinely different databases
|
||||
is rejected rather than written to the wrong one. As part of this change, an
|
||||
auto-route — contributor, maintainer or default — now opens writable for the
|
||||
commands that change an existing issue (`bd update`, `bd close`,
|
||||
`bd comment`, `bd unclaim`, `bd dep` and the other routed mutation commands,
|
||||
as well as `bd mol bond`), so the write commits where the issue lives: for a
|
||||
contributor, in the planning repository, as the contributor workflow
|
||||
documents. Every auto-route used to open read-only, so on an embedded
|
||||
workspace these writes were refused. `bd unclaim` now opens a routed issue
|
||||
writable, as `bd update --claim` does, and commits the release there; on an
|
||||
embedded workspace `bd human respond` and `bd human dismiss` now record a
|
||||
routed change as a Dolt commit in the routed repository instead of leaving it
|
||||
uncommitted in that repository's working set. A routed
|
||||
write, prefix or auto, never creates the target's database: an embedded
|
||||
repository that has not been bootstrapped yet fails the write instead of
|
||||
gaining an empty database that `bd bootstrap` would then take for the real
|
||||
one. An auto-routed store, read or write, now opens the target's own
|
||||
configured `dolt_database`, as a prefix route already did, even when
|
||||
`BEADS_DOLT_SERVER_DATABASE` names the current workspace's database. An
|
||||
auto-routed write refuses a target whose `metadata.json` is unreadable or
|
||||
names no `dolt_database`, while a target with no `metadata.json` at all (a
|
||||
planning repository nothing has been created in yet) opens the one embedded
|
||||
database it holds, or its default database when it holds none or several; a
|
||||
prefix route still requires the target's `dolt_database`. A
|
||||
routing failure, such as an unreadable `routes.jsonl` or a
|
||||
routed store that fails to open, is now reported as itself instead of as
|
||||
`no issue found matching`. Same routing-parity fix as
|
||||
[#3608](https://github.com/gastownhall/beads/issues/3608) for `bd close`.
|
||||
Fixes [#4714](https://github.com/gastownhall/beads/issues/4714).
|
||||
|
||||
- **`bd gate check` works over a connected HTTP workspace.** Its open-gate
|
||||
listing built the same raw `SearchIssues` filter `bd gate list` did before
|
||||
S20, so the HTTP backend refused the command before reading a gate and gc's
|
||||
|
|
|
|||
|
|
@ -995,7 +995,9 @@ go_test(
|
|||
"mol_bond_gwn_test.go",
|
||||
"mol_bond_proxied_integration_test.go",
|
||||
"mol_bond_ref_attach_test.go",
|
||||
"mol_bond_routing_test.go",
|
||||
"mol_bond_test.go",
|
||||
"mol_bond_var_validation_test.go",
|
||||
"mol_burn_proxied_integration_test.go",
|
||||
"mol_current_proxied_integration_test.go",
|
||||
"mol_distill_proxied_integration_test.go",
|
||||
|
|
@ -1115,6 +1117,7 @@ go_test(
|
|||
"restore_test.go",
|
||||
"root_context_lifecycle_test.go",
|
||||
"routed_local_near_miss_test.go",
|
||||
"routed_mutation_test.go",
|
||||
"routed_test.go",
|
||||
"routing_notice_test.go",
|
||||
"routing_read_remote_test.go",
|
||||
|
|
|
|||
132
cmd/bd/close.go
132
cmd/bd/close.go
|
|
@ -872,10 +872,12 @@ func resolveReasonFile(cmd *cobra.Command, hasExistingReason bool) (string, bool
|
|||
|
||||
// resolveCloseTargets resolves a batch of partial issue IDs for `bd close`,
|
||||
// preserving input order. For each ID it tries the local store first, then
|
||||
// explicit prefix routing via routes.jsonl, then a shared contributor-routed
|
||||
// store. This matches resolveAndGetIssueWithRouting's routing precedence.
|
||||
// explicit prefix routing via routes.jsonl, then a shared auto-routed store.
|
||||
// This matches resolveAndGetIssueForMutation's routing precedence and write
|
||||
// intent, and like it returns a routing failure (an unreadable routes.jsonl, a
|
||||
// routed store that fails to open) as itself rather than as a not-found.
|
||||
//
|
||||
// The contributor-routed handle is shared across the batch so bulk close does
|
||||
// The auto-routed handle is shared across the batch so bulk close does
|
||||
// not repeatedly open the same planning store and every result has a clear store
|
||||
// owner for subsequent close-time checks and writes.
|
||||
//
|
||||
|
|
@ -884,60 +886,92 @@ func resolveReasonFile(cmd *cobra.Command, hasExistingReason bool) (string, bool
|
|||
// no-op for routed-via-shared-handle entries because they don't own the handle.
|
||||
func resolveCloseTargets(ctx context.Context, localStore storage.DoltStorage, ids []string) ([]*RoutedResult, func(), error) {
|
||||
results := make([]*RoutedResult, 0, len(ids))
|
||||
var sharedRouted storage.DoltStorage
|
||||
var sharedRoutedTried bool
|
||||
shared := &closeAutoRoute{localStore: localStore}
|
||||
cleanup := func() {
|
||||
for _, r := range results {
|
||||
r.Close()
|
||||
}
|
||||
if sharedRouted != nil {
|
||||
_ = sharedRouted.Close()
|
||||
}
|
||||
}
|
||||
ensureShared := func() (storage.DoltStorage, error) {
|
||||
if sharedRouted != nil {
|
||||
return sharedRouted, nil
|
||||
}
|
||||
if sharedRoutedTried {
|
||||
return nil, fmt.Errorf("no auto-routed store available")
|
||||
}
|
||||
sharedRoutedTried = true
|
||||
rs, routed, _, err := openRoutedReadStore(ctx, localStore)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !routed {
|
||||
return nil, fmt.Errorf("no auto-routed store available")
|
||||
}
|
||||
sharedRouted = rs
|
||||
return rs, nil
|
||||
shared.Close()
|
||||
}
|
||||
for _, id := range ids {
|
||||
// Local first.
|
||||
if r, err := resolveAndGetFromStore(ctx, localStore, id, false); err == nil {
|
||||
results = append(results, r)
|
||||
continue
|
||||
} else if !isNotFoundErr(err) {
|
||||
r, err := resolveCloseTarget(ctx, localStore, shared, id)
|
||||
if err != nil {
|
||||
cleanup()
|
||||
return nil, func() {}, fmt.Errorf("resolving ID %s: %w", id, err)
|
||||
return nil, func() {}, err
|
||||
}
|
||||
// Write-intent: a prefix-routed target opens writable so the close
|
||||
// commits on the target head (#4141). Contributor auto-routing below
|
||||
// stays read-only: it hydrates foreign projects that must not be mutated.
|
||||
if r, err := resolveViaPrefixRoutingWithAccess(ctx, id, true, false); err == nil {
|
||||
results = append(results, r)
|
||||
continue
|
||||
}
|
||||
// Contributor auto-routing uses one shared store for the whole batch.
|
||||
if rs, rerr := ensureShared(); rerr == nil {
|
||||
if r, err := resolveAndGetFromStore(ctx, rs, id, true); err == nil {
|
||||
// Per-id RoutedResult does not own the shared handle; cleanup() does.
|
||||
results = append(results, r)
|
||||
continue
|
||||
}
|
||||
}
|
||||
cleanup()
|
||||
return nil, func() {}, fmt.Errorf("resolving ID %s: no issue found matching %q", id, id)
|
||||
results = append(results, r)
|
||||
}
|
||||
return results, cleanup, nil
|
||||
}
|
||||
|
||||
// resolveCloseTarget resolves one ID of a bd close batch: the local store,
|
||||
// then a prefix route, then the batch's shared auto-routed store.
|
||||
func resolveCloseTarget(ctx context.Context, localStore storage.DoltStorage, shared *closeAutoRoute, id string) (*RoutedResult, error) {
|
||||
// Local first.
|
||||
r, err := resolveAndGetFromStore(ctx, localStore, id, false)
|
||||
if err == nil {
|
||||
return r, nil
|
||||
}
|
||||
if !isNotFoundErr(err) {
|
||||
return nil, fmt.Errorf("resolving ID %s: %w", id, err)
|
||||
}
|
||||
// Write-intent: a prefix-routed target opens writable so the close
|
||||
// commits on the target head (#4141).
|
||||
r, err = resolveViaPrefixRoutingWithAccess(ctx, id, true, false)
|
||||
if err == nil {
|
||||
return r, nil
|
||||
}
|
||||
if isRoutingFailure(err) {
|
||||
return nil, fmt.Errorf("resolving ID %s: %w", id, err)
|
||||
}
|
||||
r, err = shared.resolve(ctx, id)
|
||||
if err == nil {
|
||||
return r, nil
|
||||
}
|
||||
if isRoutingFailure(err) {
|
||||
return nil, fmt.Errorf("resolving ID %s: %w", id, err)
|
||||
}
|
||||
return nil, fmt.Errorf("resolving ID %s: no issue found matching %q", id, id)
|
||||
}
|
||||
|
||||
// closeAutoRoute is the auto-routed store a bd close batch shares. It opens on
|
||||
// first use and is closed once, by the batch's cleanup.
|
||||
type closeAutoRoute struct {
|
||||
localStore storage.DoltStorage
|
||||
store storage.DoltStorage
|
||||
err error
|
||||
tried bool
|
||||
}
|
||||
|
||||
// resolve looks id up in the shared auto-routed store, opening it on the first
|
||||
// call with write intent, as resolveAndGetIssueForMutation does: the target
|
||||
// opens writable, whichever rule selected it, so the close commits where the
|
||||
// issue lives. The outcome of that open, failure included, holds for the rest
|
||||
// of the batch.
|
||||
func (a *closeAutoRoute) resolve(ctx context.Context, id string) (*RoutedResult, error) {
|
||||
if !a.tried {
|
||||
a.tried = true
|
||||
rs, routed, _, err := openAutoRoutedStore(ctx, a.localStore, true)
|
||||
switch {
|
||||
case err != nil:
|
||||
a.err = err
|
||||
case !routed:
|
||||
a.err = fmt.Errorf("%w: no auto-routed store available", errRoutingUnavailable)
|
||||
default:
|
||||
a.store = rs
|
||||
}
|
||||
}
|
||||
if a.err != nil {
|
||||
return nil, a.err
|
||||
}
|
||||
// Per-id RoutedResult does not own the shared handle; Close does.
|
||||
return resolveAndGetFromStore(ctx, a.store, id, true)
|
||||
}
|
||||
|
||||
// Close closes the shared auto-routed store, if one was opened.
|
||||
func (a *closeAutoRoute) Close() {
|
||||
if a.store != nil {
|
||||
_ = a.store.Close()
|
||||
a.store = nil
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -69,6 +69,7 @@ func TestResolveCloseTargets(t *testing.T) {
|
|||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
initConfigForTest(t)
|
||||
neutralizeRoutingModeEnv(t)
|
||||
|
||||
tmpDir := t.TempDir()
|
||||
repoDir := filepath.Join(tmpDir, "repo")
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@ import (
|
|||
"testing"
|
||||
|
||||
"github.com/steveyegge/beads/internal/storage/embeddeddolt"
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
)
|
||||
|
||||
// The TestEmbeddedContributorCreate* tests exercise the full contributor mode flow in
|
||||
|
|
@ -98,6 +99,67 @@ func TestEmbeddedContributorCreateMultiple(t *testing.T) {
|
|||
})
|
||||
}
|
||||
|
||||
// TestEmbeddedContributorRoutedWritesCommitInPlanning runs, through the bd
|
||||
// binary in a contributor checkout, the commands that change an issue living in
|
||||
// the planning repository: each writes the change there and advances the
|
||||
// planning database's HEAD, as the TestEmbeddedRoutedSiblingWritesCommitTargetHead*
|
||||
// tests pin for a prefix route. While the contributor auto-route opened its
|
||||
// target read-only, the embedded store refused every one of these writes.
|
||||
func TestEmbeddedContributorRoutedWritesCommitInPlanning(t *testing.T) {
|
||||
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
|
||||
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded dolt contributor tests")
|
||||
}
|
||||
t.Parallel()
|
||||
|
||||
bd := buildEmbeddedBD(t)
|
||||
dir, planningDir := initContributor(t, bd, "cw")
|
||||
planningBeadsDir := filepath.Join(planningDir, ".beads")
|
||||
issue := bdCreate(t, bd, dir, "Planning issue")
|
||||
question := bdCreate(t, bd, dir, "Planning question")
|
||||
dismissed := bdCreate(t, bd, dir, "Planning request")
|
||||
|
||||
for _, step := range []struct {
|
||||
name string
|
||||
args []string
|
||||
}{
|
||||
{"update --claim", []string{"update", issue.ID, "--claim"}},
|
||||
{"unclaim", []string{"unclaim", issue.ID}},
|
||||
{"comment", []string{"comment", issue.ID, "planning comment"}},
|
||||
{"close", []string{"close", issue.ID, "--reason", "done"}},
|
||||
{"human respond", []string{"human", "respond", question.ID, "--response", "answered"}},
|
||||
{"human dismiss", []string{"human", "dismiss", dismissed.ID, "--reason", "not needed"}},
|
||||
} {
|
||||
before := embeddedCurrentCommit(t, planningBeadsDir, "cw")
|
||||
bdCommand(t, bd, dir, step.args...)
|
||||
assertEmbeddedHeadAdvanced(t, planningBeadsDir, "cw", before, step.name)
|
||||
}
|
||||
|
||||
planningStore := openStore(t, planningBeadsDir, "cw")
|
||||
for _, id := range []string{issue.ID, question.ID, dismissed.ID} {
|
||||
got, err := planningStore.GetIssue(t.Context(), id)
|
||||
if err != nil {
|
||||
t.Fatalf("GetIssue(%s) in the planning store: %v", id, err)
|
||||
}
|
||||
if got.Status != types.StatusClosed {
|
||||
t.Errorf("%s status in the planning store = %q, want %q", id, got.Status, types.StatusClosed)
|
||||
}
|
||||
}
|
||||
comments, err := planningStore.GetIssueComments(t.Context(), issue.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("GetIssueComments: %v", err)
|
||||
}
|
||||
found := false
|
||||
for _, c := range comments {
|
||||
if c.Text == "planning comment" {
|
||||
found = true
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Errorf("the comment did not land in the planning store: %+v", comments)
|
||||
}
|
||||
assertIssueNotInStore(t, filepath.Join(dir, ".beads"), "cw", issue.ID)
|
||||
}
|
||||
|
||||
// initContributor sets up a project with contributor mode enabled and returns
|
||||
// the project dir and planning dir paths. The contributor wizard runs via
|
||||
// subprocess with stdin piped to answer the interactive prompts.
|
||||
|
|
|
|||
|
|
@ -1388,9 +1388,9 @@ func beadGateNotFound(err error) bool {
|
|||
|
||||
// routedBeadGateGetter gives direct-mode gate checks the same local -> prefix
|
||||
// route -> contributor fallback used by other read commands. Routed stores are
|
||||
// opened read-only and closed before the result is returned. Unlike
|
||||
// getIssueWithRouting, a route that fails or misses is reported as
|
||||
// errBeadGateTargetUnconfirmed instead of as the local not-found.
|
||||
// opened read-only and closed before the result is returned. A route that
|
||||
// fails or misses is reported as errBeadGateTargetUnconfirmed instead of as
|
||||
// the local not-found.
|
||||
type routedBeadGateGetter struct {
|
||||
localStore storage.DoltStorage
|
||||
}
|
||||
|
|
|
|||
|
|
@ -302,6 +302,12 @@ Examples:
|
|||
targetStore := result.Store
|
||||
|
||||
if issue.Status == "closed" {
|
||||
// A response whose routed commit failed left its close in the
|
||||
// target's working set, where this run finds the issue closed.
|
||||
// Nothing else commits a routed target, so commit the close here.
|
||||
if err := commitRoutedWrite(ctx, result, "human respond"); err != nil {
|
||||
return HandleErrorRespectJSON("issue %s is already closed; committing its routed close failed: %v", resolvedID, err)
|
||||
}
|
||||
return HandleErrorRespectJSON("issue %s is already closed", resolvedID)
|
||||
}
|
||||
|
||||
|
|
@ -316,6 +322,10 @@ Examples:
|
|||
return HandleErrorRespectJSON("closing bead: %v", err)
|
||||
}
|
||||
|
||||
if err := commitRoutedWrite(ctx, result, "human respond"); err != nil {
|
||||
return HandleErrorRespectJSON("committing response to %s: %v", resolvedID, err)
|
||||
}
|
||||
|
||||
fmt.Printf("%s Bead %s closed with response.\n", ui.RenderPass("✔"), resolvedID)
|
||||
return nil
|
||||
},
|
||||
|
|
@ -398,6 +408,10 @@ Examples:
|
|||
targetStore := result.Store
|
||||
|
||||
if issue.Status == "closed" {
|
||||
// As in respond: commit a dismissal whose routed commit failed.
|
||||
if err := commitRoutedWrite(ctx, result, "human dismiss"); err != nil {
|
||||
return HandleErrorRespectJSON("issue %s is already closed; committing its routed close failed: %v", resolvedID, err)
|
||||
}
|
||||
return HandleErrorRespectJSON("issue %s is already closed", resolvedID)
|
||||
}
|
||||
|
||||
|
|
@ -407,6 +421,10 @@ Examples:
|
|||
return HandleErrorRespectJSON("closing bead: %v", err)
|
||||
}
|
||||
|
||||
if err := commitRoutedWrite(ctx, result, "human dismiss"); err != nil {
|
||||
return HandleErrorRespectJSON("committing dismissal of %s: %v", resolvedID, err)
|
||||
}
|
||||
|
||||
fmt.Printf("%s Bead %s dismissed.\n", ui.RenderPass("✔"), resolvedID)
|
||||
return nil
|
||||
},
|
||||
|
|
|
|||
|
|
@ -110,7 +110,10 @@ func buildEmbeddedBD(t *testing.T) string {
|
|||
func bdEnv(dir string) []string {
|
||||
var env []string
|
||||
for _, e := range os.Environ() {
|
||||
if strings.HasPrefix(e, "BEADS_") {
|
||||
// Viper reads BD_<KEY> above config.yaml, and agent hosts export
|
||||
// BD_ROUTING_MODE, which overrides the routing.mode a test's
|
||||
// workspace holds.
|
||||
if strings.HasPrefix(e, "BEADS_") || strings.HasPrefix(e, "BD_ROUTING_MODE=") {
|
||||
continue
|
||||
}
|
||||
env = append(env, e)
|
||||
|
|
|
|||
|
|
@ -10,6 +10,7 @@ import (
|
|||
"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"
|
||||
|
|
@ -118,57 +119,143 @@ func runMolBond(cmd *cobra.Command, args []string) error {
|
|||
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 {
|
||||
issueA, formulaA, err := resolveOrDescribe(ctx, store, in.argA, in.vars)
|
||||
if err != nil {
|
||||
return HandleErrorRespectJSON("%v", err)
|
||||
}
|
||||
issueB, formulaB, err := resolveOrDescribe(ctx, store, in.argB, in.vars)
|
||||
if err != nil {
|
||||
return HandleErrorRespectJSON("%v", err)
|
||||
}
|
||||
renderMolBondDryRun(in, issueA, formulaA, issueB, formulaB)
|
||||
renderMolBondDryRun(in, plan.a.issue, plan.a.formula, plan.b.issue, plan.b.formula)
|
||||
return nil
|
||||
}
|
||||
|
||||
subgraphA, cookedA, err := resolveOrCookToSubgraph(ctx, store, in.argA, in.vars)
|
||||
// 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)
|
||||
}
|
||||
subgraphB, cookedB, err := resolveOrCookToSubgraph(ctx, store, in.argB, in.vars)
|
||||
defer closeActiveStore()
|
||||
|
||||
opA, opB, err := materializeMolBondOperands(ctx, activeStore, plan, in.vars)
|
||||
if err != nil {
|
||||
return HandleErrorRespectJSON("%v", err)
|
||||
}
|
||||
|
||||
issueA := subgraphA.Root
|
||||
issueB := subgraphB.Root
|
||||
aIsProto := issueA.IsTemplate || cookedA
|
||||
bIsProto := issueB.IsTemplate || cookedB
|
||||
|
||||
var result *BondResult
|
||||
switch {
|
||||
case aIsProto && bIsProto:
|
||||
result, err = bondProtoProto(ctx, store, issueA, issueB, in.bondType, in.customTitle, currentActor())
|
||||
case aIsProto && !bIsProto:
|
||||
if cookedA {
|
||||
result, err = bondProtoMolWithSubgraph(ctx, store, subgraphA, issueA, issueB, in.bondType, in.vars, in.childRef, currentActor(), in.ephemeral, in.pour)
|
||||
} else {
|
||||
result, err = bondProtoMol(ctx, store, issueA, issueB, in.bondType, in.vars, in.childRef, currentActor(), in.ephemeral, in.pour)
|
||||
}
|
||||
case !aIsProto && bIsProto:
|
||||
if cookedB {
|
||||
result, err = bondProtoMolWithSubgraph(ctx, store, subgraphB, issueB, issueA, in.bondType, in.vars, in.childRef, currentActor(), in.ephemeral, in.pour)
|
||||
} else {
|
||||
result, err = bondMolProto(ctx, store, issueA, issueB, in.bondType, in.vars, in.childRef, currentActor(), in.ephemeral, in.pour)
|
||||
}
|
||||
default:
|
||||
result, err = bondMolMol(ctx, store, issueA, issueB, in.bondType, currentActor())
|
||||
}
|
||||
result, err := bondMolBondOperands(ctx, activeStore, opA, opB, in)
|
||||
if err != nil {
|
||||
return HandleErrorRespectJSON("bonding: %v", err)
|
||||
}
|
||||
|
||||
return renderMolBondResult(result, issueA.ID, issueB.ID, in.ephemeral, in.pour)
|
||||
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 {
|
||||
|
|
@ -683,11 +770,169 @@ func minPriority(a, b int) int {
|
|||
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 for dry-run mode. Returns (issue, formulaName, error).
|
||||
// If it's an issue, issue is set. If it's a formula, formulaName is set.
|
||||
// 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) {
|
||||
// First, try to resolve as an existing issue
|
||||
id, err := utils.ResolvePartialID(ctx, s, operand)
|
||||
if err == nil {
|
||||
issue, err := s.GetIssue(ctx, id)
|
||||
|
|
@ -696,10 +941,6 @@ func resolveOrDescribe(ctx context.Context, s molReader, operand string, vars ma
|
|||
}
|
||||
}
|
||||
|
||||
// Not found as issue — fall through to the formula registry. parser.LoadByName
|
||||
// returns "formula %q not found in search paths" for genuinely unknown names,
|
||||
// which is the right error. This matches the resolution behavior of
|
||||
// bd formula show / bd mol seed / bd mol pour / bd cook.
|
||||
parser := formula.NewParser()
|
||||
f, err := parser.LoadByName(operand)
|
||||
if err != nil {
|
||||
|
|
|
|||
514
cmd/bd/mol_bond_routing_test.go
Normal file
514
cmd/bd/mol_bond_routing_test.go
Normal file
|
|
@ -0,0 +1,514 @@
|
|||
//go:build cgo
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/steveyegge/beads/internal/storage"
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
)
|
||||
|
||||
// TestDiscoverMolBondOperandRouting is the regression test for the mol-bond
|
||||
// routing bug (#4714): `bd mol bond <formula> <bead>` failed with
|
||||
// "'<bead>' not found as issue or formula" whenever <bead> lived in a routed
|
||||
// store (a prefix-routed rig, or the contributor planning store), even though
|
||||
// `bd show <bead>` resolved it. mol bond resolved operands against the local
|
||||
// store only and never fell through to the routing fallback that
|
||||
// show/update/close use.
|
||||
//
|
||||
// discoverMolBondOperand resolves through the same local, prefix-route, and
|
||||
// auto-route order, read-only, before the accepted home is reopened writable.
|
||||
//
|
||||
// The cases mirror TestResolveCloseTargets:
|
||||
// - maintainer-mode local resolution (no routing involved)
|
||||
// - an operand that lives only in the routed planning store, reached through
|
||||
// the contributor, maintainer, or default auto-route; each reopens its
|
||||
// home writable for the bond
|
||||
func TestDiscoverMolBondOperandRouting(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
role string
|
||||
enableRouting bool
|
||||
routingKey string
|
||||
localSeed string
|
||||
planningSeed string
|
||||
operand string
|
||||
wantWritable bool
|
||||
wantStore string
|
||||
}{
|
||||
{
|
||||
name: "maintainer_local_issue",
|
||||
role: "maintainer",
|
||||
localSeed: "shared-local",
|
||||
operand: "shared-local",
|
||||
wantStore: "local",
|
||||
},
|
||||
{
|
||||
name: "contributor_routed_issue",
|
||||
role: "contributor",
|
||||
enableRouting: true,
|
||||
routingKey: "routing.contributor",
|
||||
planningSeed: "shared-routed",
|
||||
operand: "shared-routed",
|
||||
wantWritable: true,
|
||||
wantStore: "planning",
|
||||
},
|
||||
{
|
||||
name: "maintainer_routed_issue",
|
||||
role: "maintainer",
|
||||
enableRouting: true,
|
||||
routingKey: "routing.maintainer",
|
||||
planningSeed: "shared-maintainer",
|
||||
operand: "shared-maintainer",
|
||||
wantWritable: true,
|
||||
wantStore: "planning",
|
||||
},
|
||||
{
|
||||
name: "default_routed_issue",
|
||||
role: "maintainer",
|
||||
enableRouting: true,
|
||||
routingKey: "routing.default",
|
||||
planningSeed: "shared-default",
|
||||
operand: "shared-default",
|
||||
wantWritable: true,
|
||||
wantStore: "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)
|
||||
// Force repo-local hooks so tests ignore any global hooksPath override.
|
||||
runCmd(t, repoDir, "git", "config", "core.hooksPath", ".git/hooks")
|
||||
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, tc.routingKey, planningDir); err != nil {
|
||||
t.Fatalf("set %s: %v", tc.routingKey, err)
|
||||
}
|
||||
}
|
||||
|
||||
if tc.localSeed != "" {
|
||||
seedIssue(t, ctx, primaryStore, tc.localSeed)
|
||||
}
|
||||
if tc.planningSeed != "" {
|
||||
planningStore := newTestStoreIsolatedDB(t, filepath.Join(planningDir, ".beads", "beads.db"), "shared")
|
||||
seedIssue(t, ctx, planningStore, tc.planningSeed)
|
||||
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)
|
||||
|
||||
disc, err := discoverMolBondOperand(ctx, primaryStore, tc.operand, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("discoverMolBondOperand(%q): %v", tc.operand, err)
|
||||
}
|
||||
defer disc.Close()
|
||||
if disc.issue == nil || disc.issue.ID != tc.operand || disc.formula != "" {
|
||||
t.Fatalf("operand %q discovery = %#v", tc.operand, disc)
|
||||
}
|
||||
localKey := dependencyStoreKey(primaryStore)
|
||||
if tc.wantStore == "local" && disc.storeKey != localKey {
|
||||
t.Errorf("operand %q storeKey = %q, want local %q", tc.operand, disc.storeKey, localKey)
|
||||
}
|
||||
if tc.wantStore == "planning" && disc.storeKey == localKey {
|
||||
t.Errorf("operand %q unexpectedly resolved to local store", tc.operand)
|
||||
}
|
||||
if tc.wantWritable {
|
||||
disc.Close()
|
||||
rr, err := resolveAndGetIssueForMutation(ctx, primaryStore, tc.operand)
|
||||
if err != nil {
|
||||
t.Fatalf("resolveAndGetIssueForMutation(%q): %v", tc.operand, err)
|
||||
}
|
||||
defer rr.Close()
|
||||
requireWritableAutoRoute(t, "operand "+tc.operand, rr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestDiscoverMolBondOperandFormulaWinsAmbiguousIssuePrefix preserves the
|
||||
// issue-first contract without making an ambiguous issue prefix shadow a valid
|
||||
// formula of the same name. The issue lookup error is actionable only when the
|
||||
// formula parser also rejects the operand.
|
||||
func TestDiscoverMolBondOperandFormulaWinsAmbiguousIssuePrefix(t *testing.T) {
|
||||
initConfigForTest(t)
|
||||
ctx := context.Background()
|
||||
|
||||
repoDir := t.TempDir()
|
||||
beadsDir := filepath.Join(repoDir, ".beads")
|
||||
localStore := newTestStoreIsolatedDB(t, filepath.Join(beadsDir, "beads.db"), "amb")
|
||||
seedIssue(t, ctx, localStore, "ambiguous-formula-one")
|
||||
seedIssue(t, ctx, localStore, "ambiguous-formula-two")
|
||||
|
||||
formulaDir := filepath.Join(beadsDir, "formulas")
|
||||
if err := os.MkdirAll(formulaDir, 0o755); err != nil {
|
||||
t.Fatalf("create formula directory: %v", err)
|
||||
}
|
||||
const name = "ambiguous-formula"
|
||||
formula := []byte(`formula = "ambiguous-formula"
|
||||
version = 1
|
||||
type = "workflow"
|
||||
|
||||
[[steps]]
|
||||
id = "step"
|
||||
title = "Step"
|
||||
type = "task"
|
||||
`)
|
||||
if err := os.WriteFile(filepath.Join(formulaDir, name+".formula.toml"), formula, 0o644); err != nil {
|
||||
t.Fatalf("write formula: %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)
|
||||
}
|
||||
|
||||
disc, err := discoverMolBondOperand(ctx, localStore, name, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("discoverMolBondOperand(%q): %v", name, err)
|
||||
}
|
||||
defer disc.Close()
|
||||
if disc.issue != nil || disc.formula != name {
|
||||
t.Fatalf("ambiguous issue prefix should fall back to formula: %#v", disc)
|
||||
}
|
||||
}
|
||||
|
||||
// TestMolBondPrefixRoutedWriteThrough verifies the bond MUTATION against a
|
||||
// prefix-routed rig store, not just operand resolution: both operands live in
|
||||
// a routed rig, read-only validation accepts the same-rig pair, the selected
|
||||
// store reopens writable, and the dependency is visible
|
||||
// afterward through a fresh routed read — proving the write committed in the
|
||||
// routed database rather than the local one.
|
||||
//
|
||||
// NOTE: This test uses os.Chdir and cannot run in parallel with other tests.
|
||||
func TestMolBondPrefixRoutedWriteThrough(t *testing.T) {
|
||||
initConfigForTest(t)
|
||||
ctx := context.Background()
|
||||
|
||||
tmpDir := t.TempDir()
|
||||
townBeadsDir := filepath.Join(tmpDir, ".beads")
|
||||
if err := os.MkdirAll(townBeadsDir, 0755); err != nil {
|
||||
t.Fatalf("create town beads dir: %v", err)
|
||||
}
|
||||
rigBeadsDir := filepath.Join(tmpDir, "rig", ".beads")
|
||||
if err := os.MkdirAll(rigBeadsDir, 0755); err != nil {
|
||||
t.Fatalf("create rig beads dir: %v", err)
|
||||
}
|
||||
|
||||
townDBPath := filepath.Join(townBeadsDir, "dolt")
|
||||
townStore := newTestStoreIsolatedDB(t, townDBPath, "hq")
|
||||
|
||||
rigDBPath := filepath.Join(rigBeadsDir, "dolt")
|
||||
rigStore := newTestStoreIsolatedDB(t, rigDBPath, "gt")
|
||||
seedIssue(t, ctx, rigStore, "gt-mol1")
|
||||
seedIssue(t, ctx, rigStore, "gt-mol2")
|
||||
// Release the rig store before routing reopens it.
|
||||
rigStore.Close()
|
||||
|
||||
otherRigBeadsDir := filepath.Join(tmpDir, "other-rig", ".beads")
|
||||
if err := os.MkdirAll(otherRigBeadsDir, 0755); err != nil {
|
||||
t.Fatalf("create other rig beads dir: %v", err)
|
||||
}
|
||||
otherStore := newTestStoreIsolatedDB(t, filepath.Join(otherRigBeadsDir, "dolt"), "zz")
|
||||
seedIssue(t, ctx, otherStore, "zz-other")
|
||||
otherStore.Close()
|
||||
|
||||
routesPath := filepath.Join(townBeadsDir, "routes.jsonl")
|
||||
routes := []byte("{\"prefix\":\"gt-\",\"path\":\"rig\"}\n{\"prefix\":\"zz-\",\"path\":\"other-rig\"}\n")
|
||||
if err := os.WriteFile(routesPath, routes, 0644); err != nil {
|
||||
t.Fatalf("write routes.jsonl: %v", err)
|
||||
}
|
||||
|
||||
oldDbPath := dbPath
|
||||
dbPath = townDBPath
|
||||
t.Cleanup(func() { dbPath = oldDbPath })
|
||||
|
||||
oldWd, err := os.Getwd()
|
||||
if err != nil {
|
||||
t.Fatalf("getwd: %v", err)
|
||||
}
|
||||
if err := os.Chdir(tmpDir); err != nil {
|
||||
t.Fatalf("chdir: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = os.Chdir(oldWd) })
|
||||
|
||||
discA, err := discoverMolBondOperand(ctx, townStore, "gt-mol1", nil)
|
||||
if err != nil {
|
||||
t.Fatalf("discover first routed operand: %v", err)
|
||||
}
|
||||
defer discA.Close()
|
||||
discB, err := discoverMolBondOperand(ctx, townStore, "gt-mol2", nil)
|
||||
if err != nil {
|
||||
t.Fatalf("discover second routed operand: %v", err)
|
||||
}
|
||||
defer discB.Close()
|
||||
targetID, targetKey, err := validateMolBondHomes(townStore, discA, discB)
|
||||
if err != nil {
|
||||
t.Fatalf("validate same-rig operands: %v", err)
|
||||
}
|
||||
discA.Close()
|
||||
discB.Close()
|
||||
|
||||
routed, err := resolveAndGetIssueForMutation(ctx, townStore, targetID)
|
||||
if err != nil {
|
||||
t.Fatalf("open accepted target writable: %v", err)
|
||||
}
|
||||
defer routed.Close()
|
||||
if got := dependencyStoreKey(routed.Store); got != targetKey {
|
||||
t.Fatalf("writable reopen changed store: got %q, want %q", got, targetKey)
|
||||
}
|
||||
opA, err := materializeMolBondOperand(ctx, routed.Store, discA, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("materialize first operand: %v", err)
|
||||
}
|
||||
opB, err := materializeMolBondOperand(ctx, routed.Store, discB, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("materialize second operand: %v", err)
|
||||
}
|
||||
if _, err := bondMolMol(ctx, routed.Store, opA.subgraph.Root, opB.subgraph.Root, types.BondTypeSequential, "test"); err != nil {
|
||||
t.Fatalf("bondMolMol against the routed store: %v", err)
|
||||
}
|
||||
routed.Close()
|
||||
|
||||
// Verify through a fresh routed read that the bond committed in the rig
|
||||
// database: gt-mol2 (B) now depends on gt-mol1 (A).
|
||||
rr, err := resolveViaPrefixRoutingWithAccess(ctx, "gt-mol2", false, false)
|
||||
if err != nil {
|
||||
t.Fatalf("reopening routed store to verify the write: %v", err)
|
||||
}
|
||||
defer rr.Close()
|
||||
deps, err := rr.Store.GetDependenciesWithMetadata(ctx, "gt-mol2")
|
||||
if err != nil {
|
||||
t.Fatalf("reading dependencies from the routed store: %v", err)
|
||||
}
|
||||
found := false
|
||||
for _, dep := range deps {
|
||||
if dep.ID == "gt-mol1" && dep.DependencyType == types.DepBlocks {
|
||||
found = true
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatalf("bond did not commit in the routed store: gt-mol2 dependencies = %+v", deps)
|
||||
}
|
||||
rr.Close()
|
||||
|
||||
crossA, err := discoverMolBondOperand(ctx, townStore, "gt-mol1", nil)
|
||||
if err != nil {
|
||||
t.Fatalf("discover cross-store operand A: %v", err)
|
||||
}
|
||||
defer crossA.Close()
|
||||
crossB, err := discoverMolBondOperand(ctx, townStore, "zz-other", nil)
|
||||
if err != nil {
|
||||
t.Fatalf("discover cross-store operand B: %v", err)
|
||||
}
|
||||
defer crossB.Close()
|
||||
if _, _, err := validateMolBondHomes(townStore, crossA, crossB); err == nil || !strings.Contains(err.Error(), "different stores/rigs") {
|
||||
t.Fatalf("cross-store pair error = %v, want explicit rejection", err)
|
||||
}
|
||||
crossA.Close()
|
||||
crossB.Close()
|
||||
|
||||
routes = append(routes, []byte("{\"prefix\":\"bad-\",\"path\":\"missing-rig\"}\n")...)
|
||||
if err := os.WriteFile(routesPath, routes, 0644); err != nil {
|
||||
t.Fatalf("write matched failure route: %v", err)
|
||||
}
|
||||
if _, err := discoverMolBondOperand(ctx, townStore, "bad-target", nil); err == nil || !strings.Contains(err.Error(), "no dolt_database") {
|
||||
t.Fatalf("matched-route failure = %v, want actionable target metadata error", err)
|
||||
}
|
||||
|
||||
drift, err := discoverMolBondOperand(ctx, townStore, "zz-other", nil)
|
||||
if err != nil {
|
||||
t.Fatalf("discover drift fixture: %v", err)
|
||||
}
|
||||
_, driftKey, err := validateMolBondHomes(townStore, drift)
|
||||
if err != nil {
|
||||
t.Fatalf("validate drift fixture: %v", err)
|
||||
}
|
||||
drift.Close()
|
||||
seedIssue(t, ctx, townStore, "zz-other")
|
||||
reopened, err := resolveAndGetIssueForMutation(ctx, townStore, "zz-other")
|
||||
if err != nil {
|
||||
t.Fatalf("reopen drift fixture: %v", err)
|
||||
}
|
||||
defer reopened.Close()
|
||||
if err := verifyMolBondWritableHome(reopened, driftKey); err == nil || !strings.Contains(err.Error(), "changed between discovery") {
|
||||
t.Fatalf("reopen identity mismatch = %v, want retryable safety error", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSameBondStoreSeparateHandles is the regression test for the store
|
||||
// identity check: two separately-opened handles onto the same routed database
|
||||
// (each route-open constructs a fresh store in server mode) must compare as
|
||||
// the same store, not be rejected as a cross-store bond.
|
||||
//
|
||||
// NOTE: This test uses os.Chdir and cannot run in parallel with other tests.
|
||||
func TestSameBondStoreSeparateHandles(t *testing.T) {
|
||||
initConfigForTest(t)
|
||||
ctx := context.Background()
|
||||
|
||||
tmpDir := t.TempDir()
|
||||
townBeadsDir := filepath.Join(tmpDir, ".beads")
|
||||
if err := os.MkdirAll(townBeadsDir, 0755); err != nil {
|
||||
t.Fatalf("create town beads dir: %v", err)
|
||||
}
|
||||
rigBeadsDir := filepath.Join(tmpDir, "rig", ".beads")
|
||||
if err := os.MkdirAll(rigBeadsDir, 0755); err != nil {
|
||||
t.Fatalf("create rig beads dir: %v", err)
|
||||
}
|
||||
|
||||
townDBPath := filepath.Join(townBeadsDir, "dolt")
|
||||
townStore := newTestStoreIsolatedDB(t, townDBPath, "hq")
|
||||
|
||||
rigDBPath := filepath.Join(rigBeadsDir, "dolt")
|
||||
rigStore := newTestStoreIsolatedDB(t, rigDBPath, "gt")
|
||||
seedIssue(t, ctx, rigStore, "gt-idn1")
|
||||
rigStore.Close()
|
||||
|
||||
routesPath := filepath.Join(townBeadsDir, "routes.jsonl")
|
||||
if err := os.WriteFile(routesPath, []byte(`{"prefix":"gt-","path":"rig"}`), 0644); err != nil {
|
||||
t.Fatalf("write routes.jsonl: %v", err)
|
||||
}
|
||||
|
||||
oldDbPath := dbPath
|
||||
dbPath = townDBPath
|
||||
t.Cleanup(func() { dbPath = oldDbPath })
|
||||
|
||||
oldWd, err := os.Getwd()
|
||||
if err != nil {
|
||||
t.Fatalf("getwd: %v", err)
|
||||
}
|
||||
if err := os.Chdir(tmpDir); err != nil {
|
||||
t.Fatalf("chdir: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = os.Chdir(oldWd) })
|
||||
|
||||
rrA, err := resolveViaPrefixRoutingWithAccess(ctx, "gt-idn1", true, false)
|
||||
if err != nil {
|
||||
t.Fatalf("first route-open: %v", err)
|
||||
}
|
||||
defer rrA.Close()
|
||||
rrB, err := resolveViaPrefixRoutingWithAccess(ctx, "gt-idn1", true, false)
|
||||
if err != nil {
|
||||
t.Fatalf("second route-open: %v", err)
|
||||
}
|
||||
defer rrB.Close()
|
||||
|
||||
if rrA.Store == rrB.Store {
|
||||
t.Fatal("test precondition: expected two distinct store handles from separate route-opens")
|
||||
}
|
||||
if !sameBondStore(rrA.Store, rrB.Store) {
|
||||
t.Fatal("sameBondStore: two handles onto the same routed database must compare as the same store")
|
||||
}
|
||||
|
||||
// The negative case matters just as much: genuinely different databases
|
||||
// must NOT compare as the same store, or validation would silently
|
||||
// allow the cross-store bonds it exists to reject.
|
||||
if sameBondStore(townStore, rrA.Store) {
|
||||
t.Fatal("sameBondStore: handles onto different databases must not compare as the same store")
|
||||
}
|
||||
|
||||
wrapped := storage.NewHookFiringStore(rrA.Store, nil)
|
||||
if !sameBondStore(wrapped, rrB.Store) {
|
||||
t.Fatal("sameBondStore: decorator-wrapped and raw handles onto the same database must compare equal")
|
||||
}
|
||||
}
|
||||
|
||||
// TestMolBondContributorAutoRoutedWriteThrough runs bd mol bond's pipeline
|
||||
// (planMolBond, openMolBondHome, materialize, bond) on two issues that live in a
|
||||
// contributor's planning repository, reached through the contributor
|
||||
// auto-route. The planning repository is the contributor's own, so the bond
|
||||
// commits there as an update or close of a planning issue does
|
||||
// (TestContributorAutoRouteWritesThrough): the validated home reopens writable
|
||||
// and a fresh routed read sees the dependency.
|
||||
func TestMolBondContributorAutoRoutedWriteThrough(t *testing.T) {
|
||||
primaryStore, _, _ := setupAutoRoute(t, "contributor", "routing.contributor", "shared-bond")
|
||||
ctx := context.Background()
|
||||
|
||||
in := molBondInput{argA: "shared-hub", argB: "shared-bond", bondType: types.BondTypeSequential}
|
||||
plan, err := planMolBond(ctx, primaryStore, in)
|
||||
if err != nil {
|
||||
t.Fatalf("planMolBond on two contributor-routed issues: %v", err)
|
||||
}
|
||||
defer plan.Close()
|
||||
if plan.targetStoreKey == dependencyStoreKey(primaryStore) {
|
||||
t.Fatalf("bond home resolved to the local store; want the contributor planning store")
|
||||
}
|
||||
plan.Close()
|
||||
|
||||
home, closeHome, err := openMolBondHome(ctx, primaryStore, plan)
|
||||
if err != nil {
|
||||
t.Fatalf("openMolBondHome: %v", err)
|
||||
}
|
||||
defer closeHome()
|
||||
if routedStoreIsReadOnly(t, home) {
|
||||
t.Fatalf("the contributor auto-route reopened the bond home read-only")
|
||||
}
|
||||
opA, opB, err := materializeMolBondOperands(ctx, home, plan, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("materialize operands: %v", err)
|
||||
}
|
||||
if _, err := bondMolBondOperands(ctx, home, opA, opB, in); err != nil {
|
||||
t.Fatalf("bond in the contributor planning store: %v", err)
|
||||
}
|
||||
closeHome()
|
||||
|
||||
// Verify through a fresh routed read that the bond committed in the
|
||||
// planning database: shared-bond (B) now depends on shared-hub (A).
|
||||
rr, err := resolveAndGetIssueWithRouting(ctx, primaryStore, "shared-bond")
|
||||
if err != nil {
|
||||
t.Fatalf("re-reading the routed issue: %v", err)
|
||||
}
|
||||
defer rr.Close()
|
||||
if !rr.Routed {
|
||||
t.Fatalf("re-read resolved shared-bond without routing; want the contributor auto-route")
|
||||
}
|
||||
deps, err := rr.Store.GetDependenciesWithMetadata(ctx, "shared-bond")
|
||||
if err != nil {
|
||||
t.Fatalf("reading dependencies from the planning store: %v", err)
|
||||
}
|
||||
found := false
|
||||
for _, dep := range deps {
|
||||
if dep.ID == "shared-hub" && dep.DependencyType == types.DepBlocks {
|
||||
found = true
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatalf("bond did not commit in the planning store: shared-bond dependencies = %+v", deps)
|
||||
}
|
||||
}
|
||||
198
cmd/bd/mol_bond_var_validation_test.go
Normal file
198
cmd/bd/mol_bond_var_validation_test.go
Normal file
|
|
@ -0,0 +1,198 @@
|
|||
//go:build cgo
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/steveyegge/beads/internal/formula"
|
||||
)
|
||||
|
||||
// Regression coverage for the #5253 guarantees on the routed bond path:
|
||||
// bd mol bond resolves operands through discoverMolBondOperand (read-only
|
||||
// routing discovery) rather than resolveOrDescribe, so the discovery fallback
|
||||
// must enforce the same --var enum/pattern/provided-empty validation — for
|
||||
// --dry-run and execution alike — and a var-validation failure on a real
|
||||
// formula must surface directly instead of being masked as
|
||||
// "'X' not found as issue or formula".
|
||||
|
||||
func makeMolBondVarTestCmd(dryRun bool, varFlags []string) *cobra.Command {
|
||||
c := &cobra.Command{Use: "bond"}
|
||||
c.Flags().String("type", "sequential", "")
|
||||
c.Flags().String("as", "", "")
|
||||
c.Flags().Bool("dry-run", dryRun, "")
|
||||
c.Flags().Bool("ephemeral", false, "")
|
||||
c.Flags().Bool("pour", false, "")
|
||||
c.Flags().String("ref", "", "")
|
||||
c.Flags().StringArray("var", varFlags, "")
|
||||
return c
|
||||
}
|
||||
|
||||
func runMolBondVarViolation(t *testing.T, dryRun bool) (error, string) {
|
||||
t.Helper()
|
||||
writeVarValidationFormula(t)
|
||||
s := newTestStoreWithPrefix(t, filepath.Join(t.TempDir(), "test.db"), "test")
|
||||
withWispTestGlobals(t, s, context.Background())
|
||||
|
||||
var runErr error
|
||||
stderr := captureStderr(t, func() {
|
||||
runErr = runMolBond(makeMolBondVarTestCmd(dryRun, []string{"policy=bogus", "slug=abc"}),
|
||||
[]string{"pour-wisp-var-validation-test", "pour-wisp-var-validation-test"})
|
||||
})
|
||||
return runErr, stderr
|
||||
}
|
||||
|
||||
// TestMolBondDryRunRejectsEnumViolatingVar pins #4714's framing: the dry-run
|
||||
// must fail the same way the real bond would, not preview success for a bond
|
||||
// execution refuses.
|
||||
func TestMolBondDryRunRejectsEnumViolatingVar(t *testing.T) {
|
||||
runErr, stderr := runMolBondVarViolation(t, true)
|
||||
|
||||
if runErr == nil {
|
||||
t.Fatal("mol bond --dry-run accepted a --var value outside the declared enum")
|
||||
}
|
||||
if !strings.Contains(stderr, "not in allowed values") {
|
||||
t.Fatalf("stderr = %q, want an enum-violation message", stderr)
|
||||
}
|
||||
if strings.Contains(stderr, "not found as issue or formula") {
|
||||
t.Fatalf("stderr = %q: the var-validation failure was masked as not-found", stderr)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMolBondExecutionRejectsEnumViolatingVar(t *testing.T) {
|
||||
runErr, stderr := runMolBondVarViolation(t, false)
|
||||
|
||||
if runErr == nil {
|
||||
t.Fatal("mol bond accepted a --var value outside the declared enum")
|
||||
}
|
||||
if !strings.Contains(stderr, "not in allowed values") {
|
||||
t.Fatalf("stderr = %q, want an enum-violation message", stderr)
|
||||
}
|
||||
if strings.Contains(stderr, "not found as issue or formula") {
|
||||
t.Fatalf("stderr = %q: the var-validation failure was masked as not-found", stderr)
|
||||
}
|
||||
}
|
||||
|
||||
// TestMaterializeMolBondOperandPassesVarValidationThrough covers the writable
|
||||
// phase directly: even if a violating value reaches the cook (discovery only
|
||||
// checks vars that are provided against the formula it resolved), the sentinel
|
||||
// must pass through unwrapped so callers and users see the constraint
|
||||
// violation, not a bogus not-found.
|
||||
func TestMaterializeMolBondOperandPassesVarValidationThrough(t *testing.T) {
|
||||
writeVarValidationFormula(t)
|
||||
s := newTestStoreWithPrefix(t, filepath.Join(t.TempDir(), "test.db"), "test")
|
||||
|
||||
_, err := materializeMolBondOperand(context.Background(), s,
|
||||
&molBondDiscovery{operand: "pour-wisp-var-validation-test"},
|
||||
map[string]string{"policy": "bogus", "slug": "abc"})
|
||||
if err == nil {
|
||||
t.Fatal("materializeMolBondOperand cooked a formula whose --var values violate its enum")
|
||||
}
|
||||
if !errors.Is(err, formula.ErrVarValidation) {
|
||||
t.Fatalf("err = %v, want errors.Is(err, formula.ErrVarValidation)", err)
|
||||
}
|
||||
if strings.Contains(err.Error(), "not found as issue or formula") {
|
||||
t.Fatalf("err = %q: the var-validation failure was double-wrapped as not-found", err)
|
||||
}
|
||||
}
|
||||
|
||||
// The direct (non-proxied) bond previews and executes through
|
||||
// discoverMolBondOperand and materializeMolBondOperand, not resolveOrDescribe
|
||||
// and resolveOrCookToSubgraph, so #5761's dry-run guarantee has to hold for
|
||||
// this pair too: discovery is all a --dry-run runs, so whatever it accepts is
|
||||
// previewed as a successful bond. As in mol_bond_dryrun_validation_test.go, the
|
||||
// two phases are asserted against EACH OTHER, so a validation rule added later
|
||||
// cannot re-open the gap.
|
||||
func TestDiscoverMolBondOperandRejectsWhatMaterializeRejects(t *testing.T) {
|
||||
writeSearchableFormula(t, "dryrun-invalid-gate", invalidGateFormula)
|
||||
s := newTestStoreWithPrefix(t, filepath.Join(t.TempDir(), "test.db"), "test")
|
||||
ctx := context.Background()
|
||||
|
||||
_, discoverErr := discoverMolBondOperand(ctx, s, "dryrun-invalid-gate", nil)
|
||||
_, materializeErr := materializeMolBondOperand(ctx, s,
|
||||
&molBondDiscovery{operand: "dryrun-invalid-gate"}, nil)
|
||||
|
||||
if materializeErr == nil {
|
||||
t.Fatal("materialization accepted an invalid formula, so this test is no longer testing the gap")
|
||||
}
|
||||
if discoverErr == nil {
|
||||
t.Fatalf("discovery accepted a formula materialization rejects (materialization said: %v)", materializeErr)
|
||||
}
|
||||
for name, err := range map[string]error{"discovery": discoverErr, "materialization": materializeErr} {
|
||||
if !errors.Is(err, formula.ErrValidation) {
|
||||
t.Errorf("%s error does not wrap formula.ErrValidation: %v", name, err)
|
||||
}
|
||||
if !strings.Contains(err.Error(), "waits_for") {
|
||||
t.Errorf("%s error does not name the failing field: %v", name, err)
|
||||
}
|
||||
if strings.Contains(err.Error(), "not found as issue or formula") {
|
||||
t.Errorf("%s reported an invalid formula as not found: %v", name, err)
|
||||
}
|
||||
}
|
||||
if discoverErr.Error() != materializeErr.Error() {
|
||||
t.Errorf("discovery and materialization report different errors:\n discovery: %v\n materialization: %v", discoverErr, materializeErr)
|
||||
}
|
||||
}
|
||||
|
||||
// The cook validates --var values against the MERGED formula, so discovery
|
||||
// must resolve inheritance first: a var declared only in a parent is otherwise
|
||||
// unchecked, and the dry-run previews a bond execution refuses.
|
||||
func TestDiscoverMolBondOperandValidatesVarsAgainstTheMergedFormula(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
dir := filepath.Join(root, ".beads", "formulas")
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
t.Fatalf("mkdir formulas dir: %v", err)
|
||||
}
|
||||
write := func(name, body string) {
|
||||
if err := os.WriteFile(filepath.Join(dir, name+".formula.toml"), []byte(body), 0o644); err != nil {
|
||||
t.Fatalf("write %s: %v", name, err)
|
||||
}
|
||||
}
|
||||
write("discover-parent", `formula = "discover-parent"
|
||||
version = 1
|
||||
type = "workflow"
|
||||
|
||||
[vars.env]
|
||||
enum = ["dev", "prod"]
|
||||
|
||||
[[steps]]
|
||||
id = "deploy"
|
||||
title = "Deploy to {{env}}"
|
||||
type = "task"
|
||||
`)
|
||||
write("discover-child", `formula = "discover-child"
|
||||
version = 1
|
||||
type = "workflow"
|
||||
extends = ["discover-parent"]
|
||||
`)
|
||||
t.Setenv("GT_ROOT", root)
|
||||
|
||||
s := newTestStoreWithPrefix(t, filepath.Join(t.TempDir(), "test.db"), "test")
|
||||
ctx := context.Background()
|
||||
vars := map[string]string{"env": "staging"} // not in the parent's enum
|
||||
|
||||
_, discoverErr := discoverMolBondOperand(ctx, s, "discover-child", vars)
|
||||
_, materializeErr := materializeMolBondOperand(ctx, s,
|
||||
&molBondDiscovery{operand: "discover-child"}, vars)
|
||||
|
||||
if materializeErr == nil {
|
||||
t.Fatal("materialization accepted a var value outside the inherited enum")
|
||||
}
|
||||
if discoverErr == nil {
|
||||
t.Fatalf("discovery accepted a var value materialization rejects; the enum is declared only in the parent (materialization said: %v)", materializeErr)
|
||||
}
|
||||
for name, err := range map[string]error{"discovery": discoverErr, "materialization": materializeErr} {
|
||||
if !errors.Is(err, formula.ErrVarValidation) {
|
||||
t.Errorf("%s error does not wrap formula.ErrVarValidation: %v", name, err)
|
||||
}
|
||||
}
|
||||
if discoverErr.Error() != materializeErr.Error() {
|
||||
t.Errorf("discovery and materialization report different errors:\n discovery: %v\n materialization: %v", discoverErr, materializeErr)
|
||||
}
|
||||
}
|
||||
363
cmd/bd/routed.go
363
cmd/bd/routed.go
|
|
@ -6,17 +6,22 @@ import (
|
|||
"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.
|
||||
|
|
@ -30,6 +35,15 @@ func isNotFoundErr(err error) bool {
|
|||
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
|
||||
|
|
@ -43,31 +57,51 @@ type RoutedResult struct {
|
|||
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 contributor auto-routing.
|
||||
// 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.
|
||||
//
|
||||
// Prefix-routed target stores 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).
|
||||
// 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 prefix-routed target stores in
|
||||
// writable mode so mutation commands can commit to the routed repository.
|
||||
// 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, writablePrefixRoute bool) (*RoutedResult, error) {
|
||||
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 {
|
||||
|
|
@ -78,17 +112,20 @@ func resolveAndGetIssueWithRoutingAccess(ctx context.Context, localStore storage
|
|||
// 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, writablePrefixRoute, false); prefixErr == nil {
|
||||
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 contributor auto-routing as fallback (GH#2345).
|
||||
// Auto-routed stores stay read-only even for write-intent callers (writablePrefixRoute):
|
||||
// this path hydrates foreign contributor projects, which must never be mutated.
|
||||
// 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 := resolveViaAutoRouting(ctx, localStore, id, false); autoErr == nil {
|
||||
if autoResult, autoErr := resolveViaAutoRoutingWithAccess(ctx, localStore, id, writable, false); autoErr == nil {
|
||||
return autoResult, nil
|
||||
} else if isRoutingFailure(autoErr) {
|
||||
return nil, autoErr
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -162,19 +199,23 @@ func resolveAndGetFromStoreExact(ctx context.Context, s storage.DoltStorage, id
|
|||
// 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 contributor
|
||||
// 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
|
||||
// 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").
|
||||
// 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
|
||||
|
|
@ -182,47 +223,53 @@ func resolveAndGetIssueForMutationExact(ctx context.Context, localStore storage.
|
|||
// 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.
|
||||
// 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
|
||||
|
||||
if isNotFoundErr(err) {
|
||||
prefixResult, prefixErr := resolveViaPrefixRoutingWithAccess(ctx, id, true, true)
|
||||
if prefixErr == nil {
|
||||
return prefixResult, nil
|
||||
}
|
||||
if errors.Is(prefixErr, utils.ErrAbbreviatedIDNotAllowed) {
|
||||
abbrevErr = prefixErr
|
||||
}
|
||||
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
|
||||
}
|
||||
|
||||
if isNotFoundErr(err) {
|
||||
autoResult, autoErr := resolveViaAutoRouting(ctx, localStore, id, true)
|
||||
if autoErr == nil {
|
||||
return autoResult, nil
|
||||
}
|
||||
if abbrevErr == nil && errors.Is(autoErr, utils.ErrAbbreviatedIDNotAllowed) {
|
||||
abbrevErr = autoErr
|
||||
}
|
||||
}
|
||||
|
||||
if abbrevErr != nil {
|
||||
// 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
|
||||
}
|
||||
|
||||
// resolveViaAutoRouting attempts to find an issue using contributor auto-routing.
|
||||
// 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 resolveViaAutoRouting(ctx context.Context, localStore storage.DoltStorage, id string, exact bool) (*RoutedResult, error) {
|
||||
routedStore, routed, _, err := openRoutedReadStore(ctx, localStore)
|
||||
if err != nil || !routed {
|
||||
return nil, fmt.Errorf("no auto-routed store available")
|
||||
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
|
||||
|
|
@ -267,69 +314,25 @@ func resolveViaPrefixRouting(ctx context.Context, id string) (*RoutedResult, err
|
|||
// the routed store lookup, mirroring resolveAndGetFromStore vs
|
||||
// resolveAndGetFromStoreExact.
|
||||
func resolveViaPrefixRoutingWithAccess(ctx context.Context, id string, writable bool, exact bool) (*RoutedResult, error) {
|
||||
if strings.Index(id, "-") <= 0 {
|
||||
return nil, fmt.Errorf("no prefix in ID %q", id)
|
||||
matchedRoute, targetBeadsDir, err := lookupPrefixRoute(id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Find the resolved beads directory (where routes.jsonl lives)
|
||||
currentBeadsDir := resolveCommandBeadsDir(dbPath)
|
||||
if currentBeadsDir == "" {
|
||||
return nil, fmt.Errorf("no beads directory available")
|
||||
}
|
||||
|
||||
// Load routes from routes.jsonl
|
||||
routes, err := loadPrefixRoutes(currentBeadsDir)
|
||||
if err != nil || len(routes) == 0 {
|
||||
return nil, fmt.Errorf("no routes available")
|
||||
}
|
||||
|
||||
// Find the most specific route for this ID
|
||||
matchedRoute := matchPrefixRoute(routes, id)
|
||||
if matchedRoute == nil {
|
||||
return nil, fmt.Errorf("no route for ID %q", id)
|
||||
}
|
||||
prefix := matchedRoute.Prefix
|
||||
|
||||
// Skip if the route points to current directory (town-level, already checked)
|
||||
if matchedRoute.Path == "." {
|
||||
return nil, fmt.Errorf("route points to current database")
|
||||
}
|
||||
|
||||
// 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)
|
||||
targetBeadsDir := beads.FollowRedirect(filepath.Join(rigDir, ".beads"))
|
||||
|
||||
// Check that the target has a different dolt_database
|
||||
targetDB := readDoltDatabase(targetBeadsDir)
|
||||
if targetDB == "" {
|
||||
return nil, fmt.Errorf("target rig has no dolt_database configured")
|
||||
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", prefix, matchedRoute.Path, targetDB)
|
||||
debug.Logf("[routing] Prefix %q matched route to %s (database: %s)\n", matchedRoute.Prefix, matchedRoute.Path, targetDB)
|
||||
|
||||
// We need to temporarily override BEADS_DOLT_SERVER_DATABASE so server-mode
|
||||
// stores connect to the correct database on the shared Dolt server.
|
||||
origDB := os.Getenv("BEADS_DOLT_SERVER_DATABASE")
|
||||
_ = os.Setenv("BEADS_DOLT_SERVER_DATABASE", targetDB)
|
||||
var targetStore storage.DoltStorage
|
||||
var openErr error
|
||||
if writable {
|
||||
targetStore, openErr = newDoltStoreFromConfig(ctx, targetBeadsDir)
|
||||
} else {
|
||||
targetStore, openErr = newReadOnlyStoreFromConfig(ctx, targetBeadsDir)
|
||||
}
|
||||
// Restore the original env var
|
||||
if origDB != "" {
|
||||
_ = os.Setenv("BEADS_DOLT_SERVER_DATABASE", origDB)
|
||||
} else {
|
||||
_ = os.Unsetenv("BEADS_DOLT_SERVER_DATABASE")
|
||||
}
|
||||
if openErr != nil {
|
||||
return nil, fmt.Errorf("opening routed store for %s: %w", matchedRoute.Path, openErr)
|
||||
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
|
||||
|
|
@ -351,6 +354,91 @@ func resolveViaPrefixRoutingWithAccess(ctx context.Context, id string, writable
|
|||
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
|
||||
|
|
@ -396,52 +484,57 @@ func loadPrefixRoutes(beadsDir string) ([]prefixRoute, error) {
|
|||
return routes, scanner.Err()
|
||||
}
|
||||
|
||||
// readDoltDatabase reads the dolt_database field from a .beads/metadata.json file.
|
||||
func readDoltDatabase(beadsDir string) string {
|
||||
// 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 ""
|
||||
return "", err
|
||||
}
|
||||
var meta struct {
|
||||
DoltDatabase string `json:"dolt_database"`
|
||||
}
|
||||
if json.Unmarshal(data, &meta) != nil {
|
||||
return ""
|
||||
if err := json.Unmarshal(data, &meta); err != nil {
|
||||
return "", fmt.Errorf("parsing %s: %w", metadataPath, err)
|
||||
}
|
||||
return meta.DoltDatabase
|
||||
return meta.DoltDatabase, nil
|
||||
}
|
||||
|
||||
// getIssueWithRouting gets an issue by exact ID.
|
||||
// Tries the local store first, then prefix-based routing, then contributor auto-routing.
|
||||
// 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).
|
||||
//
|
||||
// Returns a RoutedResult containing the issue and the store to use for related queries.
|
||||
// The caller MUST call result.Close() when done to release any routed storage.
|
||||
func getIssueWithRouting(ctx context.Context, localStore storage.DoltStorage, id string) (*RoutedResult, error) {
|
||||
// Try local store first.
|
||||
issue, err := localStore.GetIssue(ctx, id)
|
||||
if err == nil {
|
||||
return &RoutedResult{
|
||||
Issue: issue,
|
||||
Store: localStore,
|
||||
Routed: false,
|
||||
ResolvedID: id,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// If not found locally, try prefix-based routing via routes.jsonl.
|
||||
if isNotFoundErr(err) {
|
||||
if prefixResult, prefixErr := resolveViaPrefixRouting(ctx, id); prefixErr == nil {
|
||||
return prefixResult, nil
|
||||
// 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"))
|
||||
}
|
||||
|
||||
// If not found via prefix routing, try contributor auto-routing as fallback (GH#2345).
|
||||
if isNotFoundErr(err) {
|
||||
if autoResult, autoErr := resolveViaAutoRouting(ctx, localStore, id, false); autoErr == nil {
|
||||
return autoResult, nil
|
||||
}
|
||||
}
|
||||
|
||||
return nil, err
|
||||
return database, nil
|
||||
}
|
||||
|
|
|
|||
730
cmd/bd/routed_mutation_test.go
Normal file
730
cmd/bd/routed_mutation_test.go
Normal file
|
|
@ -0,0 +1,730 @@
|
|||
//go:build cgo
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/steveyegge/beads/internal/configfile"
|
||||
"github.com/steveyegge/beads/internal/storage"
|
||||
"github.com/steveyegge/beads/internal/storage/embeddeddolt"
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
)
|
||||
|
||||
// setupAutoRoute builds a git repo with the given beads.role whose store
|
||||
// auto-routes, through routingKey (routing.maintainer, routing.contributor,
|
||||
// ...), to a planning workspace holding the issue "shared-hub" and any
|
||||
// extraSeeds, and changes into the repo. It returns the repo's store and the
|
||||
// repo and planning directories.
|
||||
func setupAutoRoute(t *testing.T, role, routingKey string, extraSeeds ...string) (storage.DoltStorage, string, string) {
|
||||
t.Helper()
|
||||
initConfigForTest(t)
|
||||
neutralizeRoutingModeEnv(t)
|
||||
ctx := context.Background()
|
||||
|
||||
tmpDir := t.TempDir()
|
||||
repoDir := filepath.Join(tmpDir, "repo")
|
||||
planningDir := filepath.Join(tmpDir, "planning")
|
||||
|
||||
runCmd(t, tmpDir, "git", "init", repoDir)
|
||||
// Force repo-local hooks so tests ignore any global hooksPath override.
|
||||
runCmd(t, repoDir, "git", "config", "core.hooksPath", ".git/hooks")
|
||||
runCmd(t, repoDir, "git", "config", "beads.role", role)
|
||||
|
||||
primaryStore := newTestStoreIsolatedDB(t, filepath.Join(repoDir, ".beads", "beads.db"), "shared")
|
||||
if err := primaryStore.SetConfig(ctx, "routing.mode", "auto"); err != nil {
|
||||
t.Fatalf("set routing.mode: %v", err)
|
||||
}
|
||||
if err := primaryStore.SetConfig(ctx, routingKey, planningDir); err != nil {
|
||||
t.Fatalf("set %s: %v", routingKey, err)
|
||||
}
|
||||
|
||||
planningStore := newTestStoreIsolatedDB(t, filepath.Join(planningDir, ".beads", "beads.db"), "shared")
|
||||
seedIssue(t, ctx, planningStore, "shared-hub")
|
||||
for _, id := range extraSeeds {
|
||||
seedIssue(t, ctx, planningStore, id)
|
||||
}
|
||||
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 an
|
||||
// earlier test in this binary may have built for its own, now-deleted
|
||||
// repo. Rebuild it from repoDir.
|
||||
resetRepoContextCachesForTest(t)
|
||||
|
||||
return primaryStore, repoDir, planningDir
|
||||
}
|
||||
|
||||
// neutralizeRoutingModeEnv clears the environment variables that override the
|
||||
// routing.mode a routing test writes into its store. Viper binds
|
||||
// BEADS_ROUTING_MODE / BD_ROUTING_MODE onto the routing.mode key
|
||||
// (internal/config), which outranks the store's routing.mode=auto. Hosts that
|
||||
// export either var (developer shells and agent runtimes do) would otherwise
|
||||
// read routing.mode=off and never route.
|
||||
func neutralizeRoutingModeEnv(t *testing.T) {
|
||||
t.Helper()
|
||||
t.Setenv("BEADS_ROUTING_MODE", "")
|
||||
t.Setenv("BD_ROUTING_MODE", "")
|
||||
}
|
||||
|
||||
// routedStoreIsReadOnly reports whether a routed store was opened read-only.
|
||||
// The tests check this on the store itself because a server-mode read-only
|
||||
// open does not refuse a write, so a write that goes through cannot tell the
|
||||
// two opens apart.
|
||||
func routedStoreIsReadOnly(t *testing.T, s storage.DoltStorage) bool {
|
||||
t.Helper()
|
||||
routedStore, ok := storage.UnwrapStore(s).(interface{ IsReadOnly() bool })
|
||||
if !ok {
|
||||
t.Fatalf("routed store %T does not expose read-only state", s)
|
||||
}
|
||||
return routedStore.IsReadOnly()
|
||||
}
|
||||
|
||||
// requireWritableAutoRoute fails unless the write-intent resolution rr, made
|
||||
// for what, came through an auto-route that opened its target writable.
|
||||
func requireWritableAutoRoute(t *testing.T, what string, rr *RoutedResult) {
|
||||
t.Helper()
|
||||
if !rr.Routed {
|
||||
t.Fatalf("%s resolved %s without routing; want the auto-route", what, rr.ResolvedID)
|
||||
}
|
||||
if routedStoreIsReadOnly(t, rr.Store) {
|
||||
t.Fatalf("%s: the auto-route opened its target read-only for a write", what)
|
||||
}
|
||||
}
|
||||
|
||||
// TestMaintainerAutoRouteMutationWritesThrough covers the widened
|
||||
// openAutoRoutedStore behavior for write-intent callers beyond mol bond:
|
||||
// resolveAndGetIssueForMutation is the resolver bd update uses, and a
|
||||
// maintainer auto-routed store must open writable so the mutation actually
|
||||
// commits in the routed database. (TestContributorAutoRouteWritesThrough
|
||||
// covers the contributor route.)
|
||||
func TestMaintainerAutoRouteMutationWritesThrough(t *testing.T) {
|
||||
primaryStore, _, _ := setupAutoRoute(t, "maintainer", "routing.maintainer")
|
||||
ctx := context.Background()
|
||||
|
||||
rr, err := resolveAndGetIssueForMutation(ctx, primaryStore, "shared-hub")
|
||||
if err != nil {
|
||||
t.Fatalf("resolveAndGetIssueForMutation: %v", err)
|
||||
}
|
||||
defer rr.Close()
|
||||
requireWritableAutoRoute(t, "update", rr)
|
||||
if err := rr.Store.UpdateIssue(ctx, rr.ResolvedID, map[string]interface{}{"priority": 0}, "test"); err != nil {
|
||||
t.Fatalf("update through the maintainer auto-route: %v", err)
|
||||
}
|
||||
rr.Close()
|
||||
|
||||
// Verify through a fresh routed read that the update committed in the
|
||||
// planning database, not in a doomed in-memory handle.
|
||||
reread, err := resolveAndGetIssueWithRouting(ctx, primaryStore, "shared-hub")
|
||||
if err != nil {
|
||||
t.Fatalf("re-reading the routed issue: %v", err)
|
||||
}
|
||||
defer reread.Close()
|
||||
if reread.Issue.Priority != 0 {
|
||||
t.Fatalf("priority = %d after routed update, want 0", reread.Issue.Priority)
|
||||
}
|
||||
}
|
||||
|
||||
// TestMaintainerAutoRouteExactMutationWritesThrough is the same pin for
|
||||
// resolveAndGetIssueForMutationExact, the exact-match resolver bd comment and
|
||||
// bd comments add use (#5393): the maintainer auto-route must open writable,
|
||||
// as any other write-intent resolution does, and a comment written through it
|
||||
// must commit in the routed database.
|
||||
func TestMaintainerAutoRouteExactMutationWritesThrough(t *testing.T) {
|
||||
primaryStore, _, _ := setupAutoRoute(t, "maintainer", "routing.maintainer")
|
||||
ctx := context.Background()
|
||||
|
||||
rr, err := resolveAndGetIssueForMutationExact(ctx, primaryStore, "shared-hub")
|
||||
if err != nil {
|
||||
t.Fatalf("resolveAndGetIssueForMutationExact: %v", err)
|
||||
}
|
||||
defer rr.Close()
|
||||
requireWritableAutoRoute(t, "exact-match comment", rr)
|
||||
if _, err := addCommentDirect(ctx, rr.Store, rr.ResolvedID, "test", "routed comment"); err != nil {
|
||||
t.Fatalf("comment through the maintainer auto-route: %v", err)
|
||||
}
|
||||
rr.Close()
|
||||
|
||||
reread, err := resolveAndGetIssueWithRouting(ctx, primaryStore, "shared-hub")
|
||||
if err != nil {
|
||||
t.Fatalf("re-reading the routed issue: %v", err)
|
||||
}
|
||||
defer reread.Close()
|
||||
comments, err := reread.Store.GetIssueComments(ctx, reread.ResolvedID)
|
||||
if err != nil {
|
||||
t.Fatalf("reading routed comments: %v", err)
|
||||
}
|
||||
if len(comments) != 1 || comments[0].Text != "routed comment" {
|
||||
t.Fatalf("comments = %+v after the routed comment write, want the one written", comments)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAutoRouteCloseTargetWriteIntent covers bd close's shared auto-routed
|
||||
// store, which resolveCloseTargets opens with the same write intent as
|
||||
// resolveAndGetIssueForMutation: a maintainer auto-route opens writable and the
|
||||
// close commits in the routed database. (TestContributorAutoRouteWritesThrough
|
||||
// covers the contributor route.)
|
||||
func TestAutoRouteCloseTargetWriteIntent(t *testing.T) {
|
||||
t.Run("maintainer_writes_through", func(t *testing.T) {
|
||||
primaryStore, _, _ := setupAutoRoute(t, "maintainer", "routing.maintainer")
|
||||
ctx := context.Background()
|
||||
|
||||
results, cleanup, err := resolveCloseTargets(ctx, primaryStore, []string{"shared-hub"})
|
||||
if err != nil {
|
||||
t.Fatalf("resolveCloseTargets: %v", err)
|
||||
}
|
||||
defer cleanup()
|
||||
if len(results) != 1 || !results[0].Routed {
|
||||
t.Fatalf("results = %+v, want one auto-routed close target", results)
|
||||
}
|
||||
if routedStoreIsReadOnly(t, results[0].Store) {
|
||||
t.Fatalf("maintainer auto-route opened read-only for bd close")
|
||||
}
|
||||
if err := results[0].Store.CloseIssue(ctx, results[0].ResolvedID, "done", "test", ""); err != nil {
|
||||
t.Fatalf("close through the maintainer auto-route: %v", err)
|
||||
}
|
||||
cleanup()
|
||||
|
||||
reread, err := resolveAndGetIssueWithRouting(ctx, primaryStore, "shared-hub")
|
||||
if err != nil {
|
||||
t.Fatalf("re-reading the routed issue: %v", err)
|
||||
}
|
||||
defer reread.Close()
|
||||
if reread.Issue.Status != types.StatusClosed {
|
||||
t.Fatalf("status = %s after the routed close, want %s", reread.Issue.Status, types.StatusClosed)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestContributorAutoRouteWritesThrough pins the contributor side of the
|
||||
// write-intent resolvers: a contributor's auto-route target is their own
|
||||
// planning repository, the one bd create writes to, so bd update, bd comment
|
||||
// and bd close of an issue found there commit there (GH#2345, beads-0km).
|
||||
// Each route must open writable, since a server-mode read-only open does not
|
||||
// refuse a write (routedStoreIsReadOnly), while a read through the same route
|
||||
// stays read-only. An id the route does not hold is still a plain not-found.
|
||||
func TestContributorAutoRouteWritesThrough(t *testing.T) {
|
||||
primaryStore, _, _ := setupAutoRoute(t, "contributor", "routing.contributor")
|
||||
ctx := context.Background()
|
||||
|
||||
writes := []struct {
|
||||
name string
|
||||
write func(id string) error
|
||||
}{
|
||||
{"update (resolveAndGetIssueForMutation)", func(id string) error {
|
||||
rr, err := resolveAndGetIssueForMutation(ctx, primaryStore, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer rr.Close()
|
||||
requireWritableAutoRoute(t, "update", rr)
|
||||
return rr.Store.UpdateIssue(ctx, rr.ResolvedID, map[string]interface{}{"priority": 0}, "test")
|
||||
}},
|
||||
{"comment (resolveAndGetIssueForMutationExact)", func(id string) error {
|
||||
rr, err := resolveAndGetIssueForMutationExact(ctx, primaryStore, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer rr.Close()
|
||||
requireWritableAutoRoute(t, "comment", rr)
|
||||
_, err = addCommentDirect(ctx, rr.Store, rr.ResolvedID, "test", "routed comment")
|
||||
return err
|
||||
}},
|
||||
{"close (resolveCloseTargets)", func(id string) error {
|
||||
results, cleanup, err := resolveCloseTargets(ctx, primaryStore, []string{id})
|
||||
defer cleanup()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
requireWritableAutoRoute(t, "close", results[0])
|
||||
return results[0].Store.CloseIssue(ctx, results[0].ResolvedID, "done", "test", "")
|
||||
}},
|
||||
}
|
||||
for _, w := range writes {
|
||||
if err := w.write("shared-hub"); err != nil {
|
||||
t.Fatalf("%s of a contributor-routed issue: %v", w.name, err)
|
||||
}
|
||||
if err := w.write("shared-zzzz"); !isNotFoundErr(err) {
|
||||
t.Errorf("%s of an id the route does not hold: err = %v, want not-found", w.name, err)
|
||||
}
|
||||
}
|
||||
|
||||
// Verify through a fresh routed read that every write committed in the
|
||||
// planning database.
|
||||
reread, err := resolveAndGetIssueWithRouting(ctx, primaryStore, "shared-hub")
|
||||
if err != nil {
|
||||
t.Fatalf("re-reading the routed issue: %v", err)
|
||||
}
|
||||
defer reread.Close()
|
||||
if !reread.Routed {
|
||||
t.Fatalf("re-read resolved shared-hub without routing; want the contributor auto-route")
|
||||
}
|
||||
if !routedStoreIsReadOnly(t, reread.Store) {
|
||||
t.Fatalf("the contributor auto-route opened writable for a read")
|
||||
}
|
||||
if reread.Issue.Priority != 0 || reread.Issue.Status != types.StatusClosed {
|
||||
t.Fatalf("priority = %d, status = %s after the routed writes, want 0 and %s", reread.Issue.Priority, reread.Issue.Status, types.StatusClosed)
|
||||
}
|
||||
comments, err := reread.Store.GetIssueComments(ctx, reread.ResolvedID)
|
||||
if err != nil {
|
||||
t.Fatalf("reading routed comments: %v", err)
|
||||
}
|
||||
if len(comments) != 1 || comments[0].Text != "routed comment" {
|
||||
t.Fatalf("comments = %+v after the routed comment write, want the one written", comments)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRoutedMutationResolversReportRoutingFailures pins that every
|
||||
// write-intent resolver reports a route it cannot follow as that failure, not
|
||||
// as the local "no issue found matching", which would send the user looking
|
||||
// for an issue that exists. Each routing tier gets a target whose
|
||||
// metadata.json is unloadable or names no dolt_database, which a write refuses
|
||||
// on either tier.
|
||||
func TestRoutedMutationResolversReportRoutingFailures(t *testing.T) {
|
||||
t.Run("auto_route_store_fails_to_open", func(t *testing.T) {
|
||||
primaryStore, _, planningDir := setupAutoRoute(t, "maintainer", "routing.maintainer")
|
||||
// Corrupted after the issue is seeded, so the route resolves but its
|
||||
// store cannot open.
|
||||
if err := os.WriteFile(filepath.Join(planningDir, ".beads", "metadata.json"), []byte("{not json"), 0o600); err != nil {
|
||||
t.Fatalf("corrupt planning metadata.json: %v", err)
|
||||
}
|
||||
requireMutationResolversReport(t, primaryStore, "shared-hub", "failed to open routed store")
|
||||
})
|
||||
|
||||
t.Run("auto_route_target_names_no_database", func(t *testing.T) {
|
||||
primaryStore, repoDir, planningDir := setupAutoRoute(t, "contributor", "routing.contributor")
|
||||
// With no dolt_database of the target's own, the open would take the
|
||||
// launcher's from BEADS_DOLT_SERVER_DATABASE.
|
||||
launcherDB, err := loadDoltDatabase(filepath.Join(repoDir, ".beads"))
|
||||
if err != nil || launcherDB == "" {
|
||||
t.Fatalf("the launcher's metadata.json names no dolt_database (err = %v)", err)
|
||||
}
|
||||
t.Setenv("BEADS_DOLT_SERVER_DATABASE", launcherDB)
|
||||
writeTestMetadata(t, filepath.Join(planningDir, ".beads", "beads.db"), "")
|
||||
requireMutationResolversReport(t, primaryStore, "shared-hub", "no dolt_database field")
|
||||
})
|
||||
|
||||
t.Run("prefix_route_target_unloadable", func(t *testing.T) {
|
||||
initConfigForTest(t)
|
||||
tmpDir := t.TempDir()
|
||||
townBeadsDir := filepath.Join(tmpDir, ".beads")
|
||||
rigBeadsDir := filepath.Join(tmpDir, "rig", ".beads")
|
||||
for _, dir := range []string{townBeadsDir, rigBeadsDir} {
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
t.Fatalf("create %s: %v", dir, err)
|
||||
}
|
||||
}
|
||||
townDBPath := filepath.Join(townBeadsDir, "dolt")
|
||||
townStore := newTestStoreIsolatedDB(t, townDBPath, "hq")
|
||||
if err := os.WriteFile(filepath.Join(townBeadsDir, "routes.jsonl"), []byte("{\"prefix\":\"gt-\",\"path\":\"rig\"}\n"), 0o600); err != nil {
|
||||
t.Fatalf("write routes.jsonl: %v", err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(rigBeadsDir, "metadata.json"), []byte("{not json"), 0o600); err != nil {
|
||||
t.Fatalf("write rig metadata.json: %v", err)
|
||||
}
|
||||
|
||||
oldDbPath := dbPath
|
||||
dbPath = townDBPath
|
||||
t.Cleanup(func() { dbPath = oldDbPath })
|
||||
oldWD, err := os.Getwd()
|
||||
if err != nil {
|
||||
t.Fatalf("getwd: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = os.Chdir(oldWD) })
|
||||
if err := os.Chdir(tmpDir); err != nil {
|
||||
t.Fatalf("chdir: %v", err)
|
||||
}
|
||||
|
||||
requireMutationResolversReport(t, townStore, "gt-hub", "no dolt_database configured")
|
||||
})
|
||||
}
|
||||
|
||||
// TestRoutedWriteDoesNotCreateTargetDatabase pins that a write-intent routed
|
||||
// open refuses an embedded target that holds no database yet instead of
|
||||
// creating one there. The open runs before the lookup it serves, so an id that
|
||||
// misses would leave an empty database behind, and `bd bootstrap` would then
|
||||
// take it for the real one and skip the clone from sync.remote. Each tier
|
||||
// routes to a fresh clone: an embedded metadata.json and no embeddeddolt
|
||||
// directory.
|
||||
func TestRoutedWriteDoesNotCreateTargetDatabase(t *testing.T) {
|
||||
// Server mode from the environment would send the target's open to a
|
||||
// server, which never creates a missing database; this pins the embedded
|
||||
// open.
|
||||
t.Setenv("BEADS_DOLT_SERVER_MODE", "")
|
||||
t.Setenv("BEADS_DOLT_SHARED_SERVER", "")
|
||||
t.Setenv("BEADS_DOLT_SERVER_HOST", "")
|
||||
|
||||
t.Run("auto_route", func(t *testing.T) {
|
||||
primaryStore, _, _ := setupAutoRoute(t, "maintainer", "routing.maintainer")
|
||||
targetDir := filepath.Join(t.TempDir(), "fresh-clone")
|
||||
targetBeadsDir := filepath.Join(targetDir, ".beads")
|
||||
writeEmbeddedMetadata(t, targetBeadsDir, "fresh")
|
||||
if err := primaryStore.SetConfig(context.Background(), "routing.maintainer", targetDir); err != nil {
|
||||
t.Fatalf("set routing.maintainer: %v", err)
|
||||
}
|
||||
|
||||
requireMutationResolversReport(t, primaryStore, "shared-zzzz", "no embedded database")
|
||||
requireNoEmbeddedDatabase(t, targetBeadsDir)
|
||||
})
|
||||
|
||||
t.Run("prefix_route", func(t *testing.T) {
|
||||
initConfigForTest(t)
|
||||
tmpDir := t.TempDir()
|
||||
townBeadsDir := filepath.Join(tmpDir, ".beads")
|
||||
rigBeadsDir := filepath.Join(tmpDir, "rig", ".beads")
|
||||
townDBPath := filepath.Join(townBeadsDir, "dolt")
|
||||
townStore := newTestStoreIsolatedDB(t, townDBPath, "hq")
|
||||
if err := os.WriteFile(filepath.Join(townBeadsDir, "routes.jsonl"), []byte("{\"prefix\":\"gt-\",\"path\":\"rig\"}\n"), 0o600); err != nil {
|
||||
t.Fatalf("write routes.jsonl: %v", err)
|
||||
}
|
||||
writeEmbeddedMetadata(t, rigBeadsDir, "rig")
|
||||
|
||||
oldDbPath := dbPath
|
||||
dbPath = townDBPath
|
||||
t.Cleanup(func() { dbPath = oldDbPath })
|
||||
oldWD, err := os.Getwd()
|
||||
if err != nil {
|
||||
t.Fatalf("getwd: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = os.Chdir(oldWD) })
|
||||
if err := os.Chdir(tmpDir); err != nil {
|
||||
t.Fatalf("chdir: %v", err)
|
||||
}
|
||||
|
||||
requireMutationResolversReport(t, townStore, "gt-zzzz", "no embedded database")
|
||||
requireNoEmbeddedDatabase(t, rigBeadsDir)
|
||||
})
|
||||
}
|
||||
|
||||
// writeEmbeddedMetadata writes the metadata.json of an embedded workspace that
|
||||
// names database, as a fresh clone has before `bd bootstrap` runs.
|
||||
func writeEmbeddedMetadata(t *testing.T, beadsDir, database string) {
|
||||
t.Helper()
|
||||
if err := os.MkdirAll(beadsDir, 0o755); err != nil {
|
||||
t.Fatalf("create %s: %v", beadsDir, err)
|
||||
}
|
||||
cfg := &configfile.Config{
|
||||
Database: "dolt",
|
||||
Backend: configfile.BackendDolt,
|
||||
DoltMode: configfile.DoltModeEmbedded,
|
||||
DoltDatabase: database,
|
||||
}
|
||||
if err := cfg.Save(beadsDir); err != nil {
|
||||
t.Fatalf("write %s metadata.json: %v", beadsDir, err)
|
||||
}
|
||||
}
|
||||
|
||||
// requireNoEmbeddedDatabase fails if anything created beadsDir's embedded
|
||||
// database directory.
|
||||
func requireNoEmbeddedDatabase(t *testing.T, beadsDir string) {
|
||||
t.Helper()
|
||||
if _, err := os.Stat(filepath.Join(beadsDir, "embeddeddolt")); !errors.Is(err, os.ErrNotExist) {
|
||||
t.Fatalf("%s: embeddeddolt stat err = %v after a routed write missed, want it absent", beadsDir, err)
|
||||
}
|
||||
}
|
||||
|
||||
// requireMutationResolversReport resolves id through every write-intent
|
||||
// resolver and fails unless each returns the routing failure containing want.
|
||||
func requireMutationResolversReport(t *testing.T, localStore storage.DoltStorage, id, want string) {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
resolvers := []struct {
|
||||
name string
|
||||
resolve func() error
|
||||
}{
|
||||
{"resolveAndGetIssueForMutation", func() error {
|
||||
rr, err := resolveAndGetIssueForMutation(ctx, localStore, id)
|
||||
if err == nil {
|
||||
rr.Close()
|
||||
}
|
||||
return err
|
||||
}},
|
||||
{"resolveAndGetIssueForMutationExact", func() error {
|
||||
rr, err := resolveAndGetIssueForMutationExact(ctx, localStore, id)
|
||||
if err == nil {
|
||||
rr.Close()
|
||||
}
|
||||
return err
|
||||
}},
|
||||
{"resolveCloseTargets", func() error {
|
||||
_, cleanup, err := resolveCloseTargets(ctx, localStore, []string{id})
|
||||
cleanup()
|
||||
return err
|
||||
}},
|
||||
}
|
||||
for _, r := range resolvers {
|
||||
err := r.resolve()
|
||||
if err == nil || isNotFoundErr(err) || !strings.Contains(err.Error(), want) {
|
||||
t.Errorf("%s: err = %v, want the routing failure %q", r.name, err, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestAutoRouteOpensTargetDatabaseDespiteEnv pins that an auto-routed store
|
||||
// opens the target's own dolt_database. BEADS_DOLT_SERVER_DATABASE outranks
|
||||
// metadata.json and names the launching workspace's database (set by the user,
|
||||
// or by preserveRedirectSourceDatabase after a redirect), so without the
|
||||
// override a routed open connects to the launcher's database, where the issue
|
||||
// is not, and a writable one would commit there.
|
||||
func TestAutoRouteOpensTargetDatabaseDespiteEnv(t *testing.T) {
|
||||
primaryStore, repoDir, _ := setupAutoRoute(t, "maintainer", "routing.maintainer")
|
||||
ctx := context.Background()
|
||||
launcherDB, err := loadDoltDatabase(filepath.Join(repoDir, ".beads"))
|
||||
if err != nil || launcherDB == "" {
|
||||
t.Fatalf("the launcher's metadata.json names no dolt_database (err = %v)", err)
|
||||
}
|
||||
t.Setenv("BEADS_DOLT_SERVER_DATABASE", launcherDB)
|
||||
|
||||
resolvers := []struct {
|
||||
name string
|
||||
resolve func(context.Context, storage.DoltStorage, string) (*RoutedResult, error)
|
||||
}{
|
||||
{"resolveAndGetIssueWithRouting", resolveAndGetIssueWithRouting},
|
||||
{"resolveAndGetIssueForMutation", resolveAndGetIssueForMutation},
|
||||
}
|
||||
for _, r := range resolvers {
|
||||
rr, err := r.resolve(ctx, primaryStore, "shared-hub")
|
||||
if err != nil {
|
||||
t.Fatalf("%s with BEADS_DOLT_SERVER_DATABASE=%s: %v", r.name, launcherDB, err)
|
||||
}
|
||||
routed := rr.Routed
|
||||
rr.Close()
|
||||
if !routed {
|
||||
t.Fatalf("%s resolved shared-hub without routing", r.name)
|
||||
}
|
||||
if got := os.Getenv("BEADS_DOLT_SERVER_DATABASE"); got != launcherDB {
|
||||
t.Fatalf("%s left BEADS_DOLT_SERVER_DATABASE = %q, want %q restored", r.name, got, launcherDB)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestAutoRouteMissWithoutMetadataIgnoresEnv pins that an auto-route to a
|
||||
// target with no metadata.json opens the only database the target holds,
|
||||
// whatever BEADS_DOLT_SERVER_DATABASE says at use. Contributor setup names that
|
||||
// database after the variable when it is set and the default database
|
||||
// otherwise, and the target's open resolves its name the same way, the
|
||||
// variable first, so a launcher whose variable differed from setup's used to
|
||||
// read a database that is not there and, writing, create one beside setup's:
|
||||
// an embedded writable open creates the database it is given when the target
|
||||
// holds another. Each target has the shape autoConfigureForkContributor
|
||||
// leaves, one embedded database and no metadata.json, and a miss, read or
|
||||
// written, reports not found and leaves it holding only that database.
|
||||
func TestAutoRouteMissWithoutMetadataIgnoresEnv(t *testing.T) {
|
||||
t.Setenv("BEADS_DOLT_SERVER_MODE", "")
|
||||
t.Setenv("BEADS_DOLT_SHARED_SERVER", "")
|
||||
t.Setenv("BEADS_DOLT_SERVER_HOST", "")
|
||||
primaryStore, repoDir, _ := setupAutoRoute(t, "maintainer", "routing.maintainer")
|
||||
launcherDB, err := loadDoltDatabase(filepath.Join(repoDir, ".beads"))
|
||||
if err != nil || launcherDB == "" || launcherDB == configfile.DefaultDoltDatabase {
|
||||
t.Fatalf("the launcher's metadata.json names dolt_database %q (err = %v), want one of its own", launcherDB, err)
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
targetDB string // the database setup created
|
||||
useDB string // BEADS_DOLT_SERVER_DATABASE at use
|
||||
}{
|
||||
{"setup_without_variable", configfile.DefaultDoltDatabase, launcherDB},
|
||||
{"setup_with_variable", launcherDB, launcherDB},
|
||||
{"setup_with_variable_unset_at_use", launcherDB, ""},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
t.Setenv("BEADS_DOLT_SERVER_DATABASE", tt.useDB)
|
||||
targetDir := filepath.Join(t.TempDir(), "planning")
|
||||
seedEmbeddedSchema(t, targetDir, tt.targetDB)
|
||||
if err := primaryStore.SetConfig(context.Background(), "routing.maintainer", targetDir); err != nil {
|
||||
t.Fatalf("set routing.maintainer: %v", err)
|
||||
}
|
||||
|
||||
for _, writable := range []bool{false, true} {
|
||||
rr, err := resolveAndGetIssueWithRoutingAccess(context.Background(), primaryStore, "shared-zzzz", writable)
|
||||
if err == nil {
|
||||
rr.Close()
|
||||
t.Fatalf("resolved shared-zzzz (writable %v), which no workspace holds", writable)
|
||||
}
|
||||
if !isNotFoundErr(err) {
|
||||
t.Fatalf("resolve shared-zzzz (writable %v): err = %v, want not found", writable, err)
|
||||
}
|
||||
}
|
||||
entries, err := os.ReadDir(filepath.Join(targetDir, ".beads", "embeddeddolt"))
|
||||
if err != nil {
|
||||
t.Fatalf("read the target's embeddeddolt: %v", err)
|
||||
}
|
||||
var databases []string
|
||||
for _, entry := range entries {
|
||||
if entry.IsDir() {
|
||||
databases = append(databases, entry.Name())
|
||||
}
|
||||
}
|
||||
if len(databases) != 1 || databases[0] != tt.targetDB {
|
||||
t.Fatalf("the target holds databases %v after a routed miss, want only %q", databases, tt.targetDB)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestRoutedWriteRetryCommitsFailedCommit pins that the retry of a routed write
|
||||
// whose commit failed commits it. The write reaches the target's working set
|
||||
// before the commit runs, so the retry finds the issue already released or
|
||||
// closed and refuses; nothing else commits a routed target, so the refusal
|
||||
// commits the pending write first. The run whose commit failed reports no
|
||||
// success: bd unclaim neither prints the release nor emits it in --json. The
|
||||
// launcher and the rig are embedded, and the commit fails on an invalid
|
||||
// auto-commit mode, after the write.
|
||||
func TestRoutedWriteRetryCommitsFailedCommit(t *testing.T) {
|
||||
saveStorageMode(t)
|
||||
saveAndRestoreGlobals(t)
|
||||
serverMode, proxiedServerMode = false, false
|
||||
t.Setenv("BEADS_DOLT_SERVER_MODE", "")
|
||||
t.Setenv("BEADS_DOLT_SERVER_HOST", "")
|
||||
initConfigForTest(t)
|
||||
ctx := context.Background()
|
||||
|
||||
actorMu.Lock()
|
||||
savedActor, savedPending := actor, actorGitFallbackPending
|
||||
actor, actorGitFallbackPending = "alice", false
|
||||
actorMu.Unlock()
|
||||
savedRootCtx, savedJSON, savedDidWrite := rootCtx, jsonOutput, commandDidWrite.Load()
|
||||
rootCtx = ctx
|
||||
t.Cleanup(func() {
|
||||
actorMu.Lock()
|
||||
actor, actorGitFallbackPending = savedActor, savedPending
|
||||
actorMu.Unlock()
|
||||
rootCtx, jsonOutput = savedRootCtx, savedJSON
|
||||
commandDidWrite.Store(savedDidWrite)
|
||||
})
|
||||
|
||||
tmpDir := t.TempDir()
|
||||
townBeadsDir := filepath.Join(tmpDir, ".beads")
|
||||
rigDir := filepath.Join(tmpDir, "rig")
|
||||
rigBeadsDir := filepath.Join(rigDir, ".beads")
|
||||
|
||||
writeEmbeddedMetadata(t, rigBeadsDir, "rig")
|
||||
seedEmbeddedSchema(t, rigDir, "rig")
|
||||
rig, err := embeddeddolt.Open(ctx, rigBeadsDir, "rig", "main")
|
||||
if err != nil {
|
||||
t.Fatalf("open rig: %v", err)
|
||||
}
|
||||
if err := rig.SetConfig(ctx, "issue_prefix", "gt"); err != nil {
|
||||
t.Fatalf("set rig issue_prefix: %v", err)
|
||||
}
|
||||
for _, issue := range []*types.Issue{
|
||||
{ID: "gt-rel1", Status: types.StatusInProgress, Assignee: "alice"},
|
||||
{ID: "gt-rel2", Status: types.StatusInProgress, Assignee: "alice"},
|
||||
{ID: "gt-resp", Status: types.StatusOpen},
|
||||
{ID: "gt-dism", Status: types.StatusOpen},
|
||||
} {
|
||||
issue.Title, issue.Priority, issue.IssueType = "routed "+issue.ID, 2, types.TypeTask
|
||||
if err := rig.CreateIssue(ctx, issue, "test"); err != nil {
|
||||
t.Fatalf("seed %s: %v", issue.ID, err)
|
||||
}
|
||||
}
|
||||
if err := rig.Commit(ctx, "seed"); err != nil {
|
||||
t.Fatalf("commit rig seed: %v", err)
|
||||
}
|
||||
if err := rig.Close(); err != nil {
|
||||
t.Fatalf("close rig: %v", err)
|
||||
}
|
||||
|
||||
writeEmbeddedMetadata(t, townBeadsDir, "hq")
|
||||
seedEmbeddedSchema(t, tmpDir, "hq")
|
||||
town, err := embeddeddolt.Open(ctx, townBeadsDir, "hq", "main")
|
||||
if err != nil {
|
||||
t.Fatalf("open town: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = town.Close() })
|
||||
if err := town.SetConfig(ctx, "issue_prefix", "hq"); err != nil {
|
||||
t.Fatalf("set town issue_prefix: %v", err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(townBeadsDir, "routes.jsonl"), []byte("{\"prefix\":\"gt-\",\"path\":\"rig\"}\n"), 0o600); err != nil {
|
||||
t.Fatalf("write routes.jsonl: %v", err)
|
||||
}
|
||||
store = town
|
||||
storeMutex.Lock()
|
||||
storeActive = true
|
||||
storeMutex.Unlock()
|
||||
dbPath = filepath.Join(townBeadsDir, "dolt")
|
||||
t.Chdir(tmpDir)
|
||||
|
||||
unclaim := func(id string) error { return unclaimCmd.RunE(unclaimCmd, []string{id}) }
|
||||
released := func(issue *types.Issue) bool { return issue.Assignee == "" && issue.Status == types.StatusOpen }
|
||||
closed := func(issue *types.Issue) bool { return issue.Status == types.StatusClosed }
|
||||
cases := []struct {
|
||||
name string
|
||||
id string
|
||||
json bool
|
||||
run func(id string) error
|
||||
written func(*types.Issue) bool
|
||||
refusal string // the retry's, on the write it finds pending
|
||||
}{
|
||||
{"unclaim", "gt-rel1", false, unclaim, released, "issue gt-rel1 is not assigned"},
|
||||
{"unclaim --json", "gt-rel2", true, unclaim, released, "issue gt-rel2 is not assigned"},
|
||||
{"human respond", "gt-resp", false, func(id string) error {
|
||||
return humanRespondCmd.RunE(humanRespondCmd, []string{id, "approved"})
|
||||
}, closed, "issue gt-resp is already closed"},
|
||||
{"human dismiss", "gt-dism", false, func(id string) error {
|
||||
return humanDismissCmd.RunE(humanDismissCmd, []string{id})
|
||||
}, closed, "issue gt-dism is already closed"},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
jsonOutput = tc.json
|
||||
var err error
|
||||
run := func() (string, string) {
|
||||
return captureStdio(t, func() { err = tc.run(tc.id) })
|
||||
}
|
||||
|
||||
doltAutoCommit = "bogus"
|
||||
stdout, stderr := run()
|
||||
if err == nil || stdout != "" {
|
||||
t.Fatalf("run whose commit failed: err = %v, stdout = %q; want a failure and no output", err, stdout)
|
||||
}
|
||||
if !strings.Contains(stderr, `invalid --dolt-auto-commit="bogus"`) {
|
||||
t.Fatalf("run whose commit failed: stderr = %q, want the commit failure", stderr)
|
||||
}
|
||||
if tc.written(committedIssue(t, rigBeadsDir, "rig", tc.id)) {
|
||||
t.Fatalf("%s: the rig's HEAD holds the write whose commit failed", tc.id)
|
||||
}
|
||||
|
||||
doltAutoCommit = string(doltAutoCommitOn)
|
||||
_, stderr = run()
|
||||
if err == nil || !strings.Contains(stderr, tc.refusal) {
|
||||
t.Fatalf("retry: err = %v, stderr = %q; want the refusal %q", err, stderr, tc.refusal)
|
||||
}
|
||||
if !tc.written(committedIssue(t, rigBeadsDir, "rig", tc.id)) {
|
||||
t.Fatalf("%s: the retry left the write uncommitted", tc.id)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// committedIssue returns id as the HEAD commit of beadsDir's database holds
|
||||
// it, without what the working set holds uncommitted.
|
||||
func committedIssue(t *testing.T, beadsDir, database, id string) *types.Issue {
|
||||
t.Helper()
|
||||
s, err := embeddeddolt.Open(t.Context(), beadsDir, database, "main")
|
||||
if err != nil {
|
||||
t.Fatalf("open %s: %v", beadsDir, err)
|
||||
}
|
||||
defer func() { _ = s.Close() }()
|
||||
issue, err := s.AsOf(t.Context(), id, "HEAD")
|
||||
if err != nil {
|
||||
t.Fatalf("read %s at HEAD: %v", id, err)
|
||||
}
|
||||
return issue
|
||||
}
|
||||
|
|
@ -1,6 +1,10 @@
|
|||
package main
|
||||
|
||||
import "testing"
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestMatchPrefixRoute pins longest-prefix route selection: multi-hyphen
|
||||
// route prefixes must match their IDs instead of being shadowed by a
|
||||
|
|
@ -41,3 +45,53 @@ func TestMatchPrefixRoute(t *testing.T) {
|
|||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestAutoRouteTargetDatabase pins the dolt_database an auto-routed open takes
|
||||
// from its target's metadata.json: a write refuses a file it cannot parse or
|
||||
// that names no database, which a read tolerates. A target with no
|
||||
// metadata.json, the planning repository contributor setup leaves, opens the
|
||||
// only embedded database it holds either way, and its default database when it
|
||||
// holds none or several.
|
||||
func TestAutoRouteTargetDatabase(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
metadata string // metadata.json content; "" writes no file
|
||||
databases []string // embedded databases the target holds
|
||||
want string
|
||||
wantErr bool // for a writable open; a read never errs
|
||||
}{
|
||||
{"names_database", `{"dolt_database":"planning"}`, []string{"proj"}, "planning", false},
|
||||
{"no_metadata_json", "", nil, "beads", false},
|
||||
{"no_metadata_json_one_database", "", []string{"proj"}, "proj", false},
|
||||
{"no_metadata_json_several_databases", "", []string{"alpha", "proj"}, "beads", false},
|
||||
{"no_database_field", `{"backend":"dolt"}`, []string{"proj"}, "", true},
|
||||
{"unparseable", "{not json", nil, "", true},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
beadsDir := t.TempDir()
|
||||
for _, database := range tt.databases {
|
||||
marker := filepath.Join(beadsDir, "embeddeddolt", database, ".dolt")
|
||||
if err := os.MkdirAll(marker, 0o700); err != nil {
|
||||
t.Fatalf("create database %s: %v", database, err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(marker, "opaque-entry"), nil, 0o600); err != nil {
|
||||
t.Fatalf("fill database %s: %v", database, err)
|
||||
}
|
||||
}
|
||||
if tt.metadata != "" {
|
||||
if err := os.WriteFile(filepath.Join(beadsDir, "metadata.json"), []byte(tt.metadata), 0o600); err != nil {
|
||||
t.Fatalf("write metadata.json: %v", err)
|
||||
}
|
||||
}
|
||||
got, err := autoRouteTargetDatabase(beadsDir, true)
|
||||
if got != tt.want || (err != nil) != tt.wantErr {
|
||||
t.Errorf("writable: got (%q, %v), want (%q, error %v)", got, err, tt.want, tt.wantErr)
|
||||
}
|
||||
got, err = autoRouteTargetDatabase(beadsDir, false)
|
||||
if got != tt.want || err != nil {
|
||||
t.Errorf("read-only: got (%q, %v), want (%q, nil)", got, err, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -175,6 +175,20 @@ func printContributorRoutingNotice(ctx context.Context, localStore storage.DoltS
|
|||
// returned routing.RoutingRule identifies which rule matched, for callers
|
||||
// that print a routing notice.
|
||||
func openRoutedReadStore(ctx context.Context, store storage.DoltStorage) (storage.DoltStorage, bool, routing.RoutingRule, error) {
|
||||
return openAutoRoutedStore(ctx, store, false)
|
||||
}
|
||||
|
||||
// openAutoRoutedStore opens the target selected by auto-routing. Every rule,
|
||||
// maintainer, contributor and default alike, opens writable when writable is
|
||||
// set, for write-intent callers (resolveAndGetIssueForMutation and its exact
|
||||
// twin, bd close target resolution) that commit the change where the issue
|
||||
// lives. A contributor's target is their own planning repository, the one bd
|
||||
// create already writes to, so a planning issue is claimed, commented on and
|
||||
// closed there (GH#2345, beads-0km). Reads stay read-only.
|
||||
//
|
||||
// The target opens its own dolt_database, as a prefix route does
|
||||
// (openRoutedTargetStore, autoRouteTargetDatabase).
|
||||
func openAutoRoutedStore(ctx context.Context, store storage.DoltStorage, writable bool) (storage.DoltStorage, bool, routing.RoutingRule, error) {
|
||||
repoPath, rule := determineAutoRoutedRepoPath(ctx, store)
|
||||
if repoPath == "" || repoPath == "." {
|
||||
return nil, false, routing.RuleNone, nil
|
||||
|
|
@ -182,7 +196,11 @@ func openRoutedReadStore(ctx context.Context, store storage.DoltStorage) (storag
|
|||
|
||||
targetRepoPath := routing.ExpandPath(repoPath)
|
||||
targetBeadsDir := filepath.Join(targetRepoPath, ".beads")
|
||||
targetStore, err := newReadOnlyStoreFromConfig(ctx, targetBeadsDir)
|
||||
database, err := autoRouteTargetDatabase(targetBeadsDir, writable)
|
||||
if err != nil {
|
||||
return nil, false, rule, fmt.Errorf("failed to open routed store at %s: target has no dolt_database configured: %w", targetRepoPath, err)
|
||||
}
|
||||
targetStore, err := openRoutedTargetStore(ctx, targetBeadsDir, database, writable)
|
||||
if err != nil {
|
||||
return nil, false, rule, fmt.Errorf("failed to open routed store at %s: %w", targetRepoPath, err)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -143,7 +143,8 @@ func logRolePath(branch, path string, redirected bool) string {
|
|||
|
||||
// rolePathNotARepoWarned limits warnIfRolePathIsNotARepo to one warning per
|
||||
// process: an ID lookup falls back to auto-routing once per missing ID
|
||||
// (resolveViaAutoRouting), and every fallback re-runs role detection.
|
||||
// (resolveViaAutoRoutingWithAccess), and every fallback re-runs role
|
||||
// detection.
|
||||
var rolePathNotARepoWarned bool
|
||||
|
||||
// warnIfRolePathIsNotARepo warns when role detection is about to read beads.role
|
||||
|
|
|
|||
|
|
@ -155,7 +155,27 @@ func acquireEmbeddedLock(beadsDir string, serverMode bool) (util.Unlocker, error
|
|||
// keeps that true for the dolt.shared-server layer; the one deliberate
|
||||
// exception is BEADS_DOLT_SHARED_SERVER, which is machine-global in every
|
||||
// resolver in the tree (see sharedServerModeForWorkspace).
|
||||
func newDoltStoreFromConfig(ctx context.Context, beadsDir string) (s storage.DoltStorage, err error) {
|
||||
func newDoltStoreFromConfig(ctx context.Context, beadsDir string) (storage.DoltStorage, error) {
|
||||
return openDoltStoreFromConfig(ctx, beadsDir, false)
|
||||
}
|
||||
|
||||
// newExistingDoltStoreFromConfig is newDoltStoreFromConfig for a write routed
|
||||
// to another workspace (a prefix route or an auto-route, see
|
||||
// openRoutedTargetStore): it opens that workspace's database writable, but
|
||||
// refuses an embedded workspace that holds no database yet instead of creating
|
||||
// one there. The routed open runs before the lookup it serves, so a created
|
||||
// database would outlive an id that misses, and `bd bootstrap` would then take
|
||||
// the empty database for the real one and skip the clone from sync.remote. The
|
||||
// probe is embeddeddolt.HasRepository, the adapter's own marker check. A
|
||||
// server-mode open already refuses a missing database: it does not set
|
||||
// CreateIfMissing.
|
||||
func newExistingDoltStoreFromConfig(ctx context.Context, beadsDir string) (storage.DoltStorage, error) {
|
||||
return openDoltStoreFromConfig(ctx, beadsDir, true)
|
||||
}
|
||||
|
||||
// openDoltStoreFromConfig is the body of newDoltStoreFromConfig and
|
||||
// newExistingDoltStoreFromConfig; requireExisting selects the latter.
|
||||
func openDoltStoreFromConfig(ctx context.Context, beadsDir string, requireExisting bool) (s storage.DoltStorage, err error) {
|
||||
defer func() { s, err = activateEventsJournalStore(beadsDir, s, err) }()
|
||||
cfg, err := configfile.Load(beadsDir)
|
||||
if err != nil {
|
||||
|
|
@ -179,6 +199,12 @@ func newDoltStoreFromConfig(ctx context.Context, beadsDir string) (s storage.Dol
|
|||
if effectiveServerMode(beadsDir, cfg) {
|
||||
return dolt.NewFromConfig(ctx, beadsDir)
|
||||
}
|
||||
// Refuse before the sanitize migration below, which renames the legacy
|
||||
// directory and rewrites metadata.json: a refused open writes nothing.
|
||||
if requireExisting && !embeddeddolt.HasRepository(beadsDir) {
|
||||
return nil, fmt.Errorf("embeddeddolt: no embedded database at %s; a routed write does not create one (run 'bd bootstrap' in that repository first)",
|
||||
filepath.Join(beadsDir, "embeddeddolt"))
|
||||
}
|
||||
database := configfile.DefaultDoltDatabase
|
||||
if cfg != nil {
|
||||
database = cfg.GetDoltDatabase()
|
||||
|
|
|
|||
|
|
@ -89,6 +89,14 @@ func newDoltStoreFromConfig(ctx context.Context, beadsDir string) (s storage.Dol
|
|||
return nil, fmt.Errorf("%s", nocgoEmbeddedErrMsg)
|
||||
}
|
||||
|
||||
// newExistingDoltStoreFromConfig is the non-CGO twin of the CGO build's
|
||||
// routed-write factory. That one differs from newDoltStoreFromConfig only by
|
||||
// refusing to create a missing EMBEDDED database, and this build has no
|
||||
// embedded store; a server-mode open never creates a missing database.
|
||||
func newExistingDoltStoreFromConfig(ctx context.Context, beadsDir string) (storage.DoltStorage, error) {
|
||||
return newDoltStoreFromConfig(ctx, beadsDir)
|
||||
}
|
||||
|
||||
// newReadOnlyStoreFromConfig creates a read-only SQL-server-backed storage
|
||||
// backend. It does not activate the events journal: the store refuses writes,
|
||||
// so there is no mutation for a journal row to accompany (exemption is recorded
|
||||
|
|
|
|||
|
|
@ -78,8 +78,9 @@ Examples:
|
|||
diagHint())
|
||||
}
|
||||
for _, id := range args {
|
||||
// Resolve with prefix routing
|
||||
result, err := resolveAndGetIssueWithRouting(ctx, store, id)
|
||||
// Resolve with routing, opening a routed target writable so the
|
||||
// unclaim commits where the issue lives (as bd update --claim does).
|
||||
result, err := resolveAndGetIssueForMutation(ctx, store, id)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error resolving %s: %v\n", id, err)
|
||||
hasError = true
|
||||
|
|
@ -97,6 +98,15 @@ Examples:
|
|||
if unclaimErr != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error unclaiming %s: %v\n", fullID, unclaimErr)
|
||||
hasError = true
|
||||
// An unclaim whose routed commit failed left its release in
|
||||
// the target's working set, where this run finds the issue
|
||||
// unassigned. Nothing else commits a routed target, so
|
||||
// commit the release here.
|
||||
if result.Issue != nil && result.Issue.Assignee == "" {
|
||||
if err := commitRoutedWrite(ctx, result, "unclaim"); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error committing unclaim of %s: %v\n", fullID, err)
|
||||
}
|
||||
}
|
||||
result.Close()
|
||||
continue
|
||||
}
|
||||
|
|
@ -107,6 +117,14 @@ Examples:
|
|||
}
|
||||
}
|
||||
|
||||
// A release whose commit failed is not reported as unclaimed.
|
||||
if err := commitRoutedWrite(ctx, result, "unclaim"); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error committing unclaim of %s: %v\n", fullID, err)
|
||||
hasError = true
|
||||
result.Close()
|
||||
continue
|
||||
}
|
||||
|
||||
if jsonOutput {
|
||||
updated, _ := issueStore.GetIssue(ctx, fullID)
|
||||
if updated != nil {
|
||||
|
|
|
|||
|
|
@ -243,6 +243,73 @@ func TestEmbeddedUpdateRoutedStoreCommitsTargetHead(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
// TestEmbeddedRoutedWriteMissDoesNotCreateTargetDatabase pins that a routed
|
||||
// write whose id misses leaves an embedded target that has not been
|
||||
// bootstrapped yet without a database. The routed open runs before the lookup
|
||||
// it serves, so a database it created would outlive the miss, and `bd
|
||||
// bootstrap` there would then take it for the real one and skip the clone.
|
||||
// tgt-zzzz takes the prefix route and src-zzzz the maintainer auto-route; both
|
||||
// lead to the same fresh clone.
|
||||
func TestEmbeddedRoutedWriteMissDoesNotCreateTargetDatabase(t *testing.T) {
|
||||
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
|
||||
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded dolt update tests")
|
||||
}
|
||||
t.Parallel()
|
||||
|
||||
bd := buildEmbeddedBD(t)
|
||||
dir, beadsDir, _ := bdInit(t, bd, "--prefix", "src")
|
||||
|
||||
targetDir := filepath.Join(dir, "fresh-clone")
|
||||
if err := os.MkdirAll(targetDir, 0750); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
initGitRepoAt(t, targetDir)
|
||||
targetBeadsDir := filepath.Join(targetDir, ".beads")
|
||||
writeEmbeddedMetadata(t, targetBeadsDir, "tgt")
|
||||
|
||||
route := `{"prefix":"tgt-","path":"fresh-clone"}` + "\n"
|
||||
if err := os.WriteFile(filepath.Join(beadsDir, "routes.jsonl"), []byte(route), 0644); err != nil {
|
||||
t.Fatalf("write routes.jsonl: %v", err)
|
||||
}
|
||||
roleCmd := gitCommand("config", "beads.role", "maintainer")
|
||||
roleCmd.Dir = dir
|
||||
if out, err := roleCmd.CombinedOutput(); err != nil {
|
||||
t.Fatalf("git config beads.role: %v\n%s", err, out)
|
||||
}
|
||||
|
||||
env := bdEnv(dir)
|
||||
runBD := func(args ...string) (string, error) {
|
||||
cmd := exec.Command(bd, args...)
|
||||
cmd.Dir = dir
|
||||
cmd.Env = env
|
||||
out, err := cmd.CombinedOutput()
|
||||
return string(out), err
|
||||
}
|
||||
for _, args := range [][]string{
|
||||
{"config", "set", "routing.mode", "auto"},
|
||||
{"config", "set", "routing.maintainer", targetDir},
|
||||
} {
|
||||
if out, err := runBD(args...); err != nil {
|
||||
t.Fatalf("bd %s failed: %v\n%s", strings.Join(args, " "), err, out)
|
||||
}
|
||||
}
|
||||
|
||||
for _, args := range [][]string{
|
||||
{"update", "tgt-zzzz", "--priority", "0"},
|
||||
{"close", "tgt-zzzz"},
|
||||
{"update", "src-zzzz", "--priority", "0"},
|
||||
{"close", "src-zzzz"},
|
||||
} {
|
||||
t.Run(strings.Join(args, " "), func(t *testing.T) {
|
||||
out, err := runBD(args...)
|
||||
requireNoEmbeddedDatabase(t, targetBeadsDir)
|
||||
if err == nil || !strings.Contains(out, "no embedded database") {
|
||||
t.Fatalf("err = %v, want the routed open's refusal\n%s", err, out)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// The TestEmbeddedUpdateFields* and TestEmbeddedUpdateLifecycle* tests were
|
||||
// split from TestEmbeddedUpdate (originally ~267s, measured under
|
||||
// --config=embedded), first into TestEmbeddedUpdateFields and
|
||||
|
|
|
|||
|
|
@ -45,7 +45,19 @@ flowchart TD
|
|||
|
||||
Reads follow the same routing: with routing active, `bd list` and `bd ready`
|
||||
read from the routed repository, and ID lookups like `bd show` fall back to
|
||||
the routed repository when a bead isn't found locally.
|
||||
the routed repository when a bead isn't found locally. Commands that change an
|
||||
existing bead (`bd update`, `bd close`, `bd comment`, `bd unclaim`,
|
||||
`bd mol bond` and the like) follow every route, contributor, maintainer and
|
||||
default alike, opening the routed repository for writing so the change commits
|
||||
there. A routed write never creates the routed repository's database: if that
|
||||
repository has not been bootstrapped yet, the write fails until you run
|
||||
`bd bootstrap` there. A routed write also refuses a repository whose
|
||||
`.beads/metadata.json` is unreadable or names no `dolt_database`, instead of
|
||||
guessing which database to write. Through these routes a repository with no
|
||||
`metadata.json` at all, such as a planning repository nothing has been created
|
||||
in yet, opens the one embedded database it holds, or its default database when
|
||||
it holds none or several; a prefix route in an orchestrator's `routes.jsonl`
|
||||
always needs the target's `dolt_database`, for reads as well as writes.
|
||||
|
||||
## Role detection
|
||||
|
||||
|
|
|
|||
|
|
@ -10,16 +10,24 @@ import (
|
|||
// non-symlink directory with at least one entry, but entry names and private
|
||||
// repository files are never interpreted or opened.
|
||||
func HasRepository(beadsDir string) bool {
|
||||
return len(Databases(beadsDir)) > 0
|
||||
}
|
||||
|
||||
// Databases names, sorted, the databases of beadsDir's embedded Dolt
|
||||
// repository: the non-symlink directories under embeddeddolt that pass
|
||||
// HasRepository's .dolt marker probe. It is empty when beadsDir holds none.
|
||||
func Databases(beadsDir string) []string {
|
||||
root := filepath.Join(beadsDir, "embeddeddolt")
|
||||
info, err := os.Lstat(root)
|
||||
if err != nil || !info.IsDir() || info.Mode()&os.ModeSymlink != 0 {
|
||||
return false
|
||||
return nil
|
||||
}
|
||||
databases, err := os.ReadDir(root)
|
||||
entries, err := os.ReadDir(root)
|
||||
if err != nil {
|
||||
return false
|
||||
return nil
|
||||
}
|
||||
for _, database := range databases {
|
||||
var databases []string
|
||||
for _, database := range entries {
|
||||
if !database.IsDir() || database.Type()&os.ModeSymlink != 0 {
|
||||
continue
|
||||
}
|
||||
|
|
@ -27,10 +35,10 @@ func HasRepository(beadsDir string) bool {
|
|||
if err != nil || !marker.IsDir() || marker.Mode()&os.ModeSymlink != 0 {
|
||||
continue
|
||||
}
|
||||
entries, err := os.ReadDir(filepath.Join(root, database.Name(), ".dolt"))
|
||||
if err == nil && len(entries) > 0 {
|
||||
return true
|
||||
markerEntries, err := os.ReadDir(filepath.Join(root, database.Name(), ".dolt"))
|
||||
if err == nil && len(markerEntries) > 0 {
|
||||
databases = append(databases, database.Name())
|
||||
}
|
||||
}
|
||||
return false
|
||||
return databases
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ package embeddeddolt
|
|||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"testing"
|
||||
)
|
||||
|
||||
|
|
@ -75,3 +76,81 @@ func TestHasRepository(t *testing.T) {
|
|||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDatabases(t *testing.T) {
|
||||
// seed creates database under root with a nonempty .dolt marker.
|
||||
seed := func(t *testing.T, root, database string) {
|
||||
t.Helper()
|
||||
marker := filepath.Join(root, database, ".dolt")
|
||||
if err := os.MkdirAll(marker, 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(marker, "opaque-entry"), []byte("not inspected"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
setup func(t *testing.T, beadsDir string)
|
||||
want []string
|
||||
}{
|
||||
{name: "missing root"},
|
||||
{
|
||||
name: "one database",
|
||||
setup: func(t *testing.T, beadsDir string) {
|
||||
seed(t, filepath.Join(beadsDir, "embeddeddolt"), "proj")
|
||||
},
|
||||
want: []string{"proj"},
|
||||
},
|
||||
{
|
||||
name: "several databases are sorted",
|
||||
setup: func(t *testing.T, beadsDir string) {
|
||||
root := filepath.Join(beadsDir, "embeddeddolt")
|
||||
seed(t, root, "proj")
|
||||
seed(t, root, "beads")
|
||||
},
|
||||
want: []string{"beads", "proj"},
|
||||
},
|
||||
{
|
||||
name: "entries failing the marker probe are skipped",
|
||||
setup: func(t *testing.T, beadsDir string) {
|
||||
t.Helper()
|
||||
root := filepath.Join(beadsDir, "embeddeddolt")
|
||||
seed(t, root, "proj")
|
||||
if err := os.MkdirAll(filepath.Join(root, "empty", ".dolt"), 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(root, "notes"), nil, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Symlink(filepath.Join(root, "proj"), filepath.Join(root, "linked")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
},
|
||||
want: []string{"proj"},
|
||||
},
|
||||
{
|
||||
name: "symlink root is refused",
|
||||
setup: func(t *testing.T, beadsDir string) {
|
||||
t.Helper()
|
||||
elsewhere := t.TempDir()
|
||||
seed(t, elsewhere, "proj")
|
||||
if err := os.Symlink(elsewhere, filepath.Join(beadsDir, "embeddeddolt")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
beadsDir := t.TempDir()
|
||||
if tt.setup != nil {
|
||||
tt.setup(t, beadsDir)
|
||||
}
|
||||
if got := Databases(beadsDir); !slices.Equal(got, tt.want) {
|
||||
t.Fatalf("Databases() = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue