* 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>
247 lines
8.4 KiB
Go
247 lines
8.4 KiB
Go
//go:build cgo
|
|
|
|
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"os"
|
|
"os/exec"
|
|
"path/filepath"
|
|
"strings"
|
|
"testing"
|
|
|
|
"github.com/steveyegge/beads/internal/storage/embeddeddolt"
|
|
"github.com/steveyegge/beads/internal/types"
|
|
)
|
|
|
|
// The TestEmbeddedContributorCreate* tests exercise the full contributor mode flow in
|
|
// embedded Dolt: init → contributor wizard → create. This is the exact
|
|
// scenario that triggered GH#2988 ("no database selected" when the planning
|
|
// repo's .beads directory has no metadata.json).
|
|
func TestEmbeddedContributorCreateRoutesToPlanning(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)
|
|
|
|
t.Run("create_routes_to_planning_repo", func(t *testing.T) {
|
|
dir, planningDir := initContributor(t, bd, "cr")
|
|
|
|
// Create an issue — should route to the planning repo, not the project.
|
|
issue := bdCreate(t, bd, dir, "Contributor issue")
|
|
if issue.ID == "" {
|
|
t.Fatal("expected issue ID")
|
|
}
|
|
if !strings.HasPrefix(issue.ID, "cr-") {
|
|
t.Errorf("ID should have prefix cr-, got %q", issue.ID)
|
|
}
|
|
|
|
// Verify the issue landed in the planning repo's embedded store.
|
|
// The planning store database name is the sanitized prefix (same as source).
|
|
planningBeadsDir := filepath.Join(planningDir, ".beads")
|
|
assertIssueInStore(t, planningBeadsDir, "cr", issue.ID)
|
|
|
|
// Verify the issue is NOT in the project's store.
|
|
projectBeadsDir := filepath.Join(dir, ".beads")
|
|
assertIssueNotInStore(t, projectBeadsDir, "cr", issue.ID)
|
|
})
|
|
}
|
|
|
|
func TestEmbeddedContributorCreateShowReadsRouted(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)
|
|
|
|
t.Run("show_reads_routed_issue", func(t *testing.T) {
|
|
dir, _ := initContributor(t, bd, "sh")
|
|
|
|
issue := bdCreate(t, bd, dir, "Show me")
|
|
shown := bdShow(t, bd, dir, issue.ID)
|
|
if shown.Title != "Show me" {
|
|
t.Errorf("title: got %q, want %q", shown.Title, "Show me")
|
|
}
|
|
})
|
|
}
|
|
|
|
func TestEmbeddedContributorCreateMultiple(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)
|
|
|
|
t.Run("multiple_creates_succeed", func(t *testing.T) {
|
|
dir, planningDir := initContributor(t, bd, "mc")
|
|
|
|
ids := make(map[string]bool)
|
|
for i := 0; i < 3; i++ {
|
|
issue := bdCreate(t, bd, dir, fmt.Sprintf("Issue %d", i))
|
|
if issue.ID == "" {
|
|
t.Fatalf("create %d: expected issue ID", i)
|
|
}
|
|
if ids[issue.ID] {
|
|
t.Fatalf("create %d: duplicate ID %q", i, issue.ID)
|
|
}
|
|
ids[issue.ID] = true
|
|
}
|
|
|
|
// All three should be in the planning store.
|
|
planningBeadsDir := filepath.Join(planningDir, ".beads")
|
|
for id := range ids {
|
|
assertIssueInStore(t, planningBeadsDir, "mc", id)
|
|
}
|
|
})
|
|
}
|
|
|
|
// 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.
|
|
func initContributor(t *testing.T, bd, prefix string) (projectDir, planningDir string) {
|
|
t.Helper()
|
|
|
|
projectDir = t.TempDir()
|
|
planningDir = filepath.Join(t.TempDir(), "planning")
|
|
initGitRepoAt(t, projectDir)
|
|
|
|
// Run bd init with --contributor flag.
|
|
// The wizard prompts (no upstream remote):
|
|
// 1. "Continue with contributor setup? [y/N]:" → "y"
|
|
// 2. "Planning repo path [press Enter for default]:" → planningDir
|
|
args := []string{"init", "--quiet", "--prefix", prefix, "--contributor"}
|
|
cmd := exec.Command(bd, args...)
|
|
cmd.Dir = projectDir
|
|
cmd.Env = append(bdEnv(projectDir), "BD_NON_INTERACTIVE=0")
|
|
cmd.Stdin = strings.NewReader("y\n" + planningDir + "\n")
|
|
stdout, stderr, err := runCommandBuffers(t, cmd)
|
|
if err != nil {
|
|
t.Fatalf("bd init --contributor failed: %v\nstdout:\n%s\nstderr:\n%s", err, stdout.String(), stderr.String())
|
|
}
|
|
|
|
// Sanity: planning .beads dir should exist (created by wizard).
|
|
planningBeadsDir := filepath.Join(planningDir, ".beads")
|
|
requireFile(t, planningBeadsDir)
|
|
|
|
// Sanity: beads.role should be "contributor".
|
|
roleCmd := gitCommand("config", "beads.role")
|
|
roleCmd.Dir = projectDir
|
|
roleOut, err := roleCmd.Output()
|
|
if err != nil {
|
|
t.Fatalf("git config beads.role failed: %v", err)
|
|
}
|
|
if got := strings.TrimSpace(string(roleOut)); got != "contributor" {
|
|
t.Fatalf("beads.role: got %q, want %q", got, "contributor")
|
|
}
|
|
|
|
return projectDir, planningDir
|
|
}
|
|
|
|
// assertIssueInStore verifies that an issue with the given ID exists in the
|
|
// embedded Dolt store at beadsDir.
|
|
func assertIssueInStore(t *testing.T, beadsDir, database, issueID string) {
|
|
t.Helper()
|
|
dataDir := filepath.Join(beadsDir, "embeddeddolt")
|
|
db, cleanup, err := embeddeddolt.OpenSQL(t.Context(), dataDir, database, "main")
|
|
if err != nil {
|
|
t.Fatalf("OpenSQL(%s, %s): %v", beadsDir, database, err)
|
|
}
|
|
defer cleanup()
|
|
|
|
var count int
|
|
err = db.QueryRowContext(t.Context(),
|
|
"SELECT COUNT(*) FROM issues WHERE id = ?", issueID).Scan(&count)
|
|
if err != nil {
|
|
t.Fatalf("query issues for %s: %v", issueID, err)
|
|
}
|
|
if count == 0 {
|
|
t.Errorf("expected issue %s in store at %s, not found", issueID, beadsDir)
|
|
}
|
|
}
|
|
|
|
// assertIssueNotInStore verifies that an issue with the given ID does NOT
|
|
// exist in the embedded Dolt store at beadsDir.
|
|
func assertIssueNotInStore(t *testing.T, beadsDir, database, issueID string) {
|
|
t.Helper()
|
|
dataDir := filepath.Join(beadsDir, "embeddeddolt")
|
|
db, cleanup, err := embeddeddolt.OpenSQL(t.Context(), dataDir, database, "main")
|
|
if err != nil {
|
|
t.Fatalf("OpenSQL(%s, %s): %v", beadsDir, database, err)
|
|
}
|
|
defer cleanup()
|
|
|
|
var count int
|
|
err = db.QueryRowContext(t.Context(),
|
|
"SELECT COUNT(*) FROM issues WHERE id = ?", issueID).Scan(&count)
|
|
if err != nil {
|
|
t.Fatalf("query issues for %s: %v", issueID, err)
|
|
}
|
|
if count != 0 {
|
|
t.Errorf("issue %s should NOT be in store at %s, but found %d rows", issueID, beadsDir, count)
|
|
}
|
|
}
|