beads/cmd/bd/update_embedded_test.go
gascity-eddie[bot] 91a72ef7b5
fix(mol): route bond operand resolution like show/update/close (closes #4714) (follow-up to #4720) (#7622)
* fix(mol): route bond operand resolution like show/update/close (closes #4714)

bd mol bond resolved operands with utils.ResolvePartialID against the local
store only, so a bead that lived in a routed store failed with
"'<id>' not found (not an issue ID or formula name)" — even though bd show
resolved the same ID. This broke `gt sling <bead> <rig>`, which cooks the
default formula and bonds it to a rig-routed bead.

- Resolve operands through resolveAndGetIssueForMutation, the same routing
  fallback bd show/update/close use (local, then prefix-routed rig via
  routes.jsonl, then contributor auto-routing). Write-intent so a prefix-routed
  target opens writable and the bond commits where the bead lives.
- Run the bond mutation against the store that owns the resolved issue instead
  of the global local store; reject a bond whose two operands resolve to
  different stores rather than writing to the wrong database.
- Route the --dry-run preview read-only so it previews routed operands too.
- Add TestResolveMolBondOperandRouting covering local and routed resolution.

Same routing-parity fix as #3608/#3609 for bd close.

* fix(mol): fail fast on read-only routed stores, share same-rig bond handles

Address the two structural issues from the #4720 review beyond the rebase
itself (the rebase already preserves main's unconditional formula fallback
from #3874 instead of reintroducing the looksLikeFormulaName gate):

- Routed operands resolve but couldn't be bonded: contributor auto-routing
  deliberately opens stores read-only (they hydrate foreign projects that
  must never be mutated), yet the bond selected that store and dispatched
  mutations that only failed at the store layer. Operand resolution now
  mirrors resolveCloseTargets explicitly (local, then prefix-routed
  write-intent, then the shared auto-routed read-only handle) and records
  writability per operand; pickBondStore rejects a bond pinned to a
  read-only store with a clear message before any mutation is attempted.
  TestMolBondPrefixRoutedWriteThrough now verifies the actual dependency
  write commits in the routed database, not just resolution, and
  TestMolBondAutoRoutedReadOnlyFailsFast covers the fail-fast path.

- Same routed database compared as two different stores: pickBondStore
  compared Go handle identity, but each route-open constructs a fresh store
  in server mode, so two operands in the same routed rig were wrongly
  rejected as cross-store. Both operands of a bond now share one routed
  handle (an already-opened routed store is tried before opening another),
  and sameBondStore falls back to StoreLocator identity (CLIDir pins the
  concrete database) for separately-opened handles onto the same database.
  TestSameBondStoreSeparateHandles covers the two-handle case directly.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(mol): validate routed bond homes before mutation

Discover bond operands read-only, enforce dry-run parity and cross-store policy before writable reopen, unwrap decorated store identities, preserve actionable route failures, and verify the accepted home after reopen.

Co-authored-by: Johan Snyman <johan.snyman@orange.com>

Agent-Signature: codex-gpt-5.6-sol-high on behalf of matt wilkie

* fix(mol): reconcile routed bond discovery with #5253 var validation

The rebase onto current main carried two silent regressions the Aug 16
review named: the discovery-based resolution (which replaced
resolveOrDescribe on the direct-store path) never validated --var values,
so `bd mol bond --dry-run <formula> <x> --var bad=...` previewed success
for a bond execution refuses — exactly the false preview #5253 fixed —
and materializeMolBondOperand wrapped every cook error as
"'%s' not found as issue or formula", re-introducing the ErrVarValidation
double-wrap #5253 removed from resolveOrCookToSubgraph.

discoverMolBondOperand now takes the provided vars and runs
formula.ValidateProvidedVars on its formula fallback, so --dry-run and
execution reject the bond identically, before any writable reopen.
materializeMolBondOperand passes formula.ErrVarValidation through
unwrapped, matching resolveOrCookToSubgraph and pour/wisp.

Agent-Signature: claude-fable-5 on behalf of R0SEWT

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(mol): review polish — fs.ErrNotExist, hook-isolated test repos, auto-route coverage

Three non-blocking notes from the Aug 16 review:

- routed.go: errors.Is(err, fs.ErrNotExist) instead of the legacy
  os.IsNotExist, so the not-found check keeps working if loadPrefixRoutes
  ever starts wrapping its open error.
- mol_bond_routing_test.go: pin core.hooksPath to .git/hooks after each
  git init (the initGitRepoAt convention), so a developer or CI box with a
  global hooksPath override never runs foreign hooks inside test repos.
- The widened openAutoRoutedStore behavior (maintainer/default auto-routes
  open writable for any validated write-intent resolver, not just mol bond)
  now has both the CHANGELOG sentence and a write-through test:
  TestMaintainerAutoRouteMutationWritesThrough drives
  resolveAndGetIssueForMutation — the bd update resolver — through a
  maintainer auto-route, commits a real update there, and re-reads it via a
  fresh routed read.

Agent-Signature: claude-fable-5 on behalf of R0SEWT

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(mol): carry main's #5761 formula validation into routed bond discovery

Rebase adaptation for #4720 onto main b303d494df. The PR moved the direct
(non-proxied) `bd mol bond` path off resolveOrDescribe and
resolveOrCookToSubgraph onto discoverMolBondOperand and
materializeMolBondOperand. Main's #5761 meanwhile fixed the old pair so a
--dry-run fails on exactly what the real bond fails on; the new pair did not
have that fix:

- discoverMolBondOperand loaded the formula with parser.LoadByName, which
  never runs Formula.Validate, so a --dry-run previewed a successful bond for
  a formula the cook rejects (e.g. a waits_for gate with no spawner). It also
  validated --var values against the unmerged formula, so a var whose enum is
  declared only in a parent went unchecked. Discovery now resolves the
  formula with parser.Resolve first, the way resolveAndCookFormulaWithVars
  does, and wraps both failures the way the cook does, so --dry-run and
  execution report the same message.
- materializeMolBondOperand passed only formula.ErrVarValidation through
  unwrapped. A formula that fails validation was reported as "not found as
  issue or formula". formula.ErrValidation now passes through too, as in
  main's resolveOrCookToSubgraph.

TestDiscoverMolBondOperandRejectsWhatMaterializeRejects and
TestDiscoverMolBondOperandValidatesVarsAgainstTheMergedFormula assert the two
phases against each other, like main's TestBondDryRun* pair does for the
proxied route.

Also:
- The PR's routing tests now pass the `exact` argument that main's #5393
  added to resolveViaPrefixRoutingWithAccess. They pass false, which keeps
  the partial-ID resolution the tests were written against.
- The PR's three new cgo test files are added to the bd_test srcs. This is
  `make bazel-sync` output on the merged tree, and it touches nothing else.

Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Gas City Adopt-PR
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Rody Vilchez <102562850+R0SEWT@users.noreply.github.com>

* test(mol): rebuild the RepoContext cache in the PR's role-routing tests

Rebase adaptation for #4720 onto main b303d494df. Main's #5243 moved
auto-routing role detection onto beads.GetRepoContext(), which caches the
repo context once per process; before it, role detection ran
routing.DetectUserRole(".") on every call. The PR's auto-routing tests chdir
into a fresh repo and set beads.role there, so after the rebase they read
the context an earlier test built for its own, now-deleted repo. There
beads.role is unset, and the remote-URL fallback finds no origin and answers
maintainer:

- TestMolBondAutoRoutedReadOnlyFailsFast fails whenever a role-routing test
  ran before it in the same binary (reproducible alone with -count=2):
  discovery looks for the contributor operand in the local store and reports
  it not found.
- TestDiscoverMolBondOperandRouting/maintainer_routed_issue and
  TestMaintainerAutoRouteMutationWritesThrough still pass, but only because
  that fallback is also maintainer; they never read the beads.role they
  configure.

Each test now calls resetRepoContextCachesForTest after its chdir, as #5243
did for main's own role-routing tests (TestResolveCloseTargets, which
TestDiscoverMolBondOperandRouting mirrors, and the routing_read tests).

Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Gas City Adopt-PR
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Rody Vilchez <102562850+R0SEWT@users.noreply.github.com>

* fix(routing): open maintainer auto-routes writable for exact-match writes

#5393 landed after this PR was written. It moved `bd comment` and
`bd comments add` off resolveAndGetIssueForMutation onto a new
resolveAndGetIssueForMutationExact. This PR widens the former's auto-route
tier for write intent: a maintainer/default target opens writable, while a
contributor target stays read-only and MutationForbidden. On the PR's
original base that widening covered comment writes. After the rebase the
exact resolver still opened every auto-route read-only, so comment writes
lost it and the CHANGELOG's "any validated write-intent resolver" no longer
held.

The exact resolver is meant to keep the mutation resolver's routing
fallbacks and only tighten matching (#5393: it "keeps the existing
cross-rig prefix-routing and contributor auto-routing fallbacks intact").
Its auto tier now takes the same write-intent path. Matching stays exact,
and the abbreviation-refusal precedence is unchanged.

TestMaintainerAutoRouteExactMutationWritesThrough pins the change: the
routed store must not be read-only, and a comment written through it must
commit in the planning database. Without this change the read-only check
fails. The write itself still succeeds, because a server-mode read-only
open does not refuse it.

Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Gas City Adopt-PR
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Rody Vilchez <102562850+R0SEWT@users.noreply.github.com>

* fix(routing): harden routed writes and surface routing failures

Review fixes for #4720.

bd close resolved its batch's shared auto-route through
openRoutedReadStore, so the route opened read-only even though every
other write-intent resolver opened it writable. The shared handle now
opens through openAutoRoutedStore with write intent, so the close commits
where the issue lives.

A contributor auto-route now opens writable for write-intent callers, as
maintainer and default routes do. The refusal the previous revision added
(errContributorRouteMutationForbidden, contributorRouteRefusal,
RoutedResult.MutationForbidden) is gone. A contributor's route target is
their own planning repository, the one bd create writes to:
docs/multi-agent/multi-repo-migration.md and
examples/contributor-workflow/README.md have the contributor claim and
close planning issues from the fork, and GH#2345, beads-0km and GH#3608
made bd show, update and close reach those issues. The read-only rule
came from #4389's review fixes (e8ae7a291a), which kept "contributor
auto-routing" read-only to preserve the bd-6dnrw.32/GH#3231 guarantee
that "routed reads never mutate a foreign project's history". That
guarantee is about reads, and the planning repository is not a foreign
project. Base therefore split by backend: a server-mode bd update, close
or comment of a planning issue committed, because a read-only server
store accepts the write, while the embedded store refused it with "store
is read-only". Refusing in every resolver would have broken the
documented workflow on both backends. bd mol bond was the only command
that checked MutationForbidden, so its check goes too, and a bond of
planning issues commits in the planning repository like any other routed
write. Reads through every route stay read-only. This reverses the
previous revision's stance and is flagged here as a maintainer call.

bd unclaim now resolves its issue through resolveAndGetIssueForMutation,
as bd update --claim does, so a routed issue opens writable; with the
read resolver an embedded routed target refused the release with "store
is read-only". Like bd close, it commits a routed change itself
(commitPendingIfEmbedded), since the post-run auto-commit covers only the
local store. bd human respond and dismiss already opened their target
writable but never committed it, so on an embedded workspace the close
sat uncommitted in the routed repository's working set; they now commit
it the same way. resolveAndGetIssueWithRoutingAccess's
writablePrefixRoute parameter is renamed writable, since it now governs
auto routes too.

A routed commit that fails no longer looks like success, and a retry
commits it. bd unclaim printed "Unclaimed" (or listed the issue in its
--json output) even when the release's routed commit failed; it now
reports the commit error and leaves the issue out. The failed commit
leaves the release, or the close human respond and dismiss make, in the
routed repository's working set. There a retry finds the issue
unassigned or already closed and refuses before it reaches its commit,
and nothing else commits a routed target. On that refusal unclaim,
respond and dismiss now commit the pending write before reporting it,
through commitRoutedWrite, which their success paths share.

A routed write never creates the target's database. The routed open runs
before the lookup it serves, so an embedded open of a repository that had
not been bootstrapped yet created an empty database that outlived an id
that missed; bd bootstrap then took it for the real one and skipped the
clone from sync.remote. openRoutedTargetStore's writable branch now opens
through newExistingDoltStoreFromConfig, which refuses an embedded
workspace without a database (embeddeddolt.HasRepository) before the
sanitize migration can rewrite anything there. A server-mode open already
never creates one.

resolveAndGetIssueForMutation already returned a routing failure (an
unreadable routes.jsonl, a routed store that fails to open) as itself. The
exact resolver and bd close still fell through to "no issue found
matching", which misstates why the lookup missed. All of them now share
isRoutingFailure. The exact resolver checks its abbreviation refusal first,
so the auto tier still gets its chance at an exact match. A prefix route
whose target has no usable metadata.json now names the route and the file
and says why the file could not be used.

An auto-routed store now opens the target's own dolt_database, as a prefix
route already did. Otherwise BEADS_DOLT_SERVER_DATABASE, which names the
launching workspace's database, would point a server-mode open at the wrong
database on a shared server. openRoutedTargetStore holds that override for
both route kinds. A write refuses a target whose metadata.json cannot be
read or parsed or names no dolt_database (autoRouteTargetDatabase) instead
of falling back to that variable. A target with no metadata.json at all
opens, read or written, the only embedded database it holds
(embeddeddolt.Databases), or the default database
(configfile.DefaultDoltDatabase) when it holds none or several.
Contributor setup leaves the planning repository without one until the
first routed bd create writes it, and names its database the way any
workspace without metadata.json does, BEADS_DOLT_SERVER_DATABASE first.
The open would otherwise resolve that name again from the launcher's
variable, so when the two differed a read that missed failed with
"database not found" and a write that missed created a database beside
the one setup created. A server-mode target holds no embedded database,
so with the variable set such a route now opens the default database
rather than the launcher's, which is what it opens without the variable.
A read of a target whose metadata.json is unreadable or names no
database keeps the lenient lookup it had.

bd mol bond's routed home now gets the external-dependency policy and
nothing else, as wireExternalDependencyPolicy asks of routed stores. The
launching workspace's hooks and telemetry no longer wrap writes into
another rig. runMolBond's tail is split into planMolBond, openMolBondHome,
materializeMolBondOperands and bondMolBondOperands, which takes it from
cyclomatic 26 down to 10 or less per function. getIssueWithRouting and the
resolveViaAutoRouting wrapper had no callers left and are removed.

Tests:
- TestMaintainerAutoRouteMutationWritesThrough now checks that the routed
  store is writable. Without that check it passes even against a read-only
  open, because a server-mode read-only store accepts the write.
- TestAutoRouteCloseTargetWriteIntent covers bd close's write intent for a
  maintainer route.
- TestContributorAutoRouteWritesThrough replaces
  TestContributorAutoRouteRefusesWriteIntent: an update, a comment and a
  close through a contributor route each open the target writable and
  commit, a read through the same route stays read-only, and a missing id
  stays a plain not-found.
- TestEmbeddedContributorRoutedWritesCommitInPlanning runs bd update
  --claim, unclaim, comment, close, human respond and human dismiss
  through the bd binary in a contributor checkout. Each advances the
  planning database's HEAD, and the issues end up closed there and absent
  from the fork's database. The embedded shard manifest gains the test.
- TestMolBondContributorAutoRoutedWriteThrough replaces
  TestMolBondAutoRoutedReadOnlyFailsFast: bd mol bond's pipeline bonds two
  planning issues through a contributor route, and a fresh routed read
  sees the dependency; setupAutoRoute now seeds extra planning issues for
  it. TestDiscoverMolBondOperandRouting's contributor case now expects the
  writable reopen.
- TestResolveCloseTargets keeps base's contributor cases (beads-0km); the
  previous revision had moved them to routing.maintainer.
- TestRoutedWriteDoesNotCreateTargetDatabase (in-process) and
  TestEmbeddedRoutedWriteMissDoesNotCreateTargetDatabase (the bd binary)
  check that a missed write through a prefix route and through a
  maintainer auto-route leaves an embedded target that has not been
  bootstrapped without an embeddeddolt directory. The embedded shard
  manifest gains the test.
- TestRoutedMutationResolversReportRoutingFailures runs each write-intent
  resolver against an auto route whose store fails to open, an auto route
  whose target's metadata.json names no dolt_database while
  BEADS_DOLT_SERVER_DATABASE names the launcher's, and a prefix route
  whose target cannot load.
- TestAutoRouteTargetDatabase covers a write and a read of a target whose
  metadata.json names a database, is missing, names none, or cannot be
  parsed; a missing one yields the target's only embedded database, or
  the default database when it holds none or several, either way.
  TestDatabases covers the listing, which applies HasRepository's .dolt
  marker probe to each database.
- TestAutoRouteMissWithoutMetadataIgnoresEnv runs a missed read and a
  missed write through an auto-route to a target that has one database
  but no metadata.json: the default database while
  BEADS_DOLT_SERVER_DATABASE names the launcher's, and a database named
  after the launcher's with the variable set and unset at use. Each miss
  must report not found and leave the target holding only its database.
- TestRoutedWriteRetryCommitsFailedCommit fails the routed commit of bd
  unclaim (text and --json), human respond and human dismiss with an
  invalid --dolt-auto-commit. The run must fail with nothing on stdout and
  leave the routed repository's HEAD as it was; a retry must report its
  refusal and commit the write there.
- TestAutoRouteOpensTargetDatabaseDespiteEnv checks the target-database
  change.
- The auto-routing tests clear BEADS_ROUTING_MODE and BD_ROUTING_MODE
  through neutralizeRoutingModeEnv. Viper ranks them above the
  routing.mode the tests write, so a host that exports either var never
  routes. bdEnv, which builds the bd binary's environment in the
  embedded tests, now drops BD_ROUTING_MODE as it drops BEADS_*; agent
  hosts export it, and TestEmbeddedContributorRoutedWritesCommitInPlanning
  failed on such a host.
  TestEmbeddedRoutedWriteMissDoesNotCreateTargetDatabase no longer needs
  its own envWithout.
- Reverting each fix turns its test red: the contributor read-only clamp
  (the contributor tests above), unclaim's resolver or commit and the
  respond and dismiss commits (the matching step of the embedded test),
  and each autoRouteTargetDatabase rule. So does dropping unclaim's,
  respond's or dismiss's retry commit, or unclaim's skip of a release
  whose commit failed (TestRoutedWriteRetryCommitsFailedCommit); either
  earlier no-metadata.json rule, the variable, which leaves the stray
  database the review reported, or a fixed default database, which fails
  the read of a target setup named after the variable
  (TestAutoRouteMissWithoutMetadataIgnoresEnv and
  TestAutoRouteTargetDatabase), and taking the first of several databases
  (TestAutoRouteTargetDatabase); and bdEnv's BD_ROUTING_MODE drop, on a
  host that exports BD_ROUTING_MODE=off (both embedded tests).

The CHANGELOG entry now records that every auto-route opens writable for
the commands that change an existing issue, the unclaim and human
respond/dismiss commits, that a routed write never creates the target's
database, and the target-database and routing-failure changes.
docs/multi-agent/routing.md says that write commands follow every route,
contributor, maintainer and default alike, never create the routed
repository's database, and refuse a target whose metadata.json is
unreadable or names no dolt_database. Both say that an auto-route opens
a target with no metadata.json at the one embedded database it holds, or
its default database when it holds none or several, while a prefix route
always needs the target's dolt_database. That page documents
behavior that is not in a release yet, which the docs release-pin
decision (engdocs/decisions/2026-07-17-docs-release-pin.md §1) would
leave undocumented. The review asked for docs that match the behavior,
as feature PRs #6508, #5855, #5997 and #5092 also did, so it is flagged
here as a maintainer call.

Open, and not changed here. bd close has the same retry gap on base: a
re-close of an issue that a failed routed commit left closed counts as
already closed and never commits that store (mutatedStores).
commitPendingIfEmbedded gates on the launcher's mode (isEmbeddedMode),
not the routed store's, so a server-mode launcher that opens an embedded
routed repository would leave the write uncommitted there. That gate is
shared by every routed write command and is not exercised here.

Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Gas City Adopt-PR
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Rody Vilchez <102562850+R0SEWT@users.noreply.github.com>

* ci(shards): list TestDatabases in the 40-shard embedded storage manifest

The routed-write hardening added TestDatabases to
internal/storage/embeddeddolt/detection_test.go without a slot in the
Bazel-only 40-shard block of .github/scripts/embedded-storage-test-shards.txt,
so gen_embedded_storage_shard_manifest.py 40 --weights=duration --check
reported it missing and TestStorageEmbeddedShardManifestGeneratorNotStale
(go test ./scripts) failed.

Regenerated with the repository command
(gen_embedded_storage_shard_manifest.py 40 --weights=duration --write);
the incremental pack adds exactly one line, on shard 25.

Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Gas City Adopt-PR
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Rody Vilchez <102562850+R0SEWT@users.noreply.github.com>

---------

Co-authored-by: Rody Vilchez <102562850+R0SEWT@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Co-authored-by: matt wilkie <maphew@gmail.com>
Co-authored-by: Eddie the Engineer <julianknutsen@users.noreply.github.com>
Co-authored-by: Eddie the Engineer <338826946+gascity-eddie[bot]@users.noreply.github.com>
2026-10-16 21:10:12 +00:00

1033 lines
37 KiB
Go

//go:build cgo
package main
import (
"encoding/json"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"sync"
"testing"
"github.com/steveyegge/beads/internal/configfile"
"github.com/steveyegge/beads/internal/storage/embeddeddolt"
"github.com/steveyegge/beads/internal/types"
)
// ===== Shared test helpers (used by both update and close tests) =====
// bdUpdate runs "bd update" with the given args and returns stdout.
// Retries on flock contention.
func bdUpdate(t *testing.T, bd, dir string, args ...string) string {
t.Helper()
fullArgs := append([]string{"update"}, args...)
out, err := bdRunWithFlockRetry(t, bd, dir, fullArgs...)
if err != nil {
t.Fatalf("bd update %s failed: %v\n%s", strings.Join(args, " "), err, out)
}
return string(out)
}
// bdUpdateFail runs "bd update" expecting failure.
func bdUpdateFail(t *testing.T, bd, dir string, args ...string) string {
t.Helper()
fullArgs := append([]string{"update"}, args...)
cmd := exec.Command(bd, fullArgs...)
cmd.Dir = dir
cmd.Env = bdEnv(dir)
out, err := cmd.CombinedOutput()
if err == nil {
t.Fatalf("expected bd update %s to fail, but it succeeded:\n%s", strings.Join(args, " "), out)
}
return string(out)
}
// wantNotesRefusal is the expected notes-overwrite refusal line, shared by the
// embedded and proxied update tests. Spelled as a literal, not via the
// production errNotesOverwriteRefusal: reusing the constructor would make the
// wording self-verifying.
func wantNotesRefusal(id string) string {
return id + ": --notes would replace existing notes; use --force to overwrite (or --append-notes to preserve history)"
}
// bdUpdateCapture runs "bd update" expecting success, returning stdout and
// stderr separately (stdout may be JSON; warnings must not pollute it).
func bdUpdateCapture(t *testing.T, bd, dir string, args ...string) (stdout, stderr string) {
t.Helper()
fullArgs := append([]string{"update"}, args...)
cmd := exec.Command(bd, fullArgs...)
cmd.Dir = dir
cmd.Env = bdEnv(dir)
outBuf, errBuf, err := runCommandBuffers(t, cmd)
if err != nil {
t.Fatalf("bd update %s failed: %v\nstdout:\n%s\nstderr:\n%s", strings.Join(args, " "), err, outBuf.String(), errBuf.String())
}
return outBuf.String(), errBuf.String()
}
func bdRunInTimezone(t *testing.T, bd, dir, timezone string, args ...string) string {
t.Helper()
cmd := exec.Command(bd, args...)
cmd.Dir = dir
for _, env := range bdEnv(dir) {
if !strings.HasPrefix(env, "TZ=") {
cmd.Env = append(cmd.Env, env)
}
}
cmd.Env = append(cmd.Env, "TZ="+timezone)
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("bd %s failed in %s: %v\n%s", strings.Join(args, " "), timezone, err, out)
}
return string(out)
}
func embeddedCurrentCommit(t *testing.T, beadsDir, database string) string {
t.Helper()
store, err := embeddeddolt.Open(t.Context(), beadsDir, database, "main")
if err != nil {
t.Fatalf("open embedded store: %v", err)
}
defer func() { _ = store.Close() }()
head, err := store.GetCurrentCommit(t.Context())
if err != nil {
t.Fatalf("GetCurrentCommit: %v", err)
}
if head == "" {
t.Fatal("GetCurrentCommit returned empty hash")
}
return head
}
// bdShowJSON runs "bd show <id> --json" and returns the raw JSON output.
func bdShowJSON(t *testing.T, bd, dir, id string) string {
t.Helper()
cmd := exec.Command(bd, "show", id, "--json")
cmd.Dir = dir
cmd.Env = bdEnv(dir)
stdout, stderr, err := runCommandBuffers(t, cmd)
if err != nil {
t.Fatalf("bd show %s --json failed: %v\nstdout:\n%s\nstderr:\n%s", id, err, stdout.String(), stderr.String())
}
return stdout.String()
}
// hasLabel checks if a label is present in the issue's labels.
func hasLabel(issue *types.Issue, label string) bool {
for _, l := range issue.Labels {
if l == label {
return true
}
}
return false
}
// parseShowJSON parses the first JSON object from bd show --json output,
// which may be wrapped in an array or have non-JSON lines before it.
func parseShowJSON(t *testing.T, raw string) json.RawMessage {
t.Helper()
start := strings.Index(raw, "{")
if start < 0 {
t.Fatalf("no JSON object in output: %s", raw)
}
dec := json.NewDecoder(strings.NewReader(raw[start:]))
var obj json.RawMessage
if err := dec.Decode(&obj); err != nil {
t.Fatalf("parse JSON object: %v\nraw: %s", err, raw[start:])
}
return obj
}
// showLabels returns labels from bd show --json output (uses IssueDetails which includes labels).
func showLabels(t *testing.T, bd, dir, id string) []string {
t.Helper()
raw := bdShowJSON(t, bd, dir, id)
obj := parseShowJSON(t, raw)
var details struct {
Labels []string `json:"labels"`
}
if err := json.Unmarshal(obj, &details); err != nil {
t.Fatalf("parse labels: %v", err)
}
return details.Labels
}
// showDeps returns dependency IDs from bd show --json output.
func showDeps(t *testing.T, bd, dir, id string) []struct {
ID string `json:"id"`
Type string `json:"dependency_type"`
} {
t.Helper()
raw := bdShowJSON(t, bd, dir, id)
obj := parseShowJSON(t, raw)
var details struct {
Dependencies []struct {
ID string `json:"id"`
Type string `json:"dependency_type"`
} `json:"dependencies"`
}
if err := json.Unmarshal(obj, &details); err != nil {
t.Fatalf("parse deps: %v", err)
}
return details.Dependencies
}
// ===== Update tests =====
func TestEmbeddedUpdateBatchAutoCommitDoesNotAdvanceHead(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", "ub")
issue := bdCreate(t, bd, dir, "Batch update")
before := embeddedCurrentCommit(t, beadsDir, "ub")
cmd := exec.Command(bd, "--dolt-auto-commit", "batch", "update", issue.ID, "--title", "Deferred batch update")
cmd.Dir = dir
cmd.Env = bdEnv(dir)
stdout, stderr, err := runCommandBuffers(t, cmd)
if err != nil {
t.Fatalf("bd --dolt-auto-commit batch update failed: %v\nstdout:\n%s\nstderr:\n%s", err, stdout.String(), stderr.String())
}
after := embeddedCurrentCommit(t, beadsDir, "ub")
if after != before {
t.Fatalf("batch-mode update advanced HEAD; before=%s after=%s", before, after)
}
}
func TestEmbeddedUpdateRoutedStoreCommitsTargetHead(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, _, _ := bdInit(t, bd, "--prefix", "src")
targetDir := filepath.Join(dir, "target-repo")
if err := os.MkdirAll(targetDir, 0750); err != nil {
t.Fatal(err)
}
initGitRepoAt(t, targetDir)
runBDInit(t, bd, targetDir, "--prefix", "tgt")
issue := bdCreate(t, bd, targetDir, "Routed target issue")
route := `{"prefix":"tgt-","path":"target-repo"}` + "\n"
if err := os.WriteFile(filepath.Join(dir, ".beads", "routes.jsonl"), []byte(route), 0644); err != nil {
t.Fatalf("write routes.jsonl: %v", err)
}
targetBeadsDir := filepath.Join(targetDir, ".beads")
before := embeddedCurrentCommit(t, targetBeadsDir, "tgt")
bdUpdate(t, bd, dir, issue.ID, "--title", "Updated through route")
after := embeddedCurrentCommit(t, targetBeadsDir, "tgt")
if after == before {
t.Fatalf("routed update did not advance target HEAD; before=%s after=%s", before, after)
}
targetStore := openStore(t, targetBeadsDir, "tgt")
got, err := targetStore.GetIssue(t.Context(), issue.ID)
if err != nil {
t.Fatalf("GetIssue in target: %v", err)
}
if got.Title != "Updated through route" {
t.Fatalf("target title = %q, want routed update title", got.Title)
}
}
// 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
// TestEmbeddedUpdateLifecycle and then (~75s each on rbe-west) into these 5
// top-level tests over disjoint subtest groups, each with its own workspace,
// for CI shard balance (see scripts/ci/embedded_cmd_test_durations.json and
// engdocs/TESTING.md). Every original subtest is preserved exactly once.
func TestEmbeddedUpdateFieldsMappingAndRefs(t *testing.T) {
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded dolt integration tests")
}
t.Parallel()
bd := buildEmbeddedBD(t)
dir, _, _ := bdInit(t, bd, "--prefix", "tu")
t.Run("update_direct_flag_mapping", func(t *testing.T) {
issue := bdCreate(t, bd, dir, "Multi update", "--type", "task", "--metadata", `{"remove":"me"}`)
out := bdUpdate(t, bd, dir,
"--json", issue.ID,
"--status", "in_progress",
"--assignee", "bob",
"--priority", "1",
"--description", "Updated description",
"--design", "Design notes here",
"--acceptance", "AC text",
"--external-ref", "gh-42",
"--estimate", "60",
"--await-id", "run-123",
"--due", "2099-01-15",
"--set-metadata", "team=platform",
"--set-metadata", "score=99",
"--unset-metadata", "remove",
"--no-history",
)
var updated []*types.Issue
if err := json.Unmarshal([]byte(out), &updated); err != nil {
t.Fatalf("parse direct update response: %v\n%s", err, out)
}
if len(updated) != 1 {
t.Fatalf("direct update returned %d issues, want 1: %s", len(updated), out)
}
got := updated[0]
if got.Status != types.StatusInProgress {
t.Errorf("expected status in_progress, got %s", got.Status)
}
if got.Assignee != "bob" {
t.Errorf("expected assignee bob, got %q", got.Assignee)
}
if got.Priority != 1 {
t.Errorf("expected priority 1, got %d", got.Priority)
}
if got.Description != "Updated description" {
t.Errorf("expected updated description, got %q", got.Description)
}
if got.Design != "Design notes here" {
t.Errorf("expected design notes, got %q", got.Design)
}
if got.AcceptanceCriteria != "AC text" {
t.Errorf("expected acceptance criteria, got %q", got.AcceptanceCriteria)
}
if got.ExternalRef == nil || *got.ExternalRef != "gh-42" {
t.Errorf("expected external_ref gh-42, got %v", got.ExternalRef)
}
if got.EstimatedMinutes == nil || *got.EstimatedMinutes != 60 {
t.Errorf("expected estimated_minutes 60, got %v", got.EstimatedMinutes)
}
if got.AwaitID != "run-123" {
t.Errorf("expected await_id run-123, got %q", got.AwaitID)
}
if got.DueAt == nil || got.DueAt.Format("2006-01-02") != "2099-01-15" {
t.Errorf("expected due_at 2099-01-15, got %v", got.DueAt)
}
if !got.NoHistory {
t.Error("expected no_history true")
}
var metadata map[string]any
if err := json.Unmarshal(got.Metadata, &metadata); err != nil {
t.Fatalf("parse updated metadata %q: %v", got.Metadata, err)
}
if metadata["team"] != "platform" {
t.Errorf("metadata team = %v, want platform", metadata["team"])
}
// --set-metadata infers scalar types (the v1.2.2 contract): 99 lands as a
// JSON number, not the string "99".
if metadata["score"] != float64(99) {
t.Errorf("metadata score = %#v, want the JSON number 99", metadata["score"])
}
if _, ok := metadata["remove"]; ok {
t.Errorf("metadata still contains removed key: %v", metadata)
}
conflict := bdUpdateFail(t, bd, dir, issue.ID,
"--metadata", `{"other":"value"}`,
"--set-metadata", "team=other",
)
if !strings.Contains(conflict, "cannot combine --metadata with --set-metadata or --unset-metadata") {
t.Errorf("expected exact metadata conflict error, got: %s", conflict)
}
out = bdUpdate(t, bd, dir, "--json", issue.ID, "--due", "", "--history")
updated = nil
if err := json.Unmarshal([]byte(out), &updated); err != nil {
t.Fatalf("parse clearing update response: %v\n%s", err, out)
}
if len(updated) != 1 {
t.Fatalf("clearing update returned %d issues, want 1: %s", len(updated), out)
}
if updated[0].DueAt != nil {
t.Errorf("expected due_at nil after clear, got %v", updated[0].DueAt)
}
if updated[0].NoHistory {
t.Error("expected no_history false after --history")
}
})
t.Run("update_type_custom", func(t *testing.T) {
// Register "agent" as a custom type via bd config (GH#3030).
// This writes to Dolt only, NOT to .beads/config.yaml.
cfgCmd := exec.Command(bd, "config", "set", "types.custom", "agent,spike")
cfgCmd.Dir = dir
cfgCmd.Env = bdEnv(dir)
if out, err := cfgCmd.CombinedOutput(); err != nil {
t.Fatalf("bd config set types.custom failed: %v\n%s", err, out)
}
issue := bdCreate(t, bd, dir, "Custom type update", "--type", "task")
// Before the fix (GH#3030), this would fail with "invalid issue type"
// because the CLI-level validation could not read custom types from Dolt.
bdUpdate(t, bd, dir, issue.ID, "--type", "agent")
got := bdShow(t, bd, dir, issue.ID)
if string(got.IssueType) != "agent" {
t.Errorf("expected type agent, got %s", got.IssueType)
}
})
// GH#3902: --external-ref "" must clear to SQL NULL (matching buildCreateIssue's
// pointer semantics), not write an empty string. Otherwise sync/tracker code
// that checks ExternalRef == nil silently misclassifies cleared refs as still
// tracked, and two cleared issues round-trip with different JSON shapes
// (cleared via CLI emits "external_ref":"" while never-set issues omit the field).
t.Run("update_external_ref_clear", func(t *testing.T) {
a := bdCreate(t, bd, dir, "ExtRef clear A", "--type", "task", "--external-ref", "ref-a")
b := bdCreate(t, bd, dir, "ExtRef clear B", "--type", "task", "--external-ref", "ref-b")
bdUpdate(t, bd, dir, a.ID, "--external-ref", "")
// Repeat clear must succeed for a second issue — historical UNIQUE
// constraint repro from the issue report.
bdUpdate(t, bd, dir, b.ID, "--external-ref", "")
gotA := bdShow(t, bd, dir, a.ID)
gotB := bdShow(t, bd, dir, b.ID)
if gotA.ExternalRef != nil {
t.Errorf("expected A.external_ref to be nil after clear, got %q", *gotA.ExternalRef)
}
if gotB.ExternalRef != nil {
t.Errorf("expected B.external_ref to be nil after clear, got %q", *gotB.ExternalRef)
}
// JSON output: cleared ref should be omitted via omitempty, not emitted as "".
rawA := bdShowJSON(t, bd, dir, a.ID)
if strings.Contains(rawA, `"external_ref"`) {
t.Errorf("expected external_ref field to be omitted from JSON after clear, got: %s", rawA)
}
})
}
func TestEmbeddedUpdateFieldsNotesOverwrite(t *testing.T) {
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded dolt integration tests")
}
t.Parallel()
bd := buildEmbeddedBD(t)
dir, _, _ := bdInit(t, bd, "--prefix", "tu")
t.Run("update_notes_overwrite_requires_force", func(t *testing.T) {
issue := bdCreate(t, bd, dir, "Notes force test", "--type", "task")
bdUpdate(t, bd, dir, issue.ID, "--notes", "original notes")
out := bdUpdateFail(t, bd, dir, issue.ID, "--notes", "replacement notes")
wantErr := wantNotesRefusal(issue.ID)
if !strings.Contains(out, wantErr) {
t.Errorf("expected output to contain %q, got: %s", wantErr, out)
}
if got := bdShow(t, bd, dir, issue.ID); got.Notes != "original notes" {
t.Errorf("expected notes to remain %q, got %q", "original notes", got.Notes)
}
})
t.Run("update_notes_overwrite_with_force_warns", func(t *testing.T) {
issue := bdCreate(t, bd, dir, "Notes warning test", "--type", "task")
bdUpdate(t, bd, dir, issue.ID, "--notes", "original notes")
stdout, stderr := bdUpdateCapture(t, bd, dir, issue.ID, "--notes", "replacement notes", "--force")
warning := fmt.Sprintf("warning: %s: --force replaced existing notes (--append-notes preserves history)", issue.ID)
if !strings.Contains(stderr, warning) {
t.Errorf("expected stderr to contain %q, got: %s", warning, stderr)
}
if strings.Contains(stdout, "warning:") {
t.Errorf("warning must not appear on stdout, got: %s", stdout)
}
if got := bdShow(t, bd, dir, issue.ID); got.Notes != "replacement notes" {
t.Errorf("expected notes %q, got %q", "replacement notes", got.Notes)
}
})
t.Run("update_notes_overwrite_with_if_assignee_requires_force", func(t *testing.T) {
// --force and --if-assignee are no longer mutually exclusive at the
// flag level (that exclusion was the footgun: it made --force
// unpassable alongside --if-assignee, so a caller pairing --notes
// with --if-assignee could not opt into overwriting existing notes at
// all). Without --force the overwrite is still refused.
issue := bdCreate(t, bd, dir, "Notes plus if-assignee test", "--type", "task")
bdUpdate(t, bd, dir, issue.ID, "--notes", "original notes")
out := bdUpdateFail(t, bd, dir, issue.ID, "--if-assignee", "", "--notes", "replacement notes")
wantErr := wantNotesRefusal(issue.ID)
if !strings.Contains(out, wantErr) {
t.Errorf("expected output to contain %q, got: %s", wantErr, out)
}
if got := bdShow(t, bd, dir, issue.ID); got.Notes != "original notes" {
t.Errorf("expected notes to remain %q, got %q", "original notes", got.Notes)
}
})
t.Run("update_notes_overwrite_with_if_assignee_and_force_succeeds", func(t *testing.T) {
issue := bdCreate(t, bd, dir, "Notes plus if-assignee force test", "--type", "task")
bdUpdate(t, bd, dir, issue.ID, "--notes", "original notes")
bdUpdate(t, bd, dir, issue.ID, "--if-assignee", "", "--notes", "replacement notes", "--force")
if got := bdShow(t, bd, dir, issue.ID); got.Notes != "replacement notes" {
t.Errorf("expected notes %q, got %q", "replacement notes", got.Notes)
}
})
}
func TestEmbeddedUpdateFieldsNotesClearAndDefer(t *testing.T) {
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded dolt integration tests")
}
t.Parallel()
bd := buildEmbeddedBD(t)
dir, _, _ := bdInit(t, bd, "--prefix", "tu")
t.Run("update_empty_notes_refused", func(t *testing.T) {
// GH#6021: `--notes ""` is what a dead command substitution collapses
// to, so an unforced wipe must not look like success. The deliberate
// clear has its own verb, --clear-notes.
issue := bdCreate(t, bd, dir, "Notes clear guard test", "--type", "task")
bdUpdate(t, bd, dir, issue.ID, "--notes", "original notes")
out := bdUpdateFail(t, bd, dir, issue.ID, "--notes", "")
if !strings.Contains(out, "--clear-notes") {
t.Errorf("expected refusal naming --clear-notes, got:\n%s", out)
}
// --force opens the overwrite fence, not this guard: the empty value
// stays refused because the bytes still cannot prove intent.
out = bdUpdateFail(t, bd, dir, issue.ID, "--notes", "", "--force")
if !strings.Contains(out, "--clear-notes") {
t.Errorf("expected forced empty-notes refusal naming --clear-notes, got:\n%s", out)
}
if got := bdShow(t, bd, dir, issue.ID); got.Notes != "original notes" {
t.Errorf("expected notes to remain %q, got %q", "original notes", got.Notes)
}
})
t.Run("update_clear_notes_succeeds", func(t *testing.T) {
issue := bdCreate(t, bd, dir, "Notes deliberate clear test", "--type", "task")
bdUpdate(t, bd, dir, issue.ID, "--notes", "original notes")
// No --force: the fence exempts clears, so the verb alone authorizes
// the erase.
bdUpdate(t, bd, dir, issue.ID, "--clear-notes")
if got := bdShow(t, bd, dir, issue.ID); got.Notes != "" {
t.Errorf("expected notes cleared, got %q", got.Notes)
}
})
t.Run("update_clear_notes_conflicts_with_notes_flags", func(t *testing.T) {
issue := bdCreate(t, bd, dir, "Notes clear conflict test", "--type", "task")
bdUpdate(t, bd, dir, issue.ID, "--notes", "original notes")
for _, extra := range [][]string{
{"--notes", "replacement"},
{"--append-notes", "more"},
} {
args := append([]string{issue.ID, "--clear-notes"}, extra...)
out := bdUpdateFail(t, bd, dir, args...)
if !strings.Contains(out, "none of the others can be") {
t.Errorf("expected mutual-exclusion error for %v, got:\n%s", extra, out)
}
}
if got := bdShow(t, bd, dir, issue.ID); got.Notes != "original notes" {
t.Errorf("expected notes to remain %q, got %q", "original notes", got.Notes)
}
})
t.Run("update_defer", func(t *testing.T) {
issue := bdCreate(t, bd, dir, "Defer test", "--type", "task")
bdUpdate(t, bd, dir, issue.ID, "--defer", "2099-01-15")
got := bdShow(t, bd, dir, issue.ID)
if got.DeferUntil == nil {
t.Error("expected defer_until to be set")
}
// GH#3233: --defer should also set status=deferred for consistency with `bd defer`
if string(got.Status) != "deferred" {
t.Errorf("expected status=deferred, got %q", got.Status)
}
})
}
func TestEmbeddedUpdateLifecycleDefer(t *testing.T) {
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded dolt integration tests")
}
t.Parallel()
bd := buildEmbeddedBD(t)
dir, beadsDir, _ := bdInit(t, bd, "--prefix", "tu")
t.Run("relative_defer_is_persisted_in_UTC", func(t *testing.T) {
issue := bdCreate(t, bd, dir, "UTC defer test", "--type", "task")
bdRunInTimezone(t, bd, dir, "America/Denver", "update", issue.ID, "--defer", "+1h")
db, cleanup, err := embeddeddolt.OpenSQL(t.Context(), filepath.Join(beadsDir, "embeddeddolt"), "tu", "main")
if err != nil {
t.Fatalf("open embedded SQL: %v", err)
}
defer func() { _ = cleanup() }()
var future, bounded bool
if err := db.QueryRowContext(t.Context(), `
SELECT defer_until > UTC_TIMESTAMP(),
defer_until <= DATE_ADD(UTC_TIMESTAMP(), INTERVAL 2 HOUR)
FROM issues WHERE id = ?
`, issue.ID).Scan(&future, &bounded); err != nil {
t.Fatalf("query persisted defer_until: %v", err)
}
if !future || !bounded {
t.Fatalf("relative defer UTC bounds = future:%t bounded:%t, want true/true", future, bounded)
}
})
t.Run("show_renders_scheduled_dates_in_local_time", func(t *testing.T) {
issue := bdCreate(t, bd, dir, "Local date display test", "--type", "task")
const date = "2099-01-15"
bdRunInTimezone(t, bd, dir, "Pacific/Auckland", "update", issue.ID, "--due", date, "--defer", date)
output := bdRunInTimezone(t, bd, dir, "Pacific/Auckland", "--no-color", "show", issue.ID)
for _, want := range []string{"Due: " + date, "Deferred: " + date} {
if !strings.Contains(output, want) {
t.Errorf("bd show output missing %q:\n%s", want, output)
}
}
})
t.Run("update_defer_respects_explicit_status", func(t *testing.T) {
// GH#3233: explicit --status should win over the implicit deferred set by --defer
issue := bdCreate(t, bd, dir, "Defer+status test", "--type", "task")
bdUpdate(t, bd, dir, issue.ID, "--defer", "2099-01-15", "--status", "in_progress")
got := bdShow(t, bd, dir, issue.ID)
if string(got.Status) != "in_progress" {
t.Errorf("expected explicit status=in_progress to win, got %q", got.Status)
}
})
t.Run("update_defer_clear", func(t *testing.T) {
issue := bdCreate(t, bd, dir, "Defer clear test", "--type", "task")
bdUpdate(t, bd, dir, issue.ID, "--defer", "2099-01-15")
bdUpdate(t, bd, dir, issue.ID, "--defer", "")
got := bdShow(t, bd, dir, issue.ID)
if got.DeferUntil != nil {
t.Error("expected defer_until to be cleared")
}
// GH#3233: clearing defer on a deferred issue must restore ready visibility
if string(got.Status) != "open" {
t.Errorf("expected status=open after clearing defer, got %q", got.Status)
}
})
t.Run("update_defer_past_date_keeps_status_open", func(t *testing.T) {
// GH#3233: past-date --defer shouldn't flip status to deferred, because
// the warning promises the issue "will appear in bd ready immediately".
issue := bdCreate(t, bd, dir, "Past defer test", "--type", "task")
bdUpdate(t, bd, dir, issue.ID, "--defer", "2000-01-01")
got := bdShow(t, bd, dir, issue.ID)
if string(got.Status) == "deferred" {
t.Errorf("past --defer should not set status=deferred, got %q", got.Status)
}
})
t.Run("update_defer_clear_preserves_non_deferred_status", func(t *testing.T) {
// GH#3233: clearing defer_until shouldn't clobber a non-deferred status
// that was set independently (e.g. in_progress).
issue := bdCreate(t, bd, dir, "Defer clear keep status test", "--type", "task")
bdUpdate(t, bd, dir, issue.ID, "--status", "in_progress")
bdUpdate(t, bd, dir, issue.ID, "--defer", "")
got := bdShow(t, bd, dir, issue.ID)
if string(got.Status) != "in_progress" {
t.Errorf("expected status=in_progress to be preserved, got %q", got.Status)
}
})
}
func TestEmbeddedUpdateLifecycleClaimParentCommit(t *testing.T) {
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded dolt integration tests")
}
t.Parallel()
bd := buildEmbeddedBD(t)
dir, beadsDir, _ := bdInit(t, bd, "--prefix", "tu")
t.Run("update_claim_already_claimed", func(t *testing.T) {
issue := bdCreate(t, bd, dir, "Claim fail test", "--type", "task")
bdUpdate(t, bd, dir, issue.ID, "--assignee", "alice")
out := bdUpdateFail(t, bd, dir, issue.ID, "--claim")
if !strings.Contains(out, "already assigned to") {
t.Errorf("expected 'already assigned to' error, got: %s", out)
}
// The refusal must steer toward the holder, not teach an
// unclaim-then-claim eviction of a live claim (bd-at6rc / wy-zs5s2).
if !strings.Contains(out, "coordinate with the holder") {
t.Errorf("refusal should say coordinate-with-holder, got: %s", out)
}
if strings.Contains(out, "to release it before re-claiming") {
t.Errorf("refusal must not suggest plain unclaim of a foreign claim, got: %s", out)
}
// Nor may it name unclaim or --force at all: copy that names an
// eviction command gets pattern-matched by batch agents into
// `unclaim --force; claim` — a stronger steamroller than the one
// this fix removed (wy-yuclk).
if strings.Contains(out, "unclaim") || strings.Contains(out, "--force") {
t.Errorf("claim refusal must not name an eviction command, got: %s", out)
}
})
// A batch where one claim is lost and another is won must exit non-zero, so
// the lost claim is not hidden from exit-code automation (beads audit
// finding #10). The winner is still committed.
t.Run("update_claim_batch_partial_loss_exits_nonzero", func(t *testing.T) {
lost := bdCreate(t, bd, dir, "Batch lost", "--type", "task")
won := bdCreate(t, bd, dir, "Batch won", "--type", "task")
// Pre-assign `lost` to someone else so the default actor's claim loses.
bdUpdate(t, bd, dir, lost.ID, "--assignee", "alice")
out := bdUpdateFail(t, bd, dir, lost.ID, won.ID, "--claim")
if !strings.Contains(out, "already assigned to") {
t.Errorf("expected 'already assigned to' error in batch output, got: %s", out)
}
// The winning claim still lands despite the batch exiting non-zero.
gotWon := bdShow(t, bd, dir, won.ID)
if gotWon.Status != types.StatusInProgress {
t.Errorf("winning claim %s: status = %s, want in_progress", won.ID, gotWon.Status)
}
// The lost issue is untouched.
gotLost := bdShow(t, bd, dir, lost.ID)
if gotLost.Assignee != "alice" {
t.Errorf("lost issue %s assignee = %q, want alice (unchanged)", lost.ID, gotLost.Assignee)
}
})
t.Run("update_parent_change", func(t *testing.T) {
epic1 := bdCreate(t, bd, dir, "Old parent", "--type", "epic")
epic2 := bdCreate(t, bd, dir, "New parent", "--type", "epic")
child := bdCreate(t, bd, dir, "Reparent child", "--type", "task")
bdUpdate(t, bd, dir, child.ID, "--parent", epic1.ID)
bdUpdate(t, bd, dir, child.ID, "--parent", epic2.ID)
deps := showDeps(t, bd, dir, child.ID)
hasOld, hasNew := false, false
for _, d := range deps {
if d.Type == "parent-child" {
if d.ID == epic1.ID {
hasOld = true
}
if d.ID == epic2.ID {
hasNew = true
}
}
}
if hasOld {
t.Error("expected old parent dep to be removed")
}
if !hasNew {
t.Error("expected new parent dep to exist")
}
})
t.Run("update_persistent", func(t *testing.T) {
issue := bdCreate(t, bd, dir, "Persistent test", "--type", "task")
bdUpdate(t, bd, dir, issue.ID, "--ephemeral")
bdUpdate(t, bd, dir, issue.ID, "--persistent")
got := bdShow(t, bd, dir, issue.ID)
if got.Ephemeral {
t.Error("expected ephemeral to be false after --persistent")
}
})
t.Run("update_dolt_commit", func(t *testing.T) {
issue := bdCreate(t, bd, dir, "Dolt commit test", "--type", "task")
bdUpdate(t, bd, dir, issue.ID, "--status", "in_progress")
// Verify a Dolt commit exists by querying dolt_log.
dataDir := filepath.Join(beadsDir, "embeddeddolt")
cfg, _ := configfile.Load(beadsDir)
database := ""
if cfg != nil {
database = cfg.GetDoltDatabase()
}
db, cleanup, err := embeddeddolt.OpenSQL(t.Context(), dataDir, database, "main")
if err != nil {
t.Fatalf("OpenSQL: %v", err)
}
defer cleanup()
var commitCount int
err = db.QueryRowContext(t.Context(), "SELECT COUNT(*) FROM dolt_log").Scan(&commitCount)
if err != nil {
t.Fatalf("query dolt_log: %v", err)
}
// At minimum: init schema commit + create commit + update commit
if commitCount < 3 {
t.Errorf("expected at least 3 dolt commits, got %d", commitCount)
}
})
}
// TestEmbeddedUpdateConcurrent exercises create, update, and list operations
// concurrently to verify EmbeddedDoltStore handles concurrent CLI invocations
// without panics, data corruption, or deadlocks.
//
// issuesPerWorker was 5 (F1 review S1): under real CI-like load (several
// Bazel shards running concurrently, -test.parallel=4), this test's 10
// workers x 5 issues x 4 serialized `bd` subprocess invocations each (create,
// 2 updates, list; writes serialize behind the embedded engine's single-
// writer lock) measured ~452s -- the queueing-delay explanation once
// proposed for this and three other outliers was wrong (see
// scripts/ci/embedded_cmd_test_durations.json's header); this is genuine
// CPU-bound work under contention. issuesPerWorker=2 keeps the same
// invariants under test (duplicate-ID detection across all numWorkers
// concurrent processes; each worker's own list-count-is-non-decreasing check
// still exercises its loop body once) while cutting serialized work to 40%.
func TestEmbeddedUpdateConcurrent(t *testing.T) {
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded dolt integration tests")
}
t.Parallel()
bd := buildEmbeddedBD(t)
dir, beadsDir, _ := bdInit(t, bd, "--prefix", "cu")
const (
numWorkers = 10
issuesPerWorker = 2
)
type workerResult struct {
worker int
ids []string
listCounts []int
err error
}
results := make([]workerResult, numWorkers)
var wg sync.WaitGroup
wg.Add(numWorkers)
for w := 0; w < numWorkers; w++ {
go func(worker int) {
defer wg.Done()
r := workerResult{worker: worker}
for i := 0; i < issuesPerWorker; i++ {
// Create an issue.
title := fmt.Sprintf("w%d-issue-%d", worker, i)
out, err := bdRunWithFlockRetry(t, bd, dir, "create", "--silent", title)
if err != nil {
r.err = fmt.Errorf("create %d: %v\n%s", i, err, out)
results[worker] = r
return
}
id := strings.TrimSpace(string(out))
if id == "" {
r.err = fmt.Errorf("create %d: empty ID", i)
results[worker] = r
return
}
r.ids = append(r.ids, id)
// Update: change status to in_progress.
uCmd := exec.Command(bd, "update", id, "--status", "in_progress")
uCmd.Dir = dir
uCmd.Env = bdEnv(dir)
uOut, err := uCmd.CombinedOutput()
if err != nil {
r.err = fmt.Errorf("update status %d: %v\n%s", i, err, uOut)
results[worker] = r
return
}
// Update: set priority and assignee.
uCmd2 := exec.Command(bd, "update", id, "--priority", fmt.Sprintf("%d", worker%4), "--assignee", fmt.Sprintf("agent-%d", worker))
uCmd2.Dir = dir
uCmd2.Env = bdEnv(dir)
uOut2, err := uCmd2.CombinedOutput()
if err != nil {
r.err = fmt.Errorf("update fields %d: %v\n%s", i, err, uOut2)
results[worker] = r
return
}
// Update: add a label.
uCmd3 := exec.Command(bd, "update", id, "--add-label", fmt.Sprintf("team-%d", worker%3))
uCmd3.Dir = dir
uCmd3.Env = bdEnv(dir)
uOut3, err := uCmd3.CombinedOutput()
if err != nil {
r.err = fmt.Errorf("update label %d: %v\n%s", i, err, uOut3)
results[worker] = r
return
}
// List to verify consistency (interleaved with writes).
listCmd := exec.Command(bd, "list", "--json", "--limit", "0")
listCmd.Dir = dir
listCmd.Env = bdEnv(dir)
listStdout, listStderr, err := runCommandBuffers(t, listCmd)
if err != nil {
r.err = fmt.Errorf("list after update %d: %v\nstdout:\n%s\nstderr:\n%s", i, err, listStdout.String(), listStderr.String())
results[worker] = r
return
}
s := listStdout.String()
start := strings.Index(s, "[")
if start < 0 {
r.listCounts = append(r.listCounts, 0)
continue
}
var issues []json.RawMessage
if jsonErr := json.Unmarshal([]byte(s[start:]), &issues); jsonErr != nil {
r.err = fmt.Errorf("list parse %d: %v\nstdout:\n%s\nstderr:\n%s", i, jsonErr, s, listStderr.String())
results[worker] = r
return
}
r.listCounts = append(r.listCounts, len(issues))
}
results[worker] = r
}(w)
}
wg.Wait()
// Check for errors and collect IDs.
allIDs := make(map[string]bool)
var successes int
for _, r := range results {
if r.err != nil {
if !strings.Contains(r.err.Error(), "one writer at a time") {
t.Errorf("worker %d failed: %v", r.worker, r.err)
}
continue
}
successes++
for _, id := range r.ids {
if allIDs[id] {
t.Errorf("duplicate ID %q from worker %d", id, r.worker)
}
allIDs[id] = true
}
}
if successes == 0 {
t.Fatal("all workers failed — expected at least 1 success")
}
expectedIDs := successes * issuesPerWorker
if len(allIDs) != expectedIDs {
t.Errorf("expected %d unique IDs from %d successful workers, got %d", expectedIDs, successes, len(allIDs))
}
// Verify all successfully created issues exist and were updated correctly.
store := openStore(t, beadsDir, "cu")
stats, err := store.GetStatistics(t.Context())
if err != nil {
t.Fatalf("GetStatistics: %v", err)
}
if stats.TotalIssues < len(allIDs) {
t.Errorf("expected at least %d issues in DB, got %d", len(allIDs), stats.TotalIssues)
}
// Spot-check: every issue should be in_progress with an assignee.
for id := range allIDs {
issue, err := store.GetIssue(t.Context(), id)
if err != nil {
t.Errorf("GetIssue(%s): %v", id, err)
continue
}
if issue.Status != types.StatusInProgress {
t.Errorf("issue %s: expected status in_progress, got %s", id, issue.Status)
}
if issue.Assignee == "" {
t.Errorf("issue %s: expected assignee to be set", id)
}
}
// Verify list counts were monotonically non-decreasing per worker.
for _, r := range results {
if r.err != nil {
continue
}
for i := 1; i < len(r.listCounts); i++ {
if r.listCounts[i] < r.listCounts[i-1] {
t.Errorf("worker %d: list count decreased from %d to %d at step %d",
r.worker, r.listCounts[i-1], r.listCounts[i], i)
}
}
}
t.Logf("created and updated %d issues across %d/%d successful workers, %d in DB",
len(allIDs), successes, numWorkers, stats.TotalIssues)
}