Compare commits

...
Sign in to create a new pull request.

41 commits

Author SHA1 Message Date
Julian Knutsen
f3c47390e7
fix(storage): refuse graph_mode workspaces on library opens (#7721)
#7671 fences graph workspaces in cmd/bd: command admission, the store
factories and the other CLI paths refuse one, and #7722 extends that
fence to a .beads holding the graph-preview-format marker whatever its
metadata says. But the public library opens (beads.OpenBestAvailable,
OpenBestAvailableWith, OpenFromConfig, OpenGated) and the Dolt store's
metadata-driven constructors (NewFromConfig, NewFromConfigWithOptions,
NewFromConfigWithCLIOptions) still opened either kind of graph workspace
as an Issue store and ran Issue schema migrations into the graph
database (or, with no metadata beside the marker, created an Issue
database inside the graph workspace).

- Move the typed refusal into internal/configfile
  (UnsupportedWorkspaceFormatError with BeadsDir, GraphMode and
  FormatMarker; CheckWorkspaceFormat; GraphFormatMarkerFile;
  HasGraphFormatMarker) with byte-identical text and hints for both the
  graph_mode and the marker refusal, and move cmd/bd's discovery
  pre-checks there as LoadAndCheckWorkspaceFormat and
  CheckDiscoveredWorkspaceFormat (LoadForDiscovery, which never migrates
  a legacy config.json; unreadable metadata beside the marker is refused
  as the marker's format). cmd/bd's checkWorkspaceFormat,
  loadAndCheckWorkspaceFormat, hasGraphFormatMarker and
  checkDiscoveredWorkspaceFormat become thin delegates, so the CLI keeps
  its behaviour (exit 16 with the same hints) and every caller of them is
  unchanged; bootstrap's ancestor walk builds the configfile type.
- Every public metadata-driven open runs CheckDiscoveredWorkspaceFormat
  as its first statement: before OpenGated takes its gates and before
  OpenBestAvailableWith's Load can migrate config.json. A refused open
  leaves the workspace byte-identical. The type is exported as
  beads.UnsupportedWorkspaceFormatError.
- The Dolt constructors run CheckDiscoveredWorkspaceFormat before
  configfile.Load, so a graph workspace marked only by a legacy
  config.json, or by the marker beside stripped, missing or unparseable
  metadata, is refused before Load can migrate it into metadata.json
  (and drop graph_* keys this build does not know). requireDoltBackend
  re-checks the loaded config as a backstop, so they also refuse before
  resolving a server or writing a port file or Dolt root.

Tests: configfile unit tests for both refusals (exact marker text and
hint, graph_mode winning over the marker, unparseable metadata with and
without the marker); the public opens and the three Dolt constructors
against graph_mode workspaces and against marker-only, stripped
(metadata.json and legacy config.json), server, explicit dependency and
unparseable-metadata marker workspaces, each refused with the typed
error and the workspace left unchanged.

Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-20 09:29:54 +00:00
Julian Knutsen
bc1cd64c78
fix(cli): refuse graph workspaces marked by graph-preview-format (#7722)
The graph-mode fence decides a workspace's format from graph_mode in its
metadata alone. Graph-preview builds also write a
.beads/graph-preview-format marker before metadata.json (donnabox fork
commit deea8d57df, Donna Box), so that an interrupted or metadata-lost
graph workspace stays fenced. bd ignored the marker. When a bd that
predates graph_mode had rewritten metadata.json without the field, bd
opened the graph database by its recorded name and `bd list` ran Issue
schema initialization against it. When metadata.json was never written
or was lost, bd fell back to the default database name and created an
Issue database inside the graph workspace, and `bd init` initialized an
Issue workspace there.

checkWorkspaceFormat now also refuses a beadsDir that holds anything at
graph-preview-format, whatever its content and whatever the metadata
says (absent, stripped, or an explicit "dependency"). The graph_mode
check still runs first, so a normal graph workspace is still reported
by its graph_mode. The refusal is the same typed error with its own
message and a hint to restore metadata.json, so every call site, the
--json rendering and exit code 16 (ExitUnsupportedWorkspaceFormat) are
unchanged. An empty beadsDir never probes the working directory.

loadAndCheckWorkspaceFormat reads the metadata with LoadForDiscovery
and refuses metadata that cannot be parsed beside the marker as the
marker's format: the marker alone declares it. Command admission
(guardLegacyUpgradeWorkspaceForInit) uses it, and
checkDiscoveredWorkspaceFormat now delegates to it, so the paths that
check before a migrating configfile.Load (the four store factories,
create --repo's ensureBeadsDirForPath and dry-run target open, the bd
dolt loaders, bootstrap's undiscovered walk) refuse a marked workspace
too, with or without readable metadata. Other metadata load failures
are still left to the caller's own load, so a malformed legacy
config.json without the marker keeps create --repo's
auto-initialization.

bootstrap's ancestor walk (findParentConfig) refuses an ancestor that
holds the marker without metadata it can read, as it refuses one whose
metadata declares graph_mode. It used to skip a marker-only ancestor
and take a more distant workspace's metadata or the defaults, and to
report a marked ancestor with unparseable metadata as a load failure
(exit 1). With the check in checkWorkspaceFormat, bootstrap in a .beads
holding only the marker refuses it (exit 16) instead of reporting no
workspace.

validateConfiguredBackend returns early for nil metadata, so its
backstop covers the marker only when metadata was loaded; every caller
runs admission or checkDiscoveredWorkspaceFormat on the same beadsDir
first, and its comment now says so.

Tests: guard unit tests for marker-only, metadata lost, stripped
(metadata.json and legacy config.json), server, explicit dependency,
unparseable metadata, marker over a legacy Dolt root, and arbitrary
marker content; the four store factories (cgo, and the CGO_ENABLED=0
copies goreleaser ships) with stripped, missing and, for cgo,
unparseable metadata beside the marker; findParentConfig with a marked
ancestor below an ordinary workspace; the exit-code mapping;
ensureBeadsDirForPath with a malformed config.json with and without the
marker; and the subprocess e2e matrices (in-workspace commands, plain
`bd init`, and the outside entry points: create --repo, create
--dry-run, --db, BEADS_DB, init --proxied-server, bootstrap below it)
extended with four marker fixtures that must exit 16 with the marker
refusal and leave .beads byte-identical, while store-less commands
still run. The e2e subprocess timeout goes from 10s to 20s: refused
runs finish in well under a second, but an unrefused one creates or
opens a database and can approach 10s under load, so without the
fence the rows fail on their assertion rather than on the timeout.

Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-20 07:25:38 +00:00
gascity-eddie[bot]
d0d9aa2145
test(list): pin --deps scheduling ordering under --sort closed in the tree (#7703)
* test(list): pin orderSiblingsByDeps ready-set ordering under a sort-derived comparator

Drive orderSiblingsByDeps with compareIssuesForTree("closed", false) over
shuffled input so the caller-supplied compare at the initial ready-set sort
and the post-pop re-sort is exercised with an ordering that disagrees with
priority. Exact-order assertion: dropping or re-hardcoding the post-pop sort
only swaps pa-b and pa-v.

AC: AC-1

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 5c973b4ba9)

Ported-From: opus/5c973b4ba9d93def077dfabe8186622052abffd5
AC: AC-1

* test(list): pin orderSiblingsByDeps cycle fallback under a sort-derived comparator

A two-node scheduling cycle where priority and ID favor pa-x but --sort
closed favors pa-y: the cycle fallback must follow the caller's compare.

AC: AC-2

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit d29c4611e6)

Ported-From: opus/d29c4611e63422cee2ff9aee9cf2a9719b5dff71
AC: AC-2

* test(list): pin --deps scheduling ordering under --sort closed in the tree

Render the tree with depsMode=scheduling and sortBy=closed at both the root
level and under one parent: the blocks edge must still put dep before late,
while the requested sort (not priority) puts the unlinked free first. Covers
both orderSiblingsByDeps call sites in list_tree.go.

AC: AC-3

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit f434dcd5e4)

Ported-From: opus/f434dcd5e47643121c1b4f882f57c7bc68fc69a9
AC: AC-3

---------

Co-authored-by: Julian Knutsen <julianknutsen@users.noreply.github.com>
2026-10-20 02:19:13 +00:00
Julian Knutsen
1fcd715e75
fix(cli): refuse graph_mode workspaces and keep their metadata marker on save (#7671)
* fix(configfile): carry graph_mode and graph_* binding through Save

Graph-preview builds of bd persist a per-workspace format in
metadata.json: "graph_mode": "link" plus graph_scope_url,
graph_authority_id, graph_workspace, graph_schema_version and
graph_ready, beside an ordinary Dolt backend. configfile.Config had no
such fields, so every Save, and Load's config.json -> metadata.json
migration, rewrote the file without them, turning a graph workspace's
metadata into an ordinary Issue workspace's.

Config now carries the marker and the binding as omitempty fields, so
a Save round-trips them unchanged and metadata.json written for an
ordinary workspace is byte-for-byte what it was. GetGraphMode resolves
the marker: absent or "dependency" is the historical default, "link"
is recognized, and any other value is an error rather than a fallback
to the Issue store. Nothing in this build opens a non-default mode;
the CLI refusal follows in the next commit.

Ported from the donnabox fork commit deea8d57df (graph_mode.go,
graph_mode_test.go and the configfile.go fields), without any graph
code. The binding-survives-Save and omitted-from-ordinary-metadata
tests are new.

Co-authored-by: Donna Box <dbox@boxenllc.com>
Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(cli): refuse graph_mode workspaces before opening them

A workspace whose metadata.json declares a graph_mode other than
"dependency" holds a graph database behind an ordinary Dolt backend,
and nothing else in its metadata says so. bd admitted it like any
current workspace: `bd list` ran the Issue schema initialization
against the graph database (beads_graph_<id>), `bd init --force` wrote
a .gitignore and a .beads/dolt root into it, `bd dolt start` started a
server for it, and `bd doctor` reported on it as an Issue store.

guardLegacyUpgradeWorkspace, the admission check every store-opening
command, store-less command with workspace effects, init, doctor and
bootstrap already run before touching a workspace, now refuses such a
workspace first, before the legacy classifications that would admit
it or report it as a legacy store to migrate. An unknown graph_mode
value is refused the same way. The refusal is a typed error naming the
workspace and the format, rendered with a hint (as JSON under --json)
and exit code 16, ExitUnsupportedWorkspaceFormat, so a wrapper can
tell "needs a different bd build" from a generic failure.
`bd version`, `bd --version`, `bd help` and completion stay exempt, as
they are for legacy workspaces. validateConfiguredBackend refuses the
same metadata, which covers the store-open paths that skip command
admission (routed writes, cross-repository reads, create --repo).

Tests: guard and store-factory unit tests; a subprocess e2e test that
show/list/create/context/where/dolt start/doctor/bootstrap/init are
refused with exit 16 and leave .beads byte-identical (metadata.json and
legacy config.json, link and unknown markers, embedded and server
layouts), and that store-less commands still run; an embedded test
that an ordinary workspace, with the marker absent or "dependency",
still creates and lists issues and keeps the marker through a
metadata.json rewrite.

The guard hunk and graph_mode_admission_e2e_test.go are ported from
the donnabox fork commit deea8d57df; the exit code, rendering, store
factory backstop and remaining tests are new.

Co-authored-by: Donna Box <dbox@boxenllc.com>
Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(cli): refuse graph workspaces reached outside command admission

Command admission refuses a graph_mode workspace a command runs in, but
bd also reaches workspaces before or without admission: a create --repo
target, the path --db or BEADS_DB names, and the stores the factories
open for routed and cross-repository work. On those paths a workspace
marked only by a legacy config.json was changed before anything refused
it: configfile.Load migrates config.json into metadata.json before the
format check sees the loaded metadata, and create --repo initialized
such a target as a new workspace. Where the refusal did come, create
reported it with exit 1 rather than 16.

- checkDiscoveredWorkspaceFormat checks a workspace's metadata as
  configfile.LoadForDiscovery reads it, which never rewrites it.
  ensureBeadsDirForPath, the dry-run target open and the four store
  factories (cgo and nocgo builds) run it before their own load.
- resolveBeadsDirForDBPath and findDatabaseInBeadsDir locate a
  workspace with LoadForDiscovery, so resolving --db, BEADS_DB or a
  create target no longer migrates it.
- bd create renders a refused target as the workspace refusal, exit 16
  with its hint, on the initializing and both dry-run paths. A dry run
  without --parent opens no target, so it now checks a local one before
  rendering the preview (checkRepoTargetFormat).
- bd bootstrap, when discovery finds no workspace, reads each .beads
  from the working directory up to the repository root without
  migrating it and refuses one in a format this build cannot open, the
  way commands without a workspace already do. A .beads marked only by
  config.json is passed over by discovery, so bootstrap reported "no
  workspace" there instead of exit 16. The walk now returns its
  candidates (undiscoveredWorkspaceCandidates) to both checks: handing
  it the check as a func(string) error made gosec's G702 taint analysis
  connect BEADS_DIR to every func(string) error that runs git.
- backendNameForErrorFraming reads with LoadForDiscovery, and
  loadDoltBackendConfig, bd dolt status and bd dolt show refuse a graph
  workspace before their migrating configfile.Load. Admission refuses
  first on every path that reaches them today; this keeps a new caller
  from migrating a legacy config.json before the refusal.
- The CHANGELOG entry and the configfile comment now claim what holds:
  a routed read fails without touching a graph workspace but not with
  code 16, and a Save keeps only the known graph_* fields, with the
  tags graph-preview builds declare. workspace_gate.go no longer lists
  the pre-gate discovery reads as migrating.
- New e2e rows run create --repo from a workspace and from outside one,
  create --dry-run with and without --parent, --db, BEADS_DB, init
  --proxied-server, bootstrap in a workspace nested in a graph one, and
  the hook shim's bd hooks run pre-commit against every fixture; each
  refusal must exit 16 and name the format and the hint. bootstrap in a
  workspace marked only by config.json now refuses like the other
  commands. The store factory test also runs on a config.json graph
  workspace, TestWorkspaceMetadataReadersLeaveGraphWorkspaceUnchanged
  covers the framing, bd dolt loader and diagnostic reads, and
  TestNocgoStoreFactoriesRefuseGraphWorkspace covers the CGO_ENABLED=0
  factories; bazel.yml's pure lane runs it by name (PURE_CMD_BD_TESTS,
  pinned in scripts/ci_workflow_test.go).

Measured with gocyclo/gocognit: every function this changes stays below
the PR's worst changed function (guardLegacyUpgradeWorkspaceForInit
29/28, resolveBeadsDirForDBPath 26/36); showDoltConfig is 19/31 (was
18/30) and guardUndiscoveredLegacyWorkspace 3/3 (was 9/12).

Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Donna Box <dbox@boxenllc.com>
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Co-authored-by: Eddie the Engineer <338826946+gascity-eddie[bot]@users.noreply.github.com>
2026-10-20 00:05:39 +00:00
gascity-eddie[bot]
4df395698b
fix(bazel): the root go_srcs glob skips Bazel's convenience symlinks, so //cmd/bd tests cache (#7714)
The root //:go_srcs filegroup is glob(["**/*.go"]), and a glob follows the
checkout's bazel-bin/bazel-out/bazel-testlogs/bazel-beads symlinks into the
output tree. CI's test step is the first build in a fresh checkout, so it never
sees them, but in any checkout that has built before every test that reads
//:go_srcs (bd_test, bd_embedded_test, bd_embedded_part2_test,
bd_dolt_server_test, bd_proxied_test, bd_managed_local_test) gains the output
base's .go files: their inputs differ on every run, they are never cached, and
loading grows with the output tree.

Measured on main 2563f021ed with the symlinks present, `bazel test
//cmd/bd:bd_test --config=ci --test_filter='^TestResolveCommitHash$'` twice:
both runs executed all 16 shards remotely, and the analysed graph grew from
20,773 to 56,941 configured targets (14 s, then 25 s). With this change the
second run is `(cached)` in 3.6 s. In agent worktrees the glob had reached
433,026 output-tree files, a cached re-run took 36 s to load against ~3 s
without them, and 135 of 202 blocking test minutes of the factory's beads
seats went to these six targets (formula-overhead audit 4; bead ga-ylpbsy.24).

tools/bazel/go_srcs.py gives the root block exclude = ["bazel-*/**"] (the
same pattern ROOT_REPO_FILES_EXCLUDE already uses for //:repo_files); only
the root BUILD.bazel changes. CI's action keys do not change: its checkout has
no such files. scripts/bazel_policy_test.go's
TestBazelRootGoSrcsSkipsConvenienceSymlinks fails without the exclude.

Co-authored-by: Eddie the Engineer <338826946+gascity-eddie[bot]@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-19 23:30:10 +00:00
Julian Knutsen
c86a87bb20
test(oracle-a): pin BEADS_TIP_SEED so human-output scenarios stop flaking (#7707)
After a successful human-output create/show/list/ready, bd may append a
"💡 Tip:" line chosen by a probability roll whose RNG is clock-seeded
unless BEADS_TIP_SEED is set. run_scenario env_clear()s and passes only
PATH/HOME/TMPDIR + BEADS_TEST_MODE=1, so on a host with ~/.claude (claude_setup
tip eligible, p=0.6) every bd process rolled independently and out-of-scope
human-output scenarios (create_human_readable_output, show_short_mode_text,
show_multiple_short, ready_empty_no_issues_plain, ...) diverged main-vs-main.

Pass BEADS_TIP_SEED=1214 to every step for both reference and candidate.
Go math/rand's first Float64() for that seed is 0.0000159, so the
highest-priority eligible tip always wins its roll. Where the host makes a
tip eligible, it stays visible and lands on a deterministic step, so a change
to which tip prints, on which step, or to its text (including a tip leaking
into --json) still diverges instead of being normalized away. Where no tip is
eligible (no ~/.claude, beads plugin enabled, or a `bd prime` hook) none
prints and tip changes go unobserved; the README now says so.

The new unit test spawns printenv through run_scenario. That races the
existing stub-bd test, which writes its stub with std::fs::write and then
execs it: a fork while the write fd is open makes the exec fail with ETXTBSY
(rust-lang/rust#114554). Serialize both spawning tests on a SPAWN mutex.

Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-19 22:02:44 +00:00
Julian Knutsen
8988340994
ci(embedded): run every BEADS_TEST_EMBEDDED_DOLT-gated cmd/bd test in the embedded lane (#7708)
* test(cmd/bd): repair the embedded-gated tests that rotted while no lane ran them

These tests skip unless BEADS_TEST_EMBEDDED_DOLT=1 but no CI lane selected
them, so they rotted unseen. Running them shows:

- TestEventsTailFollowReportsTruncationOnTheStream raced on a plain
  bytes.Buffer that os/exec's copy goroutine writes while the test polls it.
  Use the package's syncBuffer.
- TestCorruptMetadataDiagnosticsRunAndDataFailsLoud still asserted that
  doctor and init run on a corrupt metadata.json. #4857 deliberately made
  every workspace command refuse instead (pinned for doctor by
  TestDoctorRejectsCorruptMetadataBeforeSharedServerChecks). Rewrite it to
  the shipped contract as TestEmbeddedCorruptMetadataFailsLoudUntilRestored:
  version warns, doctor/list/init refuse naming the file without touching
  it, and restoring the file brings the data back.
- dolt_remote_origin_guard_embedded_test.go was tagged
  `embeddeddolt && cgo`, a tag no lane sets, so it never compiled in CI
  (gazelle left it out of bd_test srcs). Retag it `cgo`, as #4153 did for
  its dolt_local_only sibling, and add it to srcs. Drop its four bd doctor
  git-origin tests: bd doctor runs no checks on an embedded workspace
  (GH#3794), so two could never pass and two passed vacuously on empty
  output. Rename the surviving tests into the TestEmbedded* prefix.

Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* ci(embedded): run every BEADS_TEST_EMBEDDED_DOLT-gated cmd/bd test in the embedded lane

The embedded-Dolt cmd lane selected tests with
grep '^func TestEmbedded' cmd/bd/*_embedded_test.go, and only its two
Bazel targets set BEADS_TEST_EMBEDDED_DOLT. A test that skips without the
variable but missed the name prefix or the file suffix skipped in every
lane and reported green: 92 of them, including #7203's --if-revision CLI
coverage (TestIfRevisionMatchAndMismatch, TestReassignFenceCLI, ...).

- embedded-test-shard.sh and gen_embedded_cmd_shard_manifest.py select
  TestEmbedded* by name across cmd/bd/*_test.go, as proxied-test-shard.sh
  does, leaving authors one rule.
- Rename the gated tests into the TestEmbedded* prefix
  (TestDoctorEmbedded<X> -> TestEmbeddedDoctor<X>) and update every
  reference.
- Place the new names with gen_embedded_cmd_shard_manifest.py 100
  --weights=duration --write (incremental).
- Add TestEmbeddedGatedTestsRunInTheEmbeddedLane: it walks cmd/bd's tests
  for any that reach os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" and fails
  if a shard of the lane never lists one. The proxied guard's helpers now
  take the variable and the script; a fixture test pins the walk.

Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-19 22:02:22 +00:00
Julian Knutsen
2563f021ed
perf(httpclient): remember the server's external-dependency policy across processes (#7700)
* perf(httpclient): remember the server's external-dependency policy across processes

Every bd ready over an HTTP workspace fetched GET /v0/beads/context before
its listing. listReadyWork itself needs no handshake; the fetch came from the
external-dependency decorator asking ServerEnforcesExternalDependencyPolicy
whether the server already applies the policy. In a one-shot CLI that is one
extra round trip per process (about 54 ms at a 52 ms RTT) to relearn a bit
that only changes when the server is restarted with a different composition.

The store opened from a workspace now keeps that answer in the user cache
directory (beads/http-policy/), keyed by the server URL and the project the
workspace pinned at bd connect, for BEADS_HTTP_POLICY_CACHE_TTL (5 minutes by
default; off disables it). A fresh entry answers the probe without dialing; a
handshake this process already holds wins and refreshes the entry. A
workspace with no project pin, and a store an embedder opens through
OpenWith, are not cached. Writing the entry is best effort.

The staleness this allows is bounded by the TTL: a server restarted without
the policy within the window is still trusted to enforce it until the entry
ages out. Carrying the policy on every response would close that window but
needs a server change and does nothing for servers already deployed.

Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of gascity-agent
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(httpclient): claims and closes ask the server for the policy, never the cache

Review follow-up to the policy cache. The claim and close guards (direct
claim, claim-next, batch close, the lifecycle close and claim, and the legacy
ClaimReadyIssue and CloseIssueChecked) handshake anyway, and a stale cached
"the server enforces it" would stand down their client-side refusal of
externally blocked work. Those entry points now mark their context with
storage.WithLivePolicyProbe, and httpclient.Store answers such a probe from
the server, refreshing the cache entry. Reads keep the cached answer.

Tests: externaldeps TestClaimsAndClosesAskForALivePolicyProbe and
TestRemoteClaimsAndClosesAskForALivePolicyProbe pin which entry points probe
live (every claim and close) and which do not (ready listings), over a local
and a remote store; httpclient TestALiveProbeSkipsThePolicyCache pins the
store side; TestPolicyCacheRefusesEntriesItCannotTrust now also covers an
entry written for another server URL.

Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of gascity-agent
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-19 19:05:55 +00:00
Julian Knutsen
d097b6c8a4
perf(ready): skip the countReadyWork request when bd ready --json prints no total (#7699)
* perf(ready): skip the countReadyWork request when bd ready --json prints no total

Over a remote backend, bd ready --json sent GET /v0/beads/ready and then,
whenever the page came back with has_more, GET /v0/beads/ready:count, only to
put "of N" into the stderr hint. Without BD_JSON_ENVELOPE nothing else prints
the total, so that second request (about 120 ms at a 52 ms RTT) bought a
number no caller reads.

On a remote backend without the envelope, bd ready --json now lists one row
past the limit and says whether more exist without saying how many, in the
wording the proxied route already uses. A local store keeps the in-band total
it takes in the page's own transaction, and the envelope keeps
pagination.total. A --max-rows cap at or below the limit keeps the counted
listing, so the extra row never trips the cap.

Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of gascity-agent
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(ready): say "1 ready issue", not "1 ready issues", in the no-total hint

Review follow-up. The hint the remote --json path shares with the proxied
route now agrees in number; both routes take it from readyHiddenHint, so
they stay one wording.

Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of gascity-agent
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-19 18:15:57 +00:00
Julian Knutsen
d28f56cd46
perf(startup): initialize packages on four Ps, not every CPU (#7701)
* perf(startup): initialize packages on four Ps, not every CPU

bd links several thousand packages whose init functions allocate about
20 MB before main runs, which triggers four or five garbage collections.
Each one starts mark workers and stops the world across every P, and on a
large host that costs more than the collection itself: on a 192-CPU machine
`bd version` spent about 20 of its 110 ms there, paid again by every bd
process a script or an orchestrator starts.

internal/initprocs lowers GOMAXPROCS to 4 for the duration of package
initialization. It imports only runtime and syscall, so it initializes
ahead of the heavy packages, and main hands GOMAXPROCS back first thing:
to the GOMAXPROCS environment value when one is set, else to the runtime
default, which keeps tracking the CPU limit.

cmd/bd's TestMain does the same hand-back, since tests never run main, and
resets the -test.parallel default testing derived from the capped count.

Measured on that host (40 runs each, `bd version`): p50 103 -> 86 ms.

Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of gascity-agent
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* test(initprocs): tell an explicit GOMAXPROCS hand-back from the runtime default

Review follow-up. TestDoneHonorsAnExplicitGOMAXPROCS swaps the two runtime
calls for recorders and pins that Done restores the exact value when
GOMAXPROCS is set and calls SetDefaultGOMAXPROCS when it is not; the earlier
test only saw the resulting count, which is the same either way on a host
whose default equals the saved value.

Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of gascity-agent
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-19 17:15:54 +00:00
Julian Knutsen
18b5c3cc39
fix(httpclient): name the connect failure when bd serve cannot be reached (#7702)
* fix(httpclient): name the connect failure when bd serve cannot be reached

A workspace whose server does not answer reported the transport's text:
`cannot reach bd serve at https://host:30699: Get "https://host:30699/v0/beads/context":
dial tcp 100.85.56.42:30699: i/o timeout`. It names the request rather than
the address that failed, and says nothing about what a dial timeout usually
means. An operator chasing an unreachable store had to know that "i/o
timeout" on a dial means the SYN went unanswered.

A request whose connection could not be opened now fails with a
*wire.DialError inside the *ConnectError: a refused connect names the
address and says nothing is listening there; a connect that times out names
the address that never answered, how long the attempt waited, and that a
firewall dropping the connection or a down host is the usual cause; a host
name that does not resolve is named as such. The transport's error stays
reachable through Unwrap, so errors.Is checks (ECONNREFUSED, timeouts) and
*ConnectError classification are unchanged, and a dial the caller canceled
keeps its own error. The events:watch connect gets the same classification.

Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of gascity-agent
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(httpclient): keep the transport's dial text in connect errors

Review follow-up. The refused and DNS messages dropped "connection refused"
and "dial tcp", the vocabulary gc's text classifier matches to tell an
unavailable store from other failures; without it the dispatcher's serve
loop exits and control beads are quarantined. Every DialError message now
ends with the transport's own *net.OpError text in brackets, after the
explanation.

TestACanceledDialIsTheCallersOwn now actually reaches the ctx.Err() guard:
its round tripper cancels and hands back a genuine refused dial, which the
guard alone keeps from becoming a DialError (removing the guard fails it).

Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of gascity-agent
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-19 16:54:25 +00:00
gascity-eddie[bot]
4f9174e6ba
docs(agents): bazel test is authoritative; agents never run go test (#7695)
* docs(agents): bazel test is authoritative; agents never run go test

Agents run tests only with `bazel test`, also while iterating on one
behavior: AGENTS.md shows the focused form
(`bazel test //cmd/bd:bd_test --config=ci --test_filter='^TestName$'`), the
target naming, that one --test_filter covers every target, that a cached
result for unchanged inputs is the same evidence, and that a new test file
needs `make bazel-sync` before Bazel runs it. `go test` (`./scripts/test.sh`,
`make test-go`) stays a convenience for humans working offline. TESTING.md's
focused red/green row and its plain-go-test section say the same.

Why: on the maintainer-city factory host, seats' own uncached `go test`
reruns of the same packages are the largest tool cost in adopt-pr, while
`bazel test` there executes on rbe-west and returns an unchanged target's
cached result in seconds.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* docs(agents): check that a focused test ran; exempt golden regeneration

Review fixes for #7695 (iterations 1 and 2).

The focused form exits 0 with "1 test passes" when the test never ran: a
filter that matches nothing, an integration-tagged file --config=ci does not
compile, the TestEmbedded* name skip, a -short skip, and a parent test whose
every subtest skipped (Go still prints "--- PASS" for the parent). It now
adds --test_output=all, and a run counts only when its log shows
"--- PASS: <TestName>" and no "--- SKIP" for the test or a <TestName>/...
subtest; a subtest that skips by design is left out with a subtest filter.

engdocs/TESTING.md gains "Check That the Test Ran"; AGENTS.md links there
instead of restating it. The section names the tests --config=ci does not
run and the way into each:
- Dolt-backed: the three --test_env flags, or the test's Dolt lane.
- -short-gated: --test_arg=-test.short=false.
- integration-tagged: --config=integration; the Dolt-backed ones of cmd/bd,
  tests/regression and internal/storage/dolt run in their Dolt-server lane
  target, whose env the suite needs. No lane runs those of other packages
  with Dolt, so a failure there is compared with the base commit first.
- TestEmbedded*: --test_arg=-test.skip= lifts the name skip; a test that
  then still skips for BEADS_TEST_EMBEDDED_DOLT=1 runs in its package's
  embedded-tagged target under --config=embedded (the cmd/bd and
  internal/storage/embeddeddolt targets are named).
- files BUILD.bazel does not list: make bazel-sync.
A lane's sh_test can hand the test binary its own -test.run, which
overrides --test_filter, so a trailing --test_arg=-test.run with sharding
disabled selects the test there. In a sharded target the other shards print
"testing: warning: no tests to run". The section also gives the
target-naming rule.

Golden regeneration (make corpus-regen, make githooks-regen,
BD_UPDATE_GOLDEN=1 ... go test, -update-ledger-doc) writes the source tree,
which a Bazel test cannot do: it runs from its runfiles tree, and on
rbe-west update mode fails with "permission denied". AGENTS.md and the new
"Regenerating Golden Files" section exempt these go test runs; where a host
refuses go test even for them, a maintainer regenerates. The factory seat
shim (gastownhall/workflows#102, scripts/seat-bin/go) still refuses update
mode and needs the same carve-out there.

Also: the plain-go-test opener scopes "humans working offline" to the
runner and its go test targets, so the Dolt-backend, fixture and
testing.Short() rules still bind agents; make ci-pr-core is marked plain go
test; the beads-docs skill's docsync gate is the Bazel target; RELEASING.md
and engdocs/RELEASE-STABILITY-GATE.md name the regression suite's Bazel
target (//tests/regression:regression_test under --config=doltserver-cmd)
in place of make test-regression, which is plain go test.

Measured on rbe-west (exit 0 unless noted). Iteration 1, at c4d5409895:
- a mistyped filter, and //internal/compact TestNew (integration-tagged)
  under --config=ci: "testing: warning: no tests to run"
- TestNew under --config=integration: "--- SKIP" (BEADS_TEST_SKIP=dolt);
  with the Dolt flags added it runs (and fails, exit 3, on the local
  backend: its store finds no "beads" database; outside this PR)
- TestConcurrentHeartbeatReclaimClose with the Dolt flags: "--- SKIP"
  (short mode); plus --test_arg=-test.short=false: "--- PASS"
- //cmd/bd:bd_embedded_test, sharding disabled: --test_filter alone ran
  TestEmbeddedUpdateConcurrent (manifest shard 1's test); the trailing
  -test.run ran "--- PASS: TestEmbeddedShowBasicsAndJSON"
- //scripts:go_test_sources_test
  TestEmbeddedCmdShardManifestBareWriteIsIdempotent: --config=ci "no tests
  to run"; plus --test_arg=-test.skip=: "--- PASS"
Iteration 2, at b1d25543aa (the same Go inputs):
- //internal/storage/dolt:dolt_test TestMoveIssuePersistenceInTxTransitions
  under --config=ci: "--- PASS" for the parent and "--- SKIP" for all 6
  subtests (BEADS_TEST_SKIP=dolt), "1 test passes"; with the Dolt flags and
  --test_filter='^TestMoveIssuePersistenceInTxTransitions$/^persistent-to-ephemeral$'
  "--- PASS" for the parent and that subtest only, no "--- SKIP"
- //internal/storage/embeddeddolt:embeddeddolt_test
  TestEmbeddedRemoteMigrateGate_BlocksReopen under --config=ci plus
  --test_arg=-test.skip=: "--- SKIP" (BEADS_TEST_EMBEDDED_DOLT unset);
  //internal/storage/embeddeddolt:embeddeddolt_embedded_test under
  --config=embedded, sharding disabled, trailing -test.run: "--- PASS"
  (the shard script listed 433 tests; only the named one ran)
- --config=ci plus --test_arg=-test.skip=: "--- PASS" for //tools/nogo
  TestEmbeddedConfigIsTheRepositoryConfig and //internal/tracker
  TestEmbeddedDoltExternalRefChangedAfterUsesHistoryFastPath
- sharding disabled, trailing -test.run: "--- PASS" for
  //internal/storage/dolt:dolt_server_full_test
  TestWispDeleteCascade_TransactionDeleteIssue under
  --config=doltserver-integration, and for //cmd/bd:bd_dolt_server_test
  TestCLI_ReopenClearsDeferUntil under --config=doltserver-cmd
- make check-docs: exit 0 (docsync: 10 test cases ran, none skipped)

Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Eddie the Engineer <338826946+gascity-eddie[bot]@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-19 14:04:30 +00:00
Julian Knutsen
1de9b59324
fix(setup): bd setup claude --global manages the section in ~/.claude/CLAUDE.md, not the current directory (#7696)
* fix(setup): keep bd setup claude --global's section in ~/.claude/CLAUDE.md

bd setup claude --global put its hook in ~/.claude/settings.json but wrote
the managed beads section into the current directory's CLAUDE.md, and
--remove --global stripped it from there. Run from $HOME it created
~/CLAUDE.md with project scaffolding, which stops Claude Code reading
AGENTS.md in projects below it; run inside a project it removed the
section that project's own install had written, leaving its hooks.

A global install and removal now manage the section in Claude Code's
user-level ~/.claude/CLAUDE.md (created holding only the section, no
project scaffolding), with hints naming bd setup claude --global. With
global or plugin hooks, --check reports that file when the project's
instructions have no beads section; a project install is still judged
on the project's file alone. Project installs are unchanged.

Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(setup): render the user-level CLAUDE.md section independently of the project

~/.claude/CLAUDE.md is shared by every project, but bd setup claude --global
rendered and --check judged its section with the current directory's beads
config (sync.remote, sync.git-remote, no-push). From a project with a remote
and one without, --check called the other's install stale and its hint
flipped the file back. The user-level file now always renders with the
default options, so install and --check agree across projects.

Also pin --check's fallback to the project's file and project hint when
neither file has a section, tell existing --global users to re-run it, and
name ~/.claude/CLAUDE.md in the ide-setup recipe table.

Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(setup): judge the user-level Claude files from $HOME and ~/.claude

Run from the home directory, the project's .claude/settings.json is the
global one, so bd setup claude --check reported a global install as project
hooks and judged ~/CLAUDE.md; its "Run: bd setup claude" hint then created
the ~/CLAUDE.md a global install exists to avoid. Run from ~/.claude, the
project's CLAUDE.md is the user-level file, and --check judged it with that
directory's render options and the project hint.

--check now reports hooks as global from $HOME and judges the user-level
file there and from ~/.claude with the fixed options and the --global hint.
With user-level hooks and no section in either file it names --global
unless the project has its own CLAUDE.md. A --remove run from $HOME, which
removes the global hooks, also removes the user-level section.

The init agent-artifact test ran bd setup claude with HOME at the project,
so its checks would now see a home directory; it gets a separate HOME and
its goldens are unchanged.

Rebase note (maintainer): rebased onto main after #7678 merged; main's
agent-artifact harness already runs bd with a separate HOME, so this
commit's harness edits to cmd/bd/agent_artifacts_embedded_test.go were
dropped.

Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* test(setup): pin --check's user-level choice beside project instructions

With global hooks, --check judges ~/.claude/CLAUDE.md when the project's
own CLAUDE.md has no beads section but the user-level file has one, and
when run from the home directory whose ~/CLAUDE.md has no section. Nothing
exercised either half of that condition: replacing it with false left the
suite and goldens green. Add a subtest for each; each now fails when its
half of the condition is dropped.

Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(setup): name --global when --check finds no hooks from $HOME

From the home directory --check with no hooks said 'Run: bd setup claude'.
Following it runs a project install there, which creates ~/CLAUDE.md with
project scaffolding, the file that stops Claude Code reading AGENTS.md in
the projects below it. The missing-section hint at home already names
--global; make the missing-hooks hint match, with a subtest.

Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* docs(setup): qualify the --global CHANGELOG entry; watch ~/.claude/CLAUDE.md

The CHANGELOG said --check from the home directory judges the user-level
files, but a beads section still in ~/CLAUDE.md is judged instead, and
the --global hint for a missing section applies only when the project has
no CLAUDE.md of its own. Say both, mention the new missing-hooks hint at
home, and re-wrap the paragraph.

The embedded agent-artifact harness comment said a global install writes
$HOME/CLAUDE.md; it now writes $HOME/.claude/CLAUDE.md. Track that path
too and reword the comment. The bd init goldens do not change.

Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(setup): word the user-level CLAUDE.md section for repositories that use beads

bd setup claude --global writes its section to ~/.claude/CLAUDE.md, which
Claude Code loads in every project, but rendered it with the project
wording: "This project uses bd (beads)" and "Use bd for ALL task tracking —
do NOT use TodoWrite". In a repository without beads that told the agent to
give up its own task tools and pointed it at bd, whose answer there is
"run 'bd init'", while the global hook, bd prime, stays silent outside a
workspace.

RenderOpts.UserLevel rewords the opening line and the task-tracking rules of
both profiles so they apply only in beads repositories. The global env fixes
it through agents.UserLevelRenderOpts, so install, in-place update and
--check agree on the hash from every directory, and a project-worded section
left in ~/.claude/CLAUDE.md reads as stale and is reworded by --global. The
new minimal-user and full-user variants are pinned by golden and hash; the
project rendering is unchanged.

Also pin sameDir's symlink following: --check from a symlink to $HOME or to
~/.claude still judges the user-level files.

Refreshed onto main past #7692, whose --remove takes the blank lines
around the section with it and whose setup appends a section after one
blank line: claude-setup-global-beside-project-install.golden no longer
records the old hole (an extra blank line before the appended section,
two left behind by --remove --global).

Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Co-authored-by: Eddie the Engineer <338826946+gascity-eddie[bot]@users.noreply.github.com>
2026-10-19 12:22:04 +00:00
Julian Knutsen
2829d22192
test(oracle-a): let scenarios that start with init own initialization (#7704)
run_scenario always ran `bd init -p <prefix> --quiet` before a scenario's
steps. 43 deterministic catalog scenarios start with their own
`init --prefix X --non-interactive ...`; in 40 of them that step always hit
"This workspace is already initialized" (exit 1), pinning the double-init
refusal instead of a real init. The other 3 fail flag validation first,
which is what they test, and are unchanged. Their later steps (the commands
they are named for) ran against the harness's own pre-init and are
unaffected.

A scenario whose first step's command token is `init` now owns
initialization (Scenario::owns_init) and starts in an empty workspace; every
other scenario keeps the pre-init, and a later `init` step stays a re-init.
The pre-init decision is the pure harness_init() helper, and the step loop
is run_steps(), which takes the command runner as a closure.
normalize() now collapses the `Repository ID`/`Clone ID` values a real init
prints (hashed from the random workspace path) to <REPO_ID>/<CLONE_ID>.
init_proxied_server_not_implemented is marked deterministic:false: its
premise is stale and, un-masked, it starts a managed dolt sql-server.

New tests cover the owns_init rule, the harness_init decision, the
run_steps argv sequence (via a recording closure) and the fingerprint
normalization. None spawns a process, so none can hit the write-then-exec
ETXTBSY race against the suite's process-spawning tests.

Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-19 10:57:02 +00:00
Julian Knutsen
21dac62a4c
fix(init): drop bd dolt push from AGENTS.md Quick Reference without a remote (#7694)
A new AGENTS.md written by bd init rendered its managed section with the
HasRemote/NoPush rule, but wrote the template text around it verbatim, so
the Quick Reference still listed `bd dolt push` in workspaces with no Dolt
remote or declared no-push. Add EmbeddedDefaultWithOpts, sharing one
omitsDoltPush predicate with the managed-section renderer, and use it for
new AGENTS.md files. Managed-section bytes and hashes are unchanged; an
existing AGENTS.md and a custom --agents-template are written as before.

Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-19 10:36:59 +00:00
gascity-eddie[bot]
4c473b4580
fix(query): report an uppercase duration unit as an unparseable time, not a negated internal error (#7683)
* refactor(timeparsing): export IsCompactDuration

The query lexer keeps its own copy of the compact-duration unit set, and
that copy has drifted from the grammar: it accepts the uppercase units
H D W M Y, which ParseCompactDuration rejects. Export the classifier so
the lexer can ask timeparsing instead of keeping a copy, and pin that it
agrees with ParseCompactDuration on every row, uppercase spellings
included.

AC: AC-1
Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(query): classify durations with timeparsing.IsCompactDuration

The query lexer kept its own copy of the compact-duration unit set:
isDurationSuffix for single runes and durationWords for "min". The copy
had drifted. It accepted H D W M Y, which the case-sensitive grammar
rejects, so "created>30M" reached the evaluator as a duration and failed
with the internal error `not a compact duration: "-30M"`, quoting a value
the user never typed.

Classify the whole digit-led lexeme with timeparsing.IsCompactDuration
and delete the copy (isDurationSuffix, durationWords, acceptDurationWord).
Uppercase units now lex as identifiers and fail as an unparseable time;
every lowercase input lexes as before. A unit added to compactDurationRe
now reaches the lexer with no edit here: with "sec" added to the regex
alone, TestCompactDurationGrammarReachesQueryPlane fails on the old lexer
and passes on this one. Retire that test's text naming the deleted copy.

AC: AC-2
Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(query): pin that uppercase duration units lex as identifiers

"updated>30M", "updated>30H" and "label=30D" lex the value as one
TokenIdent with the text as typed; "updated>30m" and "updated>+30d"
still lex as TokenDuration. On the base lexer the three uppercase rows
fail (typed DURATION).

AC: AC-3
Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(query): pin the error for an uppercase duration unit

created>, updated<, closed>= and started<= compared to 30M, 30D, 30W,
30Y, 30H or 1H, alone or in "... OR status=open", fail with
`cannot parse time expression: "<value as typed>"`, never with the
internal `not a compact duration` error and never quoting the negated
"-<value>". 30MIN and 30Min, which always took this path, are the
controls. On the base lexer 30 of the 40 subtests fail; the 10 controls
pass.

AC: AC-4
Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(query): bind the lexer's duration grammar to timeparsing both ways

TestCompactDurationGrammarReachesQueryPlane asserted only that every
suffix ParseCompactDuration accepts lexes as a duration. Assert the
reverse too: a suffix it rejects must not lex as TokenDuration, or the
evaluator fails on it with ParseCompactDuration's internal error about a
negated value. Widen the candidates to every one- and two-letter ASCII
suffix in either case, every three-letter lowercase one, and every case
spelling of an accepted three-letter unit.

On the base lexer the reverse sweep fails on exactly [D H M W Y]. A
mutant that case-folds before classifying fails it on those plus the
seven other spellings of "min".

AC: AC-5
Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(query): pin that a signed uppercase unit stops at the parser

"created>+30M" and "created>-30M" fail Parse and EvaluateAt with
`unexpected token "M" at position 11 (expected end of query)`, as
"created>+30x" already does: a signed digit run has no identifier
fallback, so "+30" is a number and "M" a stray token. On the base lexer
both parsed as a duration and failed in the evaluator with
`not a compact duration: "-30M"` and `"--30M"`; the +30x control passes
on both.

AC: AC-6
Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(query): pin the values rejecting uppercase units leaves alone

At a fixed now, created>+30d is still 30 days ago, updated>5pm still
17:00 that day, and label=30M / title=30M still filter the literal
"30M". TestQueryMinutesUnitResolvesAgo already pins created>30m (30
months ago) and created>30min (30 minutes ago). These rows pass on the
base lexer as well, which is the point; a lexer mutant that stops typing
signed lexemes as durations fails the +30d row.

AC: AC-7
Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Eddie the Engineer <julianknutsen@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 09:18:13 +00:00
gascity-eddie[bot]
994f5b82dd
fix(config): stop bd config set truncating config.yaml at a 64 KiB line (#7670)
* fix(config): stop bd config set truncating config.yaml at a 64 KiB line

updateYamlKey's flat-key path reads config.yaml through a default
bufio.Scanner and never checked scanner.Err(). A line of
bufio.MaxScanTokenSize (65,536) bytes or more makes Scan return false
partway through the document, so the function returned the lines read
so far with a nil error and setYamlConfigAtPath wrote them over the
file, dropping the long line and everything after it. Measured at
5c9c02ab77: a 65,550-byte document came back as the 8-byte
`k1: "zz"` when the key was present, and as 16 bytes when it was absent
(the new key appended onto the truncated prefix).

Check scanner.Err() after the loop and refuse with an error that wraps
bufio.ErrTooLong. It is returned before setYamlConfigAtPath's
os.WriteFile, so `bd config set` and `set-many` now fail and leave the
file as it was. The guard returns only on a scan error, so a document
whose lines all fit gets the same rewrite as before. Unset
(commentOutYamlKey) already splits instead of scanning, and dotted keys
rewrite through yaml.Node, so neither needs it.

TestUpdateYamlKeyRejectsOversizeLine fails at the base (nil error, 8-
and 16-byte results) and passes with the guard. Adds a CHANGELOG
Fixed entry.

AC: AC-1
Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(config): pin that a line just under the scanner limit still rewrites

The oversize-line refusal must fire only at the bufio.Scanner cliff. The
default scanner buffer holds bufio.MaxScanTokenSize (65,536) bytes, so a
line of 65,535 bytes still fits with its newline, and updateYamlKey has
to give a document with such a line the same rewrite a short document
gets: the key replaced in place when present, appended when absent.

Adds both rows to TestUpdateYamlKeyRejectsOversizeLine. They pass at the
base and with the AC-1 guard, which returns only on a scan error. Two
over-eager variants of the guard pass the existing yaml tests and the
AC-1 rows but fail these rows: capping the scanner buffer at
MaxScanTokenSize-1, and a pre-scan length check that refuses a line of
MaxScanTokenSize-1 bytes.

AC: AC-2
Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(config): pin that a refused bd config set leaves config.yaml unchanged

setYamlConfigAtPath reads config.yaml, rewrites it through
updateYamlKey, and writes the result back. The AC-1 guard makes
updateYamlKey refuse a document with a line of bufio.MaxScanTokenSize
bytes or more, and setYamlConfigAtPath returns that error before its
os.WriteFile, so the file is never touched. No test covered that order.

TestSetYamlConfigAtPathOversizeLineLeavesFileUntouched writes a
config.yaml with a 65,538-byte comment line, sets no-db, and checks that
the error wraps bufio.ErrTooLong and that the file still holds all
65,563 of its bytes. At 5c9c02ab77 it fails both checks: a nil error,
and the file cut to the 11-byte `no-db: true`. It passes with the AC-1
guard and needs no code change of its own. A variant that writes the
file before returning the error fails the byte check (0 bytes left), and
one that swallows the error fails the error check.

AC: AC-3
Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(changelog): say set-many keeps keys it wrote before a refused one

The entry said `bd config set` and `set-many` both fail and leave
config.yaml as it was. That holds for `set`, and for a `set-many` whose
first config.yaml key is the refused one. But `set-many` writes its
config.yaml pairs one at a time, in argument order, and returns on the
first error with no rollback, so a key listed before the refused
undotted key (a dotted `sync.remote`, say) is already on disk when the
command exits 1.

Measured at 0d3aa63761 with a 70,000-byte comment line in config.yaml:
`bd config set-many sync.remote=git@example.com:o/r.git actor=bob`
exits 1 and adds the `sync:` block (70,039 -> 70,083 bytes);
`set-many actor=bob sync.remote=...` and `bd config set actor bob` exit
1 and leave the file byte-identical.

de330c3e7f's message makes the same claim; this commit does not rewrite
it.

Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Eddie the Engineer <julianknutsen@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Eddie the Engineer <338826946+gascity-eddie[bot]@users.noreply.github.com>
2026-10-19 09:15:48 +00:00
Julian Knutsen
4c48829c07
fix(list): print bd list --format dot in a deterministic order (#7688)
outputDotFormat declared nodes and edges in the order of the list page it
was handed. The default page order breaks priority ties by created_at at
one-second precision, so two equal-priority issues swapped places depending
on whether they were created in the same second, and the proxied route's
edge query orders by source only. The same graph printed different bytes
(Oracle A list_dot_format_dependency_edges flipped between runs).

Declare nodes in byte order of id and each node's edges in byte order of
(target, type), on copies of the caller's slices. --sort and --limit still
choose which issues are listed.

Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-19 08:59:23 +00:00
Steve Yegge
d855ac6c88
test(bazel): pin vet policy to module toolchain (#7668)
* test(bazel): pin vet policy to module toolchain (wy-kk1b9a)

Agent-Signature: codex-unknown-model-unknown-reasoning on behalf of Steve Yegge

* test(bazel): report an unavailable pinned toolchain as a missing host tool

Review fixes for #7668 (adopt-pr iterations 1-2).

The GOTOOLCHAIN pin added a failure path that base did not have. A host
that runs another Go release and cannot fetch go.mod's toolchain
(offline, GOPROXY=off, empty module cache) failed
TestPRRunsGoTestsBazelSkips with a bare "exit status 1": cmd.Output()
keeps the go command's stderr in the ExitError, and t.Fatal printed
only the status.

- Report the failure through skipOrFailWithoutHostTool, naming the
  pinned version and the go command's stderr when it printed any.
  Plain go test skips; Bazel still fails, and there the registered SDK
  is go.mod's toolchain, so nothing is fetched.
- Compare VET_PASSES in a subtest, so the skip covers only the check
  that needs the toolchain. Given the parent's t, it skipped the whole
  test, and with it the six checks after it that read only the
  checkout. A failed subtest still fails the parent, so Bazel stays
  fail-closed.
- Pad a two-component version ("go 1.26" with no toolchain line) to
  go1.26.0 in goToolchainName, as scripts/ci/gofmt-bin.sh does.
  GOTOOLCHAIN=go1.26 is rejected as a language version, not a
  toolchain version. A table test pins 1.26, 1.26.7 and 1.26rc1.
- Say in the helper comment that the pin overrides an ambient
  GOTOOLCHAIN, local included, and may download into GOMODCACHE.

Validated with go1.26.7-built test binaries under env -i, GOPROXY=off,
with an empty HOME and module cache unless noted:
- go1.26.9 host: the VET_PASSES subtest skips, naming go1.26.7 and
  "toolchain not available", and the parent passes. With a planted
  scripts/ci/go-test-vet.sh the parent fails, as on base; iteration 1
  skipped the whole test there (rc 0). Same on go1.26.5 with
  GOTOOLCHAIN=local.
- go1.27.1 host with go1.26.7 cached: passes; base fails on
  stdversion. go1.26.7 host: passes.
- Bazel branch (TEST_SRCDIR, BEADS_TEST_GO): SDK go1.26.7 passes. SDK
  go1.26.9 fails the subtest and the parent with "executor lacks a
  host tool". A non-executable SDK path ends the message with the exec
  error, with no dangling ": ".
- go.mod "go 1.26" without a toolchain line: passes on go1.26.0 and
  under Bazel with SDK go1.26.0; a go1.26.9 host skips, naming
  go1.26.0. Iteration 1's unpadded mutant only skipped under plain go
  test (it failed under Bazel); the table test now fails it, and fails
  mutants that count dots or drop the regex anchors.
- go test ./scripts on go1.26.7: 306 pass, 0 fail, 1 skip; the only
  outcomes not on iteration 1 (305/0/1) are the two new tests passing.
  go vet ./scripts and the pinned gofmt -l are clean.

Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Eddie the Engineer <338826946+gascity-eddie[bot]@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 08:52:30 +00:00
gascity-eddie[bot]
395e7beec0
fix(config): stop bd config set dropping the file's trailing newline (#7669)
* fix(config): keep config.yaml's trailing newline on bd config set

updateYamlKey's flat-key path, which `bd config set` takes for every
single-segment key, read the document with bufio.Scanner and joined the
lines back with "\n". ScanLines drops the final terminator, so the result
was exactly one newline short of any terminated config.yaml:
"issue_prefix: vp\ndolt.mode: server\n" came back without its final
newline, a spurious no-newline-at-end-of-file change in a git-tracked file.

Re-attach the input's own trailing run at the return, the tail
commentOutYamlKey got for the unset side in #6749. One statement covers
both the in-place and the appended branch, and a document without a
trailing newline still does not acquire one. The TODO that recorded the
defect is removed in the next commit.

The test file's header now covers both verbs; the set test follows the
unset ones.

AC: AC-1
Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* chore(config): drop the TODO that deferred the bd config set newline fix

The TODO above updateYamlKey's return recorded that `bd config set` was
knowingly left one newline short, as a scope call in #6749. The previous
commit fixed that, so the TODO now describes a defect that no longer exists.

Check: searching internal/config/yaml_config.go for the phrase
"`bd config set` is knowingly left unfixed" finds one match at the base
and none after this commit.

AC: AC-11
Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(config): pin a set's blank-line trailing run, not just a final newline

A config.yaml that ends in one or two blank lines came back from
`bd config set` one newline short, so the output still ended in "\n".
Compare the exact trailing run, as the unset table does, so that loss
stays visible. Both rows fail on the base code (run "\n" vs "\n\n", and
"\n\n" vs "\n\n\n") and pass with the tail fix.

AC: AC-2
Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(config): pin the appended key's terminator on bd config set

When the key is absent, updateYamlKey appends it as the new last line,
and the old join left that line unterminated: "x\n" came back
"x\n\nnewkey: \"v\"". Pin the exact output for "x\n", where the separator
blank line is kept and the newline follows the new key, plus a table row
for the trailing run. Both fail on the base code and pass with the tail
fix.

AC: AC-3
Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(config): pin a set appended over a blank-line tail

For "x\n\n" without the key, the existing blank line already separates,
so updateYamlKey adds no second one and the document's own two-newline
run now follows the new key: "x\n\nnewkey: \"v\"\n\n". Restoring a single
newline would leave this exact shape one short again, so pin it exactly,
plus the matching table row. Both fail on the base code, which returned
"x\n\nnewkey: \"v\"", and pass with the tail fix.

AC: AC-4
Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(config): pin that a set does not invent a trailing newline

The repair re-attaches the document's own trailing run instead of appending
a newline, so a config.yaml that ends without one still ends without one
after `bd config set`. Pin that for both branches: a present key rewritten
in place, and an absent key appended as the new last line.

This passes on the base as well; it is a pin on "preserve, not append".
The always-append mutant (`return out + "\n", nil`) turns both inputs red.

AC: AC-5
Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(config): pin a set's output on a CRLF config.yaml

A set of a single-segment key has always rewritten a CRLF document to LF,
because the scan drops each line's "\r". What the old join added on top was
a missing terminator: "actor: a\r\nother: x\r\n" came back
"actor: \"b\"\nother: x". With the restored tail it comes back
"actor: \"b\"\nother: x\n", which is also how an unset of the same document
ends.

Pin the exact output, and check the trailing run against commentOutYamlKey
on the same input, in a subtest named after unset's CRLF subtest. It fails
on the base (exact and parity) and passes with the tail from AC-1.

AC: AC-6
Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(config): keep a CRLF config.yaml's blank-line tail on bd config set

The restored tail measures the trailing run on the raw content, where
strings.TrimRight(content, "\n") stops at the last "\r". On a CRLF file the
re-attached run was therefore always a bare "\n", however many blank lines
followed: "actor: a\r\nother: x\r\n\r\n\r\n" came back "…x\n", one newline
shorter than even the base's "…x\n\n".

Normalize CRLF the way commentOutYamlKey does before the scan, so the run is
the LF run and a set ends the file exactly as an unset of the same document
does. The scan output is unchanged, since ScanLines already drops each
line's "\r". The line sits below the nested dispatch, not at the top: some
updateNestedYamlKey branches carry "\r" through on untouched lines, and
this fix leaves that path alone.

Also correct the comment on unset's CRLF subtest, which still blamed a
leftover "\r" for the bare-"\n" tail; commentOutYamlKey normalizes up front,
so that mechanism no longer exists and the new set cases contradict it.

AC: AC-7
Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(config): pin the trailing newline through SetYamlConfig

setYamlConfigAtPath writes updateYamlKey's output verbatim, so the dropped
newline reached the git-tracked config.yaml. Add the writer-level twin of
TestUnsetThroughTheFileKeepsTheTrailingNewline: a .beads/config.yaml ending
in a blank line, BEADS_DIR pointed at it, SetYamlConfig("actor", "bob"),
and the re-read file must keep its "\n\n" run. It first checks that the
value landed, so an untouched file cannot pass.

On the base the run comes back "\n"; with the tail from AC-1 it is "\n\n".

AC: AC-8
Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(config): pin that a set of a dotted key bypasses the CRLF normalization

The CRLF normalization in updateYamlKey sits below the nested dispatch on
purpose. replaceFlatKeyLine and appendNestedYamlKey keep "\r" on the lines
they leave alone, so hoisting the line above the dispatch would silently
change what a dotted-key set writes:
"issue_prefix: vp\r\ndolt.mode: server\r\n" comes back
"issue_prefix: vp\r\ndolt.mode: \"embedded\"\n" today and would lose the
first "\r".

Compare updateYamlKey with updateNestedYamlKey on four CRLF documents for
dolt.mode: a literal dotted key, a nested block, an absent key, and a
comment-only document. This passes on the base as well; it pins the
boundary, not the nested writer's outputs. The hoisted mutant turns the
literal-dotted-key and comment-only rows red; the other two are re-marshalled
to LF either way.

AC: AC-9
Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(config): append an absent key after a blank-line tail as one line

updateYamlKey's flat path appends an absent key after the scan's empty
tokens for the file's trailing blank lines, so those blank lines already
sit ahead of the new line; the tail rule then re-attached content's whole
run after it as well. A set of a new single-segment key on a file ending
in blank lines therefore repeated them at EOF: "x\n\n" came back
"x\n\nnewkey: \"v\"\n\n", "x\n\n\n" came back
"x\n\n\nnewkey: \"v\"\n\n\n", and CRLF "x\r\n\r\n" came back
"x\n\nnewkey: \"v\"\n\n" -- the diff noise this PR exists to remove.

The appended branch now re-attaches only the one terminator
bufio.Scanner dropped, and only when content had it; the in-place branch
keeps the TrimRight + content's-run rule it shares with
commentOutYamlKey. The appended-key subtest now wants
"x\n\nnewkey: \"v\"\n", adds "x\n\n\n" and CRLF rows, and drops the
comment claiming a single terminator would leave it one newline short.
The suffix-run table drops its blank-tail append row, whose expectation
assumed the file's run follows the key, and
TestSetOfAnAbsentKeyThroughTheFileAddsOneLine pins the shape through
SetYamlConfig. The doc comment states the nested boundary and the tail
rule.

Not changed here: the unchecked scanner.Err() is #7670's fix (its guard
lands right after this scan loop, and ./internal/config/ is green on the
union of both PRs). The stale bufio.Scanner narration in
commentOutYamlKey's comment stays a follow-up, since #7613 edits that
function.

Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Eddie the Engineer <julianknutsen@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Eddie the Engineer <338826946+gascity-eddie[bot]@users.noreply.github.com>
2026-10-19 08:49:00 +00:00
Julian Knutsen
c67a36e5e7
fix(cli): refuse backup init/sync/remove/restore and import under strict --readonly (#7673)
* fix(cli): refuse backup init/sync/remove and import under --readonly

Strict --readonly is meant to refuse every command that writes, with
"Error: operation '<op>' is not allowed in read-only mode" and exit 1.
bd backup init, backup sync, backup remove and bd import never called
CheckReadonly, so that gate never refused them:

- On a server-mode store they ran to completion under --readonly:
  backup init and backup remove rewrote or emptied the server's
  dolt_backups registry, backup sync wrote the backup destination, and
  import wrote issues.
- On an embedded store they failed only because the store was opened
  read-only, with the storage layer's "store is read-only" text, and
  backup sync took the backup lock first and left .beads/backup.lock
  behind.

The three backup verbs now call CheckReadonly first in their RunE, as
the other write commands do. Its migration-freeze half is redundant for
them: their leaf names are not on the read-only list and they have no
preview flag, so PersistentPreRunE's early freeze gate refuses them
first.

bd import calls it only when --readonly is set. CheckReadonly also
answers a migration freeze, and does so by exiting the process, while
runImport answers a freeze by returning the error so cleanup still
runs; guarding the call leaves that path exactly as it was.

bd import --dry-run is refused too. The preview opens the store
read-only and writes nothing, so this is a policy choice. It matches
create --dry-run (also refused under --readonly) and import's own
freeze posture: a migration freeze already refuses import --dry-run
(TestImportBlockedDuringMigrationFreeze), and CheckReadonly treats the
two gates as one. The cost is small, since the same preview runs
without --readonly. bd backup status and bd backup itself (a command
group that only prints help) stay allowed.

TestBackupAndImportBlockedInReadonlyMode runs each command, plus
import --dry-run, under --readonly and --readonly --sandbox against an
embedded workspace and one on the Dolt test server. Each row expects
exit 1, exactly the standard refusal on stderr, an empty stdout, and
nothing changed: the .beads tree, the backup destination, the issue
count, and, in server mode, the dolt_backups registry.
TestBackupStatusAndListWorkInReadonlyMode is the control showing that
backup status and list still run.

Ported from the versioned-beads fork: b86df6a9eb (test) and
5a067acc56 (fix). The comment on TestImportBlockedDuringMigrationFreeze
is updated, since runImport now calls CheckReadonly under --readonly.

Co-authored-by: Jim Wordelman <jim@wordelman.name>
Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(backup): refuse --readonly backup restore before the exclusive gate

A restore replaces the store, so strict --readonly must refuse it.
Nothing did:

- In server mode no storage layer stops the connection, so
  `bd --readonly backup restore --force` ran to the end: exit 0,
  "Restore complete", and the store was replaced.
- In embedded mode the command took the EXCLUSIVE workspace gate first,
  leaving the holder sidecars (.beads.gate.lock.info,
  .beads/embeddeddolt.gate.lock.info) behind, and was stopped only
  later by the storage layer's "store is read-only".

acquireCommandWorkspaceGates now calls CheckReadonly("backup restore")
first for the exclusive (restore) case when readonlyMode is set. That
is before any gate file is created or the store is opened, so nothing
is held and the exit skips no release. The guard checks readonlyMode
alone, so a restore without --readonly, including one refused by a
migration freeze, keeps its existing order. The restore RunE also calls
CheckReadonly first, as every write command does.

This does not depend on the strict-readonly SHARED-gate change
(workspacegate.Options.ReadOnly): the refusal comes before any gate is
built.

The one visible change in proxied-server mode, where every --readonly
command is already refused: `bd --readonly backup restore` now gets
this standard refusal (plain text, exit 1). Before, the proxy
capability refusal answered it (exit 1, typed JSON under --json), and
only after the exclusive gate had been taken.

TestEmbeddedBackupRestoreStrictReadonly and
TestBackupRestoreStrictReadonlyServerMode run the built bd as a
subprocess, because CheckReadonly exits. The workspace's live store
holds three issues and its backup holds two. Each test asserts the
standard refusal with exit 1 and an empty stdout, no storage-layer
message, an unchanged project directory and .beads tree, and an
unchanged issue count. Each runs under --readonly and under
--readonly --sandbox. A control restores without --readonly and
expects two issues, so "unchanged" cannot be vacuous.

Ported from the versioned-beads fork: 1cd5f1c202 (test) and
6ac79d6207 (fix). The fork's test used a dirEntryNames helper that
belongs to its separate SHARED-gate change. It is inlined here so this
change compiles and lands on its own in either order. The server test's
comment is corrected too: the fixture's backup and the restore both run
inside the server at the same path, so it passes against a
containerized test server as well as a local one.

Co-authored-by: Jim Wordelman <jim@wordelman.name>
Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Jim Wordelman <jim@wordelman.name>
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-19 08:48:37 +00:00
Julian Knutsen
9893f9020d
fix(setup): leave a current agents-file beads section untouched (#7693)
* fix(setup): leave a current agents-file beads section untouched

installAgents rewrote the instructions file whenever it found a beads
marker, discarding ReplaceSectionWithOpts' changed flag and error. A rerun
of `bd setup claude` (and `bd init`, which runs it) replaced a byte-identical
CLAUDE.md with a new file (new inode, fresh mtime, mode reset to 0644) and
reported "Updated existing beads section", while bd init's updateAgentFile
reported AGENTS.md current in the same run. A section whose END marker was
lost or came before BEGIN was likewise "updated" without change.

Mirror updateAgentFile: write only when the section changes, report
"<file> already has the current beads section" otherwise, and return
ErrMalformedMarkers instead of rewriting. claude/gemini warn and continue;
factory/opencode/mux fail (mux before installing its .mux hooks), per their
existing error policies. Tests pin inode, mode and mtime of the untouched
file and the claude/mux policies for both malformed-marker shapes. Goldens
updated for the new rerun message.

Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(setup): keep CLAUDE.md's beads block when the AGENTS.md update fails

When CLAUDE.md is an @AGENTS.md stub that still holds a beads block,
installClaude strips that block once the redirect is active, gated only on
installAgents not having skipped a symlinked AGENTS.md. It ignored
installAgents' error, so now that installAgents returns ErrMalformedMarkers
instead of writing a malformed AGENTS.md back, the strip deleted the stub's
block while AGENTS.md kept no usable section, and the warning named
CLAUDE.md. Base had the same end state behind a false "Updated" report; the
new error is what makes the failure detectable, so the gate belongs here.

Gate the strip on a nil installAgents error too, so it runs only once
AGENTS.md holds the current section (written now or already current), and
name the file that failed in the warning (AGENTS.md when redirected). A
redirect subtest in TestInstallClaudeWarnsOnMalformedMarkers pins both, for
both malformed shapes: dropping the gate reds it on CLAUDE.md's content,
inode, mtime and mode, and naming CLAUDE.md again reds it on the warning.

Also correct updateBeadsSectionWithProfile's doc comment, which claimed an
error string it never returned: it returns the content unchanged when the
section cannot be replaced. The CHANGELOG entry notes the redirect case.

Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Co-authored-by: Eddie the Engineer <338826946+gascity-eddie[bot]@users.noreply.github.com>
2026-10-19 08:45:04 +00:00
gascity-eddie[bot]
6db46664da
test(cmd/bd): pin mixed-case dep tree --format Mermaid through the CLI (#7697)
* test(cmd/bd): pin mixed-case dep tree --format Mermaid through the CLI

TestDepTreeFormatMermaidCaseInsensitive calls isMermaidTreeFormat directly,
so reverting the runDepTree dispatch to formatStr == "mermaid" (the PR #6646
bug) kept every test green. Add a --format Mermaid call to the embedded
tree_format_mermaid subtest so the flag-to-renderer wiring is pinned.

AC: AC-1
AC: AC-2

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit c325246d4a)

Ported-From: opus/c325246d4a8e4cd5f60f9548053b5385e20a4d2e
AC: AC-1

* test(cmd/bd): record AC-2 mutant evidence for the mixed-case pin

No code change: AC-2 is the mutant-killing property of the row added in
the AC-1 commit. Evidence (bazel test //cmd/bd:bd_test --config=ci
--test_filter='TestDepTreeFormat|TestEmbeddedDepBTreeAndCycles/tree_format_mermaid'
--test_arg=-test.skip= --test_env=BEADS_TEST_EMBEDDED_DOLT=1
--test_output=all):

- Mutant M1 (cmd/bd/dep_tree.go:153 changed to formatStr == "mermaid",
  isMermaidTreeFormat left intact), row absent: all targeted tests pass —
  the hole.
- M1 applied, row present: TestEmbeddedDepBTreeAndCycles/tree_format_mermaid
  FAILS with the plain-text fall-through header ("Dependency tree for"),
  while TestDepTreeFormatMermaidCaseInsensitive, TestDepTreeFormatFlag and
  the lowercase e2e row stay green.
- M1 reverted, row kept: all pass; no SKIPs in any run.

AC: AC-2
Agent-Signature: claude-code-glm-5.3-unknown-reasoning on behalf of Julian Knutsen
Co-Authored-By: Claude Code <noreply@anthropic.com>
(cherry picked from commit 38df0c5b22)

Ported-From: glm/38df0c5b224c41fa312dd130b8e7fe378d74b0b4
AC: AC-2

---------

Co-authored-by: Julian Knutsen <julianknutsen@users.noreply.github.com>
2026-10-19 08:36:16 +00:00
gascity-eddie[bot]
8f960b1b6e
test(cmd/bd): pin count and omitted flag on the embedded wisp include view (#7698)
* test(cmd/bd): pin comments_omitted on the embedded wisp count-only view

show_json_wisp_comment_count asserted comment_count and the absent
comments slice but never read comments_omitted, the flag the GH#5565
fix unlocks. A regression that stops setting it stayed green here.

AC: AC-1

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 9b5be54bdf)

Ported-From: opus/9b5be54bdf3c4ef69f5b8eaf68770b26b102ff35
AC: AC-1

* test(cmd/bd): add the embedded --include-comments wisp twin

The proxied plane pins a wisp's comment behavior with a pair of
subtests; the embedded plane had only the count-only half. Add
show_json_wisp_comments_include_streams, which asserts that
--include-comments streams both of a wisp's comments, and let
bdShowDetails carry extra flags after --json.

AC: AC-2

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit d1795e55f1)

Ported-From: opus/d1795e55f15710e3112a37852361f577d42eeff9
AC: AC-2

* test(cmd/bd): pin count and omitted flag on the embedded wisp include view

GH#5565's symptom was --include-comments returning rows the count said
did not exist. Assert the include payload's comment_count matches the
streamed rows and that comments_omitted stays absent (omitempty) when
rows are present.

AC: AC-3

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit ae43c79065)

Ported-From: opus/ae43c790652261e5d004bdc1b23b768a391ce8a9
AC: AC-3

---------

Co-authored-by: Julian Knutsen <julianknutsen@users.noreply.github.com>
2026-10-19 08:31:05 +00:00
Julian Knutsen
ee441fdc73
fix(setup): stop leaving a blank-line hole on --remove (#7692)
`bd setup claude --remove` (and the factory, mux, opencode and gemini
recipes that share removeBeadsSection) cut exactly the managed section
and kept the blank lines that set it off, leaving a 3-line hole in the
CLAUDE.md bd init writes. installAgents then appended a re-added section
after two blank lines, so every remove/re-add cycle grew the file.

removeBeadsSection now drops the line breaks next to the section (never
text): the surrounding text is rejoined with one blank line, or none if
the section had none; a section at the top leaves no leading blank
lines and one at the bottom leaves a single final line break. CRLF is
preserved, and a marker sharing its line with text is still cut
exactly. installAgents appends like bd init's updateAgentFile: ensure a
final newline, then one blank line. remove(add(x)) == x for a file
ending in a newline, and after the first remove, setup and --remove
toggle between the same two files; a re-added section goes at the end.

Goldens regenerated with BD_UPDATE_GOLDEN=1.

Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-19 08:28:18 +00:00
Julian Knutsen
5e2158ea08
fix(setup): route Claude hook-removal lines through the installer output (#7691)
bd init --quiet still printed "✓ Removed SessionStart hook" and
"✓ Removed PreCompact hook" when the project's .claude/settings.json (or
the legacy settings.local.json) carried the bare `bd prime` hooks an older
bd registered. removeHookCommand printed with fmt.Printf straight to the
process stdout, bypassing the discarding writer that --quiet hands the
project installers.

removeHookCommand now takes the caller's writer; Claude and Gemini pass
env.stdout at every call site. bd setup claude/gemini print the same
lines in the same order; quiet init drops them while still migrating the
hooks. This is the removal half of the #7186 class; #7195 covers
addHookCommand and the two changes merge cleanly in either order.

Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-19 07:44:30 +00:00
Julian Knutsen
fb912f2438
fix(oracle-a): write scoreboard failure detail per run, not to shared /tmp (#7690)
The scoreboard dumped every in-scope failure to the host-global
/tmp/oracle-a-failures.txt, and run-oracle-a.sh copied it into its scratch
dir only after scoring finished. A concurrent scoreboard (another worktree,
a shard, another user) finishing in between overwrote or swapped the
detail, so a failing run could print nothing or another run's divergence.

The scoreboard now honors ORACLE_FAILURES_FILE (unset or empty keeps the
historical /tmp default for standalone use), and run-oracle-a.sh points it
at $SCRATCH/oracle-a-failures.txt and prints that file directly. The cp
and the /tmp fallback are gone.

Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-19 07:34:17 +00:00
Julian Knutsen
e3efb3107a
test(oracle-a): always remove the reference worktree on exit (#7689)
run-oracle-a.sh's EXIT trap removed its reference worktree only when
`git worktree list --porcelain | grep -qF "$REF_SRC"` matched. Under
pipefail that check reported a registered worktree as absent in two ways:
grep -q exits on its first match while git is still writing a large
listing, so git dies of SIGPIPE (141) and the pipeline fails; and git
lists the resolved path, which $REF_SRC never matches when $TMPDIR has a
trailing slash or runs through a symlink (both macOS defaults). Either
way the ref-src registration leaked as a prunable worktree.

Run `git worktree remove --force` unconditionally. It resolves the path
itself and fails harmlessly (silenced, `|| true`) when nothing is
registered, so cleanup is idempotent and exit codes are unchanged.

TestOracleAScriptRemovesItsReferenceWorktree runs the real script in a
fixture repo with a stand-in go that fails the reference build, covering
a >3 MB listing, a trailing-slash TMPDIR, a symlinked TMPDIR, and a run
that dies before the worktree is added.

Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-19 07:29:55 +00:00
Julian Knutsen
9e2f25c322
fix(http): bd link over a connected HTTP workspace, through the DependencyEditor role (#7685)
* fix(http): bd link over a connected HTTP workspace, through the DependencyEditor role

bd link wrote through the store's raw AddDependencyWithOptions, which the
HTTP client refuses by design (D8), so every bd link failed on an HTTP
workspace whatever the type. Its direct route now writes through the
DependencyEditor role with the helper bd dep add uses
(addDependencyEdgesDirect), which serves local stores and HTTP workspaces
alike: over HTTP one dependencies:add request, and the server already takes
any 1-32 character type.

link keeps its own checks before the write (and before the dial): the
dotted-child rule and the type's length only, never bd dep add's
well-known-type list. The proxied-server route is unchanged.

backend/http TestE2E_LinkOverHTTP covers owned-by and the other roadmap
types, the empty and over-long type refusals (no write reaches the server),
and the typed conflict for an edge of another type.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* build(bazel): auto-sync BUILD files

Applied from the bazel-sync-patch artifact of https://github.com/gastownhall/beads/actions/runs/39201892756
(`make bazel-sync`: gazelle, tools/bazel/go_srcs.py, bazel mod tidy).
Only BUILD.bazel, MODULE.bazel and MODULE.bazel.lock are ever pushed; see
scripts/bazel-autofix-push.sh.

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-10-19 07:15:13 +00:00
Julian Knutsen
786ed8a4b0
fix(show): exit 1 when bd show --as-of reads no issue (#7687)
showIssueAsOf reported each failed AS OF lookup on stderr and continued, but never counted what it read and returned nil, so a bad ref (an instant or a versioned-history address the Dolt AS OF read does not take, an unknown branch or commit) or an issue absent at the ref exited 0 with an empty stdout, under --json too. Its proxied-server twin, runShowProxiedAsOf, returned nothing and its dispatcher returned nil.

Both now count the issues they read and, when that is zero, end the way plain bd show ends a batch that found nothing: show's JSON error envelope on stdout under --json, a bare exit 1 otherwise, with the per-id reasons still on stderr. A batch that reads at least one issue still exits 0, as plain show's does. The read itself is unchanged (Dolt AS OF).

Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-19 07:10:26 +00:00
Julian Knutsen
36f81bab1c
test(cmd/bd): pin the command tree and representative --help output (#7675)
* test(cmd/bd): pin the command tree and representative --help output

Add two in-process goldens for the bd command surface, so any added,
removed, hidden or reworded command or flag fails until the goldens are
regenerated and shows up as a reviewed testdata diff:

- TestCommandTreeGolden walks the whole cobra tree (hidden commands
  included) and records, per command, Use, Aliases, Short, Long, Example,
  group, hidden/deprecated state, runnability and annotations, plus every
  local and persistent flag it defines (name, shorthand, type, default,
  usage, hidden, deprecation, annotations). Output is sorted and rendered
  twice to prove it is deterministic.
- TestCommandHelpGolden runs `bd <cmd> --help` through rootCmd for root,
  create, show, list, update, close, version, versions, config and serve.
  --help returns before the root pre-run, so no store is opened; color
  escapes are stripped. The snapshots are byte-identical to a built bd
  binary's --help output.

Both run from a fresh ordinary (dependency-mode) workspace: a
.beads/metadata.json with no graph marker and no database behind it.

The tree is primed the way the binary is (main()'s help command and its
--all/--doc/--list/--docs-root flags, ExecuteC's completion command), and
cobra's history-dependent pieces (the lazily added per-command --help flag,
the __complete request commands) are excluded, so the result does not
depend on which in-process tests ran first. The help runs reset every flag
afterwards so a later in-process command does not inherit --help.

docs/cli-docs.pin holds check-doc-flags at the v1.2.2 release, so drift on
main is not caught there; these goldens are the live guard. They pin the
cgo build (the !cgo build swaps in a federation stub). Regenerate with
BD_UPDATE_GOLDEN=1 go test -tags gms_pure_go ./cmd/bd -run '^TestCommand(Tree|Help)Golden$'.

Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* test(cmd/bd): keep the command goldens from merging flags into the shared tree

TestCommandTreeGolden read each command's flags through
LocalNonPersistentFlags, and TestCommandHelpGolden dispatches
`bd serve --help`. Both run cobra's mergePersistentFlags, which copies
every inherited persistent flag (--json, --db, ...) into the command's
own flag set for the rest of the process. TestServeFlags pins serveCmd's
exact flag set, so it failed whenever a golden test ran before it in the
same test binary: tree then serve flags, help then serve flags, and
-test.shuffle seeds 2 and 3, on the PR head and on its merge with main.
CI passes only because bd_test's 16 Bazel shards happen to run them in
different processes. Of 37 candidate tests, TestServeFlags is the only
one affected.

- goldenLocalFlags reads the set LocalNonPersistentFlags reports without
  calling it: c.Flags() minus c's own persistent flags and minus
  inherited copies. Like cobra, it treats a flag as inherited only if it
  is the nearest ancestor's own *pflag.Flag, so copies left by an
  earlier in-process execution are skipped and a flag that shadows an
  inherited one still renders.
- TestCommandTreeGolden fails if rendering changes the number of flags
  in any command's flag set.
- TestCommandHelpGolden calls restoreServeGlobals, which re-registers
  serveCmd's flags after the `bd serve --help` dispatch.

Review minors:
- The regeneration command (doc comment, failure-message constant,
  tree.golden header) sets CGO_ENABLED=1. Without cgo the file does not
  build, so the command matches no test and exits 0.
- enterOrdinaryWorkspaceForGolden calls isolateBeadsDirForTest.
- renderCommandHelpGolden's comment says when the ANSI strip matters.
- cmd/bd/AGENTS.md lists the goldens under "Adding a command" and
  "Guard tests".

Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Co-authored-by: Eddie the Engineer <338826946+gascity-eddie[bot]@users.noreply.github.com>
2026-10-19 05:56:15 +00:00
Julian Knutsen
eb5ab48950
test(setup): pin the Claude agent artifacts bd init and bd setup claude write (#7678)
* test(setup): pin the Claude agent artifacts bd init and bd setup claude write

Before-parity pin P11. Nothing pinned the agent artifacts byte for byte, so
a change to them -- a new hook event in .claude/settings.json, new text in
the minimal CLAUDE.md/AGENTS.md template and with it a new marker hash that
marks every installed section stale -- could land without anyone seeing
the user-visible diff. These goldens make any such change a reviewed diff.

- internal/templates/agents: TestManagedSectionGolden pins each managed
  section (minimal and full profile, with and without a Dolt remote)
  markers included; TestManagedSectionHashes pins their marker hashes as
  hand-maintained literals; NoPush is pinned to render the no-remote bytes.
- cmd/bd/setup: TestClaudeSetupArtifactsGolden records transcripts of
  bd setup claude, --check and --remove (project, --stealth, --global, a
  user's own settings and CLAUDE.md, a stale section, a legacy
  settings.local.json install, a CLAUDE.md that imports AGENTS.md): each
  step's result and output, and the settings and instruction files it
  creates, changes or deletes. TestClaudePluginManifestHookEvents pins the
  hook events and commands the beads Claude plugin declares.
- cmd/bd: TestEmbeddedInitAgentArtifactsGolden runs a real bd init (default
  and --agents-profile full) and then bd setup claude --check, --remove and
  a reinstall through the binary, with exit codes.

A managed section in a transcript is shown by its marker line and a
pointer to the template golden it is checked to match byte for byte, so a
template change shows up once in full and as a hash bump wherever it lands.
Regenerate with BD_UPDATE_GOLDEN=1.

CI companions: the new test files and testdata in BUILD.bazel (bd_test
gains its internal/templates/agents dep), and the new TestEmbedded* in the
100-shard embedded cmd manifest (incremental --write).

Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* test(setup): drop BD_OTEL_* and split HOME in the agent artifact golden

TestEmbeddedInitAgentArtifactsGolden pins bd's stderr byte for byte, but
bdEnv passes the caller's BD_OTEL_* variables through, and bd prints a
deprecation warning on stderr for a legacy one (BD_OTEL_METRICS_URL,
BD_OTEL_LOGS_URL, BD_OTEL_STDOUT=true) before it checks whether
telemetry is on. On a host that exports them (agent hosts do; CI does
not), both scenarios failed at the first stderr block with no code
drift.

The test now runs bd init and every bd setup claude step with
agentArtifactEnv: bdEnv(dir) without BD_OTEL_* and OTEL_*. It filters
the env slice instead of calling clearTelemetryEnv, which uses t.Setenv
and so cannot run in these parallel tests.

The same helper gives bd a HOME of its own instead of bdEnv's HOME ==
project. With the two equal, a bd that wrote the hook and CLAUDE.md into
the home directory instead of the project passed every pin. The
transcript now also records $HOME/.claude/settings.json and
$HOME/CLAUDE.md, and output paths under HOME read $HOME. bd init runs
the steps bdInit does (git repo, seeded schema) with that env.

The test doc now names what it does not pin: a proxied-server bd init
(no Codex section, HasRemote from its own remote URL), a bd init with a
remote, and the Cursor files. It also says a change to AGENTS.md's
wrapper text or Codex section can fail only here.

The goldens are unchanged.

Validation (env -i, go1.26.7, GOFLAGS=-mod=readonly, GOPROXY=off,
BEADS_TEST_EMBEDDED_DOLT=1, -tags gms_pure_go):
- the golden passes in a clean env; with BD_OTEL_METRICS_URL=x
  BD_OTEL_LOGS_URL=y; with every legacy selector plus BD_OTEL_ENABLED
  and OTEL_EXPORTER_OTLP_ENDPOINT; and under -race;
- the previous test with BD_OTEL_METRICS_URL=x BD_OTEL_LOGS_URL=y fails
  at golden line 132 on the deprecation warning;
- swapping homeDir and projectDir in setup's defaultClaudeEnv passes the
  previous test and fails this one at golden line 5 (the transcript
  shows created $HOME/.claude/settings.json).

Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Co-authored-by: Eddie the Engineer <338826946+gascity-eddie[bot]@users.noreply.github.com>
2026-10-19 05:19:28 +00:00
Julian Knutsen
3a5ade3a76
test(cmd/bd): pin workspace discovery refusal text and exit codes (#7677)
* test(cmd/bd): pin workspace discovery refusal text and exit codes

Add before-parity pins for what an ordinary bd prints, and with which
exit code, when workspace discovery cannot select a usable workspace:

- no .beads, an empty .beads, or a .beads with config.yaml but no
  metadata.json and no database ("no beads database found", and bd
  where's text and --json refusals);
- a corrupt metadata.json, for list, create, where (all refuse) and
  version (warns, exits 0);
- an exported BEADS_DIR naming a missing path, an empty directory, a
  regular file or a corrupt workspace, run from a corrupt workspace so a
  fallback to cwd discovery would show;
- .beads/.env: BEADS_DIR routing, an exported BEADS_DIR winning, BEADS_DB
  routing bd where but not a data command, BD_JSON applying only in the
  selected workspace, and a .env BD_BACKEND not being refused;
- .beads/redirect: missing and non-workspace targets (warning, then the
  source), a corrupt target, a chain, and a redirect behind BEADS_DIR;
- --db paths and names, and BEADS_DB / BD_DB, including the two
  inconsistencies main has today (a data command ignores BD_DB, and lets
  a discoverable cwd workspace shadow BEADS_DB, while bd where honors
  both);
- BD_BACKEND / BD_DATABASE_BACKEND being refused before any of the
  above, for store-less commands too.

The cases use workspaces with a corrupt metadata.json as sentinels: the
refusal names the metadata.json it failed to parse, which shows the
directory discovery selected without opening a store, so the store-less
pins need neither Dolt nor cgo. One embedded-Dolt pin covers the
store-backed .env case: BD_READONLY=true in .beads/.env refuses a write
with the read-only text and exit 1, reads still run, and an exported
BD_READONLY wins over the file.

These pin today's origin/main, not an ideal. A change that reorders
admission, discovery or checkBlockedEnvVars in the root PersistentPreRunE
now has to change an expectation here and is reviewed as a test diff.
Built from the merge base with the graph fork (46aa59cc65), bd passes
every store-less pin; the fork tip fails two (a BEADS_DIR naming a
regular file exits 5 with graph_not_initialized instead of exit 1, also
when BD_BACKEND is set).

Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* test(cmd/bd): keep the discovery pins independent of PATH and cgo

The version case under TestDiscoveryRefusalPinsCorruptMetadata pinned
bd version's full stderr. bd version also appends a "Warning: multiple
'bd' binaries found in PATH" block when the caller's PATH holds more
than one distinct bd binary (a release install plus a dev build, or
Homebrew plus go install), and the fixture passes the caller's PATH
through. Such a machine failed the pin spuriously. normalize now drops
that block from stderr, as it already drops the sandbox auto-detection
notice, so the rest of the case is still pinned exactly.

The file also said the store-less pins need no cgo. They need a cgo bd.
A CGO_ENABLED=0 bd is server-only, and its no-database hints add "run
'bd doctor' to diagnose", so a CGO_ENABLED=0 go test of the package
failed 16 cases on the hint wording alone. The file now builds only
with cgo, and its header says why. CI runs none of these in its
CGO_ENABLED=0 lane, whose -run subset is fixed by PURE_CMD_BD_TESTS.

Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* test(cmd/bd): pin a working-directory .beads that is a regular file

The ExplicitBeadsDir pins cover a BEADS_DIR that names a regular file.
This adds the same case reached by the working-directory walk instead:
a project whose .beads is a regular file. bd list and bd where both exit
1 with "Error: loading config: reading config: open
$ROOT/p/.beads/metadata.json: not a directory".

bd built from the fork merge base 46aa59cc65 passes both cases. The
fork tip b9eebc31f8 fails both: it exits 5 with "graph_not_initialized:
open $ROOT/p/.beads/graph-preview-format: not a directory", the same
reorder the BEADS_DIR pin already catches.

A .beads that is an unreadable directory (chmod 000) splits main and
the fork the same way, but it is not pinned: a test run as root can
still read the directory.

Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* test(cmd/bd): close the embedded discovery pin's environment

Maintainer fixup from the adoption review of #7677.

TestEmbeddedDiscoveryPinsEnvFileReadonly compares bd's output exactly,
but its run helper started from bdEnv, which drops only BEADS_* and
BD_ROUTING_MODE. Every other BD_* the caller exported reached bd: with
BD_OTEL_METRICS_URL/BD_OTEL_LOGS_URL set (as on agent hosts) the
deprecation warning lands in front of the read-only refusal, with
BD_JSON_ENVELOPE=1 the empty list is printed as an envelope, and in a
sandbox the "Sandbox detected" notice precedes the refusal; each failed
the pin. The run helper now uses the store-less pins' closed environment,
factored out of discoveryPinFixture.baseEnv as discoveryPinEnv (HOME stays
the directory bd init used), and drops the sandbox notice from stderr
with the same discoveryPinSandboxNotice pattern normalize now uses.

normalize collapsed every consecutive repeat of a stderr line, which also
hid a doubled "Error:" line. It now folds only repeated
"Warning: redirect" lines, the ones discovery prints once per re-resolve.

blocked-backend-not-checked used a corrupt-metadata sentinel, whose
bind-time refusal comes before the legacy guard, so a blocked-variable
check added after .env loading would not have changed its output. It now
uses a config.yaml-only workspace and pins discovery's no-database
refusal.

Measured with the PR head's bd and test binaries under env -i:
- the embedded pin passes on a clean environment and failed with
  BD_OTEL_*, BD_JSON_ENVELOPE=1, or kill(2) returning EPERM (strace
  inject); with this change it passes in all of them, plus an exported
  XDG_CONFIG_HOME, an existing BD_MIGRATION_FREEZE_FILE and the agent
  host's BD_*/BEADS_* set;
- it still fails when .beads/.env overrides the caller (gotenv.OverLoad)
  or is not loaded;
- the store-less suite passes 54/54 subtests; a bd that prints the
  legacy-guard error twice now fails 12 of them, and a bd that checks
  the blocked variables again after the legacy guard now fails
  blocked-backend-not-checked; both passed the suite before.

Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Co-authored-by: Eddie the Engineer <338826946+gascity-eddie[bot]@users.noreply.github.com>
2026-10-19 04:51:18 +00:00
Julian Knutsen
e24940e0c1
fix(workspacegate): strict --readonly never creates workspace gate files (#7672)
* fix(workspacegate): strict --readonly never creates workspace gate files

Strict --readonly is mutation-free by policy (effectiveRootStorePolicy),
but the command chokepoint took its SHARED workspace gates with
O_CREATE|O_RDWR. On a workspace no bd command had gated yet, a strict
readonly command therefore left <project>/.beads.gate.lock and the
physical-root gate file (.beads/embeddeddolt.gate.lock or
.beads/dolt.gate.lock) behind.

Add workspacegate.Options.ReadOnly. A Shared acquisition with it opens
the gate file O_RDONLY (the idiom ExclusiveHolder already uses) and never
creates it. A gate file that does not exist means nothing has ever been
gated there, so Acquire succeeds with an empty handle whose Release is a
no-op. An existing gate file is held SHARED as before, so maintenance
still sees the command and a live exclusive holder still makes it wait
and then refuses it. The option is ignored for Exclusive: maintenance has
to be able to create the file it locks.

ReadOnly composes with the fair, bounded waiting from #7225 without
changes to it: the writer-fairness probe (ExclusiveQueued) already opens
the intent file read-only and treats a missing one as nothing queued, so
a waiting ReadOnly acquisition creates no .intent or .info file either.
readonly_wait_test.go pins that seam.

The chokepoint passes ReadOnly: readonlyMode in the SHARED branch. Every
other command keeps creating the gate files, which is what makes it
visible to maintenance. Residual, documented at the chokepoint: on a
workspace that has never been gated, a strict readonly command is
invisible to a maintenance operation that starts while it runs.

Ported from the versioned-beads integration fork (donnabox):
0c86e2b205 (red tests), bac6ff95dc (fix), b7a4f96a5a (fair-wait tests),
2af5a664dc (BUILD.bazel registration), and the #7225 conflict resolution
in 9d128f8c51. The fork's `--readonly backup restore` refusal
(6ac79d6207) is a separate change and is not included.

Co-authored-by: Jim Wordelman <jim@wordelman.name>
Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(cli): release the previous command's workspace gate before acquiring

acquireCommandWorkspaceGates stored its new handle over whatever
workspaceGateHandle already held. cobra skips PersistentPostRunE when
RunE fails, so in a process that runs more than one command (tests,
embedders) a command could start with the previous command's handle
still set. Two things then went wrong:

- on the paths that take no new gate (no .beads on disk, a failed or
  fail-open acquisition) the stale handle stayed set, so the previous
  workspace stayed held for the whole command;
- on a successful acquisition the stale handle was overwritten without
  being released, so its flock stayed held on the previous workspace
  until the garbage collector closed the file, and a maintenance
  operation there was turned away by a command that had finished.

Release any held handle first. In a single-command bd process the handle
is always nil at that point, so this is a no-op there.

Ported from the versioned-beads integration fork (donnabox): 3a25b42ed1
(cherry-pick of ad87442c92). The test
TestAcquireCommandWorkspaceGatesReleasesThePreviousCommandsHold is new
here and covers the successful-acquisition case the fork's tests do not.

Co-authored-by: Donna Box <dbox@boxenllc.com>
Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(cli): close a stale store before the leading gate release

Review fixups for #7672, apply-fixes iteration 1.

The leading releaseWorkspaceGates() that the second commit added to the
chokepoint was the only production release without a
closeStoreBeforeGateRelease() first. When an in-process command's RunE
fails, Cobra skips PersistentPostRunE. The next command in the same
process then dropped that command's gates while its store and provider
were still open, and later overwrote and leaked them. Close them first,
as every other release path does. The current command assigns
store/uowProvider only after the chokepoint, so anything set there
belongs to the previous command. Only multi-command processes (tests,
embedders) are affected; production runs one command per process.

A strict --readonly hold on a never-gated workspace locks nothing. The
chokepoint still exported this PID in BEADS_GATE_SHARED_HOLDER_PID, so bd
children skipped the writer-fairness queue behind a parent that blocks
no exclusive acquirer. Add Handle.Empty and MultiHandle.Empty, and
advertise only when at least one gate is actually locked.

Tests:
- A regression test runs the chokepoint over a stub store and provider.
  It pins that both close while the previous command's gate is still
  held.
- A marker test forces advertiseSharedHoldEnabled on. It pins that a
  hold of nothing is not advertised, and that the hold is advertised
  once the gate files exist.
- The strict-readonly chokepoint subtests now require a handle that
  holds nothing. SHARED fail-open leaves no handle, so these subtests
  now fail the review's W2 mutant, which passed them before.
- A package test covers Empty.

The posture comment now says the gate follows the strict flag only.
Allowlisted reads and --dry-run/--inspect previews still create the gate
files.

Not changed: `bd --readonly backup restore` still creates gate files on
its exclusive acquisition. This PR covers shared gates only. Sibling #7673
refuses a strict-readonly restore before it takes the exclusive gate.

Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Jim Wordelman <jim@wordelman.name>
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Co-authored-by: Donna Box <dbox@boxenllc.com>
Co-authored-by: Eddie the Engineer <338826946+gascity-eddie[bot]@users.noreply.github.com>
2026-10-19 04:31:00 +00:00
Julian Knutsen
8fac20a7f1
test(oracle-a): normalize per-run revision token and workspace path so main-vs-main is clean (#7680)
* test(oracle-a): normalize the per-write revision token so main-vs-main is clean

Since #5535, `bd show --json` publishes `"revision"`, the decimal spelling
of the row's row_lock. Every create and status/ownership write remints that
token from crypto/rand (issueops.freshRowLock), so it differs between any
two runs of the same scenario. The harness did not normalize it, so Oracle A
failed against itself: on the curated tier, origin/main vs origin/main scored
31 pass / 13 fail in scope, and each failure was a `show --json` step that
differed only in `"revision"`.

normalize() now collapses a non-zero decimal `"revision"` string to `<REV>`.
It keeps everything else literal: the member name, its presence and its
string type, "0" (a row that was never stamped), number-typed values, other
`*_revision` members, and escaped text inside a JSON string. A new unit test
covers each of these cases.

Curated tier, REF_REF=origin/main, run against itself: before 31 pass /
13 fail in scope (0/1 out of scope); after 44 pass / 0 fail (1/0).

Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* test(oracle-a): normalize the per-run workspace path

Each scenario runs in a fresh tempfile::tempdir(), so any bd output that
echoes the workspace path differs on every run. When origin/main's bd was
captured twice with the deep tier (ORACLE_CATALOG=1, 546 scenarios), 40
catalog scenarios differed only in that path. All 40 start with their own
`init --prefix X --non-interactive` step, which runs in a workspace the
harness already initialized and fails with "Found existing Dolt database:
/tmp/.tmpXXXXXX/.beads/embeddeddolt/X".

run_scenario now hands normalize_in_workspace() the exact workspace path
and its symlink-resolved spelling, and that function replaces only those
strings with <WORKSPACE>, longest first. Other paths stay literal, so no
stable value is collapsed. All 40 scenarios are out of scope, so in-scope
counts do not change.

Deep tier, origin/main's bd against itself, scored by the scoreboard:
- base harness: 256 pass / 67 fail in scope, 154 / 69 out of scope.
- with both normalizers: 323 / 0 in scope, 219 / 4 out of scope.

The out-of-scope remainder changes from run to run and none of it is a
field value. It comes from randomized "Tip:" lines in human output and one
unordered `list --format dot`.

Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* test(oracle-a): document and pin the <REV> match scope and the workspace wiring (mc-ro9kg)

Review fixes for #7680, iteration 1.

revision_regex runs over the raw stdout/stderr text before any JSON
parse, so it collapses every "revision" member holding a non-zero
decimal string, at any depth and in plain text, not only the
bd show --json issue token. That includes a user metadata key named
revision, which the in-scope --set-metadata/--metadata flags can set,
so a change to its value passes the gate. The regex comment and a new
README "What green does NOT prove" bullet now say so, and
normalize_collapses_revision_by_member_name_at_any_depth pins the
scope: a nested metadata member and plain text are collapsed, while a
metadata key with any other name still gates. The old test name said
nothing else was collapsed; it is now
normalize_collapses_non_zero_revision_strings.

run_scenario_collapses_the_workspace_in_both_step_streams runs
run_scenario against a stub bd that prints its cwd on stdout and its
resolved path on stderr, and expects <WORKSPACE> in both. Before, the
two normalize_in_workspace calls in run_scenario could be reverted with
every unit test and the curated tier still green.

The remint wording in the comment and the README now names every
writer (create, update, close, reopen, claim and unclaim) instead of
only status/ownership writes.

Tests: cargo test --locked --offline (7 passed), clippy clean, no new
rustfmt hunks. Mutants, each in its own copy and target dir: reverting
either or both normalize_in_workspace calls fails the run_scenario
test; skipping a nested metadata member, or matching only after { or
",", fails the scope test.

Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Co-authored-by: Eddie the Engineer <338826946+gascity-eddie[bot]@users.noreply.github.com>
2026-10-19 04:27:28 +00:00
Julian Knutsen
05fffb1e11
test(storage): versioned-history flag-off differential and statement pins (#6132, #6135) (#7681)
* test(domain/db): pin the statements the history-off upsert Insert issues

The participation_generation write fence (#6943) gave domain/db Insert's
upsert path (CreateOnly unset: the quick, todo, gate and batch proxied
servers' create) an existence probe ahead of the upsert, skipped while
versioned history is off. Pin that skip with a sqlmock statement-sequence
test: with history off, the upsert into issues and into wisps issues
exactly the three statements the pre-stack code (4a67d0d028) issues --
the upsert, the created event's same-content scan and its insert -- and
nothing else.

The mock is reached through internal/storage/sqlcount, and the pin also
requires exactly three statements to reach the driver. sqlmock alone
answers an unscripted statement with an error and fails only if the
caller returns it, so a best-effort read whose error Insert dropped would
pass its checks; the count catches it. The history-on run of the same
script is the control: the probe (and the mint after it) must make the
pin refuse it, which shows the script is exhaustive and that Insert reads
the transaction's scope.

Passes on 4a67d0d028 and on main; main issues no extra read with history
off. Before-parity pin P2 (Insert half) from the fork gap analysis, for
gastownhall/beads#6132 / #6135.

Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* test(issueops): pin the statements the history-off defer-wake sweep issues

Port the fork's sqlmock pin of WakeExpiredDefersInTx with versioned
history off (donnabox/codex/preview3-source-catchup-46aa 11c74cb575):
a one-row sweep issues exactly the expired-row SELECT, the UPDATE, the
event's same-content SELECT and INSERT, and the empty wisps pass, so any
read added before or after waking a row while history is off fails the
pin. It passes on main unchanged and guards the fork's wake-skip change,
which checks each expired row against the mint before waking it and must
keep that check free with history off.

Adapted for main: the doc no longer describes the fork's pre-wake check
as existing; a history-on run of the same script is added as the control
(the mint's read must make the pin refuse it), so the pin cannot pass
vacuously; and the mock is reached through internal/storage/sqlcount, so
the pin also requires exactly five statements to reach the driver. That
catches a read whose error the sweep swallowed, which sqlmock alone does
not see. Passes on 4a67d0d028 and on main. Before-parity pin P2 (wake
half), for gastownhall/beads#6132 / #6135.

Co-authored-by: Jim Wordelman <jim@wordelman.name>
Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* test(storage): versioned-history flag-off differential against pre-stack goldens

gastownhall/beads#6132 and #6135 require a differential test proving that
with versioned history off (the default) storage behaves byte-identically
to before the feature. Existing coverage stops short of that:
TestDualWriteContractFlagOff only counts version rows, the
participation-generation contracts check one column, and createbatchequiv
runs its batch with history on over a column subset.

Add internal/storage/historyoffequiv. Each leg (embedded Dolt, Dolt
server, unit of work) runs one scripted mutation set through its own
front doors on a store whose history was never turned on:

- on the issues plane, every write role: creates, batch create, apply
  batch, updates, the no-op update, reparent, dependency add/remove,
  comments, claim/heartbeat/release, lease reclaim, metadata CAS,
  close/reopen, batch close with a refused item, defer and wake, delete;
- the persistence moves in both directions;
- on the wisps plane, the roles again: create, update and the no-op
  update, dependency add/remove, comment, metadata CAS, close/reopen,
  apply batch, batch close, release, defer and wake (the sweep's wisps
  pass), delete, a forced close of a no-history wisp, and the refusals
  the lease roles' contracts give a wisp (Claim, Heartbeat; Reclaim finds
  nothing);
- each leg's own surface: the store legs' DoltStorage methods (import
  upsert, promotion, RunInTransaction, ...) and the uow leg's
  CreateOnly-unset domain upsert and importer.

Neither reclaim sweep finds an expired lease, since no role can age one.
The harness then dumps every column of every base table, plus the
scenario's Dolt commit messages and the final dolt_status, and compares
per-table SHA-256 digests with goldens recorded by running the same
harness against origin/main 4a67d0d028, the commit before the stack
(#6943, #6661, #6664).

The only tolerated differences are listed in schemaAdditions: the stack's
new columns (issues/wisps.participation_generation,
issue_versions.removed_restriction) must be NULL in every row and are
then left out of the digest; its new table (epoch_minted_addresses) must
be empty; its own migration bookkeeping rows (0070-0072, ignored/0028)
may each be there once. Recording and checking apply that rule the same
way, so a golden re-recorded from main is byte-identical to the
pre-stack one (verified on all three legs). The package doc says how the
goldens are kept: a later migration whose schema flag-off leaves
untouched adds its own schemaAdditions entry; a deliberate flag-off
change, a scenario change or an engine rendering change re-records them
and shows the dump diff. Wall-clock instants, wall-clock-derived ids and
random tokens are masked by explicit, documented rules found by diffing
two runs; instants the scenario supplies stay verbatim, so a write that
starts overwriting one still shows.

All three legs pass on main. Before-parity pin P1 from the fork gap
analysis; the new embedded test is placed in the 40-shard storage block.

Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Co-authored-by: Jim Wordelman <jim@wordelman.name>
2026-10-19 03:47:00 +00:00
Julian Knutsen
f142cc2ffd
test(cli): before-parity pins for --format json, ordinary --if-revision, and version/config/history/as-of shapes (P7, P8, P10) (#7676)
* test(cli): pin --format json == --json on show, list, ready and memories

Before-parity pin P7 (gap analysis 2026-10-17, section 5a). The hidden
root --format flag is an alias for --json (GH#2612). It is a root
persistent flag, so a subcommand that registers a --format of its own
shadows it (the GH#6278 hazard): `bd list` already does and passes `json`
through by hand, and a graph-preview fork that added a local --format to
`bd show` made `bd show ID --format json` exit nonzero.

TestEmbeddedFormatJSONAliasMatchesJSON runs show, list, ready and memories
with --json and then with `--format json`, `--format=json` and a leading
`bd --format json <verb>`, and requires exit 0 and byte-identical stdout.
It adds bdRunStreams, a small helper returning stdout, stderr and the exit
status separately, which the following pins reuse.

The new TestEmbedded* function is listed in the bd_test srcs and placed in
the 100-shard embedded cmd manifest by
gen_embedded_cmd_shard_manifest.py --write (incremental).

Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* test(cli): pin the ordinary --if-revision compare-and-swap contract

Before-parity pin P8 (gap analysis 2026-10-17, section 5a). --if-revision
is the decimal int64 compare-and-swap merged in #7203, and gascity's
bdstore_conditional.go classifier reads both its exit status and its
machine body. A second, opaque-token meaning for the same flag in another
kind of workspace must leave the ordinary one unchanged.

TestEmbeddedIfRevisionOrdinaryCAS pins, through the real binary:
  - a stale decimal token on update, close, assign and delete (preview
    and --force) exits 13, prints nothing on stdout, writes nothing, and
    ends stderr with a precondition_failed body naming the id and the
    expected and current revisions as exact JSON integers;
  - a non-decimal token exits 1 with the "invalid --if-revision" refusal
    in text and --json modes, never 13, and writes nothing;
  - the current token applies on update, close, assign and delete.

It is the ordinary-workspace half of
TestGraphPreviewIfRevisionOutsideLinkModeIsUpstreamCAS from the
donnabox/codex/preview3-source-catchup-46aa branch (added in 3d16d826be,
revised in 1640940fa9, 3ff2fe73ce, 55dbb61156, 653369305a and
97446d1f08), ported onto this package's embedded helpers. The port drops
the graph-only forget refusal, extends the stale and non-decimal cases
from update/delete to close and assign, and compares revisions as
json.Number rather than float64, since they are int64 values past 2^53.

It is named TestEmbedded* so the bazel-embedded lane, which discovers
`^func TestEmbedded` in *_embedded_test.go, runs it; the existing
TestIfRevisionMatchAndMismatch is not discovered there. The file is
listed in the bd_test srcs and placed in the 100-shard embedded cmd
manifest by gen_embedded_cmd_shard_manifest.py --write (incremental).

Co-authored-by: Jim Wordelman <jim@wordelman.name>
Co-authored-by: Donna Box <dbox@boxenllc.com>
Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* test(cli): pin version, config set, history and show --as-of shapes

Before-parity pin P10 (gap analysis 2026-10-17, section 5a): the
store-less and history-adjacent commands a later versioned-history or
graph slice could change by accident.

  - TestEmbeddedVersionOutputShape: `bd version` with no arguments exits
    0 and prints one "bd version <version> (<build>...)" line, in a
    workspace and outside one; --json is one object with version, build
    and schema_version (plus commit and branch when known) agreeing with
    the text line, and --format json prints the same document; an
    argument exits 1 and points at `bd versions <arg>` (#6661), on stderr
    or as the --json error, through the real binary rather than RunE.
  - TestEmbeddedConfigSetOtherKeysSkipTheVersionedHistoryScan: in a store
    holding a row the pre-enable scan refuses over, `bd config set` and
    `bd config set-many` of another key with the value "true" exit 0,
    store it, print no refusal and leave the switch off; the switch
    itself is still refused afterwards, as a control.
  - TestEmbeddedHistoryAndShowAsOfReadDoltCommits: with versioned history
    recording, `bd history <id> --json` is still the Dolt-commit history
    (an array of CommitHash/Committer/CommitDate/Issue entries with full
    32-character Dolt hashes, no recorded-version fields, and the same
    hashes in the text output), and `bd show <id> --as-of <hash>` with a
    hash from it is the Dolt AS OF read in show's JSON shape, not the
    R7.1 as-of read over issue_versions; `--as-of main` reads the branch
    head.

The three TestEmbedded* functions are placed in the 100-shard embedded
cmd manifest by gen_embedded_cmd_shard_manifest.py --write (incremental).

Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Co-authored-by: Jim Wordelman <jim@wordelman.name>
Co-authored-by: Donna Box <dbox@boxenllc.com>
2026-10-19 03:41:08 +00:00
Julian Knutsen
f6f122894f
test(serve): before-parity pins for the httpapi startup event and ordinary-workspace bd serve (P13, P14) (#7679)
* test(httpapi): pin the startup event's capabilities and database source

TestStartupLines and TestStartupNamesTheDatabaseSource check the
event=startup line by substring, and neither reads its capabilities
field. A server could print one capability list and advertise another
on GET /v0/beads/context, or a new kind of database source could
relabel the line, and both tests would stay green.

TestStartupEventPublishesTheAdvertisedCapabilitiesAndSource parses the
line back into its fields and pins, for the provider and roles sources
with and without the external-dependency policy: the exact field
sequence, db=provider|roles, and a capabilities value equal to the
handshake's list joined with commas. It is a before-parity pin: a
future alternative source on the same server must leave this line
unchanged for the Issue API's two sources.

Test-only; no behavior change.

Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* test(serve): pin ordinary-workspace bd serve under BD_GRAPH_MODE=dependency

bd reads no BD_GRAPH_MODE today. "dependency" names the format every
existing workspace already has, so any later reader of that variable
(a graph-mode serve dispatch, for example) has to keep serving an
ordinary workspace through runServe exactly as it does now. These
tests pin that before such a reader exists.

Each test runs bd serve twice in one workspace, once with the variable
unset and once with BD_GRAPH_MODE=dependency. It requires the
event=startup and event=limits lines to match byte for byte apart
from the ephemeral port, and the GET /v0/beads/context bodies to be
equal. Each run is also checked against what runServe builds: the
serveResolvedMode label, the db source, and a startup capabilities
field equal to the handshake's list. Two runs that were both routed
somewhere else therefore cannot pass by agreeing with each other.

- TestServeOrdinaryWorkspaceIgnoresGraphModeDependency: in-process
  through rootCmd (PersistentPreRunE included), on the store source of
  a registered-backend workspace. Runs in bd_test.
- TestServerModeServeIgnoresGraphModeDependency: a real bd on a
  `bd init --server` workspace, which uses the provider source. Gated
  on BEADS_TEST_PROXIED_SERVER like the other TestServerMode* tests,
  and placed in the proxied 34-shard manifest by
  gen_proxied_shard_manifest.py --write (incremental).

The new file is listed in cmd/bd/BUILD.bazel's bd_test srcs.
Test-only; no behavior change.

Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* test(serve): stop the in-process graph-mode pin hanging when serve fails

serveInProcessSnapshot's cleanup decided whether the server was still
running by looking at rootCancel. That holds for a clean run, which
clears rootCancel in PersistentPostRunE. A run whose RunE returns an
error skips PersistentPostRunE, so rootCancel stays set even though the
main flow has already read the run's only result from done. The
cleanup then called rootCancel and blocked on done for good, and the
failure surfaced as a test-binary timeout panic that takes the whole
bd_test shard with it instead of a FAIL for this test.

The cleanup now keys on whether done has been read. A serve that binds,
answers, and then returns an error (one way a future graph-serve
dispatch could regress) now fails in about 5s with "bd serve returned
<err>, want a clean shutdown". A failure before done is read (a bad
GET, say) still cancels the server and waits for it.

Test-only; no behavior change.

Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-19 03:26:45 +00:00
Julian Knutsen
3488dc4536
fix(init): bd init --server --external starts no server; a failed bd init --server can be retried (#7674)
* fix(init): admit a retried `bd init --server` over an empty .beads/dolt

A first `bd init --server` that cannot reach its server fails after
creating the local Dolt root, leaving an empty .beads/dolt, no
.local_version witness, and no config.yaml/metadata.json recording the
server choice. The legacy-upgrade guard runs before init writes that
choice, so it saw an embedded-looking workspace with a local Dolt root
and refused every retry as a "legacy Dolt workspace"; no bd command could
repair it.

guardLegacyUpgradeWorkspaceForInit(beadsDir, initSelectsServer) carries
init's already-resolved server intent into the guard. It is consulted
for exactly one decision: an empty, witness-less .beads/dolt is admitted,
the same admission a workspace that records server mode already gets
(#6935). It is deliberately not folded into the workspace's own server
mode, so a non-empty root with an unreadable witness and an embedded
repository beside a non-empty root keep their current outcomes.
guardLegacyUpgradeWorkspace is now the initSelectsServer=false wrapper,
and only init's main guard call passes the flag; the proxied-server
init path keeps the plain wrapper.

Ported from the versioned-beads fork (donnabox/codex/preview3-source-
catchup-46aa), commits bc8d72182a (red) and 5bdfbfe5e2 (green). The
fork's graph_mode refusal in the same function is graph-preview-only
and is not carried here.

Tests: TestLegacyUpgradeGuardForInitAdmitsEmptyDoltRoot and
TestLegacyUpgradeGuardForInitAdmissionStaysNarrow pin the admission and
its narrowness at the guard; TestInitServerFlagAdmitsEmptyDoltRootWithoutConfig
and TestInitServerFlagRetryAfterFailedFirstAttempt run the real binary
against the test Dolt server and fail on main with the legacy refusal.

Co-authored-by: Jim Wordelman <jim@wordelman.name>
Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(init): `bd init --server --external` must not auto-start a server

`--external` declares the Dolt server managed outside bd ("skip server
startup", per its help), but init builds its dolt.Config by hand with
`AutoStart: initServerMode && BEADS_DOLT_AUTO_START != "0"`, so the flag
never reached the auto-start decision. A `bd init --server --external`
that named no port therefore ran dolt and tried to start a repo-local
sql-server. A named port was already declared external by rule 2c
(#5934), but its failure still advised `bd dolt start`, the one thing
--external says bd must not do, and each route (host:port, socket,
shared server, auto-start pinned off) worded the failure differently.

- AutoStart is now `initServerMode && !externalServer && ...`.
- externalServerUnreachableMessage rewrites only a failed dial
  (*net.OpError with Op "dial") under --external: it names the endpoint
  that was dialed and says bd did not start a server. A dial to port 0
  means no port was named, so that message asks for --server-port or
  BEADS_DOLT_SERVER_PORT and offers no default (GH#2098, GH#2372). Any
  other open failure keeps its own text.

Ported from the versioned-beads fork (donnabox/codex/preview3-source-
catchup-46aa), commits 234ca3d502 and a601a80e77 (red/green), 03a64a1aba
(socket helper rename), and a6ca0536c9 and 397fc4c69e (red/green: no-port
arm and wording). The fork's graph-preview dispatch at the top of init
and its --skip-hooks help text change are graph-only and not carried.
The TestInitExternalProvisionerShape doc comment is corrected: on main
every provisioner cell is a control (a named port is already external),
not a reproduction.

Tests: TestInitServerExternalDeadPortStartsNoServer,
TestInitServerExternalNoPortStartsNoServer and
TestInitExternalUnreachableMessage run the real binary against a dolt
shim that records every launch and fail on main;
TestInitSharedServerExternalDeadPortStillFails,
TestInitServerWithoutNamedPortStillStartsServer and
TestInitExternalProvisionerShape are controls; and
TestExternalServerUnreachableMessage pins which errors are rewritten.

Co-authored-by: Jim Wordelman <jim@wordelman.name>
Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Jim Wordelman <jim@wordelman.name>
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-19 03:11:14 +00:00
Jim Wordelman
5c9c02ab77
Phase 3 (R20): epoch-transition enforcement + minted-address CAS - gastownhall/beads#6136 (#6664)
* test(conformance): un-skip R16 CAS + R20 epoch tests with honest not-implemented stubs

Wires all 10 ExpectedRevisionFixture-gated Run* functions and both
EpochFixture-gated Run* functions to real (non-nil) hooks on all three
storage legs (dolt, embeddeddolt, uow), replacing the Phase 0 all-nil
fixtures that made these cases t.Skip.

Every wired hook is an unconditional "not implemented yet" stub rather
than a partial-real implementation. This is deliberate: every Run*
function under test calls its primary hook (CompareAndSetVersion, or
CurrentEpoch/MintUnderEpoch) first, before any other hook, so a stub
that errors unconditionally on that first call guarantees deterministic
RED with zero risk of an accidental pass -- a concern that's concrete,
not hypothetical, since at least one case
(RunExpectedRevisionAcceptsAWriteNamingNoVersion) would go green under
a partially-real read/unconditional-write strategy backed by Phase 1's
already-persisted current_revision/store_epoch columns.

Each case now fails for its documented reason: most via a direct
t.Fatalf quoting the stub's "not implemented" error, and two
(RefusalIsDistinguishableFromNotFound,
RefusalIsDistinguishableFromValidationFailure) via a clean want/got
mismatch against the sentinel errors they expect.

Explicitly out of scope and untouched: CrossRecordInvariantFixture
(R16.1) and the non-epoch RetentionFixture cases (R17) -- confirmed via
test run that TestRetentionContract still reports PASS with all 13
subtests SKIP on every leg.

TestEveryLegWiresEveryRoleContract (internal/storage/leg_contract_wiring_test.go)
is a source-level AST naming check independent of hook nil-ness; all 12
entrypoints were already called by every leg pre-change, so this lock
was satisfied before and remains satisfied after.

Sentinel error messages reference be-x5jqd.3 (R16 CAS implementation)
and be-x5jqd.4 (R20 epoch enforcement implementation), the two builder
children this un-skip unblocks.

Verified via go build ./..., go vet ./..., and go test -tags cgo across
all three legs: all 10 R16 + 2 R20 subtests FAIL for the documented
reason, TestRetentionContract unaffected.

Bead: be-x5jqd.1

* feat: green — Implement R20 epoch-transition enforcement (refs be-x5jqd.4)

* fix(epoch): honor R20-n's retained-mapping exception in StillServes/Resolve

StillServesInTx and ResolveEpochInTx only ever checked whether the
literal queried address's own row matched the current epoch. Per R20-n
(#5898 rev 9), a version that survives an epoch transition keeps its
prior-epoch address resolving once its id has been carried forward into
the current epoch (via CurrentAddressForInTx or a fresh
MintUnderEpochInTx) — that carried-forward row wasn't being consulted,
so a legitimately retained address would wrongly stop resolving.

Add mintedIDHasAddressAtEpochInTx and consult it as a fallback in both
functions when the queried address's own row is stale. Addresses whose
id was never carried forward are unaffected (row.mintedID has no row
at the current epoch, same false/GoneReorganization answer as before).

Round-2 response to be-rskwc's causal_disproof finding: the merge-base
commit FAILed honestly on this defect, this branch's tdd_green SKIPped
instead (attribution_evidence). This fix is real and verified via a new
sqlmock unit test (TestStillServesInTxHonorsARetainedMapping et al.),
but does not by itself flip
TestEpochContract/EpochBumpVoidsOnlyAddressesOfVersionsNoLongerServed
from SKIP to PASS: that test's own construction mints two records
identically and never carries either forward before comparing
StillServes on both, so no backend implementation can make them differ
(escalation follows on a needs-mayor bead).

refs be-x5jqd.4, be-rskwc round 2

* test(feat): red — harden EpochBumpVoidsOnlyAddressesOfVersionsNoLongerServed (refs be-9fiaw)

Per mayor ruling on be-9fiaw: fix the test rather than waive it. The
fixture already lets record-a survive an epoch bump by minting it again
under the new epoch; record-b, never re-minted, does not survive. That
asymmetry was previously only discovered after the fact (skip if
StillServes agreed for both addresses), which meant the case could pass
by observing either polarity. Assert the concrete expected values
instead: servesA must be true, servesB must be false. This makes the
case deterministically exercise both halves of R20-n, and closes a
latent gap where a backend with the polarity reversed could have
silently passed via the old discover-then-swap logic.

* fix(schema): renumber epoch_minted_addresses to 0070, linearizing our own slot collision (refs be-hs42e.7)

R20's epoch_minted_addresses and R7.1's removed_restriction both claimed
migration slot 0069 on parallel sibling branches. Neither contained the
other, so nothing in either branch's own CI could see the union: each was
green alone, and the second to merge would panic checkNoDuplicateVersions at
store open -- before any command's RunE, so every bd invocation bricks rather
than one package reddening. Same hazard bee reproduced for #6358 vs #6008.

This linearizes them instead of leaving it to merge order. R7.1 keeps 0069:
it is published beneath #6661 and cannot move without rewriting a branch a
reviewer is reading. R20 stops being a sibling, rebases onto R7.1, and takes
the next contiguous slot.

Contiguity is why the renumber could not be done pre-emptively in either
branch alone: TestAllMigrationsSQLAppliesThroughDoltCLIAndRecordsLatestVersion
asserts COUNT(*) == LatestVersion(), so a jump to a far slot fails until the
gap is filled. The order had to be settled first.

- migrations/0069_add_epoch_minted_addresses.{up,down}.sql -> 0070_*
- migration_0069_add_epoch_minted_addresses_test.go -> migration_0070_*, with
  TestLatestVersionIncludesMigration0069 -> ...0070 (want 70)
- 0069_add_removed_restriction_test.go retires its own LatestVersion pin in
  favour of 0070's, keeping the one-pin-at-a-time chain 0068 -> 0069 -> 0070

cli_migrations.go needs no change: its only override is R7.1's guarded
PREPARE, which keeps 0069. The epoch migration is a plain unguarded
CREATE TABLE IF NOT EXISTS and needs none.

Verified: TestEmbeddedMigrationSourcesHaveNoDuplicateVersions,
TestLatestVersionIncludesMigration0070,
TestAllMigrationsSQLAppliesThroughDoltCLIAndRecordsLatestVersion (applies the
full 0001..0070 chain through the dolt CLI),
TestBundleMigrationsWithPreparedALTERAreOverriddenOrJustified and
TestAllMigrationsSQLUsesDirectDDLForKnownCLIIncompatibilities all pass.
go build ./... and go vet ./... clean.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* test(feat): red — Fix PR #6664: restore R16 honest-skip (stale be-x5jqd.3 premise) + address bee's 2 blockers on epoch_cas.go (refs be-ah0jf)

* feat: green — Fix PR #6664: restore R16 honest-skip (stale be-x5jqd.3 premise) + address bee's 2 blockers on epoch_cas.go (refs be-ah0jf)

* test(feat): red — Review: Fix PR #6664: restore R16 honest-skip (stale be-x5jqd.3 premise) + address bee's 2 blockers on epoch_cas.go (refs be-yj55d)

* feat: green — Review: Fix PR #6664: restore R16 honest-skip (stale be-x5jqd.3 premise) + address bee's 2 blockers on epoch_cas.go (refs be-yj55d)

* docs(epoch): cite epoch_minted_addresses as migration 0071

Upstream's 0069_widen_issue_versions_datetime_precision (#6675) took slot
0069 first, so removed_restriction moved to 0070 and epoch_minted_addresses
to 0071. The three epoch_cas.go headers still named 0070.

Rebase note (maintainer): the migration is now 0072, per the landing-order
ruling (#6943's participation_generation is 0070 and #6661's
removed_restriction is 0071); the commit "chore(schema): renumber
epoch_minted_addresses to 0072 after #6661's 0071" updates these three
headers.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* test(feat): red — move #6664's Dolt server leg to post-transaction publish for store_epoch and epoch_minted_addresses (latent lost-update pattern)

Tests only. On the commit before this one they fail for these reasons:

- the server leg publishes store_epoch / epoch_minted_addresses inside the open
  SQL transaction (DOLT_ADD before COMMIT) for BumpEpoch, MintUnderEpoch and
  CurrentAddressFor: the lost-update hazard documented on doltAddAndCommitInTx
- MintUnderEpoch and CurrentAddressFor stage only epoch_minted_addresses, so the
  first mint leaves store_epoch modified in the working set, on both legs
  (#6664 Major 2, reproduced with Status() on a real server and embedded)
- BumpEpoch must surface a Dolt commit that fails after its SQL commit, while
  the mint paths keep their rows
- ensureStoreEpochRow seeds with INSERT IGNORE and reads the row back

TestMintOverlappingABumpCommitsAnAddressThatIsAlreadyGone characterizes current
behaviour and passes now: a mint overlapping a bump commits an address the bump
already voided. Its doc comment records why that is left as it is.

* feat: green — move #6664's Dolt server leg to post-transaction publish for store_epoch and epoch_minted_addresses (latent lost-update pattern)

Server leg (internal/storage/dolt/epoch_cas.go): BumpEpoch, MintUnderEpoch and
CurrentAddressFor no longer stage and Dolt-commit inside the open SQL
transaction. The two mint paths publish through runIssueOperationTxWithMessage,
which commits the SQL transaction first. BumpEpoch commits it, then publishes
with doltAddAndCommitPostTx and RETURNS a failed Dolt commit: a bump that is
committed but unpublished must not read as success.

Both legs: a mint stages store_epoch with epoch_minted_addresses, because the
first mint inserts the singleton row (#6664 Major 2). The set lives in
issueops.EpochMintDirtyTables so the legs cannot drift from what the body writes.

issueops: ensureStoreEpochRow seeds with INSERT IGNORE and reads the row back,
as version_history.go does for the same row.

Not changed, on purpose: a mint overlapping a concurrent bump can still commit an
address the bump already voided. Dolt has no lock for it and the only conflicting
write would overwrite bumped_at/bumped_reason; see the doc comment on
TestMintOverlappingABumpCommitsAnAddressThatIsAlreadyGone. One comment in that
test file is reworded; no test logic changed since the red commit.

* chore(bazel): bazel-sync (gazelle) for the two new epoch test files

Only the two go_test srcs entries for the test files this branch adds:
epoch_cas_publish_test.go (dolt) and epoch_cas_status_test.go (embeddeddolt).
gazelle wanted nothing else for them (no deps change).

* test(conformance): add the optional EpochFixture.LoseVersion capability

Record survival explicitly instead of inferring it (gastownhall/beads#6664,
review 5360880888, Major 1). Once an address stays served unless its own row
says the store lost it, the only way for the contract to produce a Gone
address is an explicit loss, so the contract needs a way to say "the store
lost this Version".

LoseVersion is additive and optional: no existing field changes signature,
and a nil LoseVersion makes the cases that need one skip with a named reason.
It is its own commit so that it can be judged, or replaced, on its own: the
same semantics could ride on BumpEpoch taking a lost set, and only the
plumbing would differ. Nothing uses it yet.

* chore(epoch): add signature-only stubs for the survival rework

The tests that follow exercise BumpEpochCarryingInTx, LoseVersionInTx,
ErrEpochAddressNotServed and the BumpEpochCarrying and LoseVersion store
methods (gastownhall/beads#6664, review 5360880888). Stubs give those names
so the tree builds and the tests fail for their real, behavioural reasons
instead of failing to compile.

No logic: ErrEpochAddressNotServed is a sentinel, BumpEpochCarrying advances
the counter exactly as BumpEpoch does and carries nothing, and LoseVersion
returns "not implemented". The next commit adds the tests; the one after
replaces these bodies.

* test(feat): red — record survival explicitly in epoch_minted_addresses, make CurrentAddressFor read-only, carry on a token-scheme change

Tests for the survival rework of gastownhall/beads#6664 (review 5360880888:
Major 1, Minors 3 and 4). Every test is written before any production change.

- Contract: the earlier mint-driven R20-n case is restated as three named
  phases (a survivor and a lost Version, loss is terminal, survival needs no
  upkeep), plus three new cases for a token-scheme change (carry the live
  lineages and only those, a carried address keeps resolving across later
  bumps, a lost address stays Gone across a scheme change). All three legs
  register them and wire LoseVersion and the carrying bump.
- Shared body: unit tests for the row-based resolver (exactly the address's
  row and the epoch, fail closed on a row from a future epoch), a read-only
  CurrentAddressFor with typed errors, LoseVersion, a bump that writes only
  store_epoch, a mint that never hands back a lost address, and the
  per-database counter (Minor 3). Minor 4 gets a guard that no address in the
  test file is written by hand.
- Real engine: the carry on the embedded leg (one carry row per live id, the
  lineage root, the collision rule, a row from a future epoch, a rewound
  counter, database-wide, lost lineages), the publication sets of every
  writer, and on the server leg the overlap of a mint with a bump (now a Live
  survivor) and a deterministic mint-after-loss interleaving that must not
  revive the lost address.
- Migration 0071 byte pin and a real-dolt shape check for carried_from,
  gone_at_epoch, the carried_from index and the gone-not-before-mint CHECK.

These fail on the current code, and some do not build yet because
BumpEpochCarryingInTx, LoseVersionInTx, ErrEpochAddressNotServed and the store
methods they exercise do not exist.

* feat: green — record survival explicitly in epoch_minted_addresses, make CurrentAddressFor read-only, carry on a token-scheme change

The survival rework of gastownhall/beads#6664 (review 5360880888: Major 1,
Minors 3 and 4). An address's status is now a function of its own row and the
current epoch, never inferred from other rows.

- Migration 0071 (edited in place; no new slot, no ALTER): the table gains
  carried_from, gone_at_epoch, an index on carried_from and a CHECK that a loss
  epoch is not before the mint epoch.
- Shared body: Live unless gone_at_epoch is set, and a row from an epoch that
  has not happened yet fails closed; the chain query is deleted. CurrentAddressFor
  only reads and returns typed errors. LoseVersion marks a whole lineage lost,
  once, guarded by gone_at_epoch IS NULL. BumpEpochCarrying (token-scheme change)
  writes one carry row per live lineage naming the lineage root, resolves a
  shared-id collision by carrying the newest and losing the rest, and fails if a
  row already sits at the new epoch. A mint only inserts its own root row and
  never hands back an address that is not served. A restore or reinit bump
  still writes only store_epoch.
- Both Dolt legs: BumpEpochCarrying publishes store_epoch and
  epoch_minted_addresses, LoseVersion publishes epoch_minted_addresses and
  returns a failed publication, and CurrentAddressFor runs on the read path and
  publishes nothing. The per-database epoch counter (Minor 3) and the
  requirement that a caller of the carrying bump hold the workspace gate
  exclusively are documented where they apply.

One change to tests written in the previous commit: the three real-server
publication probes that only need a clean working set now open a database of
their own, as the overlap tests do, instead of queueing on the shared test
database's schema-init lock. Its five-second acquire timeout ran out under load
and failed two of them; no assertion changed.

* test(dolt): run the epoch contract on a database of its own

TestEpochContract set up through setupTestStore, which puts every parallel
test on the shared test database and queues their schema initialization on one
lock with a five-second acquire timeout. Under host load a setup that waits
behind another parallel test's runs out of it and fails at its first line with
"schema migration lock unavailable: timeout". That failed the unchanged
first-mint test twice in the dolt lane once this change had added tests to it,
and the contract's own setup is exposed to the same timeout.

The contract now opens a database of its own, the way the overlap tests and the
publication probes already do, so this change adds no contention on the shared
database's lock. No assertion changed.

* docs: replace internal tracker ids in the epoch comments and test names with plain descriptions

Comment and text edits only; no behavior changes and no line is added or
removed (21 lines are replaced one for one). Each replaced line named an
internal tracker id in a header, a test comment, a failure message or the
migration header; it now says what it meant in plain words or cites the
upstream issue or pull request. The EpochFixture API lines and the already
published commit messages are left as they were.

* ci: list this PR's embedded storage tests in the embedded shard manifest

#7156 made the embedded-Dolt tier's shard manifests exact-once (50 cmd
shards, 15 storage shards), so every embedded test must be listed. This PR
adds eleven embedded storage tests and no embedded cmd tests; this commit is
exactly what the generators write for them:

  python3 scripts/ci/gen_embedded_cmd_shard_manifest.py 50 --weights=duration --write
  python3 scripts/ci/gen_embedded_storage_shard_manifest.py 15 --weights=duration --write

Incremental: 11 lines added, none moved; the cmd manifest is unchanged.

Rebase note (maintainer): regenerated on current main, whose embedded storage
manifest uses a 40-shard block; the generator's incremental output placed
these tests at shards 7, 9, 11, 20, 21, 28, 31, 32, 33, 34 and 36 of 40, one
test per shard (gen_embedded_storage_shard_manifest.py 40 --weights=duration
--write; --check passes).

* chore(bazel): bazel-sync for the epoch sources and migration 0071

The BUILD files did not list epoch_cas.go in the dolt, embeddeddolt and
issueops libraries, issueops' epoch_cas_test.go, or migration 0071 and its
test, so Bazel could not compile those packages' tests. This is exactly the
patch make bazel-sync writes (gazelle plus go_srcs.py; the PR's BUILD-sync
CI step printed it): 4 files, 6 lines, nothing else.

Rebase note (maintainer): the migration is now 0072, per the landing-order
ruling (#6943's participation_generation is 0070 and #6661's
removed_restriction is 0071); the commit "chore(schema): renumber
epoch_minted_addresses to 0072 after #6661's 0071" renames these BUILD
entries. On the rebased base, this commit's internal/storage/schema/BUILD.bazel
hunk is merged with the base's 0070 and 0071 entries.

* chore(schema): renumber epoch_minted_addresses to 0072 after #6661's 0071

Migrations are numbered by landing order. #6943 (participation_generation,
the versioned-history write fence) owns main-plane 0070 and #6661
(removed_restriction) owns 0071, so this PR's epoch_minted_addresses
migration moves to the next free slot, 0072. The rename is done here, as one
maintainer commit, rather than inside the replayed commits, so the history
shows exactly what changed relative to the PR as reviewed.

- migrations/0071_add_epoch_minted_addresses.{up,down}.sql become 0072_*.
  Neither header names its own number, so the SQL and its comments are
  unchanged. Neither file exists on main, #6943 or #6661, so this is not an
  edit to a shipped migration.
- cli_migrations.go needs nothing: the migration is a plain CREATE TABLE IF
  NOT EXISTS with no CLI-bundle override.
- migration_0071_add_epoch_minted_addresses_test.go becomes
  migration_0072_add_epoch_minted_addresses_test.go; its consts, tests and
  messages say 0072, it owns the one LatestVersion pin (72), and its slot
  history now records the move past #6943's 0070.
  TestLatestVersionIncludesMigration0071 in #6661's removed_restriction test
  was already retired to a pointer comment by the rebase's resolution of
  "renumber epoch_minted_addresses to 0070"; that comment now names
  TestLatestVersionIncludesMigration0072 and its file.
- BUILD.bazel embedsrcs/srcs, and the three epoch_cas.go headers (dolt,
  embeddeddolt, issueops) that cite the migration number.

The intermediate commits of the rebase are not expected to build, for two
reasons:

- a duplicate migration version: the PR's epoch_minted_addresses migration
  shares 0069 with main's 0069_widen_issue_versions_datetime_precision until
  the PR's own "renumber epoch_minted_addresses to 0070", and from there
  shares 0071 with #6661's removed_restriction until this commit;
- a helper-name collision: from the PR's "feat: green — Fix PR #6664: restore
  R16 honest-skip ... (refs be-ah0jf)" on, internal/storage/issueops declares
  readStoreEpochInTx twice, once in #6943's version_history.go and once in
  this PR's epoch_cas.go, until "fix(epoch): rename #6664's read-only
  store_epoch read past #6943's readStoreEpochInTx" later in this stack.

This commit ends the duplicate version, but it still does not compile on its
own because of the collision; the stack builds from the rename commit on.

Checked at the tip of the stack, where the rename has landed: go test
./internal/storage/schema/... with the dolt CLI lane
(including TestAllMigrationsSQLAppliesThroughDoltCLIAndRecordsLatestVersion
and TestMigration0072RecordsSurvivalInTheAddressTableThroughDoltCLI), and
scripts/check-migration-hygiene.sh with BASE_SHA=origin/main and
BASE_SHA=vh/6661-rebase.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* test(epoch): waive #6664's three new epoch contracts on main's http leg

main gained an HTTP storage leg (#7247) after this PR's base, and
TestEveryLegWiresEveryRoleContract requires every leg to name or waive every
role contract. This PR adds three EpochFixture cases
(RunTokenSchemeChangeCarriesLiveAddressesAndOnlyThose,
RunACarriedAddressKeepsResolvingAcrossLaterBumps and
RunALostAddressStaysGoneAcrossASchemeChange); dolt, embeddeddolt and uow wire
them, and the http leg did not name them.

They are waived on the http leg with the existing
retentionEpochNoRoleWaiverReason, which already covers every other
RetentionFixture/EpochFixture case there: EpochFixture is raw storage hooks
(CurrentEpoch, BumpEpoch, MintUnderEpoch, StillServes, Resolve,
CurrentAddressFor, LoseVersion) with no publicops role behind them,
and internal/httpclient is a remote client with no epoch counter or address
table of its own. The constant's doc comment now counts eighteen cases.

Test-only; no production code changes. After this, the http leg's only
unnamed entrypoints are #6943's seven RunParticipationGeneration* contracts,
whose waivers belong to #6943.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(epoch): rename #6664's read-only store_epoch read past #6943's readStoreEpochInTx

#6943's "a create stamps participation even when the row is flagged
no-history" (7c00d65fa6) adds readStoreEpochInTx to version_history.go: the
mint's read of store_epoch, which SEEDS the singleton row when it is absent.
This PR's epoch_cas.go already declared a readStoreEpochInTx of its own, so
the package stopped compiling once #6664 was stacked on that commit.

The two cannot be folded into one. This PR's helper is deliberately
read-only: an absent row answers epoch 1 without writing, so
CurrentEpochInTx, StillServesInTx, ResolveEpochInTx, CurrentAddressForInTx and
LoseVersionInTx never write from a read (review item B4, pinned by
TestCurrentAddressForNeverReseedsAnAbsentStoreEpochRow and
TestCurrentAddressForWritesAndPublishesNothing). Calling #6943's seeding read
from those paths would break that.

So #6664's helper becomes readStoreEpochWithoutSeedingInTx, and its doc
comment says why it is not readStoreEpochInTx. The five call sites and the
ensureStoreEpochRow comment that names it follow. No behavior changes on
either side: #6943's mint path keeps its seeding read, and this PR's read-only
paths keep theirs. (ensureStoreEpochRow, which BumpEpochInTx and
MintUnderEpochInTx use, now has the same body as #6943's readStoreEpochInTx;
it is left as it is rather than folded in here.)

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* test(storage): say exactly why the retention and epoch contracts stay waived on http

All but four of the participation-generation contracts (#6943's write
fence) now run over the served wire
(internal/httpclient/served_participation_generation_test.go): their subject
is a create or an update, which the client can send, and the fixture reads
the reference store's raw columns. The four stay waived, because the
mutation each needs has no form on the wire. This checked whether the
eighteen RetentionFixture/EpochFixture cases waived on the http leg,
including the three this PR adds, can be wired the same way. They cannot,
cheaply or otherwise, without a new wire operation:

- every EpochFixture hook (CurrentEpoch, BumpEpoch, MintUnderEpoch,
  StillServes, Resolve, CurrentAddressFor, LoseVersion) is the operation
  under test, not a seed or a raw read. Those operations are methods on the
  concrete *DoltStore and *EmbeddedDoltStore over issueops' *InTx bodies, on
  no storage interface, no publicops role and no wire operation. Every call
  path into them starts in a test: the methods are called only from each
  store leg's own _test.go files (its EpochFixture, which the conformance
  contracts drive, and its epoch tests), and the *InTx bodies only from those
  methods, from each other and from tests (the uow leg's fixture through a
  test-only type assertion, and issueops' and the dolt leg's own tests). No
  command, role or server handler reaches them, so no client mutation
  touches epoch state either;
- RetentionFixture's hooks (Resolve, Remove, Hold, ForceRemove, Erase, Mint)
  are implemented by no backend yet (every store leg wires them nil and its
  cases skip), and the wire has no removal, hold, erasure or gone/unknown
  resolve to bind them to.

Binding the epoch hooks to the reference store behind the served env would
pass, but as a property of that store, which the store legs already pin,
never of the client. So the waivers stay; retentionEpochNoRoleWaiverReason's
comment and reason string now say the above, in the shape #6661 gave
asOfReadNoHTTPWireWaiverReason, instead of the earlier general "raw storage
hooks with no publicops role" wording.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(epoch): report applied-but-unpublished epoch writes as indeterminate, bound address length, verify dup-key mints

Maintainer fixup for the #6664 review (adopt-pr attempt 1, iteration 1).

Major 1, applied writes reported as failed. An epoch writer whose SQL
commit has landed, or may have, now wraps storage.ErrCommitIndeterminate
on both legs and hands back what it applied, so nothing replays a bump
that has already advanced the counter:
- embedded BumpEpoch and BumpEpochCarrying return the new epoch with the
  error (failedBump), and MintUnderEpoch its address;
- server bumps wrap the sentinel on every Dolt failure after the SQL
  commit, including a failed staged-set read (unpublishedBump), and so
  does LoseVersion; an indeterminate SQL commit returns the epoch or
  address it may have committed, and a definite (typed MySQL) commit
  error returns neither.
Tests: TestEpochWritesReportAnUnpublishedCommitAsIndeterminate (new,
embedded, through an afterSQLCommit seam in runTransactionWithMessage);
on the server leg TestEpochWritesMarkAFailedStagedReadIndeterminate,
TestEpochWritesReturnWhatAnIndeterminateSQLCommitMayHaveApplied and
TestEpochWritesReturnNothingWhenTheSQLCommitFailsDefinitely, and the
sentinel asserted in every publication-failure test.

Major 2, address overflow. MintUnderEpochInTx refuses a pair whose
address would outgrow epoch_minted_addresses.address (VARCHAR(255)) at
the widest epoch the counter can reach, with a typed
ErrEpochAddressTooLong, so a carry can never fail on a lineage that
gained an epoch digit.

Major 3, duplicate-key mint. A duplicate key from the mint's INSERT is
no longer success: the row is read again and the mint stands only if
this transaction sees it served; a Gone row fails the mint with
ErrEpochAddressNotServed, an unreadable one with the duplicate-key
error. Measured on dolt-sql-server 2.2.0, the stale-snapshot INSERT does
not report a duplicate key at all: its COMMIT fails with Error 1213 and
the retried mint answers ErrEpochAddressNotServed
(TestAMintRacingTheMintAndLossOfItsAddressConflictsAtCommit).

Minors:
- absent store_epoch row: sqlmock cases pin that CurrentEpoch,
  StillServes, Resolve, CurrentAddressFor and LoseVersion never seed it;
  switching any of the five to the seeding reader now fails the test;
- the server publication tests mint their address instead of writing it
  by hand, and TestEpochCASTestsBuildEveryAddressWithEpochAddress scans
  that file too (issueops_test gains //internal/storage/dolt:go_srcs as
  data);
- stale text: the duplicate-key and carry comments, the issueops
  header's CompareAndSetVersionInTx citation, the embedded header's
  parity claim, and the 0072 header's "upserts the same row" (0072 is
  past the frozen floor).

Declined, for the owner:
- a scheme-change carry voids an older live lineage re-minted after a
  restore: rule (a), document and pin it, or rule (b), resolve the loser
  to the winner's carry, is a design call about R20-n, not a review fix;
- the uow epoch fixtures' in-transaction DOLT_COMMIT('-Am'): test-only
  fixtures with no production caller; routing them through RunTxScoped
  is follow-up work.

Validation: go build ./...; go vet; nogo (bazel --config=nogo) on
issueops, dolt and embeddeddolt; issueops epoch tests; the dolt epoch
tests against a real dolt-sql-server (56 pass) and the fake-backed
publication tests; embedded epoch tests with BEADS_TEST_EMBEDDED_DOLT=1;
uow epoch contract; the schema package; the address guard under bazel
in the local sandbox. All 14 overlay mutants of the fixes are killed.

Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Jim Wordelman <mayor@quad341.uk>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-authored-by: Julian Knutsen <julianknutsen@users.noreply.github.com>
Co-authored-by: Eddie the Engineer <338826946+gascity-eddie[bot]@users.noreply.github.com>
2026-10-18 21:20:57 +00:00
Jim Wordelman
9c6f6e15cd
bd versions + a config switch for versioned history — the minimum cut that makes versioned beads usable (#6138) (#6661)
* test(conformance): author R7.1 as-of-read conformance contract

Adds a new Phase 0 conformance contract for R7.1 (as-of reads,
gastownhall/beads#6136, design doc #5898 rev 9) -- no fixture existed for
this anywhere in backend/conformance/, so this is authored from scratch,
not un-skipped.

AsOfReadFixture supplies three hooks: Resolve (the read under test),
MintAt (seeds a version at a controlled accept-time), and
MakeUnanswerable (arranges a Gone/Unknown refusal independently of
RetentionFixture/EpochFixture's own removal machinery, since R7.1's
refusal is a sibling contract to R17/R20, not a dependent of them).

Five Run* functions cover the bead's five required-coverage points
verbatim:
- selector accepts either an instant or a version address, and both name
  the same answer when they resolve to the same version;
- resolution returns the latest version at-or-before T, with a version
  accepted after T strictly excluded even when close by;
- a served result reports the exact address it served;
- an unanswerable read refuses as a typed Gone*/Unknown outcome with a
  reason, and never substitutes a neighboring version, the nearest
  surviving version, or current state -- asserted directly by requiring
  Address == "" on every refusal;
- local completeness only (TC3): a lineage minted into one of two stores
  resolves there and refuses Unknown (FR-06) on the store that never
  received it, asserting nothing about agreement between the two.

The file's doc comment states the Memory-plane-consumer-policy non-goal
explicitly (closed-before-T boundary, sibling exclusion, supersession
exclusion are consumer policy per #5877, not part of this primitive) so
the gap reads as deliberate scope, not an oversight.

Wired onto all three storage legs (dolt, embeddeddolt, uow) with
unconditional "not implemented" stubs rather than partial-real hooks, so
every case fails via MintAt on its first fixture call -- deterministic
RED with no risk of an accidental pass, per the precedent set by
be-x5jqd.1. Sentinel error messages reference be-x5jqd.5, the
implementation child this suite is written ahead of.

TestEveryLegWiresEveryRoleContract requires zero waivers: all 5 new
entrypoints are fully wired (not nil) on all three legs.

Branch cut from the rebased be-2h167 head (5fdfb92fe5).

Verified via go build ./..., go vet ./..., gofmt -l, and go test -tags
cgo across all three legs: all 5 new subtests (8 counting the 4-way
Gone/Unknown table) FAIL for the documented reason,
TestEveryLegWiresEveryRoleContract passes cleanly on all three legs, and
TestVersionedHistoryPhase0RunsInFullSkipMode is unaffected.

Bead: be-x5jqd.2

* fix(history): refuse metadata integers binary64 cannot hold exactly (refs be-wdlod, #6358 follow-up)

canonicalDurableState canonicalizes numbers per RFC 8785 (JCS), which
renders every number as an IEEE-754 binary64 double regardless of
magnitude. An integer-valued metadata literal past 2^53-1 therefore
rounds to a DIFFERENT VALUE on the way into durable_state -- not a
formatting change, a value change -- which can collapse two distinct
issue states onto one durable_state and therefore one content token.

refuseUnrepresentableIntegers is the fix: an admission gate, one layer
above the JCS step, that parses each JSON number literal exactly with
math/big (never float64 -- float64 rounding is the exact thing being
guarded against) and refuses whenever the literal's VALUE, not its
spelling, is an integer whose magnitude exceeds 2^53-1. Value-not-form
matters because the first cut of this gate skipped any literal
containing '.', 'e', or 'E' outright, reasoning that non-integer forms
round-trip losslessly -- true for genuinely fractional literals, but
not for an integer VALUE spelled in decimal or exponential form: QA
found that 9007199254740993.0 and 9.007199254740993e15 walked straight
past that first gate and canonicalized to the same colliding target as
the bare literal. The predicate now inspects the value via
big.Rat.SetString/.IsInt, so all three spellings are refused alike.

1e300 is refused too, no notation carve-out: it denotes the integer
10^300, and binary64 spacing near that magnitude is roughly 2^248 --
vastly wider than the collision window at the 2^53 boundary this gate
exists to close. Admitting that spelling while refusing 9007199254740993
would be the same defect with a bigger window (mayor's ruling, citing
this collision-window argument as decisive). Non-integer values stay
admissible past the bound (1.5e300 is fine): ES6 shortest-round-trip
formatting is a bijection on doubles, so two non-integer literals
collide only if they already denoted the same double before this gate
ever ran, and a fractional literal never carried a promise of exact
decimal storage the way an integer -- an id, a count, a timestamp --
carries a promise of exactness that silent rounding would corrupt.

jcsCanonicalize is canonicalDurableState's RFC 8785 step pulled out on
its own, below the gate rather than behind it, because refusing 1e300
puts the admission policy at odds with one of this store's own spec-
conformance fixtures: testdata/jcs/input/values.json, one of the 10
official RFC 8785 vectors shipped verbatim from the spec's reference
suite (not authored here), itself contains 1E30. RFC 8785 conformance
is a claim about the canonicalizer, not about this store's admission
policy, so TestCanonicalDurableStateIsJCS now runs all 10 shipped
vectors -- values.json included, still asserting 1E30 folds to 1e+30
per spec -- through the ungated jcsCanonicalize, while its two local ad
hoc cases keep exercising the full gated canonicalDurableState, since
neither conflicts and both are more faithful to production traffic that
way. The gate's own refusal of that magnitude is pinned separately, on
its own terms, in version_history_integer_admission_test.go.

Severity is MINOR, not MAJOR: Dolt's JSON column type already
renormalizes metadata to float64 on every read regardless of this gate
(measured on dolt 2.2.3: 9007199254740993 reads back as
9007199254740992, 1e300 as 1e+300), which converges two distinct
in-memory states to one stored state before any version row is minted.
The collision this gate closes is therefore unreachable through normal
bd update traffic on this backend; it stays real for off-path writes --
bd sql, a hand-written JSONL import, or a TEXT-column backend -- which
is why this landed as a follow-up rather than gating Phase 2 itself.

Verified clean: a full module compile; static analysis over the
storage tree; the complete issueops package suite (260 subtests); the
schema package suite; and the broader storage tree, apart from one
dolt-package test that fails identically against the pre-this-diff
baseline (a Dolt server port collision with a concurrent session's
process on this host) -- confirmed pre-existing and environmental, not
caused by this change.

* feat(issueops): implement R7.1 as-of read's store-layer primitive (be-x5jqd.5)

Turns backend/conformance/versioned_read_contract.go (authored RED in
6aefdce60, gastownhall/beads#5898 rev 9, #6136) towards GREEN. This
commit lands the shared production seam; wiring the three per-leg
fixtures (dolt, embeddeddolt, uow) onto it is a follow-up commit.

asof_read.go (new): AsOfReadInTx resolves an AsOfSelector (an instant
or a previously-served version address) to one issue_versions row --
the latest version accepted at or before T, everything later strictly
excluded -- and reports either its state and address, or a typed
refusal (gone-retention/gone-erasure/gone-reorganization/unknown) with
a reason. storeID is accepted only for signature parity with the
fixture hook shape (Design D: the conformance suite's own ad hoc
dispatch string selects among per-leg isolated test stores; issue_versions
carries no store_id column, matching CurrentEpochInTx's precedent).
AsOfRestriction is string-backed, unlike R20's int-backed
EpochRestriction, because it round-trips directly through the new
removed_restriction column with a plain cast.

Migration 0069 adds issue_versions.removed_restriction VARCHAR(30),
nullable (NULL = live, never a stored value). Sits alongside removed_at/
removed_reason (migration 0067, virgin until this slice); AsOfReadInTx
only READS all three -- a future R17 is the real writer via hold/remove/
erase primitives, no collision. Guarded PREPARE + CLI direct-DDL
override + schema_test.go hygiene entries, all modeled on 0068's
pattern; TestLatestVersionIncludesMigration0068 is superseded per the
one-pin-at-a-time convention.

version_history.go: splits RecordVersionInTx into a versionedHistoryEnabled-
gated wrapper and a new exported RecordVersionAtInTx, both delegating to
a shared recordVersionAtInTx(..., at time.Time) body. RecordVersionAtInTx
is test-support only -- ungated, caller-chosen timestamp -- so an as-of-
read fixture's MintAt hook can mint version rows dated in the past
without flipping a store's history-enabled flag. No behavior change for
existing RecordVersionInTx callers.

The new/moved code shifted which function each completeness guard sees
as the enclosing write site, so all three needed updating, not bypassing:
- row_lock_guard_test.go's funcNameExemptions key moves from
  RecordVersionInTx to recordVersionAtInTx (the write's new actual
  enclosing function), reasoning extended to cover both callers.
- journal_completeness_test.go's beadDMLExemptions and
  version_completeness_test.go's versionExemptions each gain a
  RecordVersionAtInTx entry mirroring RecordVersionInTx's own (test-
  support twin, no production caller, no mutation of its own to
  journal/mint beyond the seam itself).

Also fixed a latent test-helper gotcha found while writing the 0069
Dolt-CLI test: queryDoltCSV trims the whole `dolt sql -r csv` output
before parsing, so a row whose ONLY selected column is NULL renders as
a bare blank line that strings.TrimSpace silently swallows when it's
the trailing line, collapsing "one row, NULL value" into "zero rows".
Fixed by selecting a non-NULL anchor column (issue_id) alongside the
column under test.

Verification performed: full module compile and static analysis, gofmt
clean; the complete internal/storage/schema suite with the real-Dolt-CLI
lane enabled; and the complete internal/storage/issueops suite,
including every completeness/row-lock structural guard -- all clean.

* feat(issueops): wire dolt, embeddeddolt, and uow onto R7.1 as-of read (be-x5jqd.5)

Turns backend/conformance/versioned_read_contract.go fully GREEN
(authored RED in 6aefdce60, gastownhall/beads#5898 rev 9, #6136): this
follows up on 4da98a9a8's shared production seam by wiring all three
storage legs' AsOfReadFixture (Resolve/MintAt/MakeUnanswerable) onto
issueops.AsOfReadInTx, per that commit's own stated plan.

Each leg's asOfReadHarness is Design D's dispatch table: the
conformance suite invents storeID strings to select among N isolated
stores, and isolating them is entirely the harness's job --
AsOfReadInTx itself stays storeID-oblivious. The three legs differ
only in how they get that isolation cheaply:
  - dolt: one shared testcontainer, N randomly-named databases
  - embeddeddolt: N fully independent on-disk databases
  - uow: one shared dolt sql-server subprocess (NewDoltServerUOWProvider's
    adoption semantics collapse repeat calls against the same root dir
    onto the same process), N randomly-named databases

All three harnesses are Fatalf/Skip-free below their own
TestAsOfReadContract body: AsOfReadFixture's hooks carry no *testing.T
of their own and run from inside t.Run subtest closures (sometimes
nested two deep), where FailNow/SkipNow would panic with "subtest may
have called FailNow on a parent test". Failures instead flow back as a
plain error into conformance.RunAsOfReadXXX, which Fatalfs correctly
on the subtest's own goroutine.

Two small companion fixes surfaced while wiring the legs on:

  - issueops.asOfVersionAddress -> AsOfVersionAddress (exported): each
    leg's MintAt needs to build the exact token its own
    RecordVersionAtInTx write will resolve against, from a different
    package than issueops.

  - recordVersionAtInTx now truncates `at` to whole seconds before
    writing it to issue_versions.change_at (DATETIME, migration 0067).
    Measured on dolt 2.2.3: the column ROUNDS a sub-second value rather
    than truncating it, so a change_at of 13:32:04.77 lands at 13:32:05
    -- strictly later than the instant it was meant to record. That
    breaks resolveAsOfRevisionInTx's "at or before T" comparison
    (asof_read.go) for any T between the true instant and the rounded-
    up one. This is a production correctness fix, not test-only:
    RecordVersionInTx hits the identical hazard on every real
    time.Now().UTC() call whose nanosecond component rounds up.

Verification performed:
  - uow: TestAsOfReadContract green standalone (5 subtests, 4 nested
    restriction variants) and the full uow package green in isolation
    (673s, includes pre-existing TestReleaserContract and everything
    else). A `go test ./internal/storage/...` full-tree sweep flagged
    uow FAIL via a 600s hang inside TestReleaserContract's migration
    lock -- traced to cross-package parallel resource contention from
    running the whole storage tree's dolt-sql-server-spinning suites
    concurrently, not a regression: the same test is clean when the
    package runs alone.
  - embeddeddolt: TestAsOfReadContract green (22.89s, all subtests and
    all 4 restriction variants).
  - dolt: skipped on this host -- no Docker for the leg's testcontainer,
    the same pre-existing skipIfNoDolt gate the whole dolt package
    already runs under, unrelated to this change.
  - TestEveryLegWiresEveryRoleContract and
    TestEveryContractImporterInTheStorageTreeIsRegistered both pass for
    all three legs.
  - gofmt clean; whole-module build and vet clean.

Bead: be-x5jqd.5

* feat(versions): bd versions + a config switch for versioned history (refs be-hs42e.6.2)

Versioned history has been buildable but not usable: migrations 0067+ create
issue_versions, and the Phase 2 writer fills it, but SetVersionedHistoryEnabled
was a Go method nothing in cmd/bd ever called. There was no supported way for a
person to turn the feature on, and no way at all to read it back without raw
Dolt SQL. This adds the switch and a reader.

- versioned-history.enabled (env BD_VERSIONED_HISTORY_ENABLED), default off,
  applied at the top of wireStorageDecorators. It MUST run on the raw store:
  the capability is a type assertion and no decorator forwards it, so applying
  it after a wrap would silently leave history off while the config said it was
  on. TestVersionedHistoryConfigAppliesToTheRawStore pins the ordering, and
  fails rather than skips if a decorator ever starts forwarding.

- storage.VersionLister + issueops.ListVersionsInTx over issue_versions, on the
  dolt and embeddeddolt legs. A narrow capability rather than a Storage method,
  following ExternalRefHistoryQuerier: a backend that cannot know must be able
  to say so instead of answering "none".

- bd versions <id>, with three distinguishable outcomes rather than two. Off,
  unsupported, and empty are different answers with different fixes; an empty
  list is a claim about the bead, and returning it for the other two would be a
  wrong answer rather than an empty one. The four removal restrictions render
  as four sentences, and unknown (no lineage knowledge here) is not gone.

- REV is printed as a local ordinal with a footer saying so. It is deliberately
  NOT presented as a citable address: AsOfVersionAddress mints over the ordinal,
  two clones can both hold revision 8 of the same bead, and the durable
  version_id primary key has not landed. An address printed now would break
  every citation once it does.

- bd version <id> now points at bd versions <id> instead of printing bd's own
  build and looking like the bead has no history. Bare bd version is unchanged.

No migration: 0067/0068/0069 already carry every column this reads.

Verified on a scratch store: create + 2 updates + close with the flag on lists
4 attributed versions; with the flag off, 0 rows in issue_versions and the
command refuses naming the key.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(versions): emit local_revision, not revision, in --json (bee's #5898 consumer read)

types.Issue already ships `json:"revision"` (types.go:1206) and it is the
row-lock CAS token — an unrelated value, and a string where this one is an
int64. Emitting "revision" from the versions payload would put two meanings
and two types on one key in the place machines read: the `bd version`
collision again, with worse consequences, since a script that learned one
shape gets the other and cannot tell.

local_revision also carries the non-citability with the value rather than
only in a footer no script parses, and needs no rename when version_id lands
beside it.

Raised by @bee-ghosttrack's consumer read on #5898, who reported a couple of
hundred script files parsing `bd … --json` — this is the part of the surface
they would actually touch. Pinned by
TestVersionsJSONDoesNotCollideWithIssueRevision.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(versions): make the advertised switch actually switch it on (#6661 review)

@bee-ghosttrack's blocking finding: the help text and the off-refusal both
told the user to run `bd config set versioned-history.enabled true`, and that
command did not turn the feature on. The key is not yaml-only, so `bd config
set` routed it to the workspace DATABASE; both readers called config.GetBool,
which is viper (yaml + env) only. The user ran exactly what they were told,
was told it was set, and recording stayed off — configured on, actually off,
one layer up from the decorator-ordering hazard this command already guards.

Takes bee's option (b): read the switch from the store's own config, where
`bd config set` already writes it. That also makes recording a property of
the STORE rather than of whoever is calling, which is what closes finding 2 —
two clients of one sql-server can no longer disagree about whether a write is
recorded.

The two planes are OR'd rather than ranked. The hazard is a write that fails
to record, never one that records when it needn't, so either saying yes is
enough and neither can silently switch the other off. BD_VERSIONED_HISTORY_ENABLED
still works for a one-off run. A store with no settings plane (proxied, no-db)
falls back to viper instead of failing the command.

Also from that review:

- finding 3: the read no longer refuses just because recording is off. A store
  that recorded for a month and was switched off HAS versions; refusing made a
  claim about the store from a fact about this invocation's config, which
  VersionLister's own doc says are independent. Rows are listed either way,
  with a note when recording is currently off; refuse-with-remedy only when
  off AND empty.
- finding 4: an unresolved id with no versions is "no such bead", not "none
  yet". Falling through on an unresolved id stays right — a deleted bead can
  still have versions — but only until the answer is empty.
- finding 5: the ordering test's escape hatch is t.Fatal, not t.Skip; a skip
  returned before the assertion that actually guards the ordering. The
  storage_chain.go doc cited a test name that never existed. version_lister.go
  promised a list of compile-time assertions that was not there; the
  assertions now exist in each leg's own package, where they can compile.
- `versioned-history.` is a recognized config prefix, so the set no longer
  prints "not a recognized config key" immediately before confirming the set.

Test: TestVersionedHistorySwitchRoundTrip_Embedded drives the real
`bd config set` through to a real `bd versions` against a real store, with
BD_VERSIONED_HISTORY_ENABLED cleared so a pass proves the store setting
carried it alone. This is the round trip bee asked for, and it is the only
shape that could have caught the original defect — a fake-backed unit test
cannot see a disagreement between two real planes.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* docs(versions): name what the OR'd switch planes cost (#6661 review)

@bee-ghosttrack, round 2: with the two planes OR'd rather than ranked, the
consequence worth naming is that once the store setting says on,
BD_VERSIONED_HISTORY_ENABLED=0 cannot countermand it for a single run. The
help now says so, and says where to turn it off instead.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(versions): gate the wiring store read on the capability, not a recover (#6661 review)

@bee-ghosttrack's round-3 blocking finding. wireStorageDecorators reads the
versioned-history switch off the raw store on every bd invocation, and did so
before anything established that the store could use the answer. cmd/bd's own
fakeProbingDoltStore embeds a nil storage.DoltStorage, so the promoted
WorkspaceConfig SIGSEGV'd at wiring time -- and a panic takes the whole test
binary down, which is why one unguarded read showed up as two red CI steps
(Test (macos-latest), PR Core (wrapper timing)) rather than one failed test.

Takes the fix bee prescribed: assert storage.VersionedHistoryConfigurer first
and read the store plane only when the store could act on the answer.

The previous round fixed this with a recover plus a WorkspaceConfig on the
fake, and left a comment arguing that no capability assertion could work. That
argument was wrong, and wrong in a specific way worth recording: it reasoned
about asserting WorkspaceConfig, which IS declared on storage.DoltStorage and
so matches every store including the nil-embedding fake. bee proposed
asserting VersionedHistoryConfigurer, which is a different interface --
SetVersionedHistoryEnabled is NOT part of DoltStorage, so the fake does not
promote it and does not satisfy it. The comment rebutted a fix that had not
been proposed. It now states what is actually true.

So the fake goes back to byte-identical with the pushed head: the wiring fix
fixes that test without touching it, as bee said it would, and the fake keeps
the "only the methods below may be called" constraint its own doc asserts.

The recover stays, as a backstop rather than the guard. It covers what the
assertion does not: versionedHistoryEnabled is also called from `bd versions`,
where the read is the point and no capability gate precedes it, and a store
that DOES implement the capability can still have a half-built settings plane.

The viper plane is still read first and unconditionally, so a set-but-unsupported
store still reaches applyVersionedHistoryConfig and still gets its warning. Only
the store-plane read is gated. The one case that loses a warning is a store whose
own settings plane says true but which lacks the capability -- and `bd config
set` could not have written that plane on such a store to begin with.

Tests, split so each layer fails for its own reason:

- TestWireStorageDecoratorsSkipsTheStoreReadForANonConfigurer asserts calls == 0,
  not merely that it survived. "It survived" is what the recover delivers too,
  which is how this regressed the first time.
- TestWireStorageDecoratorsSurvivesAStoreThatCannotAnswer keeps the recover's
  case, now on a store that IS a configurer so the guard lets it through.
- TestVersionedHistoryEnabledForWiringReadsTheStoreWhenItCanRecord pins that the
  guard did not stop reading the plane finding 1 existed to start reading.

Mutation-verified both ways: removing the guard fails the first test on
calls=1/want=0 while everything still "passes" by surviving; removing the
recover leaves the first test green and fails only the second.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* test(versions): name the embedded round-trip so CI selects it (#6661 review)

@bee-ghosttrack's round-3 finding 2. The round-trip test that proves the two
config planes agree ran only on the author's machine.

.github/scripts/embedded-test-shard.sh discovers what to run with
`grep -rh '^func TestEmbedded' cmd/bd/*_embedded_test.go` and validates
manifest entries against ^TestEmbedded[A-Za-z0-9_]+$.
TestVersionedHistorySwitchRoundTrip_Embedded matched neither, so the only
lane that sets BEADS_TEST_EMBEDDED_DOLT=1 for cmd/bd never selected it; the
generic Test jobs run without that env, where the test's own guard skipped it.
Skipped and passed look alike from outside, which is what made it invisible.

Renaming is the whole fix -- a test absent from the shard manifest still gets
a shard from the fallback distribution. Verified by running the script's own
selector over the tree and confirming the new name is discovered.

The rationale is now a comment on the test, because the old name reads more
naturally and nothing else in the file explains why the prefix is load-bearing.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* test(versions): drop the dead fixture, name the empty arm (#6661 review)

@bee-ghosttrack's round-3 finding 3. TestVersionsRefusesWhenFlagOff built a
backend holding one recorded version, handed it to nothing, and ended in
`_ = backend`.

The fixture was load-bearing for the assertion the test was named after --
that the read was refused BEFORE the backend was consulted. Finding 3 removed
that behaviour on purpose, so the assertion went with it; the fixture stayed
behind, unused, under a name still promising the old contract.

Renamed to TestVersionsOffAndEmptyRefusesWithRemedy for what it actually pins,
moved beside TestVersionsOffButRecordedStillLists so the two read as the pair
they are -- recording off decides the FOOTER, never whether to read; off with
rows lists them, off and empty is the one case that refuses -- and the dead
fixture is gone.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(proxy): give bd versions a capability row, a typed refusal (#6661)

main's proxied-server capability registry (#6582) requires every command
path to carry a row, and TestProxyCapabilityRegistryCoversCommandTree
fails for `bd versions`, which this PR adds.

It is refused, reason unimplemented, rather than permitted. It is a pure
read (issueops.ListVersionsInTx in one read transaction), so nothing
about it is unsafe on a shared backend and "design" would be wrong. But
it reaches the backend only through the optional storage.VersionLister,
which the dolt and embedded stores implement and the uow provider does
not. Permitting it would open the proxied provider in the root pre-run
(starting the proxy and dolt) and then fail untyped at
errVersionsUnsupported. The row refuses with proxy.versions.unsupported
before any side effect, and its tracking names the missing piece: a
VersionLister over the proxied uow provider (tracker #6132).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* test(uow): register verified shutdown cleanup in TestAsOfReadContract (#6661)

main's TestEveryServerFixtureRegistersVerifiedCleanup (#6441) requires
every server fixture to use verifiedShutdownCleanup(t, storeRootDir)
instead of calling proxy.Shutdown directly, so a shutdown that refuses
cannot leave a live dolt sql-server behind a green run. TestAsOfReadContract
still had its own proxy.Shutdown cleanup that only logged the error.

The cleanup is registered at the same point, so the LIFO ordering the
harness relies on (every provider closed before the shared server stops)
is unchanged.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* style(schema): gofmt cli_migrations.go after the 0070 renumber

The rebase onto upstream's 0069_widen_issue_versions_datetime_precision
(#6675) joined its const and the renumbered 0070 comment without the
separating blank line, which make fmt-check rejects.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(history): stop flooring change_at now that 0069 widened it (refs be-hs42e.10)

recordVersionAtInTx carried `at = at.Truncate(time.Second)`. That was correct
while 0067's plain DATETIME was in force: Dolt's datetime(0) does not truncate
sub-second input, it ROUNDS half-up, so a change_at could be stored strictly
LATER than the instant it recorded and break AsOfReadInTx's "latest version
accepted at or before T". Flooring first left nothing to round.

Migration 0069 widened change_at and removed_at to DATETIME(6), which removes
the rounding entirely and makes the floor actively harmful — it threw away the
microseconds the widening exists to keep. Two versions minted in the same
second collapsed onto one stored value and stopped being distinguishable by
change_at, which defeats --at, the only PORTABLE selector the read surface
offers while revision stays a per-store ordinal and no durable version address
has shipped.

This was measured, not inferred. On a store carrying both the widening and the
floor, four versions minted inside one second all read back 15:40:38.000000:
the column could hold microseconds and the writer refused to supply them. Two
correct fixes cancelling each other, and only the second one was visible.

removed_at needs no matching change: MarkLatestVersionRemovedInTx already
passes time.Now().UTC() straight through and was never floored. Audited rather
than assumed.

Pinned by TestRecordVersionKeepsSubSecondChangeAt (embeddeddolt), which mints
two versions 500ms apart inside one second and asserts both that the
fractional part survives and that the two differ. Verified it FAILS with the
floor restored — reporting exactly the 11:04:07.000000 collapse — and passes
without it, so it is a real guard rather than a test that passes either way.
The column's own half of the contract stays pinned by
TestMigration0069ChangeAtSurvivesSubSecondPrecisionThroughDoltCLI.

Also drops this branch's own tx-minting guard commit, which upstream landed
independently as #6833.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* test(feat): red — Activate versioned history in every store and provider factory, each store reading its own #6661 switch (stacked on #6661) (refs be-qxq70)

Tests first, all failing on the right reasons at fb6e219d6a (#6661's head):
- D1: on real embedded stores a routed update, a routed close and
  `bd create --repo` into a rig whose OWN row is on each gain 0
  issue_versions rows, want 1; the control (a write inside the rig) gains 1.
- D3: BD_VERSIONED_HISTORY_ENABLED=1 records into no routed store, and =0 is
  shown not to switch off a store whose row is on.
- D4: TestEveryStoreConstructionActivatesVersionedHistory flags all 9 store and
  provider factories, and its mutation probe reports "probed 0 of 9".
- wiring: wireStorageDecorators still reads the store's row (1 read) and
  switches it on; activation belongs to the factories.
- internal/versionedhistory (does not exist yet) and the doctor repair opener:
  the resolver, the provider read (K1), the error-vs-absent diagnostics and the
  shared-activation requirement.

* feat: green — Activate versioned history in every store and provider factory, each store reading its own #6661 switch (stacked on #6661) (refs be-qxq70)

Stacked on #6661 (fb6e219d6a). #6661's plane and approved commits are
unchanged: the switch stays a row of the store's own config table, OR'd with
viper, and `bd config set versioned-history.enabled true` still writes that
row and not config.yaml.

The defect: applyVersionedHistoryConfig ran only from wireStorageDecorators, so
the one store a command opens for its own workspace was activated and every
store built by newDoltStoreFromConfig (prefix-routed update/close, `bd create
--repo`, the direct-mode open) was not. With the switch on they recorded no
issue_versions row while the command reported success.

- Activation moves to where a store or unit-of-work provider is constructed
  (the store_factory.go/_nocgo.go twins, uow_factory.go's two provider
  constructors, the personal-migration planning store, and bd doctor's repair
  opener), on the raw store, before anything can wrap it. wireStorageDecorators
  no longer activates, so each store's row is read once per open.
- One resolver, in internal/versionedhistory, reachable from doctor/fix which
  cannot import package main. #6661's semantics are preserved: one key
  spelling, viper first, then the capability check, then the row read, with
  the recover backstop. The behavior-preserving refactor of #6661's
  versioned_history_switch.go / storage_chain.go is the only edit to files
  #6661 introduced; the resolver tests moved with the code, assertions
  unchanged.
- K1: a provider has no DoltStorage, so its row is read through a unit of work
  (NewUOW + ConfigUseCase().GetConfig) at construction: a pooled connection,
  one SELECT, rolled back. The constructors have already run initSchema, so
  this starts no server and creates nothing. It does not fall back to viper
  alone.
- A row read that errors resolves to off but is reported under BD_DEBUG; an
  absent row stays silent.
- Docs (configuration.md), a CHANGELOG entry, and a hint at `bd config set ...
  true` time that the setting replicates and is single-writer only.

The bazel-sync run also wanted unrelated BUILD entries for files that already
exist at #6661's head (versions.go, versioned_read_contract.go, ...); they are
not part of this change and are left out.

* test(feat): green — a served mutation records from the provider's own row, on a real server (refs be-qxq70)

K1 is the one place the resolver cannot ask a DoltStorage: `bd serve` against a
server-mode workspace writes through a unit-of-work provider, so its flag is
read through NewUOW + ConfigUseCase().GetConfig at construction. The fakes in
internal/versionedhistory prove the read; this proves it WORKS against a real
Dolt server at that moment (pool open, database selected, schema migrated).

Two server-mode workspaces on the shared test container: the one whose own row
says on records a served HTTP mutation (+1 issue_versions row), the one with no
row records none.

Measured both ways: passes with the provider activation in place, and fails
("added 0 issue_versions row(s), want 1") with it deleted from both provider
constructors in uow_factory.go.

Proxied lane only (BEADS_TEST_PROXIED_SERVER=1 BEADS_TEST_ENV_RUN_DOLT=1
TESTCONTAINERS_RYUK_DISABLED=true), like TestServeActivatesTheEventsJournal, so
it skips in a plain make test.

* test(feat): red — #6661 review round, small items: findings 2, 4, 5, 6 and 8

Tests for the small findings in the second review round on #6661.

- 2: `bd versions` must decide "recording" from the store's own setting.
  BD_VERSIONED_HISTORY_ENABLED=1 with the store's row unset and nothing
  recorded must refuse, not answer "none yet"; the help text must not offer
  the variable as a per-run switch for a read.
- 4: `bd versions --json` is one object, {"versions": [...], "recording":
  bool}, with [] rather than null when nothing is recorded.
- 5: AsOfReadInTx reports any stored removed_restriction outside its four
  values, "live" included, as unknown.
- 6: the 0070 header spells the restriction vocabulary with the underscore
  spellings the code stores and compares.
- 8: `bd version <arg>` exits 1 and points at `bd versions <arg>`. This one
  pins behaviour the branch already has, so it passes at red; it was shown
  to fail with the guard removed.

Item 7 is a comment-only fix and has no test.

* feat: green — #6661 review round, small items: findings 2, 4, 5, 6 and 7

- 2: `bd versions` reports the store's own setting. It read the environment
  and config.yaml as well, so BD_VERSIONED_HISTORY_ENABLED=1 made a store that
  never recorded answer "No versions recorded yet" instead of refusing with
  the remedy. It only reads, so those planes cannot make the store record.
  The "for one run" hint is dropped from the help and the refusal, since it
  could only ever produce the wrong answer.
- 4: `bd versions --json` is always {"versions": [...], "recording": bool},
  with [] rather than null when nothing is recorded. Previously a bare array,
  or null, and no recording flag.
- 5: AsOfReadInTx reports a stored removed_restriction outside its four
  values, "live" included, as unknown instead of passing it through.
- 6: the 0070 header and its test use the underscore spellings the code
  stores and compares. 0070 is unreleased, and this changes its content hash.
- 7: comment only. DATETIME(6) still rounds to the microsecond; the comment
  said 0069 removed the rounding entirely.

* test(fix): red — #6661 number admission: fractions past the bound, exponent cost, pre-enable scan

Tests for the review round on the number-admission gate, written before the change:

- a fraction whose nearest double is at or past 2^53 is refused (9007199254740993.5,
  9007199254740994.5, 9007199254740991.5), and the gate is closed under its own
  canonicalization, checked as a property over a corpus
- classification depends on magnitude, not on the size of an exponent: 1e100000000 and
  -1e400 are refusals, 1e-100000000 and 1e-400 are admitted, and allocation does not grow
  with the exponent
- the sentinel's text names the I-JSON exact-integer range
- CheckMetadataVersionable agrees with the mint, and FindUnversionableMetadata finds what
  the mint would refuse and skips what it never versions
- bd config set versioned-history.enabled true refuses, writing nothing, over rows the mint
  would refuse, and false never scans

Guards that pass before and after by design: the verdict on every literal as the store
returns it, the mint's refusal writing nothing, and, on the server and embedded legs, the
store-level property that no two literals reading back as different numbers share a canonical
form. Those store tests also log what each Dolt holds for a number outside the range when
history is off, and pin that a later write to such a row is refused once history is on.

* fix: green — #6661 number admission: the nearest-double rule, ParseFloat classification, a pre-enable scan at the switch

The admission gate now refuses a JSON number literal if and only if the binary64 nearest to it
has magnitude above 2^53-1, or it overflows, whatever the literal's spelling:

- a fraction that rounds to or past 2^53 (9007199254740993.5, 9007199254740994.5,
  9007199254740991.5) is refused, so the gate is closed under its own canonicalization
- literals are classified with strconv.ParseFloat, linear in their length, so 1e1000000 no
  longer builds a million-digit integer inside the writer's transaction; an overflow is the
  sentinel and a magnitude too small for binary64 is admitted; math/big is gone
- the sentinel reads "number is outside the I-JSON exact-integer range (magnitude above
  2^53-1)"; ErrIntegerNotRepresentable keeps its name, with a comment saying why
- ordinary fractions such as 0.1 stay admitted; no verdict on a value the store hands back
  changes

The header now says what the mint's refusal is: an integrity backstop inside the writer's
transaction, not an admission policy for metadata.

bd config set versioned-history.enabled true now checks the store first. It reads every issue
the mint would version, runs the mint's own function over each one's metadata
(issueops.CheckMetadataVersionable, through issueops.FindUnversionableMetadata), and refuses,
writing nothing, while any is refused, printing the count, the ids and the fix. There is no
override; setting it false never scans. The environment and config.yaml planes do not pass
through the command and rely on the refusal at write time.

Also: docs and a CHANGELOG entry, and comments in the existing admission tests that described
the old rule.

* test(fix): keep the exponent-cost allocation test stable under the race detector

TestNumberAdmissionAllocationsDoNotGrowWithTheExponent compared two
independently averaged allocation counts with a strict >. Under -race
sync.Pool drops one Put in four at random, and the refusal's fmt.Errorf
takes its printer from a pool, so a call now and then allocates one more
than it would. The test failed on most runs of `go test -race -short`, the
flag set of the required lane, and never without -race.

That noise only ever adds allocations, so compare the fewest allocations
over many single-call samples instead. The comparison stays strict, and it
still fails on the exact big.Rat gate this test exists to keep out (49
allocations for 1e1000000 against 36 for 1e400). The doc comment no longer
claims the count is deterministic under -race.

* test(fix): red — set-many skips the pre-enable scan; pin what the scan reads

bd config set-many versioned-history.enabled=true switches versioned history
on with no pre-enable scan: only bd config set makes it. With a row holding a
number outside the I-JSON exact-integer range the setting is turned on and the
next write to that row fails. The new embedded test drives the real verb over
such a row and expects the whole batch to be refused, writing nothing.

The scan's own embedded test only used open issues, so deleting AllFlag or
IncludeAllTypes, or replacing the unlimited Limit, left it green. It now adds a
closed, a pinned and a gate offender, and a second test imports more rows than
one default page and expects every one of them counted.

* fix: green — bd config set-many runs the pre-enable scan for versioned-history.enabled

bd config set refuses to turn versioned history on while an issue holds
metadata a version could not record. bd config set-many writes the same
setting through a validation loop of its own and made no such check, so it
switched history on over a row whose next write then failed. It now runs the
same check for that one key inside its validation loop, before any pair of
the batch is written, so a refusal stores nothing. The check reads through
the accessor it already used on both routes: the store the command has
opened on the direct route, the provider on the proxied one.

* chore: strip internal tracker ids from the comments and tests across #6661's range

Comment and test-text changes only; no behaviour changes. Across every commit from the
merge-base with upstream main to here, the comments and tests named internal tracker ids
(one bead id in eleven comments and in one test failure message, an example id in the
`bd version` guard's comment, and an internal decision's attribution in the huge-exponent
admission test). They now cite gastownhall/beads#5898 and #6136 only, which is what a reader
of the public branch can follow.

The 0070 migration's header comment is one of the edits. That migration is new on this branch
(it does not exist on upstream main), so the change is not an edit to a shipped migration, but
it does change the file's content hash; the schema tests that compute hashes are self-consistent.

Text that already exists on upstream main is left as it is, even where it mentions an id: this
commit does not rewrite lines the range did not add.

* chore(bazel): bazel-sync (gazelle) for the #6661 range

* fix(bazel): give fix_test the store.go its activation guard parses

TestVersionedHistoryDoctorRepairOpenerUsesTheSharedActivation parses
store.go from its working directory. `go test` runs in the package
directory, so the file is there. A Bazel test only sees its declared
runfiles, so the test failed with

    parse store.go: open store.go: no such file or directory

in //cmd/bd/doctor/fix:fix_test (--config=ci) and in shard 1 of
//cmd/bd/doctor/fix:fix_dolt_test (--config=doltserver), which runs the
same binary through data = [":fix_test"].

Declare store.go as data on fix_test.

* test(fix): red — the pre-enable scan must check the whole issue, as the mint does

bd config set versioned-history.enabled true runs a check over every issue
before it turns history on. The check looked at each issue's metadata alone,
while the mint canonicalizes the whole issue. A gate's timeout is a
time.Duration that a version holds as nanoseconds, so a gate whose timeout is
past 2^53-1 ns (about 104.25 days) holds a number outside the I-JSON
exact-integer range: the mint refuses every write to it, the scan never
looked, and the switch could be turned on over it.

- The agreement test's domain widens from metadata documents to whole issues:
  the metadata corpus, plus timeouts at 2500h (admitted), 2600h, 8760h and
  -2600h (refused), exactly 2^53-1 ns (admitted) and 2^53 ns (refused).
- The scan test covers a gate over 105 days and expects the verdict to name
  the field, "timeout".
- The mint-level refusal test covers the same gate and expects the refusal to
  name the field as well as the literal, for a number in metadata too.
- An end-to-end test on the direct route and one on the proxied route create
  gates with bd gate create --timeout, expect the enable to refuse and name
  them, and expect the issues the scan names to be exactly the issues whose
  next write the mint refuses.
- Three guards keep the scan's lite read from hiding a number: every column it
  leaves out is a string or a list of strings, nothing the mint adds and the
  scan does not load can hold a number, and no exported check over part of an
  issue exists beside the one the mint runs. Each guard is also run against
  shapes it must refuse, so it cannot pass by finding nothing.

The new symbols (CheckIssueVersionable, FindUnversionable and the Field of
UnversionableIssue) do not exist yet, so the issueops tests do not build.

* fix: green — the pre-enable scan runs the mint's own check over the whole issue

The check behind bd config set versioned-history.enabled true looked at each
issue's metadata alone. The mint canonicalizes the whole issue, and a gate's
timeout, a time.Duration held as nanoseconds, is a number outside the I-JSON
exact-integer range once it is past 2^53-1 ns (about 104.25 days). The mint
refuses every write to such a gate, the scan cleared the switch over it, and
the first write after that failed.

CheckIssueVersionable is now exactly canonicalDurableState's refusal over the
whole issue, and FindUnversionable runs it over every issue the mint would
version. It replaces FindUnversionableMetadata, and CheckMetadataVersionable
is gone, so no check over part of an issue is exported beside the one the mint
runs. A refusal names the top-level field it found the value in ("metadata",
"timeout") as well as the literal, on the mint and on the scan; the field is
located only after a refusal, so a write that is admitted still reads the
document once. A gate timeout above 2^53-1 ns is unrecordable by policy: it is
refused at the write, named by field and documented, not re-encoded.

The refusal at the switch gives the fix for each field. For a number in
metadata that is bd update --metadata or --unset-metadata, which works with
history on or off because a version is recorded from the state after the write.
For a gate timeout, which bd update cannot change, it is removing the gate with
bd delete, or setting the timeout_ns column with bd sql while history is off;
bd sql needs a server-backed store, and the text says so. It also says the
check runs once, now: a writer that does not record (an older bd, bd sql, a
pull from a clone that had history off) can add such a row afterwards, and the
first write to it then fails with the same refusal. Making the check and the
write of the setting one transaction would narrow that window, not close it.

Corrected in the comments, the docs and the changelog as well: an import is not
a path that skips the mint, since it goes through the same batch create; and
Dolt's JSON column collapses duplicate keys when it stores a document, so on a
Dolt store neither the scan nor the mint can see one, and the duplicate-key
refusal is a defence for a backend that keeps them.

* test(fix): red — the listing must answer as the as-of read does; the SDK opens must be accounted for

Three review findings on the versioned-history change and one wording fix,
tests first.

- A removed version's restriction. AsOfReadInTx answers a stored value outside
  the four-value vocabulary (a NULL or empty column, "live", a hyphenated or
  arbitrary string) as unknown, but ListVersionsInTx hands the column back as
  stored, for every row, and the label bd versions prints passes such a string
  through. A table test runs the listing and the as-of read on the same stored
  value, for a version that was removed and one that was not, and expects the
  same answer, and none for a version that was never removed. The label gets
  the same out-of-vocabulary values and is expected to render what unknown
  renders.
- The SDK's store opens. The shared construction guard now scans the repository
  root as well, so the Go SDK's five opens (Open, OpenFromConfig and OpenGated,
  and OpenBestAvailable in each build-tag twin) are noticed. Nothing accounts
  for them yet, so both guards fail on exactly those five sites.
- A bytes bound beside the allocation-count bound on the number admission
  gate. A classifier that builds the number it is asked about makes one
  allocation whatever the exponent, so the count bound passes it, and the bytes
  grow. The fewest bytes one call allocates for a literal with a huge exponent
  must be no more than for a small one plus a margin. It passes today, because
  the gate never builds the number; it fails for a gate that does.
- The refusal at the switch names the gate remedy as bd delete <id> --force,
  says that without --force bd only previews, and says that removing the gate
  unblocks anything it was blocking. The embedded and proxied end-to-end tests
  expect all three.

* fix: green — the listing answers as the as-of read does; the SDK opens are accounted for

Three review findings on the versioned-history change and one wording fix.

A removed version's restriction. A stored removed_restriction is a free string,
and only the four values of the vocabulary are answers. The as-of read already
reported anything else (a NULL or empty column, "live", a hyphenated or
arbitrary string) as unknown, but the listing handed the column back as stored,
for every row, and the label bd versions prints passed it through.
NormalizeRemovedRestriction is now the one place that decision is made.
AsOfReadInTx calls it; ListVersionsInTx calls it for a version that was removed
and gives a version that was not removed no restriction; and restrictionLabel
renders through it. The listing, its JSON and the label now say what the as-of
read says for the same row.

The SDK's store opens. The Go SDK's five opens (Open, OpenFromConfig and
OpenGated, and OpenBestAvailable in each build-tag twin) apply neither per-store
switch, the events journal's or versioned history's, and they still do not.
Applying them would change the library's behavior for every embedder, so that
is a separate change; this one declares the boundary. The shared construction
guard now accounts for the five with one exemption reason that is true of both
switches, so a new SDK open is noticed rather than missed, and its staleness
check keeps the exemptions honest. The docs gain one bullet saying that writers
built on the SDK do not apply the switch.

The bytes bound on the number admission gate needs no production change: the
gate never builds the number, which is what the bound pins.

The refusal at the switch now names the gate remedy as bd delete <id> --force,
says that without --force bd only previews, and says that removing the gate
also unblocks anything it was blocking. The docs line says the same. For a gate
that blocks an issue, bd delete without --force prints a preview and exits 1,
and with --force the gate is removed and what it blocked is ready again.

* test(bazel): declare the root package's Go source as data for //cmd/bd:bd_test

The shared store-construction scan now reads the repository root, where the Go
SDK's opens live, but //cmd/bd:bd_test declared none of the root package's
source. Under bazel test the scan therefore saw an empty directory, reported
the five SDK exemptions as no longer matching a store construction site, and
failed the events-journal guard, while go test, which sees the whole checkout,
passed.

List the root in tools/bazel/go_srcs.py so the generator emits its managed
go_srcs filegroup there, and add that filegroup to bd_test's data. The new
block is the generator's own output and nothing else changes.

* ci: list the switch scan's proxied gate-timeout test in the 30-shard manifest

Upstream main (#7129) moved the proxied-server tier to 30 duration-balanced
shards, and TestProxiedShardManifestGeneratorNotStale requires every
TestProxiedServer*/TestServerMode* test exactly once in that block. This
branch adds TestProxiedServerVersionedHistorySwitchRefusesAnUnrecordableGateTimeout
(cmd/bd/versioned_history_switch_scan_proxied_integration_test.go), so the
block needs its line. Written by the generator itself:
python3 scripts/ci/gen_proxied_shard_manifest.py 30 --weights=duration --write
(one line, shard 8); --check exits 0 afterwards.

Rebase note (maintainer): regenerated on current main, whose proxied-server
tier uses 34 shards; the generator's incremental output
(gen_proxied_shard_manifest.py 34 --weights=duration --write) placed this
test at shard 6 of the 34-shard block.

* ci: list the PR's embedded versioned-history tests in the embedded shard manifests

#7156 made the embedded-Dolt tier's shard manifests exact-once (50 cmd
shards, 15 storage shards), so every embedded test must be listed. This PR
adds five embedded cmd tests and three embedded storage tests; this commit is
exactly what the generators write for them:

  python3 scripts/ci/gen_embedded_cmd_shard_manifest.py 50 --weights=duration --write
  python3 scripts/ci/gen_embedded_storage_shard_manifest.py 15 --weights=duration --write

Incremental: 8 lines added, none moved.

Rebase note (maintainer): regenerated on current main, whose embedded
manifests use 100 cmd shards and 40 storage shards; the generator's
incremental output placed these tests at cmd shards 55
(TestEmbeddedVersionedHistorySwitchScansEveryRowNotOnePage), 56
(...SwitchRoundTrip), 57 (...SwitchRefusesUnversionableMetadata), 58
(...SwitchRefusesAnUnrecordableGateTimeout) and 59
(...SetManyRefusesUnversionableMetadata) of the 100-shard block, and at
storage shards 5 (TestRecordVersionKeepsSubSecondChangeAt), 6
(TestVersionedHistoryKeepsNumbersTheStoreDistinguishesApart) and 23
(TestAsOfReadContract) of the 40-shard block.

* test: exempt OpenBestAvailableWith, where #7188 moved the SDK's store construction

Upstream #7188 split beads.OpenBestAvailable: it now delegates to the new
OpenBestAvailableWith, which builds the store. This PR's two construction
guards (TestEveryStoreConstructionActivatesTheEventsJournal and
TestEveryStoreConstructionActivatesVersionedHistory) share one exemption
list keyed by function, so after merging main they flagged
OpenBestAvailableWith as an unexempted construction site and reported the
OpenBestAvailable entries as stale. The two build-tag twins' keys now name
OpenBestAvailableWith. The reason is unchanged: it is the SDK's library
surface for embedders, and no code in the bd binary calls it. gofmt
realigned the three neighbouring entries.

* chore(schema): renumber removed_restriction to 0071 after #6943's 0070

Migrations are numbered by landing order. #6943 (participation_generation,
the versioned-history write fence) lands first and owns main-plane 0070 and
ignored/0028, so this PR's removed_restriction migration moves to the next
free slot, 0071. The rename is done here, as one maintainer commit, rather
than inside the replayed commits, so the history shows exactly what changed
relative to the PR as reviewed; the intermediate commits of the rebase carry
a duplicate 0070 and are not expected to build.

- migrations/0070_add_removed_restriction.{up,down}.sql become 0071_*, with
  their header comments updated (the SQL itself is unchanged). Neither file
  exists on main or on #6943, so this is not an edit to a shipped migration.
- cli_migrations.go: the CLI-bundle override is keyed to the new file name
  and renamed cliMigration0071AddRemovedRestriction, and its const now sits
  after 0070's.
- migration_0070_add_removed_restriction_test.go becomes
  migration_0071_add_removed_restriction_test.go; its tests and messages say
  0071, and it now owns the one LatestVersion pin (71).
  TestLatestVersionIncludesMigration0070 in #6943's participation_generation
  test is superseded by it and replaced by the usual pointer comment, and
  0069's pointer comment now names the 0070 file that superseded it.
- schema_test.go hygiene comments, BUILD.bazel embedsrcs/srcs, and the
  asof_read.go comment that cited the migration number.

Checked: go test ./internal/storage/schema/... (with the dolt CLI lane,
including TestAllMigrationsSQLAppliesThroughDoltCLIAndRecordsLatestVersion)
and scripts/check-migration-hygiene.sh against origin/main and against
#6943's tip.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* test(versions): reconcile #6661's tests and docs with #6943's write fence

#6943's write fence (design §16.2b) makes an update-shaped write to a legacy
record -- one whose participation_generation is NULL because it was created
while versioned history was off -- a skip, not a refusal: the fence returns
before the snapshot is canonicalized, so nothing is versioned and the mint's
admission gate never runs. Several of #6661's tests seed rows with history
off and then expect a later write to them to be versioned or refused, and
several comments say every later write to an offending row fails. On a tree
that carries both PRs those tests fail and those comments are wrong.

This ports, without changing their substance, the fence-integration commits
Jim Wordelman wrote for the donnabox integration fork, where both PRs were
already folded together:

- eff898db80 / 5d2e5a2ac4 (issueops, dolt, embeddeddolt): the mocked mint
  sequence scripts the fence's participation_generation read; the number
  fidelity test splits phase 2 into 2a (a legacy row is written, not
  versioned, not refused, stays NULL) and 2b (a participating row is
  refused and left untouched); TestRecordVersionInTxSkipsALegacyRowBefore-
  TheAdmissionGate pins the fence's order against the gate.
- e0ad9d1e3c / 1528022dfa (cmd/bd): the switch round trip and the routing/env
  end-to-end tests build the rows they expect a version for after the setting
  is on, and assert that the pre-setting seeds gain nothing.
- 18b9015bf5 (cmd/bd): the embedded and proxied gate-timeout scan tests assert
  the whole scan-vs-mint truth table (legacy offenders are named by the scan
  but not refused by the mint; participating offenders are both).
- 5929ebd50c / 8ce872be03 (comments, CHANGELOG, configuration reference): the
  mint's refusal binds rows that participate in history; the pre-enable scan
  cannot see participation, so it over-approximates in the safe direction.

Left out on purpose: the fork's mintSkipsRow helper and defer-wake sweep
change, and its bd doctor "Versionable Issues" check and the docs that point
at it; none of those are part of #6661 or #6943.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Co-authored-by: Jim Wordelman <jim@wordelman.name>

* test(versions): adapt #6661's guards to what main changed under it

Three test-side adjustments for code that landed on main after #6661's last
merge of it; no production code changes.

- internal/storage/leg_contract_wiring_test.go: main gained an HTTP storage
  leg, and TestEveryLegWiresEveryRoleContract requires every leg to name or
  waive every role contract. The five R7.1 as-of read contracts this PR adds
  are a storage capability the HTTP client does not serve (internal/httpclient
  answers AsOf with an explicit unsupported error, and the wire has no
  instant/address selector or gone/unknown refusal), so they are waived on
  the http leg with that reason, as the donnabox integration fork does.
- cmd/bd/versioned_history_construction_test.go: main split
  newDoltStoreFromConfig into two thin wrappers over openDoltStoreFromConfig,
  which is where the activation defer now lives (this rebase's resolution of
  the activation commit), so the factory guard keys on that body.
- cmd/bd/versioned_history_serve_e2e_test.go: main's
  TestProxiedGatedTestsRunInTheProxiedLane requires a test that skips unless
  BEADS_TEST_PROXIED_SERVER=1 to be one the proxied lane selects, so
  TestVersionedHistoryServeActivatesTheProviderFromItsOwnRow becomes
  TestProxiedServerVersionedHistoryServeActivatesTheProviderFromItsOwnRow,
  and the 34-shard proxied manifest gains its line (written by
  gen_proxied_shard_manifest.py 34 --weights=duration --write, incremental;
  --check passes).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* chore(bazel): emit go_srcs.py's managed blocks for internal/versionedhistory

Main's tools/bazel/go_srcs.py now manages a repo_files filegroup block in
every package BUILD file, lists those filegroups in the root BUILD.bazel's
aggregates, and lists every go_library in tools/bazel's release_cross_build
target. internal/versionedhistory is a package this PR adds, so after the
rebase those managed blocks were stale and TestBazelGoSrcsBlocksCurrent
(go test ./scripts/...) failed. This is the generator's own output
(python3 tools/bazel/go_srcs.py) and nothing else; --check passes
afterwards.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(versions): don't publish change_agent in bd versions --json

`bd versions <id> --json` prints storage.IssueVersion as-is, so every JSON
tag on that struct is part of a public contract. Provenance V2
(gastownhall/beads#7510, as ruled by the maintainer) removes the ad hoc
agent field in favour of an actor chain; shipping a "change_agent" key now
would make a public contract out of a field that is on its way out.

IssueVersion.ChangeAgent is now tagged json:"-". Nothing else changes: the
issue_versions.change_agent column (migration 0067) stays, ListVersionsInTx
still reads it, change_actor and change_message are still published, and
the human listing never showed the agent. No doc or golden named the key.

TestVersionsJSONDoesNotPublishChangeAgent pins the absence with a non-empty
value, so an omitempty-style regression would still fail, and pins that
change_actor and change_message are still there.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* test(issueops): pin what the unfenced test-support mint does on #6943's new paths

#6943's two fixes to the shared mint body -- (a) no issues row means no
mint and no error, and (b) a create-shaped call on a new issues-table row
flagged no-history stamps participation_generation without minting -- were
written for its two kinds. This PR's shared body has a third,
mintUnfenced, behind RecordVersionAtInTx (the R7.1 as-of fixtures'
controlled-timestamp mint). The rebase resolution decided what (a) and (b)
mean for it; this pins that decision:

- (a) applies. It is the plane rule (FR-8: the table that holds the row
  decides its plane), not the fence, and the unfenced kind already honoured
  the flag-based form of the same rule (IsWisp). Without it, an unfenced
  mint for an unflagged wisps-table row would insert a version row that no
  issues row points at. The shared body's issues-table read now runs for
  all three kinds; only the update kind acts on the value it reads.
- (b) does not apply. The unfenced mint never declares participation, so a
  flagged row returns right after the snapshot, as before: no read, no
  stamp.
- The fence still does not apply: a legacy row is minted, and the closing
  UPDATE advances current_revision alone.

TestRecordVersionAtInTxKeepsThePlaneRuleButNotTheFence scripts each of
those three sequences exactly with sqlmock.
TestTestSupportMintsStayOutsideTheShapeSplit places RecordVersionAtInTx
outside #6943's create / dual-shape / update classification explicitly (it
is the seam's exempt twin, not a mutation entry point or mint site): it must
be in none of the shape lists, stay in versionExemptions, and reach neither
RecordVersionForCreateInTx (it never stamps) nor RecordVersionInTx (whose
gate and fence would stop the as-of fixtures minting history-off rows). The
row-lock guard's exemption comment for recordVersionAtInTx already names the
stamp-only UPDATE: #6943's own wording of it (all three UPDATE issues
statements) was carried into that exemption when the as-of read commit was
replayed.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* test(storage): say exactly why the as-of read contracts stay waived on http

#6943 now runs most of its participation-generation contracts over the
served wire (internal/httpclient/served_participation_generation_test.go):
their subject is a create or an update, which the client can send, and the
fixture reads the reference store's raw columns. This checked whether the
five R7.1 as-of read contracts can be wired the same way. They cannot,
cheaply or otherwise, without a new wire operation:

- their subject is the read itself (AsOfReadFixture.Resolve), and R7.1's
  read, issueops.AsOfReadInTx, is reached by no publicops role and served
  by no wire operation;
- the wire carries neither selector (an instant or a served version
  address) nor the gone/unknown refusal the read answers with;
- the client's only point-in-time read, DoltStorage.AsOf, is a Dolt
  commit-ref read, not R7.1, and is on the client's D8 unsupported
  allowlist.

Binding Resolve to the reference store behind the served env would pass,
but as a property of that store, which the store legs already pin, never
of the client. So the waiver stays; its comment and reason string now say
the above instead of the earlier shorthand ("HTTP AsOf is explicitly
unsupported"), which conflated the client's commit-ref AsOf with R7.1.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* docs(versions): describe what the write fence does to beads that predate recording

With #6943's write fence (design §16.2b) a bead that existed before
versioned history was turned on (participation_generation NULL) is legacy:
an update-shaped write to it is skipped, so it is never versioned however
often it is edited. Several user-facing strings from #6661 still described
the behaviour before the fence, and an independent review reproduced each
with a built bd (a legacy bead edited twice after enabling still lists no
versions; a legacy bead the switch refuses over is written without refusal
under BD_VERSIONED_HISTORY_ENABLED=1). Text only; no behaviour changes.

- bd versions help: only beads created while recording is on are versioned;
  a bead that already existed is legacy and editing it records nothing; no
  backfill. (Was: "a bead edited yesterday shows nothing until it is
  edited again".)
- bd versions empty listing: drops "yet" and says why the list is empty -- a
  bead created while recording is on always has its create version, so an
  empty list means the bead predates recording (or was made by a writer
  that was not recording), or is no-history or a wisp. The line still
  starts "No versions recorded for <id>", which the switch round-trip test
  pins.
- bd versions with recording off: only beads created after it is turned on
  are versioned.
- bd config set versioned-history.enabled true refusal: Jim's scan stays as
  conservative as he made it -- it cannot see participation, and a legacy
  row can still be minted create-shaped if it re-enters the issues plane --
  but the text now says a listed issue's writes are refused only if it
  participates (created while history was on, or entered the issues plane
  while it was on), and that legacy issues are listed because the check
  cannot tell. The closing line says the same of a value a non-recording
  writer adds later.
- docs/reference/configuration.md: the section opener says every accepted
  change to an issue created while history is on is snapshotted, and that a
  pre-existing issue is legacy; the "participates" parenthetical drops "or
  written" (a write never stamps participation; only a create-shaped mint
  does) and names entering the issues plane, matching the refusal text.

CHANGELOG already says "if it participates in history" and is unchanged.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(versions): keep updated_at across update-shaped version mints

The update-shaped mint ended with UPDATE issues SET current_revision = ?
WHERE id = ?. current_revision always changes there, so the column's
ON UPDATE CURRENT_TIMESTAMP clause fired: with versioned history on, every
label, dependency or import write moved issues.updated_at to the session's
wall clock (local time, read back as UTC). An import with
RejectStaleUpserts then stored the wall clock instead of the source's
updated_at, and the source's next genuine edit was rejected as stale. The
statement now assigns updated_at to itself, the rule #4298, blocked_state.go's
mark/unmark templates and the create-shaped mint statements already follow,
so history on leaves updated_at exactly where history off does. It is the
one statement every production update-shaped mint ends with.

Tests:
- TestEmbeddedMintLeavesUpdatedAtWhereHistoryOffDoes (embeddeddolt) ages a
  bead, adds and removes a label and a dependency, and runs two
  RejectStaleUpserts imports, with history off first as the control. With
  the fix reverted, history on fails all six arms (updated_at reads the
  wall clock, and the later source edit is rejected as stale); history off
  passes either way.
- RunParticipationGenerationFlagOffSkipsUpdateOnParticipatingRecord, wired
  on the dolt, embeddeddolt, uow and http legs: a record created with the
  flag on and updated with it off mints nothing and keeps its
  current_revision. Every other flag-off case uses a legacy record, which
  the fence stops first, so with RecordVersionInTx's gate removed this is
  the only case that fails, on all four legs. That gate is the single entry
  for every production update-shaped mint, so the one update arm covers
  label and close writes too.
- The sqlmock pin of the statement (version_history_preenable_scan_test.go)
  and the journal-completeness exemption comment follow the new SQL.
- The createbatchequiv issues_updated_at goldens of small, depadd,
  import458 and import458-reject-stale are re-recorded. They pinned the
  wall-clock bump, so each row minted a second time (eq-n2; eq-db1 and
  eq-dl; eq-b3 and eq-b250) had dropped out of the compared set; CI's
  embedded and server legs both printed the new digests. Recorded on
  embedded Dolt, the fix-reverted tree reproduces every committed golden
  byte for byte, HEAD moves only these four digests, and its rows equal
  the history-off rows in every scenario. GoldenDirEnv's comment lists it
  as the goldens' third deliberate change.
- The new embedded test has its line in the storage shard manifest
  (gen_embedded_storage_shard_manifest.py 40 --weights=duration --write),
  so TestStorageEmbeddedShardManifestGeneratorNotStale stays green. It sits
  after TestEmbeddedEveryAcceptedLifecycleMutationMintsOneVersion rather
  than at the end of the file, where #7646 appends its own test, so the two
  PRs still merge without a conflict in that file.

Docs:
- CHANGELOG: the feature's two entries under ### Fixed described fixes to a
  switch no released bd has. One ### Added entry replaces them, covering
  bd versions, the versioned-history.enabled switch and its per-store
  semantics, the pre-enable check, the single-writer caveat, migration 0071
  and the bd version <arg> refusal.
- The bd versions help, its recording-off refusal and empty-listing note,
  and the opening paragraph of the configuration doc's Versioned Issue
  History section now state the rule the pre-enable refusal prints: a bead
  participates if it was created, or entered the issues plane (a wisp
  promoted or made persistent), while recording was on.

bd version: the "did you mean bd versions" refusal now runs after the
command's metrics event is created, like the other in-RunE argument
refusals, so a mistyped bd version <id> is counted as a version invocation
instead of going uncounted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Julian Knutsen

---------

Co-authored-by: Jim Wordelman <mayor@quad341.uk>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-authored-by: Julian Knutsen <julianknutsen@users.noreply.github.com>
Co-authored-by: Eddie the Engineer <338826946+gascity-eddie[bot]@users.noreply.github.com>
2026-10-18 17:28:16 +00:00
323 changed files with 41054 additions and 950 deletions

View file

@ -201,7 +201,8 @@ document what the pinned release does, never main-only features. See
## 9. Verify before you call it done
Run the gates in [references/verification.md](references/verification.md).
The short list: `go test ./test/docsync` (nav↔file sync + link conventions),
The short list: `bazel test //test/docsync:docsync_test --config=ci`
(nav↔file sync + link conventions),
`./scripts/generate-cli-docs.sh --check` (generated docs fresh),
`./scripts/check-doc-freshness.sh` (Last reviewed markers), and a live
preview with `make docs-dev` (or `./mint.sh dev`) at `localhost:3000`.

View file

@ -39,8 +39,9 @@ don't measure that work by the word delta.
*not* simplifying — it buries the real change in the diff.
4. **Loss-check** (below).
5. **Fact-check** (below).
6. **Gates:** `go test ./test/docsync`, every fence parses, no body H1, no
HTML comments (MDX), preview with `make docs-dev`.
6. **Gates:** `bazel test //test/docsync:docsync_test --config=ci`, every
fence parses, no body H1, no HTML comments (MDX), preview with
`make docs-dev`.
7. **Preview, then commit on approval** — one page or section per batch, so
the reviewer can steer before a cut compounds across the section.

View file

@ -8,7 +8,7 @@ Run these before considering docs work complete. Ordered cheapest-first.
# 1. Docs sync: docs.json nav <-> file consistency, link conventions
# (root-relative extensionless in docs/, exact paths in engdocs/ and
# curated root files), orphan detection (only CLI_REFERENCE.md is exempt).
go test ./test/docsync
bazel test //test/docsync:docsync_test --config=ci
# 2. Generated CLI docs freshness: regenerates from the live command tree
# and diffs docs/CLI_REFERENCE.md, docs/cli-reference/, and the CLI

View file

@ -11,7 +11,7 @@
# t.Parallel) add up, parallel ones share -test.parallel=4.
# Regenerate with scripts/ci/gen_embedded_cmd_shard_manifest.py 100
# --weights=duration --write after adding, splitting or removing
# TestEmbedded* functions in cmd/bd/*_embedded_test.go. --write is
# TestEmbedded* functions in cmd/bd/*_test.go. --write is
# incremental: it keeps every already-assigned test on its current shard
# and only places newly-discovered names, onto whichever shard is
# currently lightest, so two unrelated PRs that each add one test do not
@ -59,108 +59,206 @@
100 17 TestEmbeddedReopen
100 18 TestEmbeddedLabelPropagateRename
100 18 TestEmbeddedPrune_protectsBeadCitedByCustomStatusBead
100 19 TestEmbeddedLabelConcurrent
100 19 TestEmbeddedNewDoltStore_StrictReadOnlyRefusesWritesOnFreshDatabase
100 20 TestEmbeddedInitRoleRoutingRetainedFork
100 20 TestEmbeddedMigrateSchema_IdentityMismatchRefusesBeforeApplying
100 21 TestEmbeddedMaxRowsReady
100 21 TestEmbeddedMigratePersonal_movesIssues
100 22 TestEmbeddedCount
100 22 TestEmbeddedIfRevisionCloseReplaysMoleculeAutoClose
100 23 TestEmbeddedCountConcurrent
100 23 TestEmbeddedExportExcludeOwner_flag
100 24 TestEmbeddedEventsTailFollowReportsTruncationOnTheStream
100 24 TestEmbeddedUndeferConcurrent
100 24 TestEmbeddedWispGCProtectsActiveWisps
100 25 TestEmbeddedDoltRemoteAdd_LocalOnly_FiresBeforeGuard
100 25 TestEmbeddedMaxRowsListBasic
100 25 TestEmbeddedRemovedBackendHealRejectionPerBackend
100 26 TestEmbeddedDoltRemoteAdd_JSON_AllowGitOrigin_WarningOnStderr
100 26 TestEmbeddedExternalMutationPolicy
100 26 TestEmbeddedPersistentPreRunLogsAndSkipsIdentityCheckForFreshEmbeddedWorkspace
100 27 TestEmbeddedDoltRemoteAdd_GitOriginCollision_RefusalMessageCopy
100 27 TestEmbeddedNewDoltStoreFromConfig_DottedDBName
100 27 TestEmbeddedShipConcurrent
100 28 TestEmbeddedDoltLocalOnly_RemoteAdd_RefusesExitOne
100 28 TestEmbeddedHistoryConcurrent
100 28 TestEmbeddedImportChunkedRealStoreResumeConverges
100 29 TestEmbeddedDoltLocalOnly_RemoteAdd_ErrorOnStderr
100 29 TestEmbeddedEpicCloseEligibleReasonFlag
100 29 TestEmbeddedImportChunkedNoReadyWindowWithReadinessEdgeIntoCycle
100 30 TestEmbeddedCloseGuardsAndEpics
100 30 TestEmbeddedDoltLocalOnly_Push_ExitsZeroWithMessage
100 30 TestEmbeddedImportChunkedCrossBucketBlocksEdgesResumeBackfills
100 31 TestEmbeddedDoltLocalOnly_ConfigRoundTrip
100 31 TestEmbeddedIfRevisionCloseWarnsOnForcedOpenChildren
100 31 TestEmbeddedInitSelectedExcludeRoutingForkInvalidQuiet
100 32 TestEmbeddedDoctorUnsupportedJSON
100 32 TestEmbeddedIfRevisionAdvertisedOnFourVerbs
100 32 TestEmbeddedListSearchAndOutputFormats
100 33 TestEmbeddedBootstrapJSONLAndGitOrigin
100 33 TestEmbeddedDeleteJournalsTheRequestingActor
100 33 TestEmbeddedExportExcludeOwner_verbose
100 34 TestEmbeddedCopyIssueRelations_preservesCommentWithTimestamp
100 34 TestEmbeddedEventsTailReportsTruncationToTheCLI
100 34 TestEmbeddedUnclaimBatchAndRefusals
100 34 TestEmbeddedWispGCPurgeClosedDoesNotCascadeIntoLiveSteps
100 35 TestEmbeddedAutoPruneRespectsBdConfigSet
100 35 TestEmbeddedEventsReadNoticesADisabledJournal
100 35 TestEmbeddedGateCreateBeadRename
100 35 TestEmbeddedVersionedHistoryEnvIsProcessWideAndOnlyTurnsRecordingOn
100 36 TestEmbeddedAutoPruneLeavesAnUnboundedJournalAlone
100 36 TestEmbeddedDoltRemoteResetData_UnknownRemote
100 36 TestEmbeddedGateConcurrent
100 36 TestEmbeddedUnclaimIfAssigneeCLIDifferentSpelling
100 37 TestEmbeddedAutoPruneBoundsTheJournalAfterAMutatingCommand
100 37 TestEmbeddedDoltRemoteResetData_CloudRemoteRefused
100 37 TestEmbeddedMaxRowsDepTreeAndDuplicates
100 37 TestEmbeddedSpawnMolecule_SubstitutesTemplatedStepFields
100 38 TestEmbeddedGraphConcurrent
100 38 TestEmbeddedRoutedCreateJournalsIntoTheTargetWorkspace
100 38 TestEmbeddedUnclaimIfAssigneeFlagValidation
100 39 TestEmbeddedIfRevisionRejectsLabelAndParentEdits
100 39 TestEmbeddedMaxRowsGraph
100 39 TestEmbeddedNewDoltStoreFromConfig_NoMetadata
100 40 TestEmbeddedIfRevisionOutranksReassignFenceCLI
100 40 TestEmbeddedNewDoltStoreFromConfig_HyphenatedDBName
100 40 TestEmbeddedUpdateLifecycleClaimParentCommit
100 41 TestEmbeddedDuplicateConcurrent
100 41 TestEmbeddedVersionedHistoryFollowsTheStoreItWritesInto
100 42 TestEmbeddedInitAForkAutoContributor
100 42 TestEmbeddedUpdateIfGuardsFlagValidation
100 43 TestEmbeddedIfRevisionMultiIDRejected
100 43 TestEmbeddedInitExplicitBeadsDirIsAuthoritative
100 44 TestEmbeddedIfRevisionComposesWithIfAssigneeIfStatus
100 44 TestEmbeddedStaleConcurrent
100 45 TestEmbeddedGraph
100 45 TestEmbeddedUpdateIfGuardsCLI
100 46 TestEmbeddedCloseAlreadyClosedClaimNextAndMolecule
100 46 TestEmbeddedIfRevisionMatchAndMismatch
100 47 TestEmbeddedListSearchAndOutputSearchAndSort
100 47 TestEmbeddedRevisionRemintMatrix
100 48 TestEmbeddedDeferConcurrent
100 48 TestEmbeddedReassignFenceCLI
100 49 TestEmbeddedBackupRestoreStrictReadonly
100 49 TestEmbeddedInitAPushConsentAndRemoteBootstrap
100 49 TestEmbeddedMigratePersonal_abortOnNoConfirm
100 50 TestEmbeddedDiffConcurrent
100 50 TestEmbeddedDoltRemoteAdd_AllowGitOrigin_WarningOnStderr
100 50 TestEmbeddedImportChunkedWaitsForChildImportedLaterStaysBlocked
100 50 TestEmbeddedVersionOutputShape
100 51 TestEmbeddedDoltRemoteAdd_AllowGitOrigin_Exits0
100 51 TestEmbeddedHistoryAndShowAsOfReadDoltCommits
100 51 TestEmbeddedImportChunkedStaleRejectedRowKeepsDeferredDepsOut
100 51 TestEmbeddedInitGitBootstrapRoutingFreshQuiet
100 52 TestEmbeddedConfigSetOtherKeysSkipTheVersionedHistoryScan
100 52 TestEmbeddedDoltLocalOnly_Push_LocalStoreCopy
100 52 TestEmbeddedImportChunkedNoReadyWindowAtAnyFreezePoint
100 52 TestEmbeddedSwarmConcurrent
100 53 TestEmbeddedDoltLocalOnly_Push_JSON_DisabledStatus
100 53 TestEmbeddedIfRevisionOrdinaryCAS
100 53 TestEmbeddedImportChunkedMixedRegularWispCrossBucketEdgesWired
100 53 TestEmbeddedInitSelectedExcludeRoutingStealthDecoyQuiet
100 54 TestEmbeddedDiscoveryPinsEnvFileReadonly
100 54 TestEmbeddedFormatJSONAliasMatchesJSON
100 54 TestEmbeddedGraphModeDependencyWorkspaceUnaffected
100 54 TestEmbeddedInitAgentArtifactsGolden
100 54 TestEmbeddedSearchConcurrent
100 54 TestEmbeddedShowAsOfFailureExitCodes
100 55 TestEmbeddedDoltLocalOnly_Pull_JSON_DisabledStatus
100 55 TestEmbeddedImportChunkedConcurrentUpdateKeepsDeferredDeps
100 55 TestEmbeddedUndefer
100 55 TestEmbeddedVersionedHistorySwitchScansEveryRowNotOnePage
100 56 TestEmbeddedDepNoCycleCheck
100 56 TestEmbeddedDoltLocalOnly_Pull_ExitsZeroWithMessage
100 56 TestEmbeddedImportChunkedConcurrentUpdateKeepsBlockingDeps
100 56 TestEmbeddedVersionedHistorySwitchRoundTrip
100 57 TestEmbeddedDoltLocalOnly_DoltStatus_ShowsDisabled
100 57 TestEmbeddedIfRevisionDeletePreflightGoneIsPreconditionFailed
100 57 TestEmbeddedQueryConcurrent
100 57 TestEmbeddedVersionedHistorySwitchRefusesUnversionableMetadata
100 58 TestEmbeddedDepAAddRejectionsAndBulk
100 58 TestEmbeddedDoctorUnsupportedProse
100 58 TestEmbeddedIfRevisionCascadeDelete
100 58 TestEmbeddedVersionedHistorySwitchRefusesAnUnrecordableGateTimeout
100 59 TestEmbeddedDeferAutoWake
100 59 TestEmbeddedDoctorSupportedChecks
100 59 TestEmbeddedIdentityGateRendersSchemaSkewFromForwardDriftedWorkspace
100 59 TestEmbeddedVersionedHistorySetManyRefusesUnversionableMetadata
100 60 TestEmbeddedCommentsCLI
100 60 TestEmbeddedCorruptMetadataFailsLoudUntilRestored
100 60 TestEmbeddedExportExcludeOwner_config
100 60 TestEmbeddedRoutedWriteMissDoesNotCreateTargetDatabase
100 60 TestEmbeddedWispGCPurgeClosedStillPurgesFullyClosedMolecules
100 61 TestEmbeddedBootstrapCloneFailureScrubsCredentials
100 61 TestEmbeddedContributorRoutedWritesCommitInPlanning
100 61 TestEmbeddedEventsPruneHonorsRetainRowsFloorFromConfig
100 61 TestEmbeddedUpdateRoutedStoreCommitsTargetHead
100 61 TestEmbeddedVersionedHistoryConfigSetWritesTheStoreRow
100 62 TestEmbeddedAutoPruneDoesNotRunForReadOnlyCommands
100 62 TestEmbeddedDoltRemoteResetData_GitBacked
100 62 TestEmbeddedGateCheckSkipsTemplateGates
100 62 TestEmbeddedReadyBlockersAndLabels
100 62 TestEmbeddedUnclaimIfAssigneeCLI
100 63 TestEmbeddedDepAndLinkBatchAutoCommitDoesNotAdvanceHead
100 63 TestEmbeddedGateCheckLimitCountsOnlyLiveGates
100 63 TestEmbeddedIfRevisionDeletePreflightGoneParentIsPreconditionFailed
100 63 TestEmbeddedListPageEdges
100 64 TestEmbeddedAutoExportExcludeOwner_config
100 64 TestEmbeddedDoltRemoteAdd_NoGitOrigin_ProceedsNormally
100 64 TestEmbeddedGateWaiterCheckLifecycle
100 64 TestEmbeddedPromoteMovesAWispParent
100 64 TestEmbeddedSpawnMolecule_PreservesStepLabels
100 65 TestEmbeddedIfRevisionPreflightGoneIsPreconditionFailedOnEveryVerb
100 65 TestEmbeddedRemovedBackendHealRoundTrip
100 65 TestEmbeddedSupersede
100 66 TestEmbeddedCloseBasicIsolatedStores
@ -225,6 +323,7 @@
100 71 TestEmbeddedCloseJSONReportsMoleculeAutoClose
100 71 TestEmbeddedInitRoleRoutingExplicitDefault
100 71 TestEmbeddedPrimeChangeDirRedirectNoticeFollowsTarget
100 71 TestEmbeddedRoutedCreateHonorsTheEnvOverrideOverTheTargetsConfig
100 71 TestEmbeddedSearchRoutesAgree
100 72 TestEmbeddedContributorCreateMultiple
@ -335,8 +434,10 @@
100 83 TestEmbeddedPurgeFiltered
100 83 TestEmbeddedReadyConcurrent
100 84 TestEmbeddedDoltRemoteAdd_GitOriginCollision_Exits1
100 84 TestEmbeddedInitGitBootstrapRoutingDecoyInvalid
100 84 TestEmbeddedInitSelectedExcludeRoutingStealthInvalid
100 84 TestEmbeddedMigratePersonal_preservesComments
100 85 TestEmbeddedBootstrapExistingDryRunInit
100 85 TestEmbeddedChildrenBasicAndEmpty
@ -345,8 +446,10 @@
100 85 TestEmbeddedIfRevisionReopenGuardDirect
100 85 TestEmbeddedInitArtifactRouting
100 86 TestEmbeddedDoltRemoteAdd_DifferentURL_ProceedsNormally
100 86 TestEmbeddedExplicitHierarchicalParentEdges
100 86 TestEmbeddedInitHooksRouting
100 86 TestEmbeddedMigratePersonal_noopWhenEmpty
100 87 TestEmbeddedCreateRepoProxiedTargetError
100 87 TestEmbeddedGateInheritsDownParentChain

View file

@ -186,6 +186,7 @@
40 5 TestEmbeddedClaimerRefusesIncompleteRequestsAndAnAbsentIDWithoutTouchingState
40 5 TestEmbeddedIssueOperationsCloseAndReopenAWisp
40 5 TestEmbeddedReaderListKeysetPositionResumesTheCreatedDescIDAscOrder
40 5 TestRecordVersionKeepsSubSecondChangeAt
40 5 TestWithPeerAuth
40 6 TestCreateBatchFastPathsMatchPerRowApplyWaitsFor_Embedded
@ -195,6 +196,7 @@
40 6 TestEmbeddedRelationsAnswersAWispTargetInTheOutDirection
40 6 TestPromoteStillWorksWithCollisionGuard
40 6 TestSearchWithMissingWispPlaneTables
40 6 TestVersionedHistoryKeepsNumbersTheStoreDistinguishesApart
40 7 TestConcurrencyMultiProcess
40 7 TestEmbeddedBatchCloserRecordsOneHistoryEntryForWhatLanded
@ -203,17 +205,20 @@
40 7 TestEmbeddedIssueOperationsUpdateMetadataReplaceClearsAndValidates
40 7 TestEmbeddedLenientOpenWarning_DataBehind
40 7 TestEmbeddedRelationsLeavesTheCallersRequestAlone
40 7 TestLoseVersionLeavesTheEpochTablesCommitted
40 7 TestMergeAndSettleWithStrategy_ResolvesDeclinedConflict
40 8 TestDeleterContract
40 8 TestEmbeddedDependencyEditorRoutesWispSourcedRemovalToTheWispPlane
40 8 TestEmbeddedMergeAndSettleDirtyWorkingSetSurvivesRefusedMerge
40 8 TestEmbeddedMintLeavesUpdatedAtWhereHistoryOffDoes
40 8 TestEmbeddedReaderGetBriefDepsProjectsTheDependencyRows
40 8 TestEmbeddedRelationsOrdersNeighborsFromBothPlanesTogether
40 8 TestEmbeddedReopenIssueCategorySemantics
40 8 TestGetIssueCommentsPageEmbedded
40 8 TestListWisps
40 9 TestBumpEpochCarryingNeitherCarriesNorServesARowFromAFutureEpoch
40 9 TestEmbeddedDependencyEditorRefusesCrossPlaneCycle
40 9 TestEmbeddedDependencyEditorSameTypeReAddIsIdempotent
40 9 TestEmbeddedDependencyEditorSnapshotsTheRequest
@ -232,8 +237,10 @@
40 10 TestGraphCounterContract
40 10 TestIgnoredCursorHealRespectsOperatorOverride
40 10 TestRunInTransactionPostCommitStageFailureIsIndeterminate
40 10 TestVersionedHistoryOffMatchesPreStackGolden_Embedded
40 10 TestWithPeerAuth_WarnsWhenStoredPeerSuppressesAmbientPasswordAmbient
40 11 TestABumpUnderOneStoreIDMovesTheEpochSeenThroughEveryStoreID
40 11 TestEmbeddedBatchCreateFirstVersionCarriesCreationTimeEdges
40 11 TestEmbeddedClaimerRefusalMessagesCarryTheirFragments
40 11 TestEmbeddedGuardedUpdateMintsOnceAfterItsPatches
@ -335,6 +342,7 @@
40 19 TestRemoteVerbsPresentStoredPeerCredentials
40 19 TestRenameLabelMintsOneVersionPerTouchedBead
40 20 TestBumpEpochCarryingCarriesOnlyTheLineageHoldingTheNewestRow
40 20 TestCreateIssue
40 20 TestEmbeddedCheckedWrappersRouteTheirPreconditions
40 20 TestEmbeddedIssueOperationsCreateRoutesInfraTypesToWisps
@ -346,6 +354,7 @@
40 20 TestHeartbeatRejectsWispEmbedded
40 20 TestIgnoredCursorHealNeverResurrectsRolledBackVersions
40 21 TestBumpEpochCarryingCarriesTheLiveRowsOfEveryStoreInTheDatabase
40 21 TestCreateRejectsCrossTableIDCollision
40 21 TestEmbeddedBatchCloserItemsAnswerToTheCloseGuards
40 21 TestEmbeddedDependencyEditorAcceptsATypeOutsideTheConstants
@ -369,6 +378,7 @@
40 22 TestLeaseLifecycleEmbedded
40 22 TestPolicyBlockingAnnotatorForeignOpensAreSublinear
40 23 TestAsOfReadContract
40 23 TestEmbeddedBatchCloserBackendFailureReturnsNoOutcomes
40 23 TestEmbeddedBatchCloserClaimNextHydratesWhenSomethingClosed
40 23 TestEmbeddedDependencyEditorAcceptsBlockingAcrossIssueTypes
@ -431,6 +441,7 @@
40 27 TestRemoteGitDataRefOnEngine
40 27 TestSweeperContract
40 28 TestBumpEpochCarryingDoesNotCarryALostLineage
40 28 TestEmbeddedBatchCloserForceBypassesOnlyClosePolicy
40 28 TestEmbeddedBatchCloserSettlesTheDependersOfWhatItClosed
40 28 TestEmbeddedClaimerClaimsAnUnassignedOpenIssueAndAnswersTheBareRow
@ -468,6 +479,7 @@
40 30 TestLegacyTrackedIgnoredCursorUnwedgesPull
40 30 TestUpdateMergeOps_DoltEngine_TwoIssues
40 31 TestBumpEpochCarryingWritesOneCarryRowPerLiveIDNamingTheLineageRoot
40 31 TestDualWriteContract
40 31 TestEmbeddedDependencyEditorAcceptsAForeignRepoTarget
40 31 TestEmbeddedDependencyEditorMaintainsBlockedStateAcrossPlanes
@ -480,6 +492,7 @@
40 31 TestReadyCounterContract
40 31 TestWithPeerAuth_KeyMismatchFailsClosed
40 32 TestCurrentAddressForNeverReseedsAnAbsentStoreEpochRow
40 32 TestEmbeddedClaimerGrantsALiveLeaseOnTheRowItWonAndLeavesARefusedOneAlone
40 32 TestEmbeddedDependencyEditorRefusesAMissingLocalTarget
40 32 TestEmbeddedDirtyTablesGate_BlocksReopenThenWorkingSetReconcileRecovers
@ -500,11 +513,13 @@
40 33 TestEmbeddedRelationsResolvesTheAnchorIDExactly
40 33 TestEmbeddedSyncCommitsConfigBeforeMerge
40 33 TestEventsAutoPruneThrottleSkipsTheSecondPass
40 33 TestFirstMintLeavesTheEpochTablesCommitted
40 33 TestGetDependentRecordsEmbedded
40 33 TestPruneEventsBatchDeletesTheLowestSeqsOnly
40 33 TestTreeWalkerContract
40 34 TestAddLabel
40 34 TestBumpEpochCarryingLeavesTheEpochTablesCommitted
40 34 TestDecryptPassword_KeyMismatchNamesTheLocalKey
40 34 TestEmbeddedBlockedRecheckRecordsUnblockingWrites
40 34 TestEmbeddedDependencyEditorAttributesItsEventsToTheActor
@ -528,6 +543,7 @@
40 35 TestReadyWorkWithMissingDeferredParentTables
40 35 TestReclaimExpiredLeaseSurvivesRestartEmbedded
40 36 TestBumpEpochCarryingFailsAndRollsBackWhenARowAlreadyExistsAtTheNewEpoch
40 36 TestCommenterContract
40 36 TestConcurrentOpenReturnsCached
40 36 TestEmbeddedBatchCloserAllRefusedBatchRecordsNoHistory
@ -550,6 +566,7 @@
40 37 TestEmbeddedMergeAndSettleReportsOperatorConflicts
40 37 TestEmbeddedReaderListBriefDropsTheFreeFormTextAndNothingElse
40 37 TestEmbeddedReaderListNaturalNumericIDSortTrimsAfterTheFetch
40 37 TestEpochWritesReportAnUnpublishedCommitAsIndeterminate
40 37 TestIgnoredCursorHealRespectsOverrideUnderBroaderPattern
40 38 TestCreateIssues

View file

@ -3,7 +3,7 @@
#
# Usage: embedded-test-shard.sh <shard_number> <total_shards>
#
# Discovers all TestEmbedded* top-level functions from cmd/bd/*_embedded_test.go.
# Discovers all TestEmbedded* top-level functions in cmd/bd/*_test.go.
# Tests listed in embedded-cmd-test-shards.txt for the requested shard count use
# that committed assignment; newly-added tests fall back to hash(name) % total.
# Runs the matching subset using the pre-built test binary at
@ -33,8 +33,12 @@ fi
SHARD_INDEX=$(( SHARD_NUMBER - 1 ))
MANIFEST="${BEADS_TEST_SHARD_MANIFEST:-.github/scripts/embedded-cmd-test-shards.txt}"
# Discover all top-level TestEmbedded* functions.
ALL_TESTS=$(grep -rh '^func TestEmbedded' cmd/bd/*_embedded_test.go \
# Discover all top-level TestEmbedded* functions across every cmd/bd test
# file, by name rather than by file glob (as proxied-test-shard.sh does): a
# test gated on BEADS_TEST_EMBEDDED_DOLT runs in this lane or in none, wherever
# it lives. scripts/embedded_lane_coverage_test.go fails on a gated test this
# selection misses.
ALL_TESTS=$(grep -rh '^func TestEmbedded' cmd/bd/*_test.go \
| sed 's/func \(TestEmbedded[A-Za-z0-9_]*\).*/\1/' \
| sort -u)

View file

@ -69,6 +69,7 @@
34 6 TestProxiedServerServeReadsTheJournalItJustWrote
34 6 TestProxiedServerSwarm
34 6 TestProxiedServerUpdate2B
34 6 TestProxiedServerVersionedHistorySwitchRefusesAnUnrecordableGateTimeout
34 6 TestProxiedServerWispList
34 7 TestProxiedServerCloseConcurrent
@ -156,6 +157,7 @@
34 17 TestProxiedServerPrime
34 17 TestProxiedServerSQLDatabaseFlag
34 17 TestProxiedServerServeModeGate
34 17 TestServerModeServeIgnoresGraphModeDependency
34 18 TestProxiedServerClose3
34 18 TestProxiedServerCount
@ -254,6 +256,7 @@
34 30 TestProxiedServerStatus
34 30 TestProxiedServerTodo
34 30 TestProxiedServerUpdate2
34 30 TestProxiedServerVersionedHistoryServeActivatesTheProviderFromItsOwnRow
34 31 TestProxiedServerCloseBeadGate
34 31 TestProxiedServerComment

View file

@ -1085,7 +1085,7 @@ jobs:
outputs:
result: ${{ steps.result.outputs.result }}
env:
PURE_CMD_BD_TESTS: '^Test(Help|CheckRemoteSafety|FormatDestroyToken|ShouldWireInitRemote|ExtractPrefix|IsNumericID|GetWorktreeGitDir|DriftItemStatuses|RunDriftChecks|IsServerProbablyRunning|CheckHooksDriftNotGitRepo|CheckServerDriftNoBeadsDir|CheckRemoteDriftNoBeadsDir|NocgoFactoriesHonorSharedServer|NocgoNewDoltStoreFromConfig_ErrorSuggestsCorrectFlag|NocgoNewReadOnlyStoreFromConfig_ErrorSuggestsCorrectFlag)'
PURE_CMD_BD_TESTS: '^Test(Help|CheckRemoteSafety|FormatDestroyToken|ShouldWireInitRemote|ExtractPrefix|IsNumericID|GetWorktreeGitDir|DriftItemStatuses|RunDriftChecks|IsServerProbablyRunning|CheckHooksDriftNotGitRepo|CheckServerDriftNoBeadsDir|CheckRemoteDriftNoBeadsDir|NocgoFactoriesHonorSharedServer|NocgoNewDoltStoreFromConfig_ErrorSuggestsCorrectFlag|NocgoNewReadOnlyStoreFromConfig_ErrorSuggestsCorrectFlag|NocgoStoreFactoriesRefuseGraphWorkspace)'
# The only pre-merge run of these boundaries: where it executes
# remotely --config=sole-run fails on a remote cache eviction instead
# of re-running the whole invocation (whose retry could turn a failed

View file

@ -126,9 +126,29 @@ make install # build and install bd to ~/.local/bin (canonical)
certificate `--config=remote-exec`, agent hosts whose `~/.bazelrc` names the
executor neither. Make yours the default with a `build --config=...` line in
the gitignored `.bazelrc.local`, or pass `BAZEL_FLAGS=...` to make.
- `go test` (`./scripts/test.sh`, `make test-go`) is an inner-loop
convenience only. CI does not enforce it, and it skips nogo, gofmt and the
guards; finish with `make test`.
- Agents run tests only with `bazel test`, also while iterating on one
behavior:
```bash
bazel test //cmd/bd:bd_test --config=ci --test_filter='^TestName$' --test_output=all
```
A target also passes when the test never ran (a filter that matches
nothing, a skip, a file the configuration does not compile), so count a run
only when its log shows `--- PASS: TestName` and no `--- SKIP` for the test
or a `TestName/...` subtest: Go prints `--- PASS` for a test whose every
subtest skipped. "Check That the Test Ran" in
[engdocs/TESTING.md](engdocs/TESTING.md) names the tests `--config=ci` does
not run (Dolt-backed, `-short`-gated, integration-tagged, `TestEmbedded*`
and embedded-Dolt, files `BUILD.bazel` does not list) and the way into
each. An unchanged target returns its cached result, which is the same
evidence. Finish with `make test`.
- Agents do not run `go test` (`./scripts/test.sh`, `make test-go`): CI does
not enforce it, it skips nogo, gofmt and the guards, and agent hosts may
refuse it. It stays a convenience for humans working offline. The exception
is regenerating golden files (`make corpus-regen`, `make githooks-regen`,
`BD_UPDATE_GOLDEN=1`), which Bazel cannot do: see "Regenerating Golden
Files" in [engdocs/TESTING.md](engdocs/TESTING.md).
- **Do NOT** use `go build -o bd ./cmd/bd`, `go install ./cmd/bd`, or raw
`go run ./cmd/bd ...`: they bypass the canonical build path, leave stale
binaries, and raw `go run` misses the `gms_pure_go` tag. Use `make install`,

View file

@ -74,6 +74,13 @@ exports_files(
visibility = ["//scripts:__pkg__"],
)
# //scripts:shell_scripts_test: Oracle A's runner, whose EXIT-trap removal of
# its reference worktree oracle_a_script_test.go checks in a fixture repository.
exports_files(
["tests/oracle-a/run-oracle-a.sh"],
visibility = ["//scripts:__pkg__"],
)
# The nested Go modules' go.mod files, which mark where the root module ends:
# //scripts:go_test_sources_test's scan of every _test.go file skips their
# trees, as `go test ./...` does. (go.mod is in no Go partition below: it is
@ -246,6 +253,20 @@ exports_files(
visibility = ["//internal/httpclient/encode:__pkg__"],
)
# --- begin go_srcs (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) ---
filegroup(
name = "go_srcs",
srcs = glob(
["**/*.go"],
allow_empty = True,
exclude = ["bazel-*/**"],
),
visibility = ["//:__subpackages__"],
)
# --- end go_srcs ---
# --- begin repo_files (managed by tools/bazel/go_srcs.py; run `make bazel-sync`) ---
filegroup(
@ -344,6 +365,7 @@ filegroup(
"//internal/httpclient/encode:repo_doc_files",
"//internal/httpclient/wire:repo_doc_files",
"//internal/idgen:repo_doc_files",
"//internal/initprocs:repo_doc_files",
"//internal/jira:repo_doc_files",
"//internal/linear:repo_doc_files",
"//internal/lockfile:repo_doc_files",
@ -383,6 +405,7 @@ filegroup(
"//internal/storage/externaldeps:repo_doc_files",
"//internal/storage/fs:repo_doc_files",
"//internal/storage/git:repo_doc_files",
"//internal/storage/historyoffequiv:repo_doc_files",
"//internal/storage/issueops:repo_doc_files",
"//internal/storage/journalscan:repo_doc_files",
"//internal/storage/kvkeys:repo_doc_files",
@ -413,6 +436,7 @@ filegroup(
"//internal/utils:repo_doc_files",
"//internal/validation:repo_doc_files",
"//internal/versioncheck:repo_doc_files",
"//internal/versionedhistory:repo_doc_files",
"//internal/workapi:repo_doc_files",
"//internal/workapi/storecounter:repo_doc_files",
"//internal/workapi/storequerier:repo_doc_files",
@ -578,6 +602,7 @@ filegroup(
"//internal/httpclient/encode:repo_go_srcs",
"//internal/httpclient/wire:repo_go_srcs",
"//internal/idgen:repo_go_srcs",
"//internal/initprocs:repo_go_srcs",
"//internal/jira:repo_go_srcs",
"//internal/linear:repo_go_srcs",
"//internal/lockfile:repo_go_srcs",
@ -617,6 +642,7 @@ filegroup(
"//internal/storage/externaldeps:repo_go_srcs",
"//internal/storage/fs:repo_go_srcs",
"//internal/storage/git:repo_go_srcs",
"//internal/storage/historyoffequiv:repo_go_srcs",
"//internal/storage/issueops:repo_go_srcs",
"//internal/storage/journalscan:repo_go_srcs",
"//internal/storage/kvkeys:repo_go_srcs",
@ -647,6 +673,7 @@ filegroup(
"//internal/utils:repo_go_srcs",
"//internal/validation:repo_go_srcs",
"//internal/versioncheck:repo_go_srcs",
"//internal/versionedhistory:repo_go_srcs",
"//internal/workapi:repo_go_srcs",
"//internal/workapi/storecounter:repo_go_srcs",
"//internal/workapi/storequerier:repo_go_srcs",
@ -797,6 +824,7 @@ filegroup(
"//internal/httpclient/encode:repo_go_test_srcs",
"//internal/httpclient/wire:repo_go_test_srcs",
"//internal/idgen:repo_go_test_srcs",
"//internal/initprocs:repo_go_test_srcs",
"//internal/jira:repo_go_test_srcs",
"//internal/linear:repo_go_test_srcs",
"//internal/lockfile:repo_go_test_srcs",
@ -836,6 +864,7 @@ filegroup(
"//internal/storage/externaldeps:repo_go_test_srcs",
"//internal/storage/fs:repo_go_test_srcs",
"//internal/storage/git:repo_go_test_srcs",
"//internal/storage/historyoffequiv:repo_go_test_srcs",
"//internal/storage/issueops:repo_go_test_srcs",
"//internal/storage/journalscan:repo_go_test_srcs",
"//internal/storage/kvkeys:repo_go_test_srcs",
@ -866,6 +895,7 @@ filegroup(
"//internal/utils:repo_go_test_srcs",
"//internal/validation:repo_go_test_srcs",
"//internal/versioncheck:repo_go_test_srcs",
"//internal/versionedhistory:repo_go_test_srcs",
"//internal/workapi:repo_go_test_srcs",
"//internal/workapi/storecounter:repo_go_test_srcs",
"//internal/workapi/storequerier:repo_go_test_srcs",
@ -1025,6 +1055,7 @@ filegroup(
"//internal/httpclient/encode:repo_other_files",
"//internal/httpclient/wire:repo_other_files",
"//internal/idgen:repo_other_files",
"//internal/initprocs:repo_other_files",
"//internal/jira:repo_other_files",
"//internal/linear:repo_other_files",
"//internal/lockfile:repo_other_files",
@ -1064,6 +1095,7 @@ filegroup(
"//internal/storage/externaldeps:repo_other_files",
"//internal/storage/fs:repo_other_files",
"//internal/storage/git:repo_other_files",
"//internal/storage/historyoffequiv:repo_other_files",
"//internal/storage/issueops:repo_other_files",
"//internal/storage/journalscan:repo_other_files",
"//internal/storage/kvkeys:repo_other_files",
@ -1094,6 +1126,7 @@ filegroup(
"//internal/utils:repo_other_files",
"//internal/validation:repo_other_files",
"//internal/versioncheck:repo_other_files",
"//internal/versionedhistory:repo_other_files",
"//internal/workapi:repo_other_files",
"//internal/workapi/storecounter:repo_other_files",
"//internal/workapi/storequerier:repo_other_files",

View file

@ -9,6 +9,41 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
- `bd versions <id>` lists the versions recorded for a bead, and
`versioned-history.enabled` turns recording on. While it is on, every
accepted change to a bead created while it is on, or that enters the issues
plane while it is on (a wisp promoted or made persistent), stores a
snapshot of it as a row of `issue_versions` in the same transaction. It is
off by default and nothing is backfilled: a bead already on the issues
plane when it is turned on is legacy, and editing it records nothing. A
recorded write leaves `updated_at` where an unrecorded one would, so
`bd import`'s stale check sees the same timestamps either way.
`bd versions --json` answers `{"versions": [...], "recording": bool}`; the
command still lists what was recorded after recording is turned off, and
proxied-server and HTTP workspaces refuse it. The setting is a row of each
store's `config` table (`bd config set versioned-history.enabled true`),
and every store reads its own when it is opened: a write routed into
another workspace (a prefix-routed `bd update` or `bd close`,
`bd create --repo`) follows the target store's row, a proxied-server
provider reads it when it is constructed, and a long-lived `bd serve`
keeps the value it read until it restarts.
`BD_VERSIONED_HISTORY_ENABLED=1` (or a `config.yaml` value) turns
recording on for every store the process opens, and never turns it off.
The row replicates on `bd dolt push`/`pull`, and recording is single-writer
only: two clones recording at once can mint the same revision and fail the
pull, and a write from a writer that is not recording is folded into the
next recorded version under that version's actor, so keep recording on for
every writer of a store or off for all of them. Turning it on with
`bd config set` first checks every issue the store would version and
refuses, writing nothing, while any holds a number outside the I-JSON
exact-integer range (magnitude above 2^53-1, however it is spelled) in its
metadata or in a gate's timeout (held as nanoseconds, so about 104.25
days), and prints the count, the ids, the field and the fix. There is no
override, and the check runs once; after that, a recorded write that would
hold such a number fails atomically. Migration 0071 adds a nullable
`removed_restriction` column to `issue_versions`. `bd version` now refuses
an argument and suggests `bd versions <arg>`, instead of printing bd's
build for a mistyped `bd version bd-123`.
- `bd blocked --flags` prints the blocked flag for each id read from stdin
(one per line; blank lines and repeats ignored), with `--json` as
`[{"id","is_blocked"}]` in the order the ids were given, omitting an id that
@ -464,6 +499,24 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Changed
- Over an HTTP workspace, `bd ready --json` without `BD_JSON_ENVELOPE` no
longer sends `GET /v0/beads/ready:count` after a page the limit cut short:
the total only went into the stderr hint. It lists one row past the limit
instead, and the hint says more issues matched without saying how many
(the wording the proxied-server route already uses). A local store, and the
envelope's `pagination.total`, keep the total.
- `bd` initializes its packages with `GOMAXPROCS` capped at 4 and hands it
back before `main` runs anything, so the garbage collections package
initialization triggers do not stop the world across every CPU of a large
host. On a 192-CPU machine this takes about 17 ms off every bd process. An
explicit `GOMAXPROCS` is restored as set.
- Over an HTTP workspace, `bd ready` no longer fetches `GET /v0/beads/context`
before its listing in every process only to learn whether the server
enforces the external-dependency policy. The answer is kept for 5 minutes
per server URL and pinned project under the user cache directory
(`BEADS_HTTP_POLICY_CACHE_TTL`, a duration, a number of seconds, or `off`),
and a handshake the process already holds still wins. Claims and closes
always ask the server.
- `bd serve` normalizes every RFC 3339 time bound on the issue listing and
count (`created_*`, `updated_*`, `closed_*`, and the new `defer_*` and
`due_*`) to UTC before it reaches storage. A bound carrying an offset
@ -728,6 +781,175 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
- An HTTP workspace whose server cannot be reached now says which step
failed. A connect that is refused names the address and says nothing is
listening; one that times out (a filtered port, a down host) names the
address that never answered and how long it waited; a host name that does
not resolve is named as such. The error was the transport's
`Get "https://…/v0/beads/context": dial tcp …: i/o timeout`, which named the
request rather than the address.
- **`bd link` works over a connected HTTP workspace.** It wrote through the
store's raw `AddDependencyWithOptions`, which the HTTP client refuses, so
every `bd link` failed there with `operation "AddDependencyWithOptions" not
supported by the http backend`, whatever the type. It now writes through
the `DependencyEditor` role, the route `bd dep add` takes, on the direct
and HTTP routes alike (the proxied-server route is unchanged). Over HTTP
that is one `dependencies:add` request, so `bd link` keeps accepting any
non-empty type of at most 32 characters (`owned-by`, `ships-in`, ...).
An empty or over-long type is still refused before anything is written,
and an edge that already exists with another type still reports the typed
conflict. On a Dolt store the history commit is now the role's, like
`bd dep add`'s: `bd: dep add <from> <to>` in place of
`dependency: add <type> <from> -> <to>`.
- **`bd query` reports an uppercase duration unit as an unparseable time, not
a negated internal error.** `created>30M` failed with
`not a compact duration: "-30M"`, naming a value nobody typed; it now fails
with `cannot parse time expression: "30M"`. A signed spelling
(`created>+30M`) stops at the parser, as `created>+30x` already did, so
quote one to match it as a literal (`label="+30M"`). Units remain lowercase
(`30min`, `6h`, `7d`, `2w`, `3m`, `1y`); help and docs already say so.
- **Strict `--readonly` no longer creates workspace gate files.** A
`bd --readonly` command took its shared workspace gates with
create-if-missing, so on a workspace no bd command had gated yet it left
`<project>/.beads.gate.lock` and the physical-root gate file
(`.beads/embeddeddolt.gate.lock` or `.beads/dolt.gate.lock`) behind, although
strict readonly promises not to mutate the workspace. It now opens an
existing gate file read-only and holds it shared as before, so a maintenance
operation still sees it and a running one still makes it wait; when no gate
file exists it holds nothing. Every other command still creates the files.
- **Strict `--readonly` refuses `bd backup init`, `backup sync`,
`backup remove`, `backup restore` and `bd import`.** None of them checked
readonly mode. On a server-mode store they ran to completion under
`--readonly`: `backup init` and `backup remove` rewrote or emptied the
server's backup registry, `backup sync` wrote the backup destination,
`backup restore --force` replaced the store, and `import` wrote issues. On
an embedded store they failed with the storage layer's `store is read-only`
error instead, after `backup sync` had left `.beads/backup.lock` behind and
`backup restore` had left workspace-gate holder files. They now exit 1 with
the standard `Error: operation '<op>' is not allowed in read-only mode`,
and a restore is refused before it takes the exclusive workspace gate.
`bd import --dry-run` is refused too, as `bd create --dry-run` already is
and as a migration freeze already refuses it. `bd backup status` still runs
under `--readonly`.
- **`bd init --server --external` no longer starts a Dolt server of its own.**
Init builds its store config by hand and turned auto-start on for every
server init, so an `--external` init that named no port launched a
repo-local `dolt sql-server`, although `--external` says the server is
managed outside bd. `--external` now turns auto-start off. When the
external server cannot be reached, init gives one message on every route
(host and port, socket, shared server, auto-start pinned off): it names the
endpoint it dialed, says that bd did not start a server, and no longer
advises `bd dolt start`. With no port named at all, it asks for one
(`--server-port` or `BEADS_DOLT_SERVER_PORT`) instead of offering a default.
- **A failed `bd init --server` can be retried.** A first attempt that could
not reach its server left an empty `.beads/dolt` and nothing on disk that
records the server choice, so the legacy-upgrade guard refused every retry
as a "legacy Dolt workspace" and no bd command could repair it. When init
itself selects server mode, the guard now admits exactly that root: empty,
with no `.local_version` witness. A pre-1.0 witness, or a `.beads/dolt` that
holds anything, is still refused, and commands other than `bd init` are
decided as before.
- **A graph-mode workspace is refused instead of opened as an Issue store.**
Graph-preview builds mark their workspaces with `"graph_mode": "link"` and
`graph_*` binding fields in `metadata.json`, beside an ordinary Dolt
backend. bd opened such a workspace as an Issue store and ran Issue schema
initialization against the graph database, and every `metadata.json` rewrite
(including the `config.json` to `metadata.json` migration) dropped the
marker and the binding. Now any `graph_mode` other than `dependency`,
including a value bd does not recognize, makes every command that runs in
the workspace or names it with `--db` or `BEADS_DB` (`bd init`, `bd doctor`
and `bd bootstrap` included), and `bd create --repo` aimed at it, refuse it
before touching anything. The refusal names the format and exits with code
16, so installed beads git hooks refuse commits and pushes there too.
Commands that reach such a workspace only through a route from another
one, such as a routed `bd show`, fail without touching it, but not with
code 16. Store-less commands such as `bd version` and `bd help` still run.
A `metadata.json` rewrite keeps `graph_mode` and the `graph_*` fields
graph-preview builds write, and like those builds it omits a zero
`graph_schema_version` and a false `graph_ready`.
- **A graph workspace without `graph_mode` in its metadata is refused too.**
Graph-preview builds write a `.beads/graph-preview-format` marker before
`metadata.json`. bd ignored it. When an older bd had rewritten
`metadata.json` without `graph_mode`, bd opened the graph database by its
recorded name and ran Issue schema initialization against it; when
`metadata.json` was never written or was lost, bd fell back to the default
database name and created an Issue database inside the graph workspace, and
`bd init` initialized an Issue workspace there. A `.beads` holding that
marker, whatever it contains and whatever its metadata says (absent,
stripped, unparseable or an explicit `dependency`), is now refused wherever
a `graph_mode` workspace is: commands run in it or naming it with `--db` or
`BEADS_DB`, `bd create --repo` aimed at it, and `bd bootstrap` in a
workspace below it that would take its metadata exit with code 16 and a
hint to restore `metadata.json`, and routed and cross-repository opens fail
without opening its database.
- **The Go library's opens refuse a graph workspace too.**
`beads.OpenBestAvailable`, `OpenBestAvailableWith`, `OpenFromConfig` and
`OpenGated` opened a workspace whose `metadata.json` declares a
`graph_mode` other than `dependency`, or whose `.beads` holds the
`graph-preview-format` marker, as an Issue store and ran Issue schema
migrations into the graph database. They now
return `*beads.UnsupportedWorkspaceFormatError` (match it with `errors.As`)
before opening, creating or changing anything, the same refusal the CLI
exits 16 with.
- **`bd setup claude --remove` no longer leaves a blank-line hole.** Removing
the beads section from `CLAUDE.md` (or, with the other setup recipes, from
`AGENTS.md` or `GEMINI.md`) left the blank lines around it behind, three in
the `CLAUDE.md` `bd init` writes, and setup then re-added the section after
two more, so every remove and re-add grew the file. `--remove` now takes
those blank lines with the section, and setup appends a section after one
blank line, so removing and re-adding it toggles between the same two files.
A re-added section goes at the end of the file.
- **`bd config set` no longer truncates a `config.yaml` that has a line of
64 KiB or more.** Setting an undotted key (such as `actor` or `no-db`)
rewrites the file line by line, and a line of 65,536 bytes or more ended
that read early without an error, so the command reported success and wrote
back only the lines before the long one, plus the key it set. Dotted keys
and `bd config unset` were not affected. Setting an undotted key in such a
file now fails with `bufio.Scanner: token too long`. `bd config set` leaves
the file as it was. `set-many` stops at that key, but it has already written
any `config.yaml` keys listed before it, such as a dotted `sync.remote`.
- **`bd show --as-of` exits 1 when it reads no issue.** A ref the Dolt AS OF
read does not take (an instant, a versioned-history address), a ref that
does not exist, or an issue that did not exist at the ref was reported on
stderr while the command exited 0 with nothing on stdout, even under
`--json`. It now ends the way plain `bd show` does: exit 1, with the JSON
error envelope on stdout under `--json`. A batch that reads at least one of
its ids still exits 0. Both the direct and the proxied-server routes
changed.
- **`bd list --format dot` prints the same graph the same way every time.**
Nodes are declared in id order and edges in source, target and type order.
They used to follow the listing order, which breaks a priority tie by
creation time to the second, so two equal-priority issues swapped places
depending on whether they were created in the same second, and the
proxied-server route did not pin the order of one issue's edges. `--sort`
and `--limit` still choose which issues are listed.
- **`bd init --quiet` no longer prints "Removed SessionStart hook" or "Removed
PreCompact hook"** when the project's `.claude/settings.json` (or the legacy
`.claude/settings.local.json`) still carries the bare `bd prime` hooks an
older bd registered. The hooks are still migrated to the SessionStart
`bd prime --hook-json` hook; the removal lines now go to the installer's own
output, which `--quiet` discards, instead of straight to stdout.
- **A new `AGENTS.md` from `bd init` lists `bd dolt push` in its Quick
Reference only when the workspace has a Dolt remote.** The managed Beads
section already left out its push lines when no Dolt remote is configured or
the workspace is `no-push`, but the Quick Reference above it still showed
`bd dolt push # Push beads data to remote`. It now follows the same rule.
`bd init` still leaves an existing `AGENTS.md` alone outside the managed
section, and writes an `--agents-template` as given.
- **`bd setup claude` no longer rewrites a CLAUDE.md whose beads section is
already current.** A rerun (and `bd init`, which runs it) wrote the same
bytes back as a new file, resetting its mode to 0644 and its mtime, and
reported "Updated existing beads section"; it now leaves the file alone and
reports the section current (the report `bd init` already gives a current
AGENTS.md). `bd setup factory`, `opencode`, `mux` and `gemini` share the
fix. A section whose END marker is missing or comes before BEGIN, which was
also reported as updated while nothing changed, is now reported as an error:
`bd setup factory`, `opencode` and `mux` exit 1 (`mux` before installing its
`.mux` hooks), while `claude` and `gemini` warn and carry on. When CLAUDE.md
is an `@AGENTS.md` stub and it is AGENTS.md that cannot be updated, `claude`
now names AGENTS.md in the warning and keeps the beads block left in the
stub, which it used to delete although AGENTS.md was never updated.
- **Time-bound filters and the keyset cursor compare the same instant on every
engine, whatever zone they are given in.** The storage filter builder binds
every time bound (`created_*`, `updated_*`, `closed_*`, `started_*`,
@ -739,6 +961,27 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
driver sends a `time.Time` as its wall clock with no zone, so a library
caller paging with a cursor in another zone was answered from the wrong
position there (server Dolt was unaffected).
- **`bd setup claude --global` keeps its beads section in `~/.claude/CLAUDE.md`.**
It wrote the section into the current directory's `CLAUDE.md`: run from your
home directory it created `~/CLAUDE.md`, which by default stops Claude Code
reading `AGENTS.md` in the projects below it, and `--remove --global`
stripped the section a project's own install had put in its `CLAUDE.md`
while leaving that project's hooks in place. A global install and removal now
use only the user-level files beside `~/.claude/settings.json`. A new
`~/.claude/CLAUDE.md` holds just the section, rendered the same whichever
project you run from. Claude Code loads that file in every project, so its
section, task-tracking rules included, applies only in repositories that use
beads. With global or plugin hooks `--check` accepts it when the project's
instructions have none, or names `--global` when it is missing and the
project has no `CLAUDE.md` of its own. Run from `~/.claude`,
or from your home directory unless `~/CLAUDE.md` still holds a section an
earlier run left there, `--check` judges the user-level files, and from your
home directory it names `--global` when no hooks are installed. From your
home directory, whose `.claude/settings.json` is the global one, `--remove`
removes the user-level section with the hooks. If you ran `--global` before,
re-run `bd setup claude --global` to add the section to `~/.claude/CLAUDE.md`.
A section an earlier `--global` run left in a directory's `CLAUDE.md` stays
there; delete it by hand if you don't want it.
- **`bd blocked --label`, `--label-any` and `--exclude-label` apply to a row
blocked only by an unsatisfied `external:` dependency.** The
external-dependency policy lists such a row itself, after the label query

View file

@ -275,10 +275,24 @@ instead of 60s, because `bd serve` gives such a request its
`--large-apply-ceiling` (5 minutes by default) and finishes it even after the
client has given up. A server whose ceiling is raised past about 5m15s can
still outlast the client. A dial or TLS timeout stays a plain connection
error, since the server never saw the request. `off` turns off only the
error, since the server never saw the request, and a connect that fails says
so: it names the address that refused the connection (nothing listening) or
never answered (a filtered port or a down host, after the dialer's 30s), or
the host name that did not resolve. `off` turns off only the
header timer: a reset read is still retried, and a write's timeout is still
reported as above.
Whether the server applies bd's external-dependency policy itself (the
`policy.external_dependencies` capability) is remembered for 5 minutes per
server URL and pinned project, in `beads/http-policy/` under the user cache
directory, so `bd ready` does not fetch the server's context before every
listing just to learn it. `BEADS_HTTP_POLICY_CACHE_TTL` sets that window (a
duration such as `1m`, a number of seconds, or `off`); a server restarted
with a different composition is seen once it passes. Claims and closes never
use the cached answer: they ask the server, since a stale one could skip the
client-side refusal of externally blocked work. A workspace connected without
a project pin is not cached.
`bd search`, `bd show --current` and `bd recompute-blocked` work over HTTP
too, each in its own way. `bd search` asks the server's listing with its text (`q`, behind the `issues.list.search` capability) and
refuses before dialing against a server that does not advertise it. `bd list

View file

@ -145,7 +145,8 @@ Before starting a release:
- [ ] All tests passing (`make test`, the Bazel test lane)
- [ ] npm package tests passing (`cd npm-package && npm run test:all`)
- [ ] **Upgrade smoke tests pass** (`make test-upgrade`) — see [Release Stability Gate](engdocs/RELEASE-STABILITY-GATE.md)
- [ ] **Regression tests pass** (`make test-regression`)
- [ ] **Regression tests pass**
(`bazel test //tests/regression:regression_test --config=doltserver-cmd`)
- [ ] **Every release target cross-compiles** — see
[Cross-compile before tagging](#cross-compile-before-tagging). PR CI
builds them only with cgo off, and a target that fails at tag time

View file

@ -65,6 +65,7 @@ go_library(
"transaction_parity.go",
"tree_walker_contract.go",
"version_reconciler_contract.go",
"versioned_read_contract.go",
"workspaceconfig_contract.go",
],
importpath = "github.com/steveyegge/beads/backend/conformance",

View file

@ -267,6 +267,65 @@ func RunParticipationGenerationProceedsForPromotedRecord(t *testing.T, ctx conte
}
}
// RunParticipationGenerationFlagOffSkipsUpdateOnParticipatingRecord pins the
// switch's off half for a record the fence would let through: created with
// the flag on (so participation_generation is stamped), then updated after
// the flag is turned back off, it must mint nothing. ProceedsForPromotedRecord
// shows the fence passes such a record, so only the flag stands between this
// update and a mint. No other case can see a writer that ignores the flag on
// updates: every other flag-off record is legacy, and the fence stops those
// first.
func RunParticipationGenerationFlagOffSkipsUpdateOnParticipatingRecord(t *testing.T, ctx context.Context, fixture ParticipationGenerationFixture) {
t.Helper()
if err := fixture.SetFlag(ctx, true); err != nil {
t.Fatalf("enabling versioned history: %v", err)
}
id := fixture.IssuePrefix + "-flag-off-skip"
if err := fixture.Mutate(ctx, id); err != nil {
t.Fatalf("mutating %s: %v", id, err)
}
if gen, err := fixture.ParticipationGeneration(ctx, id); err != nil {
t.Fatalf("reading participation_generation for %s: %v", id, err)
} else if gen == nil {
t.Fatalf("participation_generation for %s is NULL immediately after a create with the flag on — "+
"this case cannot test the flag against a record the fence would have stopped anyway", id)
}
if err := fixture.SetFlag(ctx, false); err != nil {
t.Fatalf("disabling versioned history: %v", err)
}
beforeRevision, err := fixture.CurrentRevision(ctx, id)
if err != nil {
t.Fatalf("reading current_revision for %s: %v", id, err)
}
beforeCount, err := fixture.VersionRowCount(ctx, id)
if err != nil {
t.Fatalf("counting version rows for %s: %v", id, err)
}
if err := fixture.MutateExisting(ctx, id); err != nil {
t.Fatalf("mutating existing %s: %v", id, err)
}
afterRevision, err := fixture.CurrentRevision(ctx, id)
if err != nil {
t.Fatalf("reading current_revision for %s: %v", id, err)
}
afterCount, err := fixture.VersionRowCount(ctx, id)
if err != nil {
t.Fatalf("counting version rows for %s: %v", id, err)
}
if afterCount != beforeCount {
t.Errorf("version row count for %s went from %d to %d across an update-shaped mutation with the "+
"flag off, want unchanged: turning versioned history off stops minting for every record, "+
"including one that already participates", id, beforeCount, afterCount)
}
if afterRevision != beforeRevision {
t.Errorf("current_revision for %s went from %d to %d across the same update with the flag off, "+
"want unchanged", id, beforeRevision, afterRevision)
}
}
// RunParticipationGenerationWispPromotionBeginsHistory pins that promoting a
// wisp onto the issues plane is CREATE-shaped in design §16.2b's sense. (This
// is wisp promotion, PromoteFromEphemeral: not R2.3's promotion of a legacy

View file

@ -769,7 +769,21 @@ type EpochFixture struct {
// Version now resolves to under the new epoch. A nil hook means this
// backend cannot report that, and the case that needs it skips with
// that reason.
//
// It only reads: it mints nothing and changes no state. It returns the
// address it was given when nothing carried the Version to a new one,
// and an error for an address the store does not serve.
CurrentAddressFor func(ctx context.Context, storeID string, oldAddress Address) (Address, error)
// LoseVersion records that storeID no longer serves the Version named by
// address. That address, and every address the same Version was carried
// to or from by a token-scheme change, resolves GoneReorganization from
// then on, in every later epoch: an epoch voids what the store lost,
// never what it still serves (R20-n). It is idempotent, never revives
// anything, and returns an error for an address storeID never minted. A
// nil LoseVersion means this backend cannot record a loss, and the cases
// that need one skip with that reason.
LoseVersion func(ctx context.Context, storeID string, address Address) error
}
// RunAnEpochBumpIsTriggeredOnlyByRestoreReinitOrSchemeChange pins R20-m: a
@ -819,94 +833,258 @@ func RunAnEpochBumpIsTriggeredOnlyByRestoreReinitOrSchemeChange(t *testing.T, ct
// RunEpochBumpVoidsOnlyAddressesOfVersionsNoLongerServed pins R20-n — "Rev7
// tightening... the clause most likely to be gotten wrong" in the
// architecture doc's own words. A prior-epoch Address goes
// GoneReorganization UNLESS the backend still serves that Version, in which
// case it must stay Live AND additionally report the Address it now
// resolves to under the new epoch.
// architecture doc's own words: an epoch voids what the store lost, never
// what it still serves.
//
// StillServes is an ORACLE here, not a control: this case cannot make a real
// backend keep serving one address and drop another, since Phase 0 wires no
// real backend. It asks StillServes what the fixture (once real) decided,
// and checks the rest of the contract's promise against that decision for
// both outcomes.
// Survival is RECORDED, never inferred (gastownhall/beads#6664, bee-ghosttrack
// review 5360880888, Major 1). An earlier form of this case made a Version
// survive by minting it again in every later epoch, and treated a Version
// nobody minted again as lost. That reads loss off the absence of a mint, so
// it could not express a Version the store lost after minting it, and it
// voided every survivor that nobody happened to mint again. Here a restore or
// a destructive reinit leaves every address row alone: an address the store
// still serves stays Live at its own address with no upkeep, and the only way
// an address goes Gone is LoseVersion saying so.
//
// Each phase is a named subtest, so a backend that cannot record a loss skips
// only the phases that need LoseVersion, and a failure names its phase.
func RunEpochBumpVoidsOnlyAddressesOfVersionsNoLongerServed(t *testing.T, ctx context.Context, fixture EpochFixture) {
t.Helper()
if fixture.MintUnderEpoch == nil {
t.Skip("this backend has no way to mint a Version under a known epoch (MintUnderEpoch is nil)")
}
if fixture.BumpEpoch == nil {
t.Skip("this backend has no epoch concept yet (BumpEpoch is nil)")
}
if fixture.StillServes == nil {
t.Skip("this backend cannot report whether it still serves a prior-epoch Version (StillServes is nil)")
}
if fixture.Resolve == nil {
t.Skip("this backend does not yet report retention state (Resolve is nil)")
}
if fixture.CurrentAddressFor == nil {
t.Skip("this backend cannot report a still-served Version's new Address (CurrentAddressFor is nil)")
}
store := epochStore(fixture, "voids")
epochSkipUnlessReady(t, fixture, false)
addrA, err := fixture.MintUnderEpoch(ctx, store, "record-a")
if err != nil {
t.Fatalf("MintUnderEpoch(record-a): %v", err)
// survivor-and-lost: of two Versions minted before a transition, the one
// the store loses goes Gone and the other stays Live at the address it
// already had, with no re-mint, for both triggers that leave addresses
// alone.
t.Run("survivor-and-lost", func(t *testing.T) {
if fixture.LoseVersion == nil {
t.Skip(epochLoseVersionSkip)
}
for _, trigger := range []EpochBumpTrigger{EpochBumpTriggerRestore, EpochBumpTriggerDestructiveReinit} {
t.Run(trigger.String(), func(t *testing.T) {
store := epochStore(fixture, "survivor-"+trigger.String())
addrA := epochMintAddress(t, ctx, fixture, store, "record-a")
addrB := epochMintAddress(t, ctx, fixture, store, "record-b")
newEpoch := epochBumpTo(t, ctx, fixture, store, trigger)
epochLoseAddress(t, ctx, fixture, store, addrB)
epochRequireLive(t, ctx, fixture, store, addrA, newEpoch,
"record-a was never lost, so the transition leaves it served at its own address with no re-mint (R20-n's exception)")
epochRequireGone(t, ctx, fixture, store, addrB, newEpoch,
"record-b was lost, so the transition voids it (R20-n)")
current := epochCurrentAddress(t, ctx, fixture, store, addrA)
epochRequireLive(t, ctx, fixture, store, current, newEpoch,
"the address CurrentAddressFor reports for a survivor must be served")
epochRequireLive(t, ctx, fixture, store, addrA, newEpoch,
"asking CurrentAddressFor must not retire or move the survivor's address")
if lostCurrent, err := fixture.CurrentAddressFor(ctx, store, addrB); err == nil {
t.Errorf("CurrentAddressFor(a lost address) = %s with no error, want an error: a lost Version has no current address", lostCurrent)
}
epochRequireGone(t, ctx, fixture, store, addrB, newEpoch,
"CurrentAddressFor on a lost address must not bring it back")
})
}
})
// gone-is-terminal: once an address is lost it stays lost. A later mint of
// the same id starts a new lineage under a new address, and neither that
// mint nor CurrentAddressFor revives the lost one (bee-ghosttrack's
// assertion for Major 1: a read-only lookup must not mint a replacement
// that makes a lost address look served).
t.Run("gone-is-terminal", func(t *testing.T) {
if fixture.LoseVersion == nil {
t.Skip(epochLoseVersionSkip)
}
store := epochStore(fixture, "terminal")
lost := epochMintAddress(t, ctx, fixture, store, "record-g")
epochBumpTo(t, ctx, fixture, store, EpochBumpTriggerRestore)
epochLoseAddress(t, ctx, fixture, store, lost)
laterEpoch := epochBumpTo(t, ctx, fixture, store, EpochBumpTriggerRestore)
fresh := epochMintAddress(t, ctx, fixture, store, "record-g")
if fresh == lost {
t.Fatalf("MintUnderEpoch(record-g) returned %s, the address already lost: a lost address is never handed out again", lost)
}
epochRequireLive(t, ctx, fixture, store, fresh, laterEpoch,
"a fresh mint of the id is a new lineage and is served")
epochRequireGone(t, ctx, fixture, store, lost, laterEpoch,
"a later mint of the same id must not revive a lost address")
if replacement, err := fixture.CurrentAddressFor(ctx, store, lost); err == nil {
t.Errorf("CurrentAddressFor(a lost address) = %s with no error, want an error: asking where a lost address resolves must not mint a replacement", replacement)
}
epochRequireGone(t, ctx, fixture, store, lost, laterEpoch,
"CurrentAddressFor on a lost address must not revive it")
// Losing it a second time is a no-op that leaves the fresh lineage
// alone.
epochLoseAddress(t, ctx, fixture, store, lost)
epochRequireLive(t, ctx, fixture, store, fresh, laterEpoch,
"losing the old address again must leave the fresh lineage served")
})
// survival-needs-no-upkeep: with nothing lost, an address stays Live across
// any number of counter-only transitions without being minted again, and a
// later mint of the same id neither retires it nor revives anything. This
// is the phase the earlier, mint-driven form failed: it answered Gone for
// every survivor nobody minted again.
t.Run("survival-needs-no-upkeep", func(t *testing.T) {
store := epochStore(fixture, "upkeep")
kept := epochMintAddress(t, ctx, fixture, store, "record-c")
epochBumpTo(t, ctx, fixture, store, EpochBumpTriggerRestore)
epochBumpTo(t, ctx, fixture, store, EpochBumpTriggerDestructiveReinit)
finalEpoch := epochBumpTo(t, ctx, fixture, store, EpochBumpTriggerRestore)
epochRequireLive(t, ctx, fixture, store, kept, finalEpoch,
"nothing was lost, so three counter-only transitions leave the address served without a re-mint")
fresh := epochMintAddress(t, ctx, fixture, store, "record-c")
if fresh == kept {
t.Fatalf("MintUnderEpoch(record-c) returned %s again after three bumps, want a new address for the new epoch", kept)
}
epochRequireLive(t, ctx, fixture, store, kept, finalEpoch,
"a later mint of the same id must not retire a served address")
epochRequireLive(t, ctx, fixture, store, fresh, finalEpoch,
"the fresh mint is served")
current := epochCurrentAddress(t, ctx, fixture, store, kept)
epochRequireLive(t, ctx, fixture, store, current, finalEpoch,
"the current address of a survivor must be served")
epochRequireLive(t, ctx, fixture, store, kept, finalEpoch,
"asking for the current address must not change the survivor")
})
}
// RunTokenSchemeChangeCarriesLiveAddressesAndOnlyThose pins R20-n's retained
// mapping for the one trigger that changes how addresses are encoded. A
// token-scheme-change bump gives every Version the store still serves a new
// address under the new epoch and keeps the old address resolving, so a holder
// of the old address is neither stranded nor pointed at something else. A
// Version the store already lost gets no new address and stays Gone.
func RunTokenSchemeChangeCarriesLiveAddressesAndOnlyThose(t *testing.T, ctx context.Context, fixture EpochFixture) {
t.Helper()
epochSkipUnlessReady(t, fixture, true)
store := epochStore(fixture, "scheme-change")
addrA := epochMintAddress(t, ctx, fixture, store, "record-a")
addrB := epochMintAddress(t, ctx, fixture, store, "record-b")
// record-b is lost in the epoch it was minted in, which a store may do.
epochLoseAddress(t, ctx, fixture, store, addrB)
newEpoch := epochBumpTo(t, ctx, fixture, store, EpochBumpTriggerTokenSchemeChange)
epochRequireLive(t, ctx, fixture, store, addrA, newEpoch,
"record-a is still served after the scheme change, through the retained mapping")
epochRequireGone(t, ctx, fixture, store, addrB, newEpoch,
"record-b was lost before the scheme change, which must not carry it")
carried := epochCurrentAddress(t, ctx, fixture, store, addrA)
if carried == addrA {
t.Errorf("CurrentAddressFor(%s) = the same address after a token-scheme change, want a new one: a scheme change re-encodes every served address, which is what tells a carry from a no-op", addrA)
}
addrB, err := fixture.MintUnderEpoch(ctx, store, "record-b")
if err != nil {
t.Fatalf("MintUnderEpoch(record-b): %v", err)
epochRequireLive(t, ctx, fixture, store, carried, newEpoch,
"the carried address must be served under the new epoch")
epochRequireLive(t, ctx, fixture, store, addrA, newEpoch,
"the old address must keep resolving after its carried address is looked up")
if again := epochCurrentAddress(t, ctx, fixture, store, carried); again != carried {
t.Errorf("CurrentAddressFor(%s) = %s, want the carried address itself: from the newest address the mapping is already current", carried, again)
}
if lostCurrent, err := fixture.CurrentAddressFor(ctx, store, addrB); err == nil {
t.Errorf("CurrentAddressFor(a lost address) = %s with no error, want an error: a lost Version is not carried", lostCurrent)
}
}
// RunACarriedAddressKeepsResolvingAcrossLaterBumps pins that a carried mapping
// is recorded once and then simply persists: later counter-only transitions do
// not change it, and a second token-scheme change extends it to the newest
// address without breaking any older one. Every address of the Version points
// directly at the newest address (one hop from any member), never along a
// chain.
func RunACarriedAddressKeepsResolvingAcrossLaterBumps(t *testing.T, ctx context.Context, fixture EpochFixture) {
t.Helper()
epochSkipUnlessReady(t, fixture, false)
store := epochStore(fixture, "carried-later")
addrA := epochMintAddress(t, ctx, fixture, store, "record-a")
epochBumpTo(t, ctx, fixture, store, EpochBumpTriggerRestore)
epochBumpTo(t, ctx, fixture, store, EpochBumpTriggerTokenSchemeChange)
addrA1 := epochCurrentAddress(t, ctx, fixture, store, addrA)
if addrA1 == addrA {
t.Fatalf("CurrentAddressFor(%s) = the same address after a token-scheme change, want a new one", addrA)
}
newEpoch, err := fixture.BumpEpoch(ctx, store, EpochBumpTriggerRestore)
if err != nil {
t.Fatalf("BumpEpoch: %v", err)
// Two counter-only transitions, with nothing minted in between.
epochBumpTo(t, ctx, fixture, store, EpochBumpTriggerRestore)
counterEpoch := epochBumpTo(t, ctx, fixture, store, EpochBumpTriggerDestructiveReinit)
epochRequireLive(t, ctx, fixture, store, addrA, counterEpoch,
"the original address must still resolve after counter-only transitions")
epochRequireLive(t, ctx, fixture, store, addrA1, counterEpoch,
"the carried address must still resolve after counter-only transitions")
if got := epochCurrentAddress(t, ctx, fixture, store, addrA); got != addrA1 {
t.Errorf("CurrentAddressFor(%s) = %s, want %s: a counter-only transition does not change the mapping", addrA, got, addrA1)
}
servesA, err := fixture.StillServes(ctx, store, addrA)
if err != nil {
t.Fatalf("StillServes(%s): %v", addrA, err)
// A second scheme change carries the Version again.
secondEpoch := epochBumpTo(t, ctx, fixture, store, EpochBumpTriggerTokenSchemeChange)
addrA2 := epochCurrentAddress(t, ctx, fixture, store, addrA)
if addrA2 == addrA || addrA2 == addrA1 {
t.Fatalf("CurrentAddressFor(%s) = %s after a second scheme change, want an address different from %s and %s", addrA, addrA2, addrA, addrA1)
}
servesB, err := fixture.StillServes(ctx, store, addrB)
if err != nil {
t.Fatalf("StillServes(%s): %v", addrB, err)
for _, member := range []Address{addrA, addrA1, addrA2} {
epochRequireLive(t, ctx, fixture, store, member, secondEpoch,
"every address of a carried Version must resolve after a second scheme change")
}
if servesA == servesB {
t.Skip("this scenario needs one still-served and one no-longer-served address to exercise both halves of R20-n; StillServes reported the same answer for both, so this fixture gives this case nothing to contrast")
if got := epochCurrentAddress(t, ctx, fixture, store, addrA1); got != addrA2 {
t.Errorf("CurrentAddressFor(%s) = %s, want %s: every address of the Version points straight at the newest one", addrA1, got, addrA2)
}
stillServed, noLongerServed := addrA, addrB
if servesB && !servesA {
stillServed, noLongerServed = addrB, addrA
finalEpoch := epochBumpTo(t, ctx, fixture, store, EpochBumpTriggerRestore)
epochRequireLive(t, ctx, fixture, store, addrA2, finalEpoch,
"the newest carried address must still resolve after a later restore")
}
// RunALostAddressStaysGoneAcrossASchemeChange pins that loss is terminal even
// across a token-scheme change. Losing a Version loses every address of its
// lineage at once, and a later scheme change must not carry a lost lineage
// back into service.
func RunALostAddressStaysGoneAcrossASchemeChange(t *testing.T, ctx context.Context, fixture EpochFixture) {
t.Helper()
epochSkipUnlessReady(t, fixture, true)
store := epochStore(fixture, "lost-scheme-change")
addrA := epochMintAddress(t, ctx, fixture, store, "record-a")
epochBumpTo(t, ctx, fixture, store, EpochBumpTriggerTokenSchemeChange)
addrA1 := epochCurrentAddress(t, ctx, fixture, store, addrA)
lostEpoch := epochBumpTo(t, ctx, fixture, store, EpochBumpTriggerRestore)
// One lineage, two addresses: losing either loses both.
epochLoseAddress(t, ctx, fixture, store, addrA)
epochRequireGone(t, ctx, fixture, store, addrA, lostEpoch,
"the original address of a lost Version must be Gone")
epochRequireGone(t, ctx, fixture, store, addrA1, lostEpoch,
"the carried address of a lost Version must be Gone too")
schemeEpoch := epochBumpTo(t, ctx, fixture, store, EpochBumpTriggerTokenSchemeChange)
epochRequireGone(t, ctx, fixture, store, addrA, schemeEpoch,
"a later scheme change must not carry a lost lineage back into service")
epochRequireGone(t, ctx, fixture, store, addrA1, schemeEpoch,
"a later scheme change must not carry a lost lineage back into service")
for _, lostAddress := range []Address{addrA, addrA1} {
if current, err := fixture.CurrentAddressFor(ctx, store, lostAddress); err == nil {
t.Errorf("CurrentAddressFor(%s) = %s with no error, want an error: a lost lineage has no current address", lostAddress, current)
}
}
voidedAnswer, err := fixture.Resolve(ctx, store, noLongerServed)
if err != nil {
t.Fatalf("Resolve(no-longer-served): %v", err)
}
if voidedAnswer.Restriction != RestrictionGoneReorganization {
t.Errorf("Resolve(a prior-epoch Address no longer served) = %s, want RestrictionGoneReorganization (R20-n)", voidedAnswer.Restriction)
}
if voidedAnswer.Epoch == nil {
t.Fatal("Resolve(a prior-epoch Address no longer served).Epoch = nil, want the current epoch populated (R20-n: the answer must name the current epoch, not just Restriction alone)")
} else if *voidedAnswer.Epoch != newEpoch {
t.Errorf("Resolve(a prior-epoch Address no longer served).Epoch = %d, want the current epoch %d", *voidedAnswer.Epoch, newEpoch)
}
keptAnswer, err := fixture.Resolve(ctx, store, stillServed)
if err != nil {
t.Fatalf("Resolve(still-served): %v", err)
}
if keptAnswer.Restriction != RestrictionLive {
t.Errorf("Resolve(a prior-epoch Address the backend still serves) = %s, want RestrictionLive (R20-n's exception)", keptAnswer.Restriction)
}
newAddr, err := fixture.CurrentAddressFor(ctx, store, stillServed)
if err != nil {
t.Fatalf("CurrentAddressFor(%s): %v", stillServed, err)
}
if newAddr == "" {
t.Error("CurrentAddressFor(a still-served prior-epoch Address) returned an empty Address, want a real one under the new epoch")
fresh := epochMintAddress(t, ctx, fixture, store, "record-a")
if fresh == addrA || fresh == addrA1 {
t.Fatalf("MintUnderEpoch(record-a) returned %s, an address of the lost lineage: a lost address is never handed out again", fresh)
}
epochRequireLive(t, ctx, fixture, store, fresh, schemeEpoch,
"a fresh mint of the id after the loss is a new lineage and is served")
}
// --- fixture helpers -------------------------------------------------------
@ -953,6 +1131,137 @@ func epochStore(fixture EpochFixture, tag string) string {
return fixture.IssuePrefix + "-epoch-store-" + tag
}
// epochLoseVersionSkip is the skip reason of every phase that needs
// EpochFixture.LoseVersion.
const epochLoseVersionSkip = "this backend cannot record that the store lost a Version (LoseVersion is nil)"
// epochSkipUnlessReady skips the case when the fixture lacks a capability the
// epoch cases need. The cases that record a loss also need LoseVersion. The
// all-nil wiring test runs every case against an empty fixture, so each case
// must call this before it touches any of them.
func epochSkipUnlessReady(t *testing.T, fixture EpochFixture, needsLoseVersion bool) {
t.Helper()
if fixture.MintUnderEpoch == nil {
t.Skip("this backend has no way to mint a Version under a known epoch (MintUnderEpoch is nil)")
}
if fixture.BumpEpoch == nil {
t.Skip("this backend has no epoch concept yet (BumpEpoch is nil)")
}
if fixture.StillServes == nil {
t.Skip("this backend cannot report whether it still serves a prior-epoch Version (StillServes is nil)")
}
if fixture.Resolve == nil {
t.Skip("this backend does not yet report retention state (Resolve is nil)")
}
if fixture.CurrentAddressFor == nil {
t.Skip("this backend cannot report a still-served Version's new Address (CurrentAddressFor is nil)")
}
if needsLoseVersion && fixture.LoseVersion == nil {
t.Skip(epochLoseVersionSkip)
}
}
// epochMintAddress mints id on store, failing the case if minting fails.
func epochMintAddress(t *testing.T, ctx context.Context, fixture EpochFixture, store, id string) Address {
t.Helper()
address, err := fixture.MintUnderEpoch(ctx, store, id)
if err != nil {
t.Fatalf("MintUnderEpoch(%s, %s): %v", store, id, err)
}
return address
}
// epochBumpTo bumps store's epoch for trigger and returns the epoch it
// reports. Epochs are captured from the return value, never assumed: the
// counter is one per database, shared by every store the suite uses.
func epochBumpTo(t *testing.T, ctx context.Context, fixture EpochFixture, store string, trigger EpochBumpTrigger) int {
t.Helper()
epoch, err := fixture.BumpEpoch(ctx, store, trigger)
if err != nil {
t.Fatalf("BumpEpoch(%s, %s): %v", store, trigger, err)
}
return epoch
}
// epochLoseAddress records that store lost the Version behind address.
func epochLoseAddress(t *testing.T, ctx context.Context, fixture EpochFixture, store string, address Address) {
t.Helper()
if err := fixture.LoseVersion(ctx, store, address); err != nil {
t.Fatalf("LoseVersion(%s, %s): %v", store, address, err)
}
}
// epochCurrentAddress asks where address now resolves, failing the case on an
// error or an empty answer.
func epochCurrentAddress(t *testing.T, ctx context.Context, fixture EpochFixture, store string, address Address) Address {
t.Helper()
current, err := fixture.CurrentAddressFor(ctx, store, address)
if err != nil {
t.Fatalf("CurrentAddressFor(%s, %s): %v", store, address, err)
}
if current == "" {
t.Fatalf("CurrentAddressFor(%s, %s) returned an empty Address, want a real one", store, address)
}
return current
}
// epochRequireLive asserts that address is served at epoch: StillServes is true
// and Resolve answers RestrictionLive naming that epoch. why says what the
// assertion is checking, for the failure message.
func epochRequireLive(t *testing.T, ctx context.Context, fixture EpochFixture, store string, address Address, epoch int, why string) {
t.Helper()
serves, err := fixture.StillServes(ctx, store, address)
if err != nil {
t.Fatalf("StillServes(%s): %v", address, err)
}
if !serves {
t.Errorf("StillServes(%s) = false, want true: %s", address, why)
}
answer, err := fixture.Resolve(ctx, store, address)
if err != nil {
t.Fatalf("Resolve(%s): %v", address, err)
}
if answer.Restriction != RestrictionLive {
t.Errorf("Resolve(%s) = %s, want RestrictionLive: %s", address, answer.Restriction, why)
}
epochRequireAnswerEpoch(t, answer, address, epoch, why)
}
// epochRequireGone asserts that address is no longer served at epoch:
// StillServes is false and Resolve answers RestrictionGoneReorganization
// naming that epoch.
func epochRequireGone(t *testing.T, ctx context.Context, fixture EpochFixture, store string, address Address, epoch int, why string) {
t.Helper()
serves, err := fixture.StillServes(ctx, store, address)
if err != nil {
t.Fatalf("StillServes(%s): %v", address, err)
}
if serves {
t.Errorf("StillServes(%s) = true, want false: %s", address, why)
}
answer, err := fixture.Resolve(ctx, store, address)
if err != nil {
t.Fatalf("Resolve(%s): %v", address, err)
}
if answer.Restriction != RestrictionGoneReorganization {
t.Errorf("Resolve(%s) = %s, want RestrictionGoneReorganization: %s", address, answer.Restriction, why)
}
epochRequireAnswerEpoch(t, answer, address, epoch, why)
}
// epochRequireAnswerEpoch asserts that a Live or Gone answer names the current
// epoch (R20-n: the answer carries the epoch, not just the Restriction).
func epochRequireAnswerEpoch(t *testing.T, answer RetentionAnswer, address Address, epoch int, why string) {
t.Helper()
if answer.Epoch == nil {
t.Errorf("Resolve(%s).Epoch = nil, want the current epoch %d: %s", address, epoch, why)
return
}
if *answer.Epoch != epoch {
t.Errorf("Resolve(%s).Epoch = %d, want the current epoch %d: %s", address, *answer.Epoch, epoch, why)
}
}
// sameRetentionAnswer compares two RetentionAnswer values by content rather
// than identity, so a case can assert "this did not change" without
// depending on the concrete Restriction the backend happened to pick.

View file

@ -129,5 +129,14 @@ func TestVersionedHistoryPhase0RunsInFullSkipMode(t *testing.T) {
t.Run("EpochBumpVoidsOnlyAddressesOfVersionsNoLongerServed", func(t *testing.T) {
RunEpochBumpVoidsOnlyAddressesOfVersionsNoLongerServed(t, ctx, fixture)
})
t.Run("TokenSchemeChangeCarriesLiveAddressesAndOnlyThose", func(t *testing.T) {
RunTokenSchemeChangeCarriesLiveAddressesAndOnlyThose(t, ctx, fixture)
})
t.Run("ACarriedAddressKeepsResolvingAcrossLaterBumps", func(t *testing.T) {
RunACarriedAddressKeepsResolvingAcrossLaterBumps(t, ctx, fixture)
})
t.Run("ALostAddressStaysGoneAcrossASchemeChange", func(t *testing.T) {
RunALostAddressStaysGoneAcrossASchemeChange(t, ctx, fixture)
})
})
}

View file

@ -0,0 +1,356 @@
package conformance
import (
"context"
"testing"
"time"
)
// This file holds the contract for R7.1 (gastownhall/beads#6136, design doc
// gastownhall/beads#5898 revision 9): the as-of read — the "versioned
// reads" half of Phase 3's title, authored here from scratch, since no
// fixture for it exists anywhere in this package to un-skip.
//
// R7.1, VERBATIM (design doc #5898 rev 9): "An as-of read is a named read
// whose selector is an instant. Given an instant T or a version address, a
// store returns one Bead's durable state as of that point — the latest
// version it holds that was accepted at or before T, with everything later
// excluded — under R7's record shape, marking the address it served, or
// refuses as gone or unknown with the reason (R8, R20). Like every history
// answer it is complete for the answering store's holdings and may change
// after a sync (TC3)."
//
// ADDRESS, RESTRICTION, AND CHANGEATTRIBUTION ARE DECLARED IN
// expected_revision_contract.go — see that file's package-level note on
// where this suite's shared vocabulary lives and why. This file reuses
// Restriction's five values as-is for the gone-or-unknown refusal outcome
// (R8): an as-of read never invents a sixth state, and never distinguishes
// "gone" from "unknown" any differently than R20 already does.
//
// EVERY HOOK ON THE FIXTURE BELOW IS INDEPENDENTLY NILABLE — see the
// package-level note in expected_revision_contract.go. Every case
// nil-checks every hook it uses and SKIPS BY NAME when one is missing. No
// backend implements as-of reads yet — the implementation is
// the child this suite is written ahead of.
//
// EXPLICIT NON-GOAL: MEMORY-PLANE CONSUMER POLICY IS NOT PART OF THIS
// PRIMITIVE. R7.1's own text is explicit that a closed-before-T boundary,
// sibling exclusion, and supersession exclusion "are Memory-plane policies
// a consumer layers on this primitive (#5877), not part of it." This suite
// does not implement or assert any of the three — a future reader who finds
// them absent should read that as this file honoring R7.1's own scope, not
// as an oversight. This is the read-side analog of the R16/R16.1 boundary
// risk already recorded in expected_revision_contract.go: do not conflate
// the primitive with policy layered on top of it.
//
// THIS SUITE ASSERTS LOCAL COMPLETENESS ONLY (TC3). Nothing below requires,
// or even checks, that two stores asked about the same lineage agree — R7.1
// itself says an as-of answer "may change after a sync," so two stores at
// different sync points are expected to answer differently, and neither is
// wrong. RunAsOfReadIsCompleteOnlyForTheAnsweringStoresHoldings is the one
// case that touches more than one store, and what it asserts is exactly
// this: each store answers strictly from its own holdings, never a
// sibling's — not that the two agree.
// AsOfSelector names the point R7.1 resolves against: either a wall-clock
// instant, or a specific version Address treated as the selector itself —
// "the read that names its own answer" (R7.1: "an instant T or a version
// address"). Exactly one of At/Version is populated in every case this file
// exercises; R7.1 does not speak to the shape where both or neither are
// set, so this suite does not either.
type AsOfSelector struct {
At *time.Time
Version *Address
}
// AsOfReadRefusal is R8's typed outcome for an as-of read that cannot be
// answered. Restriction is always one of the four Gone*/Unknown values,
// never RestrictionLive — a live answer is a served AsOfReadResult, not a
// refusal. Reason explains why (R8).
type AsOfReadRefusal struct {
Restriction Restriction
Reason string
}
// AsOfReadResult is the outcome of an as-of read (R7.1). Address/State and
// Refusal are mutually exclusive: read Address/State only when Refusal is
// nil.
type AsOfReadResult struct {
// Address is the version this read served, marking "the address it
// served" (R7.1). Populated only when Refusal is nil.
Address Address
// State is the served version's durable state under R7's record shape.
// Opaque to this suite: the fixture adapter translates a backend's real
// record shape into this map, and no case here asserts its field-level
// content — only that a served result carries an Address.
State map[string]any
// Refusal is populated instead of Address/State when the read cannot be
// answered (R8). Nil means the read was served.
Refusal *AsOfReadRefusal
}
// AsOfRead resolves storeID's answer to an as-of read against id's lineage,
// at selector (R7.1).
type AsOfRead func(ctx context.Context, storeID, id string, selector AsOfSelector) (AsOfReadResult, error)
// AsOfReadFixture supplies the capability under test for R7.1: a read whose
// selector is an instant or a version address, resolving to the latest
// version accepted at or before that point, or a typed refusal.
type AsOfReadFixture struct {
IssuePrefix string
// Resolve performs the as-of read under test (R7.1). A nil hook means
// this backend does not implement as-of reads yet, and every case in
// this file skips with that reason.
Resolve AsOfRead
// MintAt mints a fresh version for id under storeID, recorded as
// accepted at the given instant, and returns its Address. Cases use
// this to build a lineage with known accept-times to resolve an as-of
// read against. A nil hook means this backend has no way to mint a
// version at a controlled accept-time, and cases that need one skip
// with that reason.
MintAt func(ctx context.Context, storeID, id string, acceptedAt time.Time) (Address, error)
// MakeUnanswerable arranges for id to be unanswerable at storeID for
// the given Restriction (one of RestrictionGoneRetention/GoneErasure/
// GoneReorganization/Unknown) — independently of
// RetentionFixture/EpochFixture's own removal machinery, since R7.1's
// refusal is a sibling contract to R17/R20, not a dependent of them. A
// nil hook means this backend has no way to arrange this, and the case
// that needs it skips with that reason.
MakeUnanswerable func(ctx context.Context, storeID, id string, restriction Restriction) error
}
// RunAsOfReadSelectorAcceptsEitherAnInstantOrAVersionAddress pins R7.1's
// selector shape: an instant T and the version address that instant
// resolves to are two names for the same answer, and a store must accept
// either.
func RunAsOfReadSelectorAcceptsEitherAnInstantOrAVersionAddress(t *testing.T, ctx context.Context, fixture AsOfReadFixture) {
t.Helper()
if fixture.Resolve == nil {
t.Skip("this backend does not implement as-of reads (Resolve is nil)")
}
if fixture.MintAt == nil {
t.Skip("this backend has no way to mint a version at a controlled accept-time (MintAt is nil)")
}
store := asOfReadStore(fixture, "selector-kinds")
id := fixture.IssuePrefix + "-asof-selector"
t0 := time.Now().UTC().Add(-time.Hour)
asOfReadMint(t, ctx, fixture, store, id, t0)
t1 := t0.Add(time.Minute)
second := asOfReadMint(t, ctx, fixture, store, id, t1)
byInstant, err := fixture.Resolve(ctx, store, id, AsOfSelector{At: &t1})
if err != nil {
t.Fatalf("Resolve(selector=instant): %v", err)
}
if byInstant.Refusal != nil {
t.Fatalf("Resolve(selector=instant) = %+v, want a served result", byInstant)
}
byVersion, err := fixture.Resolve(ctx, store, id, AsOfSelector{Version: &second})
if err != nil {
t.Fatalf("Resolve(selector=version address): %v", err)
}
if byVersion.Refusal != nil {
t.Fatalf("Resolve(selector=version address) = %+v, want a served result", byVersion)
}
if byInstant.Address != second {
t.Errorf("Resolve(selector=instant matching a version's own accept-time).Address = %s, want %s", byInstant.Address, second)
}
if byVersion.Address != second {
t.Errorf("Resolve(selector=version address).Address = %s, want the same address named %s", byVersion.Address, second)
}
if byInstant.Address != byVersion.Address {
t.Errorf("an instant selector (served %s) and a version-address selector naming the same version (served %s) resolved to different addresses; R7.1 accepts either as a name for the same answer", byInstant.Address, byVersion.Address)
}
}
// RunAsOfReadReturnsTheLatestVersionAtOrBeforeTStrictlyExcludingLater pins
// R7.1's ordering promise: resolving at T returns the latest version
// accepted at or before T, and a version accepted after T is excluded even
// when its own instant is close by.
func RunAsOfReadReturnsTheLatestVersionAtOrBeforeTStrictlyExcludingLater(t *testing.T, ctx context.Context, fixture AsOfReadFixture) {
t.Helper()
if fixture.Resolve == nil {
t.Skip("this backend does not implement as-of reads (Resolve is nil)")
}
if fixture.MintAt == nil {
t.Skip("this backend has no way to mint a version at a controlled accept-time (MintAt is nil)")
}
store := asOfReadStore(fixture, "ordering")
id := fixture.IssuePrefix + "-asof-ordering"
t0 := time.Now().UTC().Add(-time.Hour)
asOfReadMint(t, ctx, fixture, store, id, t0)
t1 := t0.Add(time.Minute)
middle := asOfReadMint(t, ctx, fixture, store, id, t1)
t2 := t0.Add(2 * time.Minute)
asOfReadMint(t, ctx, fixture, store, id, t2)
atExactly, err := fixture.Resolve(ctx, store, id, AsOfSelector{At: &t1})
if err != nil {
t.Fatalf("Resolve(T=middle's own instant): %v", err)
}
if atExactly.Refusal != nil || atExactly.Address != middle {
t.Errorf("Resolve(T=middle's own instant) = %+v, want the version accepted exactly at T (%s), not a later one", atExactly, middle)
}
between := t1.Add(30 * time.Second)
betweenResult, err := fixture.Resolve(ctx, store, id, AsOfSelector{At: &between})
if err != nil {
t.Fatalf("Resolve(T strictly between two versions): %v", err)
}
if betweenResult.Refusal != nil || betweenResult.Address != middle {
t.Errorf("Resolve(T strictly between two versions) = %+v, want the latest version at-or-before T (%s); the version accepted after T must be strictly excluded", betweenResult, middle)
}
}
// RunAsOfReadReportsTheAddressItServed pins R7.1's "marking the address it
// served": a served result names the exact Address of the version it
// returned, not merely a truthy success.
func RunAsOfReadReportsTheAddressItServed(t *testing.T, ctx context.Context, fixture AsOfReadFixture) {
t.Helper()
if fixture.Resolve == nil {
t.Skip("this backend does not implement as-of reads (Resolve is nil)")
}
if fixture.MintAt == nil {
t.Skip("this backend has no way to mint a version at a controlled accept-time (MintAt is nil)")
}
store := asOfReadStore(fixture, "reports-address")
id := fixture.IssuePrefix + "-asof-reports-address"
at := time.Now().UTC()
address := asOfReadMint(t, ctx, fixture, store, id, at)
result, err := fixture.Resolve(ctx, store, id, AsOfSelector{At: &at})
if err != nil {
t.Fatalf("Resolve: %v", err)
}
if result.Refusal != nil {
t.Fatalf("Resolve = %+v, want a served result", result)
}
if result.Address == "" {
t.Fatal("Resolve returned an empty Address on a served result, want the address of the version it served (R7.1)")
}
if result.Address != address {
t.Errorf("Resolve(...).Address = %s, want the served version's own address %s", result.Address, address)
}
}
// RunAsOfReadRefusesAsGoneOrUnknownNeverSubstitutingAnotherVersion pins R8:
// a read that cannot be answered refuses as a typed Gone or Unknown outcome
// with a reason, and never silently returns a neighboring version, the
// nearest surviving version, or current state as a substitute — R8's own
// text names all three as non-answers.
func RunAsOfReadRefusesAsGoneOrUnknownNeverSubstitutingAnotherVersion(t *testing.T, ctx context.Context, fixture AsOfReadFixture) {
t.Helper()
if fixture.Resolve == nil {
t.Skip("this backend does not implement as-of reads (Resolve is nil)")
}
if fixture.MintAt == nil {
t.Skip("this backend has no way to mint a version at a controlled accept-time (MintAt is nil)")
}
if fixture.MakeUnanswerable == nil {
t.Skip("this backend has no way to make a lineage unanswerable (MakeUnanswerable is nil)")
}
for _, restriction := range []Restriction{
RestrictionGoneRetention,
RestrictionGoneErasure,
RestrictionGoneReorganization,
RestrictionUnknown,
} {
t.Run(restriction.String(), func(t *testing.T) {
store := asOfReadStore(fixture, "unanswerable-"+restriction.String())
id := fixture.IssuePrefix + "-asof-unanswerable-" + restriction.String()
at := time.Now().UTC()
address := asOfReadMint(t, ctx, fixture, store, id, at)
if err := fixture.MakeUnanswerable(ctx, store, id, restriction); err != nil {
t.Fatalf("MakeUnanswerable(%s, %s): %v", id, restriction, err)
}
result, err := fixture.Resolve(ctx, store, id, AsOfSelector{At: &at})
if err != nil {
t.Fatalf("Resolve after MakeUnanswerable(%s): %v", restriction, err)
}
if result.Refusal == nil {
t.Fatalf("Resolve after MakeUnanswerable(%s) = %+v, want a Refusal, not a served result (R8)", restriction, result)
}
if result.Refusal.Restriction != restriction {
t.Errorf("Refusal.Restriction = %s, want %s", result.Refusal.Restriction, restriction)
}
if result.Refusal.Reason == "" {
t.Error("Refusal.Reason is empty, want a reason (R8)")
}
if result.Address != "" {
t.Errorf("Resolve on a refusal returned Address = %s, want empty: R8 forbids silently substituting a neighboring version, the nearest surviving version, or current state (the pre-refusal address was %s)", result.Address, address)
}
})
}
}
// RunAsOfReadIsCompleteOnlyForTheAnsweringStoresHoldings pins R7.1's closing
// clause and TC3: an as-of answer "is complete for the answering store's
// holdings and may change after a sync." This case asserts NOTHING about
// agreement between two stores asked about the same lineage — proving that
// absence is the point, not a gap. It mints a lineage into exactly one of
// two stores and confirms each store answers strictly from its own
// holdings: the store that holds the lineage serves it, and the store that
// never received it answers Unknown (FR-06, reused from R20) rather than
// reaching across to a sibling store's knowledge, erroring, or answering
// Gone — which would claim knowledge of a lineage it never held.
func RunAsOfReadIsCompleteOnlyForTheAnsweringStoresHoldings(t *testing.T, ctx context.Context, fixture AsOfReadFixture) {
t.Helper()
if fixture.Resolve == nil {
t.Skip("this backend does not implement as-of reads (Resolve is nil)")
}
if fixture.MintAt == nil {
t.Skip("this backend has no way to mint a version at a controlled accept-time (MintAt is nil)")
}
holds := asOfReadStore(fixture, "tc3-holds-the-lineage")
neverSynced := asOfReadStore(fixture, "tc3-never-synced")
id := fixture.IssuePrefix + "-asof-tc3"
at := time.Now().UTC()
address := asOfReadMint(t, ctx, fixture, holds, id, at)
local, err := fixture.Resolve(ctx, holds, id, AsOfSelector{At: &at})
if err != nil {
t.Fatalf("Resolve on the store that holds the lineage: %v", err)
}
if local.Refusal != nil || local.Address != address {
t.Fatalf("Resolve on the store that holds the lineage = %+v, want it served from that store's own holdings (%s)", local, address)
}
remote, err := fixture.Resolve(ctx, neverSynced, id, AsOfSelector{At: &at})
if err != nil {
t.Fatalf("Resolve on a store that never received this lineage: %v", err)
}
if remote.Refusal == nil {
t.Fatalf("Resolve on a store that never received this lineage = %+v, want a Refusal: an as-of answer is complete for the answering store's own holdings, not a sibling's (TC3)", remote)
}
if remote.Refusal.Restriction != RestrictionUnknown {
t.Errorf("Refusal.Restriction on the never-synced store = %s, want RestrictionUnknown: no lineage knowledge is Unknown, not Gone (FR-06)", remote.Refusal.Restriction)
}
}
// --- fixture helpers -------------------------------------------------------
// asOfReadStore names a storeID namespaced by the fixture's IssuePrefix and
// tag, so cases that need more than one store (e.g. the TC3 local-
// completeness case) get independent ones.
func asOfReadStore(fixture AsOfReadFixture, tag string) string {
return fixture.IssuePrefix + "-asof-store-" + tag
}
// asOfReadMint mints a version for id on store at the given instant via
// fixture.MintAt, fataling the case if minting fails.
func asOfReadMint(t *testing.T, ctx context.Context, fixture AsOfReadFixture, store, id string, at time.Time) Address {
t.Helper()
address, err := fixture.MintAt(ctx, store, id, at)
if err != nil {
t.Fatalf("MintAt(%s, %s, %s): %v", store, id, at, err)
}
return address
}

View file

@ -37,6 +37,7 @@ go_test(
"e2e_export_test.go",
"e2e_gates_test.go",
"e2e_heartbeat_test.go",
"e2e_link_test.go",
"e2e_list_filters_test.go",
"e2e_list_page_edges_test.go",
"e2e_mol_test.go",

View file

@ -0,0 +1,137 @@
//go:build cgo
package bdhttp_test
import (
"encoding/json"
"strings"
"testing"
)
// TestE2E_LinkOverHTTP runs `bd link` through the real `bd` binary against an
// in-process `bd serve`.
//
// bd link writes through the DependencyEditor role (one addDependencies
// request), so it is served over http for any type a workspace spells, well-
// known or not: the server takes any 1-32 character type. Its own checks —
// a non-empty type of at most 32 characters — refuse before anything is
// written, and an edge that already exists with another type reports the
// typed conflict.
func TestE2E_LinkOverHTTP(t *testing.T) {
skipUnlessEmbeddedDolt(t)
bin := buildBD(t)
addr := startE2EServer(t)
proxyAddr, counter := startCountingProxy(t, addr)
f := newHTTPFixture(t, bin, proxyAddr)
t.Run("custom types are served", func(t *testing.T) {
for _, depType := range []string{"owned-by", "ships-in", "available-in", "excluded-from", "advances", "launches", "blocks"} {
from := f.create("link source " + depType)
to := f.create("link target " + depType)
counter.reset()
r := f.mustRun(nil, "link", from, to, "--type", depType, "--json")
var out map[string]any
if err := json.Unmarshal([]byte(strings.TrimSpace(r.stdout)), &out); err != nil {
t.Fatalf("bd link --json: %v\n%s", err, r.stdout)
}
if out["status"] != "added" || out["issue_id"] != from || out["depends_on_id"] != to || out["type"] != depType {
t.Errorf("bd link --type %s --json = %v, want added %s -> %s", depType, out, from, to)
}
adds := 0
for _, p := range counter.snapshot() {
if p == "POST /v0/beads/dependencies:add" {
adds++
}
}
if adds != 1 {
t.Errorf("bd link --type %s sent %d addDependencies requests, want exactly one: %v", depType, adds, counter.snapshot())
}
list := f.mustRun(nil, "dep", "list", from, "--json").stdout
if !depListHas(t, list, to, depType) {
t.Errorf("bd dep list %s does not show the %s edge to %s: %s", from, depType, to, list)
}
}
})
t.Run("text output names both issues", func(t *testing.T) {
from := f.create("text link source")
to := f.create("text link target")
r := f.mustRun(nil, "link", from, to, "--type", "owned-by")
if !strings.Contains(r.stdout, "Linked:") || !strings.Contains(r.stdout, "text link source") ||
!strings.Contains(r.stdout, "text link target") || !strings.Contains(r.stdout, "(owned-by)") {
t.Errorf("bd link output = %q, want the Linked line with both titles and the type", r.stdout)
}
})
t.Run("invalid types refuse before any write", func(t *testing.T) {
from := f.create("invalid link source")
to := f.create("invalid link target")
for _, depType := range []string{"", strings.Repeat("x", 33)} {
counter.reset()
r := f.run(nil, "link", from, to, "--type", depType)
if r.code == 0 {
t.Fatalf("bd link --type %q exited 0: %s", depType, r.stdout)
}
if !strings.Contains(r.stderr, "invalid dependency type") {
t.Errorf("bd link --type %q stderr = %s, want the invalid-type refusal", depType, r.stderr)
}
for _, p := range counter.snapshot() {
if !strings.HasPrefix(p, "GET ") {
t.Errorf("bd link --type %q wrote %s; the refusal must come before any write", depType, p)
}
}
}
if list := f.mustRun(nil, "dep", "list", from, "--json").stdout; depListHas(t, list, to, "") {
t.Errorf("a refused link left an edge %s -> %s: %s", from, to, list)
}
})
t.Run("an edge of another type is a typed conflict", func(t *testing.T) {
from := f.create("conflict source")
to := f.create("conflict target")
f.mustRun(nil, "link", from, to, "--type", "owned-by")
r := f.run(nil, "link", from, to, "--type", "ships-in")
if r.code == 0 {
t.Fatalf("bd link over an existing owned-by edge with ships-in exited 0: %s", r.stdout)
}
// The server answers the role's typed conflict as 409
// dependency_exists, which the client surfaces verbatim.
if !strings.Contains(r.stderr, "dependency_exists") || !strings.Contains(r.stderr, "different type") {
t.Errorf("conflict stderr = %s, want the typed dependency_exists conflict", r.stderr)
}
list := f.mustRun(nil, "dep", "list", from, "--json").stdout
if !depListHas(t, list, to, "owned-by") || depListHas(t, list, to, "ships-in") {
t.Errorf("the conflicting link changed the edge: %s", list)
}
// Re-asserting the same edge is idempotent.
f.mustRun(nil, "link", from, to, "--type", "owned-by")
})
}
// depListHas reports whether `bd dep list --json` lists an edge to target of
// depType (any type when depType is empty).
func depListHas(t *testing.T, out, target, depType string) bool {
t.Helper()
trimmed := strings.TrimSpace(out)
if trimmed == "" || trimmed == "null" {
return false
}
var rows []map[string]any
if err := json.Unmarshal([]byte(trimmed), &rows); err != nil {
t.Fatalf("parse bd dep list --json: %v\n%s", err, out)
}
for _, row := range rows {
if row["id"] != target && row["depends_on_id"] != target {
continue
}
if depType == "" {
return true
}
if row["dependency_type"] == depType || row["type"] == depType {
return true
}
}
return false
}

View file

@ -53,8 +53,15 @@ func TestE2E_PerCommandRequestBudget(t *testing.T) {
args []string
}{
{"ready", 2, []string{"ready", "--json"}},
// The limit hides rows, and without BD_JSON_ENVELOPE nothing
// prints their count: one listing, no ready:count after it.
{"ready --limit 1", 2, []string{"ready", "--json", "--limit", "1"}},
{"list", 4, []string{"list", "--json"}},
{"show", 1, []string{"show", target, "--json"}},
// The first ready learned the server's external-dependency
// policy from the handshake; a later process reads it from the
// policy cache instead of fetching the context again.
{"ready, policy cached", 1, []string{"ready", "--json"}},
{"create", 2, []string{"create", "budget created", "-t", "task", "--json"}},
{"update --append-notes", 3, []string{"update", target, "--append-notes", "more", "--json"}},
{"update --status", 3, []string{"update", target, "--status", "in_progress", "--json"}},

View file

@ -99,6 +99,18 @@ func configuredBackendUnavailable(backend, beadsDir string, cfg *configfile.Conf
}
}
// UnsupportedWorkspaceFormatError is returned by OpenBestAvailable,
// OpenBestAvailableWith, OpenFromConfig and OpenGated when the workspace
// declares a data model this build cannot open: a metadata.json graph_mode
// other than "dependency", such as the "link" workspaces graph-preview builds
// of bd write, or the .beads/graph-preview-format marker those builds write
// beside it (FormatMarker), whatever the metadata says. Nothing was opened,
// created or modified. Match it with errors.As to read BeadsDir, GraphMode and
// FormatMarker; the bd CLI refuses the same workspaces with exit code 16.
// Aliased here because internal/configfile is unimportable outside this
// module.
type UnsupportedWorkspaceFormatError = configfile.UnsupportedWorkspaceFormatError
// Transaction provides atomic multi-operation support within a database transaction.
// Use Storage.RunInTransaction() to obtain a Transaction instance.
type Transaction = beads.Transaction
@ -369,6 +381,9 @@ func Open(ctx context.Context, dbPath string) (Storage, error) {
// name configuration.
// beadsDir is the path to the .beads directory.
func OpenFromConfig(ctx context.Context, beadsDir string) (Storage, error) {
if err := configfile.CheckDiscoveredWorkspaceFormat(beadsDir); err != nil {
return nil, err
}
return dolt.NewFromConfigWithOptions(ctx, beadsDir, &dolt.Config{CreateIfMissing: true})
}
@ -403,6 +418,11 @@ func OpenFromConfig(ctx context.Context, beadsDir string) (Storage, error) {
// operation holds one exclusively; zero means fail fast. A busy gate is
// reported as ErrGateBusy (match with errors.Is).
func OpenGated(ctx context.Context, beadsDir string, wait time.Duration) (Storage, error) {
// Before the gates: taking them creates gate files in and beside a
// workspace this build must leave untouched.
if err := configfile.CheckDiscoveredWorkspaceFormat(beadsDir); err != nil {
return nil, err
}
wsGate, err := workspacegate.ForWorkspace(beadsDir)
if err != nil {
return nil, err

View file

@ -46,6 +46,11 @@ func OpenBestAvailable(ctx context.Context, beadsDir string) (Storage, error) {
// typed refusal (the matching ErrXWithoutOpenWith sentinel), never a silent
// open with the field ignored.
func OpenBestAvailableWith(ctx context.Context, beadsDir string, opts OpenOptions) (Storage, error) {
// Before Load, which can migrate a legacy config.json, and before any
// backend is chosen, as the CLI store factories do.
if err := configfile.CheckDiscoveredWorkspaceFormat(beadsDir); err != nil {
return nil, err
}
cfg, err := configfile.Load(beadsDir)
if err != nil {
return nil, fmt.Errorf("loading storage metadata: %w", err)

View file

@ -32,6 +32,11 @@ func OpenBestAvailable(ctx context.Context, beadsDir string) (Storage, error) {
// rationale; behavior here is identical except that embedded Dolt is
// unavailable without CGO.
func OpenBestAvailableWith(ctx context.Context, beadsDir string, opts OpenOptions) (Storage, error) {
// Before Load, which can migrate a legacy config.json, and before any
// backend is chosen, as the CLI store factories do.
if err := configfile.CheckDiscoveredWorkspaceFormat(beadsDir); err != nil {
return nil, err
}
cfg, err := configfile.Load(beadsDir)
if err != nil {
return nil, fmt.Errorf("loading storage metadata: %w", err)

View file

@ -38,6 +38,10 @@ Which tier a test belongs in, and which command runs it, is decided by
6. Regenerate the CLI reference with `scripts/generate-cli-docs.sh`;
`scripts/check-cli-docs-drift.sh` fails a PR whose command-surface change
leaves the generated docs stale.
7. Regenerate the command-surface goldens and review the testdata diff:
`BD_UPDATE_GOLDEN=1 CGO_ENABLED=1 go test -tags gms_pure_go ./cmd/bd -run '^TestCommand(Tree|Help)Golden$'`.
`TestCommandTreeGolden` fails on any added, removed or reworded command or
flag until you do.
Prefer a flag on an existing command over a new command, and route
recovery/repair operations to `bd doctor --fix`; see the CLI design principles
@ -85,6 +89,9 @@ no linter enforces it).
or serialize the call under `stdioMutex`.
- `TestCorpusGolden` (`protocol/`) — no unreviewed change to the `--json`
wire shapes.
- `TestCommandTreeGolden` and `TestCommandHelpGolden` — no unreviewed change
to the command tree (every command and flag, hidden ones included) or to
the pinned `--help` output in `testdata/command_tree/`.
Fresh-workspace command fixtures call `isolateBeadsDirForTest(t)` before
setup or dispatch and must not use `t.Parallel()`.

View file

@ -375,9 +375,13 @@ go_library(
"version.go",
"version_proxied_server.go",
"version_tracking.go",
"versioned_history.go",
"versioned_history_switch.go",
"versions.go",
"where.go",
"wisp.go",
"wisp_proxied_server.go",
"workspace_format_guard.go",
"workspace_gate.go",
"worktree.go",
"worktree_cmd.go",
@ -418,6 +422,7 @@ go_library(
"//internal/httpapi",
"//internal/httpclient",
"//internal/httpclient/wire",
"//internal/initprocs",
"//internal/jira",
"//internal/linear",
"//internal/lockfile",
@ -463,6 +468,7 @@ go_library(
"//internal/utils",
"//internal/validation",
"//internal/versioncheck",
"//internal/versionedhistory",
"//internal/workapi",
"//internal/workspacegate",
"//internal/worktreeremove",
@ -543,6 +549,7 @@ go_test(
"actor_test.go",
"ado_roundtrip_test.go",
"ado_test.go",
"agent_artifacts_embedded_test.go",
"agent_hook_test.go",
"assign_fence_embedded_test.go",
"assign_fence_proxied_test.go",
@ -600,6 +607,7 @@ go_test(
"cobra_flag_reset_test.go",
"codex_hook_test.go",
"command_telemetry_test.go",
"command_tree_golden_test.go",
"comment_promote_embedded_test.go",
"comment_proxied_integration_test.go",
"comment_reserved_word_test.go",
@ -710,6 +718,8 @@ go_test(
"dependency_hierarchy_embedded_test.go",
"diff_embedded_test.go",
"directory_flag_test.go",
"discovery_refusal_pins_embedded_test.go",
"discovery_refusal_pins_test.go",
"doctor_backend_guard_test.go",
"doctor_check_gate_test.go",
"doctor_context_test.go",
@ -751,6 +761,7 @@ go_test(
"dolt_remote_add_test.go",
"dolt_remote_adopt_test.go",
"dolt_remote_json_test.go",
"dolt_remote_origin_guard_embedded_test.go",
"dolt_remote_origin_guard_test.go",
"dolt_remote_remove_proxied_integration_test.go",
"dolt_remote_reset_data_embedded_test.go",
@ -800,6 +811,7 @@ go_test(
"find_duplicates_test.go",
"flags_test.go",
"flatten_embedded_test.go",
"format_json_alias_embedded_test.go",
"formula_fixture_proxied_test.go",
"formula_help_test.go",
"formula_primitives_test.go",
@ -832,6 +844,8 @@ go_test(
"graph_apply_thread_spawner_embedded_test.go",
"graph_embedded_test.go",
"graph_export_test.go",
"graph_mode_admission_e2e_test.go",
"graph_mode_dependency_embedded_test.go",
"graph_proxied_integration_test.go",
"graph_test.go",
"graph_visual_test.go",
@ -861,6 +875,7 @@ go_test(
"identity_preview_refusal_test.go",
"if_revision_embedded_test.go",
"if_revision_gc_matcher_embedded_test.go",
"if_revision_ordinary_cas_embedded_test.go",
"if_revision_proxied_close_delete_test.go",
"if_revision_proxied_integration_test.go",
"if_revision_reassign_fence_embedded_test.go",
@ -883,10 +898,13 @@ go_test(
"info_kv_exclusion_test.go",
"info_proxied_integration_test.go",
"info_test.go",
"init_agent_test.go",
"init_cancel_e2e_test.go",
"init_commit_test.go",
"init_embedded_test.go",
"init_explicit_beads_dir_embedded_test.go",
"init_external_autostart_test.go",
"init_external_message_test.go",
"init_gateway_test.go",
"init_git_bootstrap_routing_test.go",
"init_guard_force_e2e_test.go",
@ -935,6 +953,8 @@ go_test(
"legacy_upgrade_guard_e2e_test.go",
"legacy_upgrade_guard_empty_root_test.go",
"legacy_upgrade_guard_external_server_test.go",
"legacy_upgrade_guard_init_flag_e2e_test.go",
"legacy_upgrade_guard_init_flag_test.go",
"legacy_upgrade_guard_test.go",
"legacy_upgrade_guard_witness_test.go",
"linear_roundtrip_test.go",
@ -1086,6 +1106,7 @@ go_test(
"ready_embedded_test.go",
"ready_explain_ids_test.go",
"ready_input_test.go",
"ready_json_no_total_test.go",
"ready_max_rows_proxied_test.go",
"ready_max_rows_test.go",
"ready_proxied_integration_test.go",
@ -1148,6 +1169,7 @@ go_test(
"serve_delete_proxied_integration_test.go",
"serve_dependencies_proxied_integration_test.go",
"serve_edge_counts_proxied_integration_test.go",
"serve_graph_mode_env_test.go",
"serve_inprocess_test.go",
"serve_list_sort_proxied_integration_test.go",
"serve_proxied_integration_test.go",
@ -1290,6 +1312,14 @@ go_test(
"version_embedded_test.go",
"version_test.go",
"version_tracking_test.go",
"versioned_history_construction_test.go",
"versioned_history_e2e_test.go",
"versioned_history_serve_e2e_test.go",
"versioned_history_switch_scan_embedded_test.go",
"versioned_history_switch_scan_proxied_integration_test.go",
"versioned_history_switch_test.go",
"versions_switch_embedded_test.go",
"versions_test.go",
"where_cgo_test.go",
"where_embedded_test.go",
"where_test.go",
@ -1299,6 +1329,7 @@ go_test(
"wisp_gc_purge_closed_embedded_test.go",
"wisp_proxied_integration_test.go",
"wisp_test.go",
"workspace_format_guard_test.go",
"workspace_gate_test.go",
"workspace_identity_test.go",
"worktree_cmd_test.go",
@ -1319,6 +1350,7 @@ go_test(
":go_srcs",
":preflight_go_fixture",
"//:bd_test_files",
"//:go_srcs",
"//cmd/bd/doctor:go_srcs",
"//cmd/bd/doctor/fix:go_srcs",
"//internal/storage/embeddeddolt/cmd:go_srcs",
@ -1354,6 +1386,7 @@ go_test(
"//internal/httpclient",
"//internal/httpclient/encode",
"//internal/httpclient/wire",
"//internal/initprocs",
"//internal/linear",
"//internal/metrics",
"//internal/migration",
@ -1385,6 +1418,7 @@ go_test(
"//internal/storage/uow",
"//internal/storage/versioncontrolops",
"//internal/telemetry",
"//internal/templates/agents",
"//internal/testutil",
"//internal/testutil/bazeltest",
"//internal/testutil/credentialcmd",
@ -1457,7 +1491,7 @@ go_test(
)
# bd_embedded_test and bd_embedded_part2_test run the TestEmbedded* functions
# of *_embedded_test.go between them: the manifest's 100-shard block
# of cmd/bd's _test.go files between them: the manifest's 100-shard block
# (duration-balanced; see scripts/ci/embedded_cmd_test_durations.json) is
# more than Bazel's 50-shard cap per rule, so bd_embedded_test runs its
# shards 1-50 and bd_embedded_part2_test its shards 51-100

View file

@ -0,0 +1,310 @@
//go:build cgo
package main
import (
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"github.com/steveyegge/beads/internal/templates/agents"
)
// TestEmbeddedInitAgentArtifactsGolden pins the Claude agent artifacts a real
// `bd init` writes — .claude/settings.json with its hook events and commands,
// CLAUDE.md and AGENTS.md with their managed sections — and what
// `bd setup claude --check`, `--remove` and a reinstall then report and leave
// behind, through the bd binary. Each scenario is a transcript golden under
// testdata/agent_artifacts/, so a change to any artifact or outcome (a new
// hook event, a changed command, new template text and its hash) shows up as
// a reviewed golden diff.
//
// A managed section is shown by its BEGIN marker line (profile and hash) and a
// pointer to the internal/templates/agents golden that pins its bytes
// (TestManagedSectionGolden), after checking the file holds exactly that
// section; one that matches no rendered variant is shown in full. The
// in-process `bd setup claude` scenarios are pinned by
// TestClaudeSetupArtifactsGolden in cmd/bd/setup.
//
// The scenarios run a direct (embedded) bd init with no Dolt remote. Not
// pinned here: a proxied-server bd init, which installs no Codex section and
// decides HasRemote from its own remote URL; a bd init with a remote, which
// renders the managed section's with-remote variant; and the Cursor files.
// AGENTS.md is shown in full apart from its managed section, so a change to
// its wrapper text or its Codex section can pass the cmd/bd/setup and
// internal/templates/agents tests and fail only here.
//
// bd runs with HOME outside the project, so an artifact written to the home
// directory instead of the project shows up under $HOME.
//
// Regenerate with
//
// BEADS_TEST_EMBEDDED_DOLT=1 BD_UPDATE_GOLDEN=1 go test -tags gms_pure_go ./cmd/bd/ -run TestEmbeddedInitAgentArtifactsGolden
func TestEmbeddedInitAgentArtifactsGolden(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)
scenarios := []struct {
name string
initArgs []string
steps [][]string
}{
{
name: "init-default",
initArgs: []string{"--prefix", "aa"},
steps: [][]string{
{"setup", "claude", "--check"},
{"setup", "claude"},
{"setup", "claude", "--remove"},
{"setup", "claude", "--check"},
{"setup", "claude"},
{"setup", "claude", "--check"},
},
},
{
name: "init-agents-profile-full",
initArgs: []string{"--prefix", "ab", "--agents-profile", "full"},
steps: [][]string{
{"setup", "claude", "--check"},
},
},
}
for _, sc := range scenarios {
t.Run(sc.name, func(t *testing.T) {
t.Parallel()
// bdInit, with HOME in a directory of its own.
dir, home := t.TempDir(), t.TempDir()
initGitRepoAt(t, dir)
database, seeded := seededInitDatabase(sc.initArgs)
if seeded {
seedEmbeddedSchema(t, dir, database)
}
initArgs := append([]string{"init", "--quiet"}, sc.initArgs...)
if stdout, stderr, exitCode := runAgentArtifactCommand(t, bd, dir, home, initArgs...); exitCode != 0 {
t.Fatalf("bd %s: exit %d\nstdout:\n%s\nstderr:\n%s", strings.Join(initArgs, " "), exitCode, stdout, stderr)
}
if seeded {
requireSeededEmbeddedInit(t, filepath.Join(dir, ".beads"), database)
}
var transcript strings.Builder
fmt.Fprintf(&transcript, "# bd init agent artifact transcript: %s\n", sc.name)
fmt.Fprintf(&transcript, "# Regenerate with BEADS_TEST_EMBEDDED_DOLT=1 BD_UPDATE_GOLDEN=1 go test -tags gms_pure_go ./cmd/bd/ -run TestEmbeddedInitAgentArtifactsGolden\n")
fmt.Fprintf(&transcript, "\n=== bd %s\n", strings.Join(initArgs, " "))
previous := map[string]string{}
writeAgentArtifactChanges(t, &transcript, dir, home, previous)
for _, args := range sc.steps {
stdout, stderr, exitCode := runAgentArtifactCommand(t, bd, dir, home, args...)
fmt.Fprintf(&transcript, "\n=== bd %s\n", strings.Join(args, " "))
fmt.Fprintf(&transcript, "exit: %d\n", exitCode)
writeAgentArtifactBlock(&transcript, "stdout", normalizeAgentArtifactOutput(stdout, dir, home))
writeAgentArtifactBlock(&transcript, "stderr", normalizeAgentArtifactOutput(stderr, dir, home))
writeAgentArtifactChanges(t, &transcript, dir, home, previous)
}
assertAgentArtifactGolden(t, filepath.Join("testdata", "agent_artifacts", sc.name+".golden"), transcript.String())
})
}
}
// agentArtifactPaths are the Claude agent artifacts bd init and bd setup
// claude write in a project ($PROJECT), and those in the home directory
// ($HOME): the $HOME/.claude/ files a global install writes, and the
// $HOME/CLAUDE.md an older --global run from $HOME wrote.
var agentArtifactPaths = []string{
"$PROJECT/.claude/settings.json",
"$PROJECT/.claude/settings.local.json",
"$PROJECT/AGENTS.md",
"$PROJECT/CLAUDE.md",
"$HOME/.claude/settings.json",
"$HOME/.claude/CLAUDE.md",
"$HOME/CLAUDE.md",
}
// agentArtifactManagedSections maps each managed section bd renders to the
// internal/templates/agents golden file that pins its bytes.
var agentArtifactManagedSections = []struct {
golden string
profile agents.Profile
opts agents.RenderOpts
}{
{golden: "managed-section-minimal.md", profile: agents.ProfileMinimal, opts: agents.RenderOpts{HasRemote: true}},
{golden: "managed-section-minimal-no-remote.md", profile: agents.ProfileMinimal, opts: agents.RenderOpts{}},
{golden: "managed-section-minimal-user.md", profile: agents.ProfileMinimal, opts: agents.UserLevelRenderOpts()},
{golden: "managed-section-full.md", profile: agents.ProfileFull, opts: agents.RenderOpts{HasRemote: true}},
{golden: "managed-section-full-no-remote.md", profile: agents.ProfileFull, opts: agents.RenderOpts{}},
{golden: "managed-section-full-user.md", profile: agents.ProfileFull, opts: agents.UserLevelRenderOpts()},
}
// elideAgentArtifactManagedSection replaces the body of a managed section
// that is byte-identical to a rendered variant with a pointer to that
// variant's golden, keeping the BEGIN marker line (profile and hash) and the
// END marker.
func elideAgentArtifactManagedSection(content string) string {
const endMarker = "<!-- END BEADS INTEGRATION -->\n"
begin := strings.Index(content, "<!-- BEGIN BEADS INTEGRATION")
if begin < 0 {
return content
}
rel := strings.Index(content[begin:], endMarker)
if rel < 0 {
return content
}
end := begin + rel + len(endMarker)
section := content[begin:end]
for _, v := range agentArtifactManagedSections {
if section == agents.RenderSectionWithOpts(v.profile, v.opts) {
marker, _, _ := strings.Cut(section, "\n")
return content[:begin] + marker + "\n[managed section body: byte-identical to internal/templates/agents/testdata/" + v.golden + "]\n" + endMarker + content[end:]
}
}
return content
}
// runAgentArtifactCommand runs bd in dir with HOME at home and returns its
// stdout, stderr and exit code.
func runAgentArtifactCommand(t *testing.T, bd, dir, home string, args ...string) (stdout, stderr string, exitCode int) {
t.Helper()
cmd := exec.Command(bd, args...)
cmd.Dir = dir
cmd.Env = agentArtifactEnv(dir, home)
outBuf, errBuf, err := runCommandBuffers(t, cmd)
if err != nil {
var exitErr *exec.ExitError
if !errors.As(err, &exitErr) {
t.Fatalf("bd %s: %v", strings.Join(args, " "), err)
}
exitCode = exitErr.ExitCode()
}
return outBuf.String(), errBuf.String(), exitCode
}
// agentArtifactEnv is bdEnv(dir) with HOME at home and without the caller's
// BD_OTEL_* and OTEL_* variables: bd warns on stderr about a legacy BD_OTEL_*
// one whether or not telemetry is on, and the transcript pins stderr byte for
// byte. (clearTelemetryEnv cannot be used: it calls t.Setenv, and these tests
// run in parallel.)
func agentArtifactEnv(dir, home string) []string {
var env []string
for _, e := range bdEnv(dir) {
if strings.HasPrefix(e, "BD_OTEL_") || strings.HasPrefix(e, "OTEL_") || strings.HasPrefix(e, "HOME=") {
continue
}
env = append(env, e)
}
return append(env, "HOME="+home)
}
// writeAgentArtifactChanges appends every artifact created, modified or
// deleted since previous (which it then updates), with its contents.
func writeAgentArtifactChanges(t *testing.T, b *strings.Builder, dir, home string, previous map[string]string) {
t.Helper()
roots := strings.NewReplacer("$PROJECT", dir, "$HOME", home)
changed := false
for _, path := range agentArtifactPaths {
data, err := os.ReadFile(filepath.FromSlash(roots.Replace(path)))
before, existed := previous[path]
switch {
case os.IsNotExist(err):
if existed {
fmt.Fprintf(b, "--- files: deleted %s\n", path)
delete(previous, path)
changed = true
}
case err != nil:
t.Fatalf("read %s: %v", path, err)
case !existed || before != string(data):
verb := "created"
if existed {
verb = "modified"
}
shown := string(data)
if strings.HasSuffix(path, ".md") {
shown = elideAgentArtifactManagedSection(shown)
}
writeAgentArtifactBlock(b, fmt.Sprintf("files: %s %s", verb, path), shown)
previous[path] = string(data)
changed = true
}
}
if !changed {
b.WriteString("--- files: unchanged\n")
}
}
// writeAgentArtifactBlock appends a titled block, marking empty content and a
// missing trailing newline so neither is lost in the golden.
func writeAgentArtifactBlock(b *strings.Builder, title, content string) {
fmt.Fprintf(b, "--- %s\n", title)
switch {
case content == "":
b.WriteString("(empty)\n")
case !strings.HasSuffix(content, "\n"):
b.WriteString(content)
b.WriteString("\n(no newline at end of file)\n")
default:
b.WriteString(content)
}
}
// normalizeAgentArtifactOutput replaces the project and home directories (as
// given and with symlinks resolved, since bd reports the paths it sees) with
// $PROJECT and $HOME and uses forward slashes, so the transcript is the same
// on every host.
func normalizeAgentArtifactOutput(s, dir, home string) string {
for _, root := range []struct{ path, label string }{{dir, "$PROJECT"}, {home, "$HOME"}} {
if resolved, err := filepath.EvalSymlinks(root.path); err == nil && resolved != root.path {
s = strings.ReplaceAll(s, resolved, root.label)
}
s = strings.ReplaceAll(s, root.path, root.label)
}
if filepath.Separator != '/' {
s = strings.ReplaceAll(s, string(filepath.Separator), "/")
}
return s
}
// assertAgentArtifactGolden compares got with the golden file at path, or
// rewrites the file when BD_UPDATE_GOLDEN=1.
func assertAgentArtifactGolden(t *testing.T, path, got string) {
t.Helper()
if os.Getenv("BD_UPDATE_GOLDEN") == "1" {
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
t.Fatalf("mkdir %s: %v", filepath.Dir(path), err)
}
if err := os.WriteFile(path, []byte(got), 0o644); err != nil {
t.Fatalf("write golden %s: %v", path, err)
}
t.Logf("updated golden %s", path)
return
}
want, err := os.ReadFile(path)
if err != nil {
t.Fatalf("read golden %s (regenerate with BD_UPDATE_GOLDEN=1): %v", path, err)
}
if got == string(want) {
return
}
wantLines, gotLines := strings.Split(string(want), "\n"), strings.Split(got, "\n")
line := func(lines []string, i int) string {
if i >= len(lines) {
return "(end of output)"
}
return fmt.Sprintf("%q", lines[i])
}
i := 0
for i < len(wantLines) && i < len(gotLines) && wantLines[i] == gotLines[i] {
i++
}
t.Errorf("bd init agent artifacts drifted from %s (regenerate with BD_UPDATE_GOLDEN=1 if intended)\nfirst difference at line %d:\n want: %s\n got: %s\n--- got ---\n%s", path, i+1, line(wantLines, i), line(gotLines, i), got)
}

View file

@ -43,7 +43,7 @@ func bdRunOK(t *testing.T, bd, dir string, args ...string) string {
return string(out)
}
// TestReassignFenceCLI drives the bd-98s5c live-claim reassign fence
// TestEmbeddedReassignFenceCLI drives the bd-98s5c live-claim reassign fence
// end-to-end: plain `bd update -a` and `bd assign` were the last unfenced
// cross-actor takeover path (--claim, unclaim, and close all refuse without
// --force). The fence must refuse ONLY the silent steamroll — a different
@ -51,7 +51,7 @@ func bdRunOK(t *testing.T, bd, dir string, args ...string) string {
// leave routine dispatch untouched: open-bead reassigns, self-edits,
// idempotent re-asserts, pool-alias takes, and holder-aware --if-assignee
// transfers all proceed without --force.
func TestReassignFenceCLI(t *testing.T) {
func TestEmbeddedReassignFenceCLI(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")
}

View file

@ -12,10 +12,23 @@ import (
// the rejection inspects it (read-only) so a workspace that already holds a Dolt
// database is told to fix the stale "backend" value rather than to export and
// reinitialize. Pass "" only where there is genuinely no workspace directory.
//
// It also refuses metadata that declares a workspace format this build cannot
// open (checkWorkspaceFormat). Command admission refuses those first, and the
// store factories check before their migrating configfile.Load
// (checkDiscoveredWorkspaceFormat), so here it backs up any other caller that
// validates metadata it loaded itself. It returns early for a nil cfg, so that
// backstop covers the graph format marker only when metadata was loaded; a
// caller that may have none must check beadsDir with
// checkDiscoveredWorkspaceFormat or command admission first, as every caller
// does today.
func validateConfiguredBackend(cfg *configfile.Config, beadsDir string) error {
if cfg == nil {
return nil
}
if err := checkWorkspaceFormat(cfg, beadsDir); err != nil {
return err
}
if backends.Registered(cfg.Backend) {
return nil
}
@ -80,14 +93,16 @@ func openStoreError(backendName string, err error) error {
return fmt.Errorf("failed to open database: %w", err)
}
// backendNameForErrorFraming best-effort loads metadata.json to learn which
// backendNameForErrorFraming best-effort reads metadata.json to learn which
// backend a failed open was for, so a caller that does not already have cfg
// in scope (for example direct mode's single-shot store-open) can still give
// openStoreError the name it needs. A failure to even read the config
// degrades to "" — openStoreError's default, Dolt-shaped framing — rather
// than compounding one error with another.
// than compounding one error with another. It reads with LoadForDiscovery:
// the open it frames may have just refused the workspace, and
// configfile.Load would migrate a legacy config.json into metadata.json.
func backendNameForErrorFraming(beadsDir string) string {
cfg, err := configfile.Load(beadsDir)
cfg, err := configfile.LoadForDiscovery(beadsDir)
if err != nil || cfg == nil {
return ""
}
@ -95,6 +110,12 @@ func backendNameForErrorFraming(beadsDir string) string {
}
func loadDoltBackendConfig(beadsDir string) (*configfile.Config, error) {
// Refuse a workspace format this build cannot open before configfile.Load,
// which would otherwise migrate a legacy config.json into metadata.json
// before requireDoltBackend's own format check could refuse it.
if err := checkDiscoveredWorkspaceFormat(beadsDir); err != nil {
return nil, err
}
cfg, err := configfile.Load(beadsDir)
if err != nil {
return nil, fmt.Errorf("loading config: %w", err)

View file

@ -53,6 +53,8 @@ After adding, run 'bd backup sync' to push your data.`,
SilenceUsage: true,
SilenceErrors: true,
RunE: func(cmd *cobra.Command, args []string) error {
CheckReadonly("backup init")
evt := metrics.NewCommandEvent("backup-init")
defer func() {
if c := metrics.Global(); c != nil {
@ -134,6 +136,8 @@ Run 'bd backup init <path>' first to configure a destination.`,
SilenceUsage: true,
SilenceErrors: true,
RunE: func(cmd *cobra.Command, args []string) error {
CheckReadonly("backup sync")
evt := metrics.NewCommandEvent("backup-sync")
defer func() {
if c := metrics.Global(); c != nil {
@ -439,6 +443,8 @@ backup configuration. The backup data at the destination is not deleted.`,
SilenceUsage: true,
SilenceErrors: true,
RunE: func(cmd *cobra.Command, args []string) error {
CheckReadonly("backup remove")
evt := metrics.NewCommandEvent("backup-remove")
defer func() {
if c := metrics.Global(); c != nil {

View file

@ -217,3 +217,78 @@ func TestEmbeddedBackupConcurrent(t *testing.T) {
t.Error("backup destination should exist after concurrent syncs")
}
}
// TestEmbeddedBackupRestoreStrictReadonly pins the refusal of a strict
// --readonly restore. A restore replaces the store, so CheckReadonly must stop
// it with the standard message before the command takes the exclusive workspace
// gate. Embedded mode used to be stopped only by the storage layer
// ("embeddeddolt: store is read-only"), after the gate had already left its
// holder files in the workspace. The control proves the fixture really does
// restore when --readonly is not asked for, so "the store is unchanged" below
// cannot be vacuous.
func TestEmbeddedBackupRestoreStrictReadonly(t *testing.T) {
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded dolt backup tests")
}
t.Parallel()
bd := buildEmbeddedBD(t)
// newWorkspace returns a workspace whose live store holds one issue its
// backup does not (three against two), so a restore that really ran shows up
// as a changed issue count. Each case gets its own: a restore that runs
// replaces the store and would hide a leak from the next.
newWorkspace := func(t *testing.T, prefix string) (dir, backupDir string) {
t.Helper()
dir, _, _ = bdInit(t, bd, "--prefix", prefix)
bdCreateSilent(t, bd, dir, "issue in the backup A")
bdCreateSilent(t, bd, dir, "issue in the backup B")
backupDir = filepath.Join(t.TempDir(), "dolt-backup")
if err := os.MkdirAll(backupDir, 0o750); err != nil {
t.Fatal(err)
}
bdBackup(t, bd, dir, "init", "file://"+backupDir)
bdBackup(t, bd, dir, "sync")
bdCreateSilent(t, bd, dir, "issue created after the backup")
return dir, backupDir
}
t.Run("control_restore_without_readonly", func(t *testing.T) {
dir, backupDir := newWorkspace(t, "rrctl")
stdout, stderr, code := runBDMigrationFreeze(t, bd, dir, "backup", "restore", "--force", backupDir)
if code != 0 {
t.Fatalf("restore without --readonly exited %d\nstdout:\n%s\nstderr:\n%s", code, stdout, stderr)
}
if !strings.Contains(stdout, "Restore complete") {
t.Errorf("stdout is missing %q:\n%s", "Restore complete", stdout)
}
if got := len(bdListJSON(t, bd, dir)); got != 2 {
t.Errorf("issue count after a real restore = %d, want 2: the backup holds two issues and the live store held three", got)
}
})
for _, tc := range []struct {
name string
prefix string
flags []string
}{
{"readonly", "rrro", []string{"--readonly"}},
{"readonly_sandbox", "rrrosb", []string{"--readonly", "--sandbox"}},
} {
t.Run(tc.name, func(t *testing.T) {
dir, backupDir := newWorkspace(t, tc.prefix)
before := snapshotWorkspace(t, dir)
args := append(append([]string{}, tc.flags...), "backup", "restore", "--force", backupDir)
stdout, stderr, code := runBDMigrationFreeze(t, bd, dir, args...)
assertStrictReadonlyRestoreRefused(t, stdout, stderr, code)
assertWorkspaceUnchanged(t, dir, before)
if got := len(bdListJSON(t, bd, dir)); got != 3 {
t.Errorf("issue count after the refused restore = %d, want 3: the restore replaced the store", got)
}
})
}
}

View file

@ -34,6 +34,8 @@ To initialize and restore in one step, use: bd init && bd backup restore`,
SilenceUsage: true,
SilenceErrors: true,
RunE: func(cmd *cobra.Command, args []string) error {
CheckReadonly("backup restore")
evt := metrics.NewCommandEvent("backup-restore")
defer func() {
if c := metrics.Global(); c != nil {

View file

@ -4,14 +4,22 @@ package main
import (
"context"
"encoding/json"
"fmt"
"os"
"path/filepath"
"slices"
"sort"
"strings"
"testing"
"time"
"github.com/steveyegge/beads/internal/beads"
"github.com/steveyegge/beads/internal/configfile"
"github.com/steveyegge/beads/internal/git"
"github.com/steveyegge/beads/internal/storage/dolt"
"github.com/steveyegge/beads/internal/testutil"
"github.com/steveyegge/beads/internal/types"
)
func TestBackupRestoreMissingDir(t *testing.T) {
@ -84,3 +92,257 @@ func TestSyncProjectIDFromDB_NoWorkspaceUsesActiveWorkspaceError(t *testing.T) {
t.Fatalf("syncProjectIDFromDB should not create local .beads, stat err = %v", statErr)
}
}
// strictReadonlyRestoreRefusal is the line CheckReadonly prints when a write
// command is run under strict --readonly.
const strictReadonlyRestoreRefusal = "Error: operation 'backup restore' is not allowed in read-only mode\n"
// assertStrictReadonlyRestoreRefused checks one refused `bd --readonly backup
// restore` run: the standard CheckReadonly refusal (text and exit code), nothing
// on stdout, and none of the storage-layer message that embedded mode gives when
// the command gets past CheckReadonly and opens the store.
func assertStrictReadonlyRestoreRefused(t *testing.T, stdout, stderr string, code int) {
t.Helper()
if code != 1 {
t.Errorf("exit code = %d, want 1\nstdout:\n%s\nstderr:\n%s", code, stdout, stderr)
}
if !strings.Contains(stderr, strictReadonlyRestoreRefusal) {
t.Errorf("stderr is missing the standard refusal %q:\n%s", strictReadonlyRestoreRefusal, stderr)
}
if strings.Contains(stderr, "embeddeddolt: store is read-only") {
t.Errorf("stderr carries the storage-layer refusal, so the command opened the store before being refused:\n%s", stderr)
}
if strings.TrimSpace(stdout) != "" {
t.Errorf("stdout should be empty when the restore is refused, got:\n%s", stdout)
}
}
// workspaceSnapshot is what a refused command must leave alone: the entries of
// the project directory (the workspace gate file and its holder sidecar sit
// beside .beads, not in it) and everything below .beads, content included.
type workspaceSnapshot struct {
projectEntries []string
beads readonlyTreeSnapshot
}
func snapshotWorkspace(t *testing.T, dir string) workspaceSnapshot {
t.Helper()
entries, err := os.ReadDir(dir)
if err != nil {
t.Fatal(err)
}
names := make([]string, 0, len(entries))
for _, e := range entries {
names = append(names, e.Name())
}
return workspaceSnapshot{
projectEntries: names,
beads: snapshotReadonlyTree(t, filepath.Join(dir, ".beads")),
}
}
// assertWorkspaceUnchanged fails, naming each path, when the workspace under dir
// no longer matches a snapshot taken before a refused command.
func assertWorkspaceUnchanged(t *testing.T, dir string, before workspaceSnapshot) {
t.Helper()
after := snapshotWorkspace(t, dir)
var diffs []string
for _, name := range before.projectEntries {
if !slices.Contains(after.projectEntries, name) {
diffs = append(diffs, "removed: "+name)
}
}
for _, name := range after.projectEntries {
if !slices.Contains(before.projectEntries, name) {
diffs = append(diffs, "created: "+name)
}
}
for path, want := range before.beads.Entries {
switch got, ok := after.beads.Entries[path]; {
case !ok:
diffs = append(diffs, "removed: .beads/"+path)
case got != want:
diffs = append(diffs, "changed: .beads/"+path)
}
}
for path := range after.beads.Entries {
if _, ok := before.beads.Entries[path]; !ok {
diffs = append(diffs, "created: .beads/"+path)
}
}
if len(diffs) == 0 {
return
}
sort.Strings(diffs)
const show = 20
if len(diffs) > show {
diffs = append(diffs[:show], fmt.Sprintf("... and %d more", len(diffs)-show))
}
t.Errorf("the refused restore changed the workspace:\n%s", strings.Join(diffs, "\n"))
}
// TestBackupRestoreStrictReadonlyServerMode is the server-mode counterpart of
// TestEmbeddedBackupRestoreStrictReadonly. Server mode is where the missing
// refusal mattered: no storage layer stops a server connection, so a
// `bd --readonly backup restore --force` ran to the end and replaced the store.
// It drives the built bd as a subprocess because CheckReadonly exits the
// process. Both the fixture's backup and the restore run inside the Dolt
// server, against the same path on the server's own filesystem, so a local
// and a containerized test server both serve.
func TestBackupRestoreStrictReadonlyServerMode(t *testing.T) {
if testDoltServerPort == 0 {
t.Skip("Dolt test server not available")
}
if testutil.DoltContainerCrashed() {
t.Skipf("Dolt test server crashed: %v", testutil.DoltContainerCrashError())
}
bd := buildBDForInitTests(t)
// newWorkspace builds a server-mode workspace on the test server whose live
// store holds one issue its backup does not (three against two), so a restore
// that really ran shows up as a changed issue count. Each case gets its own: a
// restore that runs replaces the store and would hide a leak from the next.
newWorkspace := func(t *testing.T) (dir string, env []string, backupDir string) {
t.Helper()
dir = t.TempDir()
beadsDir := filepath.Join(dir, ".beads")
if err := os.MkdirAll(beadsDir, 0o700); err != nil {
t.Fatal(err)
}
database := uniqueTestDBName(t)
if err := (&configfile.Config{
Backend: configfile.BackendDolt,
DoltMode: configfile.DoltModeServer,
DoltServerHost: "127.0.0.1",
DoltServerPort: testDoltServerPort,
DoltDatabase: database,
}).Save(beadsDir); err != nil {
t.Fatalf("save workspace metadata: %v", err)
}
ctx := context.Background()
seedStore, err := dolt.New(ctx, &dolt.Config{
Path: filepath.Join(beadsDir, "dolt"),
BeadsDir: beadsDir,
ServerHost: "127.0.0.1",
ServerPort: testDoltServerPort,
Database: database,
CreateIfMissing: true,
})
if err != nil {
t.Fatalf("create the server-mode database: %v", err)
}
t.Cleanup(func() { dropTestDatabase(database, testDoltServerPort) })
defer func() { _ = seedStore.Close() }()
if err := seedStore.SetConfig(ctx, "issue_prefix", "rr"); err != nil {
t.Fatalf("set issue_prefix: %v", err)
}
seed := func(id, title string) {
t.Helper()
now := time.Now()
issue := &types.Issue{
ID: id,
Title: title,
Status: types.StatusOpen,
Priority: 2,
IssueType: types.TypeTask,
CreatedAt: now,
UpdatedAt: now,
}
if err := seedStore.CreateIssue(ctx, issue, "test-user"); err != nil {
t.Fatalf("create issue %s: %v", id, err)
}
}
commit := func(message string) {
t.Helper()
if err := seedStore.Commit(ctx, message); err != nil && !strings.Contains(err.Error(), "nothing to commit") {
t.Fatalf("commit %q: %v", message, err)
}
}
seed("rr-1", "issue in the backup A")
seed("rr-2", "issue in the backup B")
commit("issues the backup holds")
backupDir = filepath.Join(t.TempDir(), "dolt-backup")
if err := os.MkdirAll(backupDir, 0o750); err != nil {
t.Fatal(err)
}
if err := seedStore.BackupDatabase(ctx, backupDir); err != nil {
t.Fatalf("back up the database (the Dolt server must be able to write %s): %v", backupDir, err)
}
seed("rr-3", "issue created after the backup")
commit("issue the backup lacks")
env = []string{
"BEADS_TEST_MODE=1",
// The subprocess connects to a testdb_* database on the test server;
// this is the opt-in the test-database firewall asks for.
"BEADS_TEST_SERVER=1",
"BEADS_DIR=" + beadsDir,
"XDG_CONFIG_HOME=" + t.TempDir(),
// Keep the subprocess's circuit-breaker state in the suite's own
// directory rather than the host's temp dir.
"BEADS_TEST_CIRCUIT_DIR=" + os.Getenv("BEADS_TEST_CIRCUIT_DIR"),
}
return dir, env, backupDir
}
issueCount := func(t *testing.T, dir string, env []string) int {
t.Helper()
stdout, stderr, code := runBDMigrationFreezeWithEnv(t, bd, dir, env, "list", "--json")
if code != 0 {
t.Fatalf("bd list --json exited %d\nstdout:\n%s\nstderr:\n%s", code, stdout, stderr)
}
start := strings.Index(stdout, "[")
if start < 0 {
t.Fatalf("no JSON array in bd list --json output:\n%s", stdout)
}
var issues []json.RawMessage
if err := json.Unmarshal([]byte(stdout[start:]), &issues); err != nil {
t.Fatalf("parse bd list --json output: %v\n%s", err, stdout)
}
return len(issues)
}
// The control proves the fixture really does restore when --readonly is not
// asked for, so "the store is unchanged" below cannot be vacuous.
t.Run("control_restore_without_readonly", func(t *testing.T) {
dir, env, backupDir := newWorkspace(t)
stdout, stderr, code := runBDMigrationFreezeWithEnv(t, bd, dir, env, "backup", "restore", "--force", backupDir)
if code != 0 {
t.Fatalf("restore without --readonly exited %d\nstdout:\n%s\nstderr:\n%s", code, stdout, stderr)
}
if !strings.Contains(stdout, "Restore complete") {
t.Errorf("stdout is missing %q:\n%s", "Restore complete", stdout)
}
if got := issueCount(t, dir, env); got != 2 {
t.Errorf("issue count after a real restore = %d, want 2: the backup holds two issues and the live store held three", got)
}
})
for _, tc := range []struct {
name string
flags []string
}{
{"readonly", []string{"--readonly"}},
{"readonly_sandbox", []string{"--readonly", "--sandbox"}},
} {
t.Run(tc.name, func(t *testing.T) {
dir, env, backupDir := newWorkspace(t)
before := snapshotWorkspace(t, dir)
args := append(append([]string{}, tc.flags...), "backup", "restore", "--force", backupDir)
stdout, stderr, code := runBDMigrationFreezeWithEnv(t, bd, dir, env, args...)
assertStrictReadonlyRestoreRefused(t, stdout, stderr, code)
assertWorkspaceUnchanged(t, dir, before)
if got := issueCount(t, dir, env); got != 3 {
t.Errorf("issue count after the refused restore = %d, want 3: the restore replaced the store", got)
}
})
}
}

View file

@ -207,6 +207,12 @@ Examples:
}
if beadsDir == "" {
// Discovery passes over a .beads marked only by a legacy
// config.json. One in a format this build cannot open is refused
// as that, not reported as no workspace.
if err := checkUndiscoveredWorkspaceFormat(); err != nil {
return handleWorkspaceGuardError(err)
}
if jsonOutput {
if err := outputJSON(noWorkspaceBootstrapPayload()); err != nil {
return err
@ -219,7 +225,7 @@ Examples:
}
if err := guardLegacyUpgradeWorkspace(beadsDir); err != nil {
return HandleError("%v", err)
return handleWorkspaceGuardError(err)
}
// Load config from .beads/metadata.json. When the beadsDir was
@ -234,7 +240,9 @@ Examples:
}
if cfg == nil {
cfg, err = findParentConfig(beadsDir)
if err != nil {
if isUnsupportedWorkspaceFormat(err) {
return handleWorkspaceGuardError(err)
} else if err != nil {
return HandleError("failed to load ancestor storage metadata: %v; no storage database was opened or modified; fix or restore metadata.json and retry", err)
}
}
@ -1586,6 +1594,9 @@ func isNonInteractiveBootstrap(flagValue bool) bool {
// parent workspace does. Returns nil if no parent config is found. A malformed
// or unreadable ancestor metadata file is authoritative and returned as an error;
// bootstrap must not skip it and select a more distant workspace or defaults.
// An ancestor holding the graph format marker without metadata it can read is
// a graph workspace, refused like one whose metadata declares graph_mode,
// rather than skipped or reported as a metadata load failure.
func findParentConfig(beadsDir string) (*configfile.Config, error) {
// Start from the parent of beadsDir's enclosing directory.
// beadsDir is typically "<project>/.beads", so we start from <project>'s parent.
@ -1603,6 +1614,9 @@ func findParentConfig(beadsDir string) (*configfile.Config, error) {
for dir, ok := walk.Next(); ok; dir, ok = walk.Next() {
candidate := filepath.Join(dir, ".beads")
cfg, err := configfile.LoadForDiscovery(candidate)
if (err != nil || cfg == nil) && hasGraphFormatMarker(candidate) {
return nil, &configfile.UnsupportedWorkspaceFormatError{BeadsDir: candidate, FormatMarker: true}
}
if err != nil {
return nil, fmt.Errorf("%s: %w", configfile.ConfigPath(candidate), err)
}

View file

@ -79,6 +79,9 @@ const (
trackSync = "proxied-parity S5 (bd sync)"
trackDegradation = "proxied-parity S6 (doctor, config show, degradations)"
trackLongTail = "proxied-parity S7 (long-tail policy pass)"
// Versioned history (gastownhall/beads#6132) is not a proxied-parity slice:
// its reads need a storage.VersionLister over the proxied uow provider.
trackVersionedHistory = "versioned history: VersionLister over the proxied uow provider (gastownhall/beads#6132)"
)
// capabilityRow is one command-path policy row. ArgSet is the sorted set of
@ -451,6 +454,16 @@ var proxyCapabilityRegistry = []capabilityRow{
// at the front door would leave those modes with no way to flush.
permitted("dolt commit").withHistory(HistoryProxySupported),
// --- versioned history ----------------------------------------------------
// `bd versions` is a pure read (issueops.ListVersionsInTx in one read
// transaction), so nothing about it is unsafe on a shared backend. It is
// refused only because no proxied route exists yet: it reaches the backend
// through the optional storage.VersionLister, which the dolt and embedded
// stores implement and the uow provider does not. Permitting it would open
// the proxied provider in the root pre-run and then fail untyped at
// errVersionsUnsupported, so it is refused here, before any side effect.
refusedPath("versions", "proxy.versions.unsupported", ProxyReasonUnimplemented, trackVersionedHistory),
// --- untyped refusals inside RunE ---------------------------------------
// The gate permits these paths and the command refuses itself with a bare
// string, so a JSON consumer gets no code and no mutates flag. They are

View file

@ -10,7 +10,7 @@ import (
"github.com/steveyegge/beads/internal/types"
)
// TestIfRevisionCloseReplaysMoleculeAutoClose pins mc-zndi7.75 item 1 on the
// TestEmbeddedIfRevisionCloseReplaysMoleculeAutoClose pins mc-zndi7.75 item 1 on the
// embedded/direct --if-revision close route: runCloseDirectIfRevision bypasses
// `bd close`'s batch architecture entirely (A8, beads#4682 — BatchCloseItem
// carries no per-item ExpectedVersion), so it must re-drive molecule auto-close
@ -22,7 +22,7 @@ import (
// state a crash between the final step's close and its root auto-close would
// leave), then re-close the final step — this time guarded — and require the
// stranded-open root to heal.
func TestIfRevisionCloseReplaysMoleculeAutoClose(t *testing.T) {
func TestEmbeddedIfRevisionCloseReplaysMoleculeAutoClose(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")
}
@ -60,12 +60,12 @@ func TestIfRevisionCloseReplaysMoleculeAutoClose(t *testing.T) {
}
}
// TestIfRevisionCloseWarnsOnForcedOpenChildren pins mc-zndi7.75 item 3: the
// TestEmbeddedIfRevisionCloseWarnsOnForcedOpenChildren pins mc-zndi7.75 item 3: the
// "warning: closing X with N open child issue(s) still active" line
// (close.go:194-196) must still print on the guarded direct close route when
// --force waives the engine's open-children refusal, exactly as it does on
// the unguarded batch path.
func TestIfRevisionCloseWarnsOnForcedOpenChildren(t *testing.T) {
func TestEmbeddedIfRevisionCloseWarnsOnForcedOpenChildren(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")
}

View file

@ -10,7 +10,7 @@ import (
)
// TestProxiedServerIfRevisionCloseReplaysMoleculeAutoClose is
// TestIfRevisionCloseReplaysMoleculeAutoClose's proxied-server twin, pinning
// TestEmbeddedIfRevisionCloseReplaysMoleculeAutoClose's proxied-server twin, pinning
// mc-zndi7.75 item 1 on the route `bd serve` actually runs:
// runCloseProxiedIfRevision bypasses the batch entirely (A8, beads#4682), so
// it must re-drive molecule auto-close itself via its own post-close unit of
@ -53,7 +53,7 @@ func TestProxiedServerIfRevisionCloseReplaysMoleculeAutoClose(t *testing.T) {
}
// TestProxiedServerIfRevisionCloseWarnsOnForcedOpenChildren is
// TestIfRevisionCloseWarnsOnForcedOpenChildren's proxied-server twin, pinning
// TestEmbeddedIfRevisionCloseWarnsOnForcedOpenChildren's proxied-server twin, pinning
// mc-zndi7.75 item 3 on the proxied route.
func TestProxiedServerIfRevisionCloseWarnsOnForcedOpenChildren(t *testing.T) {
requireSharedProxiedServer(t)

View file

@ -0,0 +1,444 @@
//go:build cgo
// cgo only: the goldens pin the cgo build, which every lane that runs this
// package's full suite compiles. The !cgo build replaces the federation
// subtree with a one-command stub (federation_nocgo.go), so its tree differs
// by design.
package main
import (
"bytes"
"fmt"
"os"
"path/filepath"
"sort"
"strings"
"testing"
"github.com/charmbracelet/x/ansi"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
)
// The committed command-surface goldens. Regenerate after an intentional CLI
// change, then review the diff like code:
//
// BD_UPDATE_GOLDEN=1 CGO_ENABLED=1 go test -tags gms_pure_go ./cmd/bd -run '^TestCommand(Tree|Help)Golden$'
//
// CGO_ENABLED=1 because this file builds only with cgo: with cgo off the
// command matches no test, exits 0 and leaves the goldens as they were.
const (
commandTreeGoldenPath = "testdata/command_tree/tree.golden"
commandHelpGoldenDir = "testdata/command_tree/help"
commandGoldenRegen = "BD_UPDATE_GOLDEN=1 CGO_ENABLED=1 go test -tags gms_pure_go ./cmd/bd -run '^TestCommand(Tree|Help)Golden$'"
)
// commandHelpGoldenArgs is the representative set of commands whose exact
// --help output is pinned, each as the argv after "bd". The tree golden
// covers every command's metadata; these cover the rendering (usage line,
// flag table layout, inherited global flags, root command groups).
var commandHelpGoldenArgs = [][]string{
{},
{"create"},
{"show"},
{"list"},
{"update"},
{"close"},
{"version"},
{"versions"},
{"config"},
{"serve"},
}
// TestCommandTreeGolden pins the whole bd command tree: for every command and
// subcommand, hidden ones included, its Use, Aliases, Short, Long, Example,
// group, hidden/deprecated state, runnability and annotations, and every
// local and persistent flag it defines (name, shorthand, type, default,
// usage, hidden, deprecation, annotations). Any added, removed or reworded
// command or flag fails this test until the golden is regenerated, so the
// change shows up as a reviewed testdata diff. It reads the in-memory tree
// only: no store or subprocess.
//
// docs/cli-docs.pin pins the generated CLI reference (and check-doc-flags)
// to a release, so drift on main is not caught there; this golden is the
// live guard for the command surface.
func TestCommandTreeGolden(t *testing.T) {
pkgDir := enterOrdinaryWorkspaceForGolden(t)
primeCommandTreeForGolden()
flagCounts := commandFlagCounts(rootCmd)
got := renderCommandTreeGolden(rootCmd)
// A renderer that iterated a map would pass on the run that regenerated
// the golden and flake afterwards.
if again := renderCommandTreeGolden(rootCmd); again != got {
t.Fatalf("command tree rendering is not deterministic:\n%s", goldenLineDiff(got, again))
}
// Nor may rendering change the tree it reads: tests sharing this binary
// pin a command's exact flag set (TestServeFlags). See goldenLocalFlags.
if after := commandFlagCounts(rootCmd); after != flagCounts {
t.Fatalf("rendering the command tree added flags to a command's own flag set:\n%s", goldenLineDiff(flagCounts, after))
}
checkCommandGolden(t, pkgDir, commandTreeGoldenPath, got)
}
// TestCommandHelpGolden pins the exact `bd <command> --help` output of a
// representative set of commands, executed in-process through the real root
// command. --help returns before the root pre-run, so no store is opened.
// Color escapes are stripped so the snapshot is independent of terminal
// detection; otherwise the snapshots are byte-identical to what a built bd
// prints.
func TestCommandHelpGolden(t *testing.T) {
pkgDir := enterOrdinaryWorkspaceForGolden(t)
// Parsing `bd serve --help` merges the root's persistent flags into
// serveCmd's own flag set, which TestServeFlags pins; restoreServeGlobals
// re-registers that set afterwards.
restoreServeGlobals(t)
want := map[string]bool{}
for _, args := range commandHelpGoldenArgs {
name := strings.Join(append([]string{"bd"}, args...), "_")
file := name + ".golden"
want[file] = true
t.Run(name, func(t *testing.T) {
checkCommandGolden(t, pkgDir, filepath.Join(commandHelpGoldenDir, file), renderCommandHelpGolden(t, args))
})
}
// The directory holds exactly the listed snapshots: a command dropped
// from the list must not leave a stale file that still looks pinned.
dir := filepath.Join(pkgDir, commandHelpGoldenDir)
entries, err := os.ReadDir(dir)
if err != nil {
t.Fatalf("read %s: %v", commandHelpGoldenDir, err)
}
for _, e := range entries {
if want[e.Name()] {
continue
}
if os.Getenv("BD_UPDATE_GOLDEN") == "1" {
if err := os.Remove(filepath.Join(dir, e.Name())); err != nil {
t.Fatalf("remove stale help golden %s: %v", e.Name(), err)
}
t.Logf("removed stale help golden %s", e.Name())
continue
}
t.Errorf("%s/%s is not in commandHelpGoldenArgs; delete it or regenerate with %s", commandHelpGoldenDir, e.Name(), commandGoldenRegen)
}
}
// enterOrdinaryWorkspaceForGolden moves the test into a fresh ordinary
// (dependency-mode) workspace: a .beads/metadata.json with no graph marker
// and no database behind it, so nothing can be read from or written to a
// store. It returns the package directory, where the goldens live.
func enterOrdinaryWorkspaceForGolden(t *testing.T) string {
t.Helper()
isolateBeadsDirForTest(t)
pkgDir, err := os.Getwd()
if err != nil {
t.Fatal(err)
}
ws := t.TempDir()
beadsDir := filepath.Join(ws, ".beads")
if err := os.Mkdir(beadsDir, 0o750); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(beadsDir, "metadata.json"), []byte(`{"backend":"dolt"}`), 0o600); err != nil {
t.Fatal(err)
}
t.Chdir(ws)
return pkgDir
}
// primeCommandTreeForGolden completes the tree the way the bd binary does
// before it dispatches: main() adds cobra's help command and its
// --all/--doc/--list/--docs-root flags, and ExecuteC adds the completion
// command. All three are idempotent, so the tree is the same whether or not
// an earlier in-process test already executed rootCmd.
func primeCommandTreeForGolden() {
rootCmd.InitDefaultHelpCmd()
registerHelpAllFlag()
rootCmd.InitDefaultCompletionCmd()
}
// renderCommandTreeGolden walks cmd's tree depth first, children sorted by
// name, and renders one block per command.
func renderCommandTreeGolden(root *cobra.Command) string {
var b strings.Builder
b.WriteString("# bd command tree (cgo build), pinned by TestCommandTreeGolden.\n")
b.WriteString("# Regenerate after an intentional CLI change:\n")
b.WriteString("# " + commandGoldenRegen + "\n")
var walk func(*cobra.Command)
walk = func(c *cobra.Command) {
writeCommandGoldenBlock(&b, c)
children := append([]*cobra.Command(nil), c.Commands()...)
sort.Slice(children, func(i, j int) bool { return children[i].Name() < children[j].Name() })
for _, sub := range children {
// cobra adds the hidden shell-completion request commands only
// for an execution that invokes them, and then never removes
// them: whether they are present depends on test history, not
// on the bd surface.
if sub.Name() == cobra.ShellCompRequestCmd || sub.Name() == cobra.ShellCompNoDescRequestCmd {
continue
}
walk(sub)
}
}
walk(root)
return b.String()
}
func writeCommandGoldenBlock(b *strings.Builder, c *cobra.Command) {
fmt.Fprintf(b, "\n%s\n", c.CommandPath())
fmt.Fprintf(b, " use: %q\n", c.Use)
if len(c.Aliases) > 0 {
fmt.Fprintf(b, " aliases: %q\n", c.Aliases)
}
fmt.Fprintf(b, " short: %q\n", c.Short)
if c.GroupID != "" {
fmt.Fprintf(b, " group: %q\n", c.GroupID)
}
fmt.Fprintf(b, " hidden: %t\n", c.Hidden)
if c.Deprecated != "" {
fmt.Fprintf(b, " deprecated: %q\n", c.Deprecated)
}
fmt.Fprintf(b, " runnable: %t\n", c.Runnable())
if c.DisableFlagParsing {
b.WriteString(" disable-flag-parsing: true\n")
}
if len(c.ValidArgs) > 0 {
fmt.Fprintf(b, " valid-args: %q\n", c.ValidArgs)
}
if len(c.Annotations) > 0 {
fmt.Fprintf(b, " annotations: %s\n", formatGoldenAnnotations(c.Annotations))
}
writeGoldenTextBlock(b, "long", c.Long)
writeGoldenTextBlock(b, "example", c.Example)
for _, line := range commandGoldenFlagLines(c.PersistentFlags()) {
fmt.Fprintf(b, " persistent-flag %s\n", line)
}
for _, line := range commandGoldenFlagLines(goldenLocalFlags(c)) {
fmt.Fprintf(b, " flag %s\n", line)
}
}
// goldenLocalFlags returns the non-persistent flags c registers itself,
// including any that shadow an inherited flag: the set
// c.LocalNonPersistentFlags() reports, read without calling it. That
// accessor, like LocalFlags and InheritedFlags, runs cobra's
// mergePersistentFlags, which copies every inherited persistent flag into
// c.Flags() for the rest of the process. Over the whole tree that would leave
// `bd serve` carrying the root's --json, --db and the rest, and break
// TestServeFlags (see TestNoSubcommandShadowsRootJSONFlag).
//
// c.Flags() may already hold such copies from an earlier in-process
// execution. They are recognized by identity, the way cobra itself tells
// them apart: an inherited flag is the nearest ancestor's own *pflag.Flag of
// that name, and a shadowing flag is a different one.
func goldenLocalFlags(c *cobra.Command) *pflag.FlagSet {
local := pflag.NewFlagSet(c.Name(), pflag.ContinueOnError)
c.Flags().VisitAll(func(f *pflag.Flag) {
if c.PersistentFlags().Lookup(f.Name) != nil {
return // rendered as a persistent-flag line
}
for p := c.Parent(); p != nil; p = p.Parent() {
if inherited := p.PersistentFlags().Lookup(f.Name); inherited != nil {
if inherited == f {
return
}
break
}
}
local.AddFlag(f)
})
return local
}
// commandFlagCounts renders how many flags each command's own flag set holds,
// one line per command, read without merging anything into it.
func commandFlagCounts(root *cobra.Command) string {
var b strings.Builder
var walk func(*cobra.Command)
walk = func(c *cobra.Command) {
n := 0
c.Flags().VisitAll(func(*pflag.Flag) { n++ })
fmt.Fprintf(&b, "%s %d\n", c.CommandPath(), n)
for _, sub := range c.Commands() {
walk(sub)
}
}
walk(root)
return b.String()
}
// writeGoldenTextBlock writes a multi-line field one source line per golden
// line, behind a "|" gutter so leading whitespace and blank lines survive.
func writeGoldenTextBlock(b *strings.Builder, name, text string) {
if text == "" {
return
}
fmt.Fprintf(b, " %s:\n", name)
for _, line := range strings.Split(text, "\n") {
if line == "" {
b.WriteString(" |\n")
continue
}
fmt.Fprintf(b, " | %s\n", line)
}
}
// commandGoldenFlagLines renders each flag of fs on one line, sorted by name.
// cobra's own lazily added --help flag (FlagSetByCobraAnnotation) is skipped:
// it exists only on commands an earlier in-process execution reached.
func commandGoldenFlagLines(fs *pflag.FlagSet) []string {
var flags []*pflag.Flag
fs.VisitAll(func(f *pflag.Flag) {
if _, byCobra := f.Annotations[cobra.FlagSetByCobraAnnotation]; byCobra {
return
}
flags = append(flags, f)
})
sort.Slice(flags, func(i, j int) bool { return flags[i].Name < flags[j].Name })
lines := make([]string, 0, len(flags))
for _, f := range flags {
var b strings.Builder
fmt.Fprintf(&b, "--%s", f.Name)
if f.Shorthand != "" {
fmt.Fprintf(&b, " -%s", f.Shorthand)
}
fmt.Fprintf(&b, " type=%s default=%q", f.Value.Type(), f.DefValue)
if f.NoOptDefVal != "" && !implicitNoOptDefault(f) {
fmt.Fprintf(&b, " no-opt-default=%q", f.NoOptDefVal)
}
if f.Hidden {
b.WriteString(" hidden")
}
if f.Deprecated != "" {
fmt.Fprintf(&b, " deprecated=%q", f.Deprecated)
}
if f.ShorthandDeprecated != "" {
fmt.Fprintf(&b, " shorthand-deprecated=%q", f.ShorthandDeprecated)
}
if len(f.Annotations) > 0 {
fmt.Fprintf(&b, " annotations=%s", formatGoldenAnnotations(f.Annotations))
}
fmt.Fprintf(&b, " usage=%q", f.Usage)
lines = append(lines, b.String())
}
return lines
}
// implicitNoOptDefault reports whether f's NoOptDefVal is the one pflag gives
// every flag of its type (a bare --bool means true, a bare --count adds one),
// which would only repeat the type on each line.
func implicitNoOptDefault(f *pflag.Flag) bool {
switch f.Value.Type() {
case "bool":
return f.NoOptDefVal == "true"
case "count":
return f.NoOptDefVal == "+1"
}
return false
}
// formatGoldenAnnotations renders a command's or a flag's annotations sorted
// by key.
func formatGoldenAnnotations[V string | []string](m map[string]V) string {
keys := make([]string, 0, len(m))
for k := range m {
keys = append(keys, k)
}
sort.Strings(keys)
parts := make([]string, 0, len(keys))
for _, k := range keys {
parts = append(parts, fmt.Sprintf("%s=%q", k, m[k]))
}
return "{" + strings.Join(parts, " ") + "}"
}
// renderCommandHelpGolden runs `bd <args> --help` through rootCmd in-process
// and returns its stdout with color escapes stripped. cobra keeps the parsed
// --help value on the shared tree, so every flag is put back afterwards: a
// later in-process `bd create ...` must not print help instead.
//
// internal/ui decides color once, at init, from CLICOLOR_FORCE and whether the
// test binary's stdout is a terminal. CI never gives it one, so there the
// strip removes nothing; it is what keeps a run from a terminal matching the
// goldens.
func renderCommandHelpGolden(t *testing.T, args []string) string {
t.Helper()
argv := append(append([]string(nil), args...), "--help")
primeCommandTreeForGolden()
var execErr error
out := captureStdout(t, func() error {
rootCmd.SetArgs(argv)
defer rootCmd.SetArgs(nil)
defer resetCommandFlags(rootCmd)
_, execErr = rootCmd.ExecuteC()
return nil
})
if execErr != nil {
t.Fatalf("bd %s: %v", strings.Join(argv, " "), execErr)
}
return ansi.Strip(out)
}
// checkCommandGolden compares got with the golden at rel under pkgDir, or
// rewrites the golden when BD_UPDATE_GOLDEN=1 (the package's shared golden
// switch).
func checkCommandGolden(t *testing.T, pkgDir, rel, got string) {
t.Helper()
path := filepath.Join(pkgDir, rel)
if os.Getenv("BD_UPDATE_GOLDEN") == "1" {
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
t.Fatalf("mkdir %s: %v", filepath.Dir(rel), err)
}
if err := os.WriteFile(path, []byte(got), 0o644); err != nil {
t.Fatalf("write golden %s: %v", rel, err)
}
t.Logf("updated golden %s", rel)
return
}
want, err := os.ReadFile(path)
if err != nil {
t.Fatalf("read golden %s (regenerate with %s): %v", rel, commandGoldenRegen, err)
}
if bytes.Equal([]byte(got), want) {
return
}
t.Errorf("bd command surface drifted from %s.\n%s\nIf the change is intended, regenerate with\n %s\nand review the testdata diff.",
rel, goldenLineDiff(string(want), got), commandGoldenRegen)
}
// goldenLineDiff reports the region where want and got differ: the common
// leading and trailing lines are trimmed and the rest is shown as -/+ lines,
// capped so a large drift stays readable (the reviewed artifact is the
// regenerated testdata diff, not this message).
func goldenLineDiff(want, got string) string {
const maxLines = 40
w := strings.Split(want, "\n")
g := strings.Split(got, "\n")
pre := 0
for pre < len(w) && pre < len(g) && w[pre] == g[pre] {
pre++
}
suf := 0
for suf < len(w)-pre && suf < len(g)-pre && w[len(w)-1-suf] == g[len(g)-1-suf] {
suf++
}
var b strings.Builder
fmt.Fprintf(&b, "first difference at line %d:\n", pre+1)
write := func(sign string, lines []string) {
for i, line := range lines {
if i == maxLines {
fmt.Fprintf(&b, "%s ... (%d more lines)\n", sign, len(lines)-maxLines)
return
}
fmt.Fprintf(&b, "%s %s\n", sign, line)
}
}
write("-", w[pre:len(w)-suf])
write("+", g[pre:len(g)-suf])
return b.String()
}

View file

@ -280,6 +280,12 @@ var configSetCmd = &cobra.Command{
if err != nil {
return HandleError("%v", err)
}
// Per-key validation that needs the store rather than the key alone: turning
// versioned history on refuses, writing nothing, while any issue holds a value a
// version could not record. The store is open here, on whichever route this is.
if err := checkVersionedHistoryCanBeEnabled(rootCtx, key, value); err != nil {
return HandleError("%v", err)
}
result, err := settings.SetSetting(rootCtx, issueops.SetSettingRequest{Key: key, Value: value})
if err != nil {
return HandleError("setting config: %v", err)
@ -1222,6 +1228,14 @@ Examples:
return HandleError("%v", err)
}
}
// The pre-enable check `bd config set` makes: turning versioned history
// on refuses while any issue holds a value a version could not record.
// This verb writes the same setting through a loop of its own, so it
// makes the check itself, here and before any pair is written: a refusal
// stores nothing from the batch.
if err := checkVersionedHistoryCanBeEnabled(rootCtx, p.key, p.value); err != nil {
return HandleError("%v", err)
}
}
var yamlPairs, gitPairs, dbPairs []kvPair
@ -1352,7 +1366,7 @@ var recognizedConfigPrefixes = []string{
"status.", "types.", "doctor.suppress.", "routing.", "sync.", "git.",
"directory.", "repos.", "external_projects.", "validation.",
"lint.", "hierarchy.", "ai.", "backup.", "federation.", "metrics.",
"agent.", "claim.", "storage-class.",
"agent.", "claim.", "storage-class.", "versioned-history.",
}
// validateStorageClassConfig validates a storage-class.<type> per-type

View file

@ -4,6 +4,8 @@ import (
"fmt"
"os"
"strings"
"github.com/steveyegge/beads/internal/versionedhistory"
)
// configSideEffect describes a hint or warning to show after a config change.
@ -65,6 +67,11 @@ func checkConfigSetSideEffects(key, value string) []configSideEffect {
Message: fmt.Sprintf("Git sync remote set to %q. Ensure this git remote exists.", value),
Command: fmt.Sprintf("git remote -v | grep %s", value),
})
case key == versionedHistorySettingKey && versionedhistory.ValueEnables(value):
effects = append(effects, configSideEffect{
Message: "Versioned history now records for this store. The setting replicates on 'bd dolt push' and 'bd dolt pull', so every clone that pulls it records too, and it is safe with a single writer only: keep one writer at a time per store (docs/reference/configuration.md#versioned-issue-history).",
})
}
return effects

View file

@ -2,6 +2,7 @@ package main
import (
"os"
"strings"
"testing"
)
@ -105,6 +106,34 @@ func TestCheckConfigSetSideEffects_UnknownKey(t *testing.T) {
}
}
// versioned-history.enabled is a row of the store's config table, which
// replicates on `bd dolt push` and `bd dolt pull`, and the feature is single
// writer only. `bd config set ... true` is the moment someone turns it on, so it
// is where that caveat belongs -- said once, at the command that has the effect.
func TestVersionedHistoryConfigSetHintsAboutReplicationAndSingleWriter(t *testing.T) {
for _, on := range []string{"true", "TRUE", " true ", "1", "t"} {
effects := checkConfigSetSideEffects(versionedHistorySettingKey, on)
if len(effects) != 1 {
t.Errorf("value %q turns recording on: expected 1 hint, got %d", on, len(effects))
continue
}
for _, want := range []string{"replicates", "single writer"} {
if !strings.Contains(strings.ToLower(effects[0].Message), want) {
t.Errorf("value %q: the hint does not mention %q: %s", on, want, effects[0].Message)
}
}
}
// Turning it off, or anything that does not turn it on, needs no caveat.
for _, off := range []string{"false", "0", "", "off", "nonsense"} {
if effects := checkConfigSetSideEffects(versionedHistorySettingKey, off); len(effects) != 0 {
t.Errorf("value %q does not turn recording on: expected no hint, got %d", off, len(effects))
}
}
if effects := checkConfigUnsetSideEffects(versionedHistorySettingKey); len(effects) != 0 {
t.Errorf("unsetting the key needs no hint, got %d", len(effects))
}
}
func TestCheckConfigUnsetSideEffects_FederationRemote(t *testing.T) {
effects := checkConfigUnsetSideEffects("federation.remote")
if len(effects) != 1 {

View file

@ -373,6 +373,11 @@ var createCmd = &cobra.Command{
}
if dryRun && parentID == "" {
// The preview opens no target, but it refuses a local one in a
// format this build cannot open, as the create it previews would.
if err := checkRepoTargetFormat(repoPath); err != nil {
return handleWorkspaceGuardError(err)
}
return renderDryRun()
}
@ -402,6 +407,9 @@ var createCmd = &cobra.Command{
// flag value can be ambiguous.
allowCreate := !isAmbiguousRepoTarget(cmd.Flags().Changed("repo"), repoOverride)
if err := ensureBeadsDirForPath(rootCtx, targetBeadsDir, store, allowCreate); err != nil {
if isUnsupportedWorkspaceFormat(err) {
return handleWorkspaceGuardError(err)
}
return HandleError("failed to initialize target repo: %v", err)
}
@ -969,8 +977,12 @@ func init() {
}
// handleCreateTargetStoreError preserves the existing text path for ordinary
// store failures while rendering capability refusals as typed JSON when asked.
// store failures while rendering capability refusals as typed JSON when asked,
// and a target in a format this build cannot open as the workspace refusal.
func handleCreateTargetStoreError(err error, targetPath, fallbackFormat string) error {
if isUnsupportedWorkspaceFormat(err) {
return handleWorkspaceGuardError(err)
}
var capErr *ProxyCapabilityError
if !errors.As(err, &capErr) {
return HandleError(fallbackFormat, err)
@ -1020,6 +1032,12 @@ func openDryRunTargetStore(ctx context.Context, repoPath string) (storage.DoltSt
targetPath := routing.ExpandPath(repoPath)
beadsDir := filepath.Join(targetPath, ".beads")
// A target in a format this build cannot open is refused as that, even
// one marked only by a legacy config.json, which the check below would
// report as not initialized.
if err := checkDiscoveredWorkspaceFormat(beadsDir); err != nil {
return nil, err
}
metadataPath := filepath.Join(beadsDir, "metadata.json")
if _, err := os.Stat(metadataPath); err != nil {
if os.IsNotExist(err) {
@ -1035,6 +1053,17 @@ func openDryRunTargetStore(ctx context.Context, repoPath string) (storage.DoltSt
return store, nil
}
// checkRepoTargetFormat refuses a local create target in a format this build
// cannot open, reading its metadata without opening or migrating it. The
// command's own workspace (".") has passed admission already, and a remote
// target has no local metadata to read, so both pass.
func checkRepoTargetFormat(repoPath string) error {
if repoPath == "." || remotecache.IsRemoteURL(repoPath) {
return nil
}
return checkDiscoveredWorkspaceFormat(filepath.Join(routing.ExpandPath(repoPath), ".beads"))
}
// isAmbiguousRepoTarget reports whether an explicit --repo value is a
// bare/relative filesystem path (not absolute, not "~/"-prefixed). Such a
// value silently resolves against the current working directory (see
@ -1055,6 +1084,14 @@ func ensureBeadsDirForPath(ctx context.Context, targetPath string, sourceStore s
beadsDir := filepath.Join(targetPath, ".beads")
metadataPath := filepath.Join(beadsDir, "metadata.json")
// A target in a format this build cannot open is refused before anything
// below: one marked only by a legacy config.json or by the graph format
// marker file has no metadata.json, so it would otherwise be initialized
// here, with an Issue database and a metadata.json written beside it.
if err := checkDiscoveredWorkspaceFormat(beadsDir); err != nil {
return err
}
// Check if beads directory already exists with a Dolt database.
// metadata.json is the canonical marker for an initialized beads dir.
if _, err := os.Stat(metadataPath); err == nil {

View file

@ -390,6 +390,14 @@ func TestEmbeddedDepBTreeAndCycles(t *testing.T) {
if !strings.Contains(out, "flowchart") && !strings.Contains(out, "graph") {
t.Errorf("expected mermaid flowchart/graph syntax: %s", out)
}
// Mixed-case pins case-folding at the runDepTree dispatch site.
// TestDepTreeFormatMermaidCaseInsensitive calls isMermaidTreeFormat
// directly and would stay green if the call site went back to
// formatStr == "mermaid" (the PR #6646 bug).
mixed := bdDep(t, bd, dir, "tree", epic.ID, "--format", "Mermaid")
if !strings.Contains(mixed, "flowchart") && !strings.Contains(mixed, "graph") {
t.Errorf("expected mermaid flowchart/graph syntax for --format Mermaid: %s", mixed)
}
})
t.Run("tree_json_output", func(t *testing.T) {

View file

@ -0,0 +1,86 @@
//go:build cgo
package main
import (
"bytes"
"encoding/json"
"errors"
"os"
"os/exec"
"path/filepath"
"testing"
)
// TestEmbeddedDiscoveryPinsEnvFileReadonly is the store-backed member of the
// before-parity discovery pins (discovery_refusal_pins_test.go holds the
// store-less ones). It pins how an ordinary workspace applies a BD_READONLY
// supplied by its own .beads/.env: a write is refused with the read-only text
// and exit 1, also under --json, while reads still run; and a BD_READONLY the
// caller exports wins over the file.
func TestEmbeddedDiscoveryPinsEnvFileReadonly(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", "pin")
if err := os.WriteFile(filepath.Join(beadsDir, ".env"), []byte("BD_READONLY=true\n"), 0o600); err != nil {
t.Fatalf("write .beads/.env: %v", err)
}
run := func(extraEnv []string, args ...string) (exit int, stdout, stderr string) {
t.Helper()
cmd := exec.Command(bd, args...)
cmd.Dir = dir
// The store-less pins' closed environment: no BD_*/BEADS_* the caller
// exports (BD_READONLY, BD_JSON_ENVELOPE, BD_OTEL_*, ...) reaches bd.
// HOME stays dir, where bd init ran.
cmd.Env = append(discoveryPinEnv(dir, filepath.Join(dir, "no-such-freeze-marker")),
"BEADS_DOLT_AUTO_START=0", "BEADS_NO_DAEMON=1")
cmd.Env = append(cmd.Env, extraEnv...)
var out, errOut bytes.Buffer
cmd.Stdout, cmd.Stderr = &out, &errOut
if err := cmd.Run(); err != nil {
var exitErr *exec.ExitError
if !errors.As(err, &exitErr) {
t.Fatalf("run bd %v: %v", args, err)
}
exit = exitErr.ExitCode()
}
return exit, out.String(), discoveryPinSandboxNotice.ReplaceAllLiteralString(errOut.String(), "")
}
exit, stdout, stderr := run(nil, "create", "refused by .env", "--json")
if exit != 1 || stdout != "" || stderr != "Error: operation 'create' is not allowed in read-only mode\n" {
t.Fatalf("create under .env BD_READONLY=true: exit=%d stdout=%q stderr=%q; want exit=1, no stdout, the read-only refusal", exit, stdout, stderr)
}
exit, stdout, stderr = run(nil, "list", "--json")
if exit != 0 || stdout != "[]\n" {
t.Fatalf("list under .env BD_READONLY=true: exit=%d stdout=%q stderr=%q; want exit=0 and an empty list", exit, stdout, stderr)
}
exit, stdout, stderr = run([]string{"BD_READONLY=false"}, "create", "allowed by the caller", "--json")
if exit != 0 {
t.Fatalf("create with exported BD_READONLY=false: exit=%d stdout=%q stderr=%q; want the caller's setting to win", exit, stdout, stderr)
}
var created struct {
Title string `json:"title"`
}
if err := json.Unmarshal([]byte(stdout), &created); err != nil || created.Title != "allowed by the caller" {
t.Fatalf("create with exported BD_READONLY=false printed %q (decode error %v)", stdout, err)
}
exit, stdout, stderr = run(nil, "list", "--json")
var listed []struct {
Title string `json:"title"`
}
if exit != 0 {
t.Fatalf("list after the allowed create: exit=%d stderr=%q", exit, stderr)
}
if err := json.Unmarshal([]byte(stdout), &listed); err != nil || len(listed) != 1 || listed[0].Title != "allowed by the caller" {
t.Fatalf("list after the allowed create = %q (decode error %v); want only the allowed issue, the refused create wrote nothing", stdout, err)
}
}

View file

@ -0,0 +1,885 @@
//go:build cgo
package main
// Before-parity pins for workspace discovery refusals.
//
// These tests hold the exact text and exit code an ordinary bd prints when
// workspace discovery cannot select a usable workspace: a missing or corrupt
// metadata.json, an explicit BEADS_DIR that names no workspace, selection
// supplied by .beads/.env, .beads/redirect files, --db / BEADS_DB / BD_DB
// selection, and the blocked backend environment variables. They pin what
// origin/main does today, not what it ideally should do. A change that
// reorders admission, discovery or checkBlockedEnvVars in the root
// PersistentPreRunE has to change an expectation here, so it shows up in
// review as a test diff rather than as an unexplained behavior change.
//
// Every case runs the real bd binary in a fresh fixture and stops before any
// store is opened, so these need no Dolt server or database. Fixture
// workspaces with a corrupt metadata.json double as sentinels: the refusal
// names the metadata.json it failed to parse, so the text shows which
// directory discovery selected without opening a database.
//
// The pinned no-database hints are an embedded-capable bd's. A CGO_ENABLED=0
// bd is server-only and adds "run 'bd doctor' to diagnose" to them, so this
// file builds only with cgo, and the bd it runs (built by
// buildBDForInitTests, or BEADS_TEST_BD_BINARY) must be a cgo build too.
import (
"bytes"
"errors"
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime"
"sort"
"strings"
"testing"
"github.com/steveyegge/beads/internal/testutil"
)
// pinNoDatabaseRefusal is what a store-requiring command prints when
// discovery finds no workspace with a database.
const pinNoDatabaseRefusal = "Error: no beads database found\n" +
"Hint: run 'bd where' to inspect the resolved workspace, or 'bd init' to create a new database\n" +
" or set BEADS_DIR to point to your .beads directory\n"
// pinNoWorkspaceWhereRefusal is bd where's text refusal when no workspace is
// selected.
const pinNoWorkspaceWhereRefusal = "Error: No active beads workspace found.\n" +
"Hint: check BEADS_DIR/worktree setup, or run 'bd init' to create a new database\n"
// pinNoWorkspaceWhereJSON is bd where --json's refusal. It goes to stdout.
const pinNoWorkspaceWhereJSON = `{
"error": "no_beads_directory",
"hint": "check BEADS_DIR/worktree setup, or run 'bd init' to create a new database",
"message": "No active beads workspace found.",
"schema_version": 1
}
`
// pinCorruptMetadata is the content of every corrupt metadata.json fixture.
const pinCorruptMetadata = "{\n"
// pinCorruptMetadataWarning is the warning printed while the selected
// workspace is bound, before the refusal itself.
func pinCorruptMetadataWarning(beadsDir string) string {
return "warning: load " + beadsDir + "/metadata.json: parsing config: unexpected end of JSON input; " +
"no storage database was opened or modified (storage mode unknown; data commands refuse to fall back to the embedded store)\n"
}
// pinCorruptMetadataRefusal is the full stderr of a command refused because
// the selected workspace's metadata.json does not parse.
func pinCorruptMetadataRefusal(beadsDir string) string {
return pinCorruptMetadataWarning(beadsDir) +
"Error: loading config: parsing config: unexpected end of JSON input\n"
}
// pinBlockedEnvRefusal is checkBlockedEnvVars' refusal for name.
func pinBlockedEnvRefusal(name string) string {
return "Error: " + name + " env var is not supported and has been removed to prevent data fragmentation.\n" +
"Unset " + name + "; storage selection comes from .beads/metadata.json. " +
"To choose a different supported backend, follow 'bd help init-safety'; do not edit metadata.json by hand\n"
}
// discoveryPinCase is one bd invocation and its exact expected result. The
// arguments and the expected strings write the fixture root as $ROOT.
type discoveryPinCase struct {
name string
// setup builds the fixture and returns the working directory and any
// environment the invocation adds to the hermetic base.
setup func(f *discoveryPinFixture) (cwd string, env []string)
args []string
exit int
stdout string
stderr string
// stderrPrefix compares only the start of stderr. Use it only where the
// rest of the output is not part of the pin.
stderrPrefix bool
}
func runDiscoveryPinCases(t *testing.T, cases []discoveryPinCase) {
t.Helper()
if runtime.GOOS == "windows" {
t.Skip("the pinned texts embed POSIX paths")
}
t.Parallel()
bd := buildBDForInitTests(t)
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
f := newDiscoveryPinFixture(t)
cwd, env := tc.setup(f)
args := make([]string, len(tc.args))
for i, arg := range tc.args {
args[i] = strings.ReplaceAll(arg, "$ROOT", f.root)
}
exit, stdout, stderr := f.run(bd, cwd, env, args...)
if exit != tc.exit {
t.Errorf("bd %s: exit = %d, want %d", strings.Join(tc.args, " "), exit, tc.exit)
}
if stdout != tc.stdout {
t.Errorf("bd %s: stdout differs\n got: %q\nwant: %q", strings.Join(tc.args, " "), stdout, tc.stdout)
}
gotStderr := stderr
if tc.stderrPrefix && len(gotStderr) > len(tc.stderr) {
gotStderr = gotStderr[:len(tc.stderr)]
}
if gotStderr != tc.stderr {
t.Errorf("bd %s: stderr differs\n got: %q\nwant: %q", strings.Join(tc.args, " "), stderr, tc.stderr)
}
})
}
}
type discoveryPinFixture struct {
t *testing.T
root string
forms []string // spellings of root to rewrite as $ROOT, longest first
}
func newDiscoveryPinFixture(t *testing.T) *discoveryPinFixture {
t.Helper()
root := t.TempDir()
forms := []string{root}
if resolved, err := filepath.EvalSymlinks(root); err == nil && resolved != root {
forms = append(forms, resolved)
}
sort.Slice(forms, func(i, j int) bool { return len(forms[i]) > len(forms[j]) })
f := &discoveryPinFixture{t: t, root: root, forms: forms}
f.mkdir("home")
return f
}
// path returns the absolute path of a root-relative slash path.
func (f *discoveryPinFixture) path(rel string) string {
return filepath.Join(f.root, filepath.FromSlash(rel))
}
func (f *discoveryPinFixture) mkdir(rel string) string {
f.t.Helper()
dir := f.path(rel)
if err := os.MkdirAll(dir, 0o700); err != nil {
f.t.Fatalf("mkdir %s: %v", dir, err)
}
return dir
}
func (f *discoveryPinFixture) write(rel, content string) {
f.t.Helper()
if err := os.WriteFile(f.path(rel), []byte(content), 0o600); err != nil {
f.t.Fatalf("write %s: %v", rel, err)
}
}
// project creates rel as a git repository with no .beads. The repository
// root is the discovery walk's boundary, so nothing above the fixture leaks
// into a case.
func (f *discoveryPinFixture) project(rel string) string {
f.t.Helper()
dir := f.mkdir(rel)
initGitRepoAt(f.t, dir)
return dir
}
// workspace creates project rel with a .beads directory holding files, each
// named relative to .beads.
func (f *discoveryPinFixture) workspace(rel string, files map[string]string) string {
f.t.Helper()
dir := f.project(rel)
f.mkdir(rel + "/.beads")
for name, content := range files {
f.write(rel+"/.beads/"+name, content)
}
return dir
}
// corruptWorkspace creates project rel whose metadata.json does not parse,
// plus any extra .beads files.
func (f *discoveryPinFixture) corruptWorkspace(rel string, extra map[string]string) string {
f.t.Helper()
files := map[string]string{"metadata.json": pinCorruptMetadata}
for name, content := range extra {
files[name] = content
}
return f.workspace(rel, files)
}
// yamlWorkspace creates project rel whose .beads holds only a config.yaml
// (no metadata.json and no database), plus any extra .beads files.
func (f *discoveryPinFixture) yamlWorkspace(rel string, extra map[string]string) string {
f.t.Helper()
files := map[string]string{"config.yaml": "# discovery pin fixture\n"}
for name, content := range extra {
files[name] = content
}
return f.workspace(rel, files)
}
// discoveryPinEnv is the caller environment without any BEADS_*/BD_*
// selector or setting and without git repository-location variables, with
// HOME and XDG_CONFIG_HOME under home, metrics and event flush off, and the
// migration freeze marker pointed at freezeMarker, a path that does not exist.
func discoveryPinEnv(home, freezeMarker string) []string {
var env []string
for _, kv := range testutil.WithoutGitRepoLocationEnv(os.Environ()) {
key, _, _ := strings.Cut(kv, "=")
if strings.HasPrefix(key, "BEADS_") || strings.HasPrefix(key, "BD_") ||
key == "HOME" || key == "XDG_CONFIG_HOME" {
continue
}
env = append(env, kv)
}
return append(env,
"HOME="+home,
"XDG_CONFIG_HOME="+filepath.Join(home, ".config"),
"BD_DISABLE_METRICS=1",
"BD_DISABLE_EVENT_FLUSH=1",
"BD_MIGRATION_FREEZE_FILE="+freezeMarker,
)
}
func (f *discoveryPinFixture) run(bd, cwd string, extraEnv []string, args ...string) (exit int, stdout, stderr string) {
f.t.Helper()
cmd := exec.Command(bd, args...)
cmd.Dir = cwd
cmd.Env = append(discoveryPinEnv(f.path("home"), f.path("no-such-freeze-marker")), extraEnv...)
var out, errOut bytes.Buffer
cmd.Stdout, cmd.Stderr = &out, &errOut
if err := cmd.Run(); err != nil {
var exitErr *exec.ExitError
if !errors.As(err, &exitErr) {
f.t.Fatalf("run bd %s: %v", strings.Join(args, " "), err)
}
exit = exitErr.ExitCode()
}
return exit, f.normalize(out.String(), false), f.normalize(errOut.String(), true)
}
var discoveryPinVersionLine = regexp.MustCompile(`(?m)^bd version .*$`)
// discoveryPinDuplicateBinaries matches the warning bd version appends when
// the caller's PATH holds more than one distinct bd binary.
var discoveryPinDuplicateBinaries = regexp.MustCompile(
`\nWarning: multiple 'bd' binaries found in PATH:\n(?: [^\n]*\n)*` +
`The first one is being used\. Remove duplicates to avoid confusion\.\n`)
// discoveryPinSandboxNotice matches the notice bd prints when it auto-detects
// a sandbox, which it does when it is not allowed to signal its own process.
var discoveryPinSandboxNotice = regexp.MustCompile(`(?m)^.*Sandbox detected, using direct mode\n`)
// normalize rewrites the fixture root as $ROOT and the build's version line
// as "bd version $VERSION". For stderr it also drops the notices that depend
// on the caller's environment rather than on the fixture (sandbox
// auto-detection, and bd version's duplicate binaries in PATH) and collapses
// consecutive repeats of a "Warning: redirect" line: discovery re-resolves
// the same redirect several times per invocation and how many times it warns
// is not part of the pin. Any other repeated line, such as a doubled
// "Error:", is kept.
func (f *discoveryPinFixture) normalize(s string, stderr bool) string {
for _, form := range f.forms {
s = strings.ReplaceAll(s, form, "$ROOT")
}
s = discoveryPinVersionLine.ReplaceAllLiteralString(s, "bd version $VERSION")
if !stderr {
return s
}
s = discoveryPinDuplicateBinaries.ReplaceAllLiteralString(s, "")
s = discoveryPinSandboxNotice.ReplaceAllLiteralString(s, "")
var b strings.Builder
prev := ""
for _, line := range strings.SplitAfter(s, "\n") {
if line == prev && strings.HasPrefix(line, "Warning: redirect ") {
continue
}
b.WriteString(line)
prev = line
}
return b.String()
}
// TestDiscoveryRefusalPinsMissingMetadata pins discovery when no workspace,
// a workspace without metadata.json and without a database, or a .beads that
// is a regular file is found.
func TestDiscoveryRefusalPinsMissingMetadata(t *testing.T) {
noBeads := func(f *discoveryPinFixture) (string, []string) { return f.project("p"), nil }
regularFileBeads := func(f *discoveryPinFixture) (string, []string) {
cwd := f.project("p")
f.write("p/.beads", "not a workspace\n")
return cwd, nil
}
runDiscoveryPinCases(t, []discoveryPinCase{
{
name: "no-beads-dir/list",
setup: noBeads,
args: []string{"list"},
exit: 1,
stderr: pinNoDatabaseRefusal,
},
{
// --json does not turn the refusal into a JSON document.
name: "no-beads-dir/list-json",
setup: noBeads,
args: []string{"list", "--json"},
exit: 1,
stderr: pinNoDatabaseRefusal,
},
{
name: "no-beads-dir/where",
setup: noBeads,
args: []string{"where"},
exit: 1,
stderr: pinNoWorkspaceWhereRefusal,
},
{
name: "no-beads-dir/where-json",
setup: noBeads,
args: []string{"where", "--json"},
exit: 1,
stdout: pinNoWorkspaceWhereJSON,
},
{
name: "empty-beads-dir/list",
setup: func(f *discoveryPinFixture) (string, []string) {
return f.workspace("p", nil), nil
},
args: []string{"list"},
exit: 1,
stderr: pinNoDatabaseRefusal,
},
{
name: "config-yaml-only/list",
setup: func(f *discoveryPinFixture) (string, []string) {
return f.yamlWorkspace("p", nil), nil
},
args: []string{"list"},
exit: 1,
stderr: pinNoDatabaseRefusal,
},
{
// The same directory is a workspace to bd where.
name: "config-yaml-only/where",
setup: func(f *discoveryPinFixture) (string, []string) {
return f.yamlWorkspace("p", nil), nil
},
args: []string{"where"},
stdout: "$ROOT/p/.beads\n",
},
{
// The working-directory walk selects a .beads that is a regular
// file, then fails to read its metadata.json (the BEADS_DIR form
// is in TestDiscoveryRefusalPinsExplicitBeadsDir).
name: "beads-is-regular-file/list",
setup: regularFileBeads,
args: []string{"list"},
exit: 1,
stderr: "Error: loading config: reading config: open $ROOT/p/.beads/metadata.json: not a directory\n",
},
{
name: "beads-is-regular-file/where",
setup: regularFileBeads,
args: []string{"where"},
exit: 1,
stderr: "Error: loading config: reading config: open $ROOT/p/.beads/metadata.json: not a directory\n",
},
})
}
// TestDiscoveryRefusalPinsCorruptMetadata pins the refusal for a discovered
// workspace whose metadata.json does not parse.
func TestDiscoveryRefusalPinsCorruptMetadata(t *testing.T) {
corrupt := func(f *discoveryPinFixture) (string, []string) { return f.corruptWorkspace("p", nil), nil }
runDiscoveryPinCases(t, []discoveryPinCase{
{
name: "list",
setup: corrupt,
args: []string{"list"},
exit: 1,
stderr: pinCorruptMetadataRefusal("$ROOT/p/.beads"),
},
{
name: "list-json",
setup: corrupt,
args: []string{"list", "--json"},
exit: 1,
stderr: pinCorruptMetadataRefusal("$ROOT/p/.beads"),
},
{
name: "create",
setup: corrupt,
args: []string{"create", "must not be written", "--json"},
exit: 1,
stderr: pinCorruptMetadataRefusal("$ROOT/p/.beads"),
},
{
// bd where never opens a store, but it still refuses.
name: "where",
setup: corrupt,
args: []string{"where"},
exit: 1,
stderr: pinCorruptMetadataRefusal("$ROOT/p/.beads"),
},
{
name: "where-json",
setup: corrupt,
args: []string{"where", "--json"},
exit: 1,
stderr: pinCorruptMetadataRefusal("$ROOT/p/.beads"),
},
{
// bd version warns and succeeds.
name: "version",
setup: corrupt,
args: []string{"version"},
stdout: "bd version $VERSION\n",
stderr: pinCorruptMetadataWarning("$ROOT/p/.beads"),
},
})
}
// TestDiscoveryRefusalPinsExplicitBeadsDir pins an exported BEADS_DIR that
// names no workspace. Each case runs from a corrupt workspace, so falling
// back to discovery from the working directory would print that workspace's
// refusal instead.
func TestDiscoveryRefusalPinsExplicitBeadsDir(t *testing.T) {
from := func(beadsDir func(f *discoveryPinFixture) string) func(f *discoveryPinFixture) (string, []string) {
return func(f *discoveryPinFixture) (string, []string) {
cwd := f.corruptWorkspace("cwd", nil)
return cwd, []string{"BEADS_DIR=" + beadsDir(f)}
}
}
missing := from(func(f *discoveryPinFixture) string { return f.path("missing/.beads") })
runDiscoveryPinCases(t, []discoveryPinCase{
{
name: "missing-dir/list",
setup: missing,
args: []string{"list"},
exit: 1,
stderr: pinNoDatabaseRefusal,
},
{
name: "missing-dir/where",
setup: missing,
args: []string{"where"},
exit: 1,
stderr: pinNoWorkspaceWhereRefusal,
},
{
name: "missing-dir/where-json",
setup: missing,
args: []string{"where", "--json"},
exit: 1,
stdout: pinNoWorkspaceWhereJSON,
},
{
name: "empty-dir/list",
setup: from(func(f *discoveryPinFixture) string { return f.mkdir("empty") }),
args: []string{"list"},
exit: 1,
stderr: pinNoDatabaseRefusal,
},
{
name: "regular-file/list",
setup: from(func(f *discoveryPinFixture) string {
f.write("file", "not a workspace\n")
return f.path("file")
}),
args: []string{"list"},
exit: 1,
stderr: "Error: loading config: reading config: open $ROOT/file/metadata.json: not a directory\n",
},
{
name: "corrupt-workspace/list",
setup: from(func(f *discoveryPinFixture) string {
f.corruptWorkspace("other", nil)
return f.path("other/.beads")
}),
args: []string{"list"},
exit: 1,
stderr: pinCorruptMetadataRefusal("$ROOT/other/.beads"),
},
})
}
// TestDiscoveryRefusalPinsBeadsEnvFile pins settings supplied by the
// discovered workspace's .beads/.env.
func TestDiscoveryRefusalPinsBeadsEnvFile(t *testing.T) {
runDiscoveryPinCases(t, []discoveryPinCase{
{
// A .env BEADS_DIR routes discovery to its target.
name: "beads-dir-routes-to-target",
setup: func(f *discoveryPinFixture) (string, []string) {
f.corruptWorkspace("target", nil)
return f.yamlWorkspace("p", map[string]string{".env": "BEADS_DIR=" + f.path("target/.beads") + "\n"}), nil
},
args: []string{"list"},
exit: 1,
stderr: pinCorruptMetadataRefusal("$ROOT/target/.beads"),
},
{
// The routing workspace's own corrupt metadata.json causes no refusal.
name: "beads-dir-route-skips-local-metadata",
setup: func(f *discoveryPinFixture) (string, []string) {
return f.corruptWorkspace("p", map[string]string{".env": "BEADS_DIR=" + f.path("missing/.beads") + "\n"}), nil
},
args: []string{"list"},
exit: 1,
stderr: pinNoDatabaseRefusal,
},
{
// An exported BEADS_DIR wins; the .env is never read.
name: "exported-beads-dir-wins",
setup: func(f *discoveryPinFixture) (string, []string) {
f.corruptWorkspace("target", nil)
cwd := f.yamlWorkspace("p", map[string]string{".env": "BEADS_DIR=" + f.path("target/.beads") + "\n"})
return cwd, []string{"BEADS_DIR=" + f.path("missing/.beads")}
},
args: []string{"list"},
exit: 1,
stderr: pinNoDatabaseRefusal,
},
{
// A .env BEADS_DB does not route a data command away from the
// workspace that holds the .env (the shadowing
// TestDiscoveryRefusalPinsDBSelection records for an exported
// BEADS_DB) ...
name: "beads-db-list",
setup: func(f *discoveryPinFixture) (string, []string) {
f.corruptWorkspace("target", nil)
return f.yamlWorkspace("p", map[string]string{".env": "BEADS_DB=" + f.path("target/.beads/dolt") + "\n"}), nil
},
args: []string{"list"},
exit: 1,
stderr: pinNoDatabaseRefusal,
},
{
// ... but it does route bd where.
name: "beads-db-where",
setup: func(f *discoveryPinFixture) (string, []string) {
f.corruptWorkspace("target", nil)
return f.yamlWorkspace("p", map[string]string{".env": "BEADS_DB=" + f.path("target/.beads/dolt") + "\n"}), nil
},
args: []string{"where"},
exit: 1,
stderr: pinCorruptMetadataRefusal("$ROOT/target/.beads"),
},
{
// Settings in the selected workspace's .env apply (BD_JSON here).
name: "setting-applies-in-selected-workspace",
setup: func(f *discoveryPinFixture) (string, []string) {
return f.yamlWorkspace("p", map[string]string{".env": "BD_JSON=true\n"}), nil
},
args: []string{"where"},
stdout: "{\n \"path\": \"$ROOT/p/.beads\",\n \"schema_version\": 1\n}\n",
},
{
// A .env that routes elsewhere contributes only its selector:
// its other settings are not imported, so the refusal is text.
name: "setting-not-imported-from-routing-source",
setup: func(f *discoveryPinFixture) (string, []string) {
return f.yamlWorkspace("p", map[string]string{".env": "BD_JSON=true\nBEADS_DIR=" + f.path("missing/.beads") + "\n"}), nil
},
args: []string{"where"},
exit: 1,
stderr: pinNoWorkspaceWhereRefusal,
},
{
// checkBlockedEnvVars sees only the exported environment, and runs
// before any .env is loaded: a .env BD_BACKEND is not refused, here
// or anywhere before discovery's own no-database refusal.
name: "blocked-backend-not-checked",
setup: func(f *discoveryPinFixture) (string, []string) {
return f.yamlWorkspace("p", map[string]string{".env": "BD_BACKEND=sqlite\n"}), nil
},
args: []string{"list"},
exit: 1,
stderr: pinNoDatabaseRefusal,
},
})
}
// TestDiscoveryRefusalPinsRedirect pins .beads/redirect handling: the
// warnings for unusable targets and which directory is selected afterwards.
func TestDiscoveryRefusalPinsRedirect(t *testing.T) {
runDiscoveryPinCases(t, []discoveryPinCase{
{
// A missing target is ignored and discovery keeps the source.
name: "missing-target",
setup: func(f *discoveryPinFixture) (string, []string) {
return f.corruptWorkspace("p", map[string]string{"redirect": f.path("missing/.beads") + "\n"}), nil
},
args: []string{"list"},
exit: 1,
stderr: "Warning: redirect target does not exist or is not a directory: $ROOT/missing/.beads\n" +
pinCorruptMetadataRefusal("$ROOT/p/.beads"),
},
{
// A target without project files is ignored the same way.
name: "target-without-workspace",
setup: func(f *discoveryPinFixture) (string, []string) {
f.mkdir("bare/.beads")
return f.corruptWorkspace("p", map[string]string{"redirect": "../bare/.beads\n"}), nil
},
args: []string{"list"},
exit: 1,
stderr: "Warning: ignoring redirect from $ROOT/p/.beads to $ROOT/bare/.beads because the target has no database or metadata.json; fix or delete the redirect file\n" +
pinCorruptMetadataRefusal("$ROOT/p/.beads"),
},
{
name: "corrupt-target",
setup: func(f *discoveryPinFixture) (string, []string) {
f.corruptWorkspace("target", nil)
return f.workspace("p", map[string]string{"redirect": "../target/.beads\n"}), nil
},
args: []string{"list"},
exit: 1,
stderr: pinCorruptMetadataRefusal("$ROOT/target/.beads"),
},
{
// Only one level is followed.
name: "chain",
setup: func(f *discoveryPinFixture) (string, []string) {
f.corruptWorkspace("final", nil)
f.corruptWorkspace("middle", map[string]string{"redirect": "../final/.beads\n"})
return f.workspace("p", map[string]string{"redirect": "../middle/.beads\n"}), nil
},
args: []string{"list"},
exit: 1,
stderr: "Warning: redirect chains not allowed, ignoring redirect in $ROOT/middle/.beads\n" +
pinCorruptMetadataRefusal("$ROOT/middle/.beads"),
},
{
// An explicit BEADS_DIR is followed through its redirect.
name: "explicit-beads-dir",
setup: func(f *discoveryPinFixture) (string, []string) {
f.corruptWorkspace("target", nil)
f.workspace("source", map[string]string{"redirect": "../target/.beads\n"})
return f.project("p"), []string{"BEADS_DIR=" + f.path("source/.beads")}
},
args: []string{"list"},
exit: 1,
stderr: pinCorruptMetadataRefusal("$ROOT/target/.beads"),
},
{
name: "where-reports-source",
setup: func(f *discoveryPinFixture) (string, []string) {
f.yamlWorkspace("target", nil)
return f.workspace("p", map[string]string{"redirect": "../target/.beads\n"}), nil
},
args: []string{"where"},
stdout: "$ROOT/target/.beads\n (via redirect from $ROOT/p/.beads)\n",
},
})
}
// TestDiscoveryRefusalPinsDBSelection pins database selection by --db and by
// the BEADS_DB and BD_DB environment variables.
//
// Two of these record inconsistencies as they stand rather than endorse
// them: a data command ignores BD_DB, and lets a discoverable workspace in
// the working directory shadow BEADS_DB, while bd where honors both.
func TestDiscoveryRefusalPinsDBSelection(t *testing.T) {
target := func(f *discoveryPinFixture) string {
f.corruptWorkspace("target", nil)
return f.path("target/.beads/dolt")
}
runDiscoveryPinCases(t, []discoveryPinCase{
{
// A --db path selects the workspace that owns it.
name: "db-path",
setup: func(f *discoveryPinFixture) (string, []string) {
target(f)
return f.project("p"), nil
},
args: []string{"--db", "$ROOT/target/.beads/dolt", "list"},
exit: 1,
stderr: pinCorruptMetadataRefusal("$ROOT/target/.beads"),
},
{
name: "db-path-beats-beads-dir",
setup: func(f *discoveryPinFixture) (string, []string) {
target(f)
f.corruptWorkspace("other", nil)
return f.project("p"), []string{"BEADS_DIR=" + f.path("other/.beads")}
},
args: []string{"--db", "$ROOT/target/.beads/dolt", "list"},
exit: 1,
stderr: pinCorruptMetadataRefusal("$ROOT/target/.beads"),
},
{
name: "db-path-beats-working-directory",
setup: func(f *discoveryPinFixture) (string, []string) {
target(f)
return f.corruptWorkspace("p", nil), nil
},
args: []string{"--db", "$ROOT/target/.beads/dolt", "list"},
exit: 1,
stderr: pinCorruptMetadataRefusal("$ROOT/target/.beads"),
},
{
// A --db value that is a database name rather than an existing
// path leaves discovery to the working directory.
name: "db-name-without-workspace",
setup: func(f *discoveryPinFixture) (string, []string) {
return f.project("p"), nil
},
args: []string{"--db", "pindb", "list"},
exit: 1,
stderr: pinNoDatabaseRefusal,
},
{
name: "db-name-in-workspace",
setup: func(f *discoveryPinFixture) (string, []string) {
return f.corruptWorkspace("p", nil), nil
},
args: []string{"--db", "pindb", "list"},
exit: 1,
stderr: pinCorruptMetadataRefusal("$ROOT/p/.beads"),
},
{
name: "beads-db-env",
setup: func(f *discoveryPinFixture) (string, []string) {
return f.project("p"), []string{"BEADS_DB=" + target(f)}
},
args: []string{"list"},
exit: 1,
stderr: pinCorruptMetadataRefusal("$ROOT/target/.beads"),
},
{
// Inconsistency: the working directory's workspace shadows BEADS_DB.
name: "beads-db-env-shadowed-by-working-directory",
setup: func(f *discoveryPinFixture) (string, []string) {
return f.corruptWorkspace("p", nil), []string{"BEADS_DB=" + target(f)}
},
args: []string{"list"},
exit: 1,
stderr: pinCorruptMetadataRefusal("$ROOT/p/.beads"),
},
{
name: "beads-db-env-where",
setup: func(f *discoveryPinFixture) (string, []string) {
return f.corruptWorkspace("p", nil), []string{"BEADS_DB=" + target(f)}
},
args: []string{"where"},
exit: 1,
stderr: pinCorruptMetadataRefusal("$ROOT/target/.beads"),
},
{
// Inconsistency: a data command ignores BD_DB.
name: "bd-db-env",
setup: func(f *discoveryPinFixture) (string, []string) {
return f.project("p"), []string{"BD_DB=" + target(f)}
},
args: []string{"list"},
exit: 1,
stderr: pinNoDatabaseRefusal,
},
{
name: "bd-db-env-where",
setup: func(f *discoveryPinFixture) (string, []string) {
return f.project("p"), []string{"BD_DB=" + target(f)}
},
args: []string{"where"},
exit: 1,
stderr: pinCorruptMetadataRefusal("$ROOT/target/.beads"),
},
})
}
// TestDiscoveryRefusalPinsBlockedEnvVarsRunFirst pins that the blocked
// backend variables are refused before any discovery, for every command.
func TestDiscoveryRefusalPinsBlockedEnvVarsRunFirst(t *testing.T) {
runDiscoveryPinCases(t, []discoveryPinCase{
{
name: "no-workspace",
setup: func(f *discoveryPinFixture) (string, []string) {
return f.project("p"), []string{"BD_BACKEND=sqlite"}
},
args: []string{"list"},
exit: 1,
stderr: pinBlockedEnvRefusal("BD_BACKEND"),
},
{
name: "corrupt-metadata",
setup: func(f *discoveryPinFixture) (string, []string) {
return f.corruptWorkspace("p", nil), []string{"BD_BACKEND=sqlite"}
},
args: []string{"list"},
exit: 1,
stderr: pinBlockedEnvRefusal("BD_BACKEND"),
},
{
name: "explicit-beads-dir",
setup: func(f *discoveryPinFixture) (string, []string) {
return f.project("p"), []string{"BD_BACKEND=sqlite", "BEADS_DIR=" + f.path("missing/.beads")}
},
args: []string{"list"},
exit: 1,
stderr: pinBlockedEnvRefusal("BD_BACKEND"),
},
{
// A BEADS_DIR that cannot even be read as a directory is still
// reached only after the blocked variable is refused.
name: "unreadable-beads-dir",
setup: func(f *discoveryPinFixture) (string, []string) {
f.write("file", "not a workspace\n")
return f.project("p"), []string{"BD_BACKEND=sqlite", "BEADS_DIR=" + f.path("file")}
},
args: []string{"list"},
exit: 1,
stderr: pinBlockedEnvRefusal("BD_BACKEND"),
},
{
name: "db-path",
setup: func(f *discoveryPinFixture) (string, []string) {
f.corruptWorkspace("target", nil)
return f.project("p"), []string{"BD_BACKEND=sqlite"}
},
args: []string{"--db", "$ROOT/target/.beads/dolt", "list"},
exit: 1,
stderr: pinBlockedEnvRefusal("BD_BACKEND"),
},
{
// --json does not turn the refusal into a JSON document.
name: "database-backend-json",
setup: func(f *discoveryPinFixture) (string, []string) {
return f.corruptWorkspace("p", nil), []string{"BD_DATABASE_BACKEND=dolt"}
},
args: []string{"list", "--json"},
exit: 1,
stderr: pinBlockedEnvRefusal("BD_DATABASE_BACKEND"),
},
{
name: "where-json",
setup: func(f *discoveryPinFixture) (string, []string) {
return f.project("p"), []string{"BD_BACKEND=sqlite"}
},
args: []string{"where", "--json"},
exit: 1,
stderr: pinBlockedEnvRefusal("BD_BACKEND"),
},
{
name: "version-command",
setup: func(f *discoveryPinFixture) (string, []string) {
return f.project("p"), []string{"BD_BACKEND=sqlite"}
},
args: []string{"version"},
exit: 1,
stderr: pinBlockedEnvRefusal("BD_BACKEND"),
},
{
// The root command then prints cobra's error and usage; only the
// refusal itself is pinned.
name: "version-flag",
setup: func(f *discoveryPinFixture) (string, []string) {
return f.project("p"), []string{"BD_BACKEND=sqlite"}
},
args: []string{"--version"},
exit: 1,
stderr: pinBlockedEnvRefusal("BD_BACKEND"),
stderrPrefix: true,
},
})
}

View file

@ -220,7 +220,7 @@ Examples:
if err := validateDoctorWorkspaceBackend(absPath); isLegacyUpgradeRefusal(err) {
return printLegacyUpgradeDiagnostic(err)
} else if err != nil {
return HandleError("%v", err)
return handleWorkspaceGuardError(err)
}
if doctorFix && isOrchestratorRoot(absPath) {

View file

@ -43,6 +43,7 @@ go_library(
"//internal/storage/issueops",
"//internal/types",
"//internal/utils",
"//internal/versionedhistory",
"@com_github_burntsushi_toml//:toml",
"@com_github_go_sql_driver_mysql//:mysql",
"@in_gopkg_yaml_v3//:yaml_v3",
@ -81,7 +82,11 @@ go_test(
"testmain_cgo_test.go",
"testmain_nocgo_test.go",
"validation_test.go",
"versioned_history_activation_test.go",
],
# versioned_history_activation_test.go parses store.go from its working
# directory, and a Bazel test only sees its declared runfiles.
data = ["store.go"],
embed = [":fix"],
deps = [
"//internal/configfile",

View file

@ -5,10 +5,11 @@ import (
"github.com/steveyegge/beads/internal/eventsjournal"
"github.com/steveyegge/beads/internal/storage/dolt"
"github.com/steveyegge/beads/internal/versionedhistory"
)
// openBeadMutatingStore opens a repair handler's store WITH the workspace's
// events-journal activation applied.
// events-journal and versioned-history activation applied.
//
// Most of bd doctor inspects and repairs workspace state — schema cursors,
// metadata, remotes, fingerprints, git — and none of that belongs in a journal
@ -17,7 +18,10 @@ import (
// fresh-clone import paths CREATE them. Those are ordinary bead mutations, and
// a consumer whose mirror silently diverges because someone ran
// `bd doctor --fix` is exactly the failure the journal exists to prevent — the
// more so because a repair is unattended and nobody is watching the diff.
// more so because a repair is unattended and nobody is watching the diff. The
// same repairs are also ordinary issue mutations for version history, and an
// issue_versions trail with a silent gap where `bd doctor --fix` ran is the same
// failure one table over.
//
// The read-only and workspace-state handlers deliberately keep opening the
// store directly; they carry their exemption in the construction guard, with a
@ -27,7 +31,7 @@ import (
// is what a repair path legitimately does.
func openBeadMutatingStore(ctx context.Context, beadsDir string) (*dolt.DoltStore, error) {
store, err := dolt.NewFromConfig(ctx, beadsDir)
return activated(beadsDir, store, err)
return activated(ctx, beadsDir, store, err)
}
// openBeadMutatingStoreCreating is openBeadMutatingStore for the fresh-clone
@ -36,15 +40,23 @@ func openBeadMutatingStore(ctx context.Context, beadsDir string) (*dolt.DoltStor
// guard rather than failing on an absent database.
func openBeadMutatingStoreCreating(ctx context.Context, beadsDir string) (*dolt.DoltStore, error) {
store, err := dolt.NewFromConfigWithOptions(ctx, beadsDir, &dolt.Config{CreateIfMissing: true})
return activated(beadsDir, store, err)
return activated(ctx, beadsDir, store, err)
}
// activated applies the workspace's journal setting and closes the store if it
// cannot be honored. A failed open passes straight through, so the typed-nil
// store never reaches the activation.
func activated(beadsDir string, store *dolt.DoltStore, err error) (*dolt.DoltStore, error) {
// activated applies the workspace's journal setting and the store's own
// versioned-history setting, and closes the store if the journal cannot be
// honored. A failed open passes straight through, so the typed-nil store never
// reaches the activation.
//
// Versioned history cannot fail an open (a plumbing that cannot version simply
// records nothing), so it needs no error handling of its own; it runs after the
// journal so a store the journal refused is never activated. It is the shared
// internal/versionedhistory rule, not a copy: package main cannot be imported
// from here.
func activated(ctx context.Context, beadsDir string, store *dolt.DoltStore, err error) (*dolt.DoltStore, error) {
if _, err = eventsjournal.ActivateStore(beadsDir, store, err); err != nil {
return nil, err
}
_, _ = versionedhistory.ActivateStore(ctx, store, nil)
return store, nil
}

View file

@ -0,0 +1,87 @@
package fix
import (
"go/ast"
"go/parser"
"go/token"
"strconv"
"strings"
"testing"
)
const (
versionedHistoryPkg = "github.com/steveyegge/beads/internal/versionedhistory"
// package main cannot be imported at all; the guard below is that the
// activation this package applies lives in a package it CAN import, so the
// repair handlers apply the identical rule as the command surface rather than
// a copy of it.
beadMutatingStoreFile = "store.go"
)
// TestVersionedHistoryDoctorRepairOpenerUsesTheSharedActivation holds the one
// construction site the cmd/bd construction guard cannot see. bd doctor is exempted
// from that guard as a package (its CHECKS are read-only), so the repair opener --
// which opens the store the bead-mutating repairs (stale-closed cleanup, pollution
// cleanup, the fresh-clone imports) write through -- is held to the property here.
//
// A repair that deletes or creates issues is an ordinary mutation for version
// history: an issue_versions trail with a silent gap where `bd doctor --fix` ran is
// the same failure the routed-write bug produced, one command over, and the more
// dangerous for being unattended.
//
// The check is structural for the same reason the cmd/bd guard is: activation
// failing is invisible from inside the process. It requires the activation that
// `activated` applies to come from internal/versionedhistory -- the ONE
// implementation of the rule, which this package can import and package main cannot
// be.
func TestVersionedHistoryDoctorRepairOpenerUsesTheSharedActivation(t *testing.T) {
fset := token.NewFileSet()
file, err := parser.ParseFile(fset, beadMutatingStoreFile, nil, 0)
if err != nil {
t.Fatalf("parse %s: %v", beadMutatingStoreFile, err)
}
imports := map[string]string{}
for _, spec := range file.Imports {
path, err := strconv.Unquote(spec.Path.Value)
if err != nil {
t.Fatalf("unquote import %s: %v", spec.Path.Value, err)
}
name := path[strings.LastIndex(path, "/")+1:]
if spec.Name != nil {
name = spec.Name.Name
}
imports[name] = path
}
var activated *ast.FuncDecl
for _, decl := range file.Decls {
if fn, ok := decl.(*ast.FuncDecl); ok && fn.Name.Name == "activated" {
activated = fn
}
}
if activated == nil {
t.Fatalf("%s has no `activated` function: the repair opener's activation moved and this guard no longer looks at it", beadMutatingStoreFile)
}
called := false
ast.Inspect(activated, func(n ast.Node) bool {
call, ok := n.(*ast.CallExpr)
if !ok {
return true
}
sel, ok := call.Fun.(*ast.SelectorExpr)
if !ok {
return true
}
if ident, ok := sel.X.(*ast.Ident); ok && imports[ident.Name] == versionedHistoryPkg && sel.Sel.Name == "ActivateStore" {
called = true
}
return true
})
if !called {
t.Errorf("`activated` in %s never calls versionedhistory.ActivateStore: every repair that mutates issues through it "+
"mints NO issue_versions row while `bd doctor --fix` reports success. Apply the shared activation there; "+
"it is the same rule as the command surface and package main cannot be imported to reuse it.", beadMutatingStoreFile)
}
}

View file

@ -43,10 +43,10 @@ func runBDSplit(t *testing.T, bd, dir string, args ...string) (stdout, stderr st
return stdoutBuf.String(), stderrBuf.String(), err
}
// TestDoctorEmbeddedSupportedChecks verifies that --check=artifacts,
// TestEmbeddedDoctorSupportedChecks verifies that --check=artifacts,
// --check=conventions, and --check=pollution run in embedded mode rather
// than hitting the "not yet supported" stub (GH#3597).
func TestDoctorEmbeddedSupportedChecks(t *testing.T) {
func TestEmbeddedDoctorSupportedChecks(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")
}
@ -83,11 +83,11 @@ func TestDoctorEmbeddedSupportedChecks(t *testing.T) {
}
}
// TestDoctorEmbeddedUnsupportedJSON verifies that variants which still require
// TestEmbeddedDoctorUnsupportedJSON verifies that variants which still require
// server mode (bare doctor, --check=validate) emit a structured JSON payload
// when --json or --agent --json is set, rather than the prose stub. Tooling
// can detect "unsupported" without text-matching (GH#3597).
func TestDoctorEmbeddedUnsupportedJSON(t *testing.T) {
func TestEmbeddedDoctorUnsupportedJSON(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")
}
@ -150,10 +150,10 @@ func TestDoctorEmbeddedUnsupportedJSON(t *testing.T) {
}
}
// TestDoctorEmbeddedUnsupportedProse verifies that bare bd doctor (without
// TestEmbeddedDoctorUnsupportedProse verifies that bare bd doctor (without
// --json) still emits the human-readable prose stub for terminal users,
// pointing at the supported --check=* variants (GH#3597).
func TestDoctorEmbeddedUnsupportedProse(t *testing.T) {
func TestEmbeddedDoctorUnsupportedProse(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")
}

View file

@ -9,16 +9,28 @@
// beside the rest of the freeze suite; both halves share the helpers below and
// the hermetic subprocess harness declared there.
//
// The same gate for `bd backup init`, `backup remove`, `backup sync` and
// `bd import` sits further down, between the doctor tests it mirrors.
//
// This file MUST NOT carry a cgo build tag: it drives a bd binary built with
// the gms_pure_go tag via subprocess, and asserts only on files and output.
// the gms_pure_go tag via subprocess, and asserts on files and output (and, for
// the server rows of the backup/import tests, on the Dolt test server's tables).
package main
import (
"context"
"database/sql"
"encoding/json"
"fmt"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"testing"
"github.com/steveyegge/beads/internal/storage/doltutil"
)
// doctorMutationSurface is one class of doctor invocation that mutates the
@ -122,6 +134,306 @@ func TestDoctorMutationBlockedInReadonlyMode(t *testing.T) {
}
}
// The backup and import commands: the same gate, a different failure.
//
// `bd backup init`, `backup remove`, `backup sync` and `bd import` never called
// CheckReadonly, so strict --readonly only held as far as the store underneath
// happened to refuse. An embedded store is opened read-only, so those commands
// failed, but with the storage layer's text rather than the standard refusal,
// and `backup sync` took the backup lock first and left .beads/backup.lock
// behind. A server-mode store has no such floor: the same commands ran to
// completion and rewrote or emptied the backup registry, wrote the backup
// destination, or imported issues. So every row runs in both flavours, and the
// checks go past the file tree: a server-mode import leaves .beads untouched
// even when it succeeds, so the issue count and the registry are compared too.
//
// `backup status` and `list` only read, and stay allowed;
// TestBackupStatusAndListWorkInReadonlyMode pins that. `bd backup` on its own is
// a command group that only prints help, and is left as it is.
// backupImportSurface is one command that strict --readonly must refuse.
type backupImportSurface struct {
name string
// args are the command and its arguments; the test appends the global flags.
args []string
// op is the operation label the gate reports.
op string
}
func backupImportSurfaces(w *readonlyGateWorkspace) []backupImportSurface {
return []backupImportSurface{
// A destination other than the registered one, so a run that goes
// through shows up as a changed registry.
{name: "backup-init", args: []string{"backup", "init", filepath.Join(w.dir, "other-backup-dest")}, op: "backup init"},
{name: "backup-remove", args: []string{"backup", "remove"}, op: "backup remove"},
{name: "backup-sync", args: []string{"backup", "sync"}, op: "backup sync"},
{name: "import", args: []string{"import", w.importFile}, op: "import"},
// A preview writes nothing, but strict --readonly already refuses
// `create --dry-run`, so import's is refused the same way.
{name: "import-dry-run", args: []string{"import", "--dry-run", w.importFile}, op: "import"},
}
}
// readonlyGateFlagSets are the global flag combinations every row runs under.
// --sandbox changes how bd treats the store (it disables auto-push); the gate
// has to hold with it as well.
var readonlyGateFlagSets = []struct {
name string
flags []string
}{
{name: "readonly", flags: []string{"--readonly"}},
{name: "readonly-sandbox", flags: []string{"--readonly", "--sandbox"}},
}
// readonlyGateFlavours are the two stores the gate has to hold over.
var readonlyGateFlavours = []struct {
name string
setup func(*testing.T) *readonlyGateWorkspace
}{
{name: "embedded", setup: newEmbeddedReadonlyGateWorkspace},
{name: "server", setup: newServerReadonlyGateWorkspace},
}
// readonlyGateWorkspace is an initialized workspace holding one issue and one
// registered backup, plus what a refused command has to leave alone.
type readonlyGateWorkspace struct {
bd, dir string
prefix string
dest string // directory behind the registered default backup
importFile string // a one-issue JSONL file for `bd import`
// Server flavour only: the shared test server and this workspace's database
// on it. A zero port means the embedded flavour.
port int
database string
}
// readonlyGateState is everything a refused command could have changed.
type readonlyGateState struct {
tree readonlyTreeSnapshot // the whole .beads directory
dest readonlyTreeSnapshot // the backup destination
issues int // what `bd list` reports
registry string // server flavour only: dolt_backups as name=url rows
}
func newEmbeddedReadonlyGateWorkspace(t *testing.T) *readonlyGateWorkspace {
t.Helper()
bd, dir := setupMigrationFreezeWorkspace(t)
w := &readonlyGateWorkspace{bd: bd, dir: dir, prefix: "test"}
w.seed(t)
return w
}
// newServerReadonlyGateWorkspace is the same workspace on the shared Dolt test
// server. The default lane starts none, so it skips there, as the other
// server-mode readonly test in this package does.
func newServerReadonlyGateWorkspace(t *testing.T) *readonlyGateWorkspace {
t.Helper()
port, err := strconv.Atoi(os.Getenv("BEADS_DOLT_PORT"))
if err != nil || port <= 0 {
t.Skip("shared Dolt test server is unavailable")
}
dir := t.TempDir()
bd := buildBDForInitTests(t)
runGitForBootstrapTest(t, dir, "init", "-q")
runGitForBootstrapTest(t, dir, "config", "core.hooksPath", ".git/hooks")
// The prefix names the database on the shared server, so it must be unique.
prefix := "rog" + strings.TrimPrefix(uniqueTestDBName(t), "testdb_")
stdout, stderr, code := runBDMigrationFreeze(t, bd, dir, "init", "--server", "--server-host", "127.0.0.1",
"--server-port", strconv.Itoa(port), "--external", "--prefix", prefix,
"--quiet", "--non-interactive", "--skip-hooks", "--skip-agents")
if code != 0 {
t.Fatalf("bd init --server failed (exit %d):\nstdout:\n%s\nstderr:\n%s", code, stdout, stderr)
}
var meta struct {
Database string `json:"dolt_database"`
}
data, err := os.ReadFile(filepath.Join(dir, ".beads", "metadata.json"))
if err != nil {
t.Fatalf("reading metadata.json: %v", err)
}
if err := json.Unmarshal(data, &meta); err != nil || meta.Database == "" {
t.Fatalf("metadata.json names no dolt_database (%v):\n%s", err, data)
}
t.Cleanup(func() {
db, err := sql.Open("mysql", doltutil.ServerDSN{Host: "127.0.0.1", Port: port, User: "root"}.String())
if err != nil {
return
}
defer db.Close()
_, _ = db.ExecContext(context.Background(), fmt.Sprintf("DROP DATABASE IF EXISTS `%s`", meta.Database)) //nolint:gosec // generated test name
})
w := &readonlyGateWorkspace{bd: bd, dir: dir, prefix: prefix, port: port, database: meta.Database}
w.seed(t)
return w
}
// seed gives the workspace one issue, one registered backup and a JSONL file
// whose single issue is not in the workspace yet.
func (w *readonlyGateWorkspace) seed(t *testing.T) {
t.Helper()
w.dest = filepath.Join(w.dir, "backup-dest")
w.importFile = filepath.Join(w.dir, "import.jsonl")
record := fmt.Sprintf(`{"id":"%s-gate1","title":"imported under readonly","status":"open","priority":2,"issue_type":"task","created_at":"2026-01-01T00:00:00Z"}`+"\n", w.prefix)
if err := os.WriteFile(w.importFile, []byte(record), 0o644); err != nil {
t.Fatalf("writing %s: %v", w.importFile, err)
}
if stdout, stderr, code := w.run(t, "create", "seed issue", "-p", "2"); code != 0 {
t.Fatalf("bd create failed (exit %d):\nstdout:\n%s\nstderr:\n%s", code, stdout, stderr)
}
w.registerBackup(t)
}
func (w *readonlyGateWorkspace) run(t *testing.T, args ...string) (stdout, stderr string, exitCode int) {
t.Helper()
return runBDMigrationFreeze(t, w.bd, w.dir, args...)
}
// registerBackup points the default backup at w.dest. Rows call it before each
// run: a row that went through when it should have been refused may have moved
// or removed the backup, and the next row still needs one to be refused against.
func (w *readonlyGateWorkspace) registerBackup(t *testing.T) {
t.Helper()
if stdout, stderr, code := w.run(t, "backup", "init", "file://"+w.dest); code != 0 {
t.Fatalf("bd backup init failed (exit %d):\nstdout:\n%s\nstderr:\n%s", code, stdout, stderr)
}
}
func (w *readonlyGateWorkspace) state(t *testing.T) readonlyGateState {
t.Helper()
// Count the issues first: that is itself a strict --readonly read, so
// anything it creates lazily exists before the snapshot instead of showing
// up in it as a change.
s := readonlyGateState{issues: w.issueCount(t)}
s.tree = snapshotReadonlyTree(t, filepath.Join(w.dir, ".beads"))
s.dest = snapshotReadonlyTree(t, w.dest)
if w.port != 0 {
s.registry = w.backupRegistry(t)
}
return s
}
func (w *readonlyGateWorkspace) issueCount(t *testing.T) int {
t.Helper()
stdout, stderr, code := w.run(t, "list", "--json", "--readonly")
if code != 0 {
t.Fatalf("bd list failed (exit %d):\nstdout:\n%s\nstderr:\n%s", code, stdout, stderr)
}
var issues []json.RawMessage
if err := json.Unmarshal([]byte(stdout), &issues); err != nil {
t.Fatalf("bd list --json is not a JSON array: %v\n%s", err, stdout)
}
return len(issues)
}
// backupRegistry reads the backups the server has registered for this
// workspace's database. No bd command prints them, and the file tree never
// shows them, so a refused run is checked against the server itself.
func (w *readonlyGateWorkspace) backupRegistry(t *testing.T) string {
t.Helper()
db, err := sql.Open("mysql", doltutil.ServerDSN{Host: "127.0.0.1", Port: w.port, User: "root", Database: w.database}.String())
if err != nil {
t.Fatalf("connecting to the test server: %v", err)
}
defer db.Close()
rows, err := db.QueryContext(context.Background(), "SELECT name, url FROM dolt_backups ORDER BY name")
if err != nil {
t.Fatalf("reading dolt_backups: %v", err)
}
defer rows.Close()
var lines []string
for rows.Next() {
var name, url string
if err := rows.Scan(&name, &url); err != nil {
t.Fatalf("scanning dolt_backups: %v", err)
}
lines = append(lines, name+"="+url)
}
if err := rows.Err(); err != nil {
t.Fatalf("reading dolt_backups: %v", err)
}
return strings.Join(lines, "\n")
}
// assertUnchanged proves a refusal happened before any mutation, not merely
// that the refusal text was printed.
func (w *readonlyGateWorkspace) assertUnchanged(t *testing.T, before readonlyGateState) {
t.Helper()
after := w.state(t)
if diff := readonlyTreeDiff(before.tree, after.tree); len(diff) > 0 {
t.Errorf("a refused run changed .beads:\n %s", strings.Join(diff, "\n "))
}
if diff := readonlyTreeDiff(before.dest, after.dest); len(diff) > 0 {
t.Errorf("a refused run changed the backup destination:\n %s", strings.Join(diff, "\n "))
}
if after.issues != before.issues {
t.Errorf("a refused run changed the issue count: %d -> %d", before.issues, after.issues)
}
if after.registry != before.registry {
t.Errorf("a refused run changed the backup registry:\nbefore:\n%s\nafter:\n%s", before.registry, after.registry)
}
}
// readonlyTreeDiff names what differs between two snapshots, so a leaked
// mutation reads as "+ backup.lock" rather than as two opaque hash maps.
func readonlyTreeDiff(before, after readonlyTreeSnapshot) []string {
var diff []string
if before.Exists != after.Exists {
diff = append(diff, fmt.Sprintf("exists: %t -> %t", before.Exists, after.Exists))
}
for path, was := range before.Entries {
if now, ok := after.Entries[path]; !ok {
diff = append(diff, "- "+path)
} else if now != was {
diff = append(diff, "~ "+path)
}
}
for path := range after.Entries {
if _, ok := before.Entries[path]; !ok {
diff = append(diff, "+ "+path)
}
}
sort.Strings(diff)
return diff
}
// TestBackupAndImportBlockedInReadonlyMode is the readonly gate for the backup
// and import commands. One workspace per flavour serves every row; each row
// re-registers the backup first, so none depends on what the previous one did.
func TestBackupAndImportBlockedInReadonlyMode(t *testing.T) {
for _, flavour := range readonlyGateFlavours {
t.Run(flavour.name, func(t *testing.T) {
w := flavour.setup(t)
for _, tt := range backupImportSurfaces(w) {
t.Run(tt.name, func(t *testing.T) {
for _, flagSet := range readonlyGateFlagSets {
t.Run(flagSet.name, func(t *testing.T) {
w.registerBackup(t)
before := w.state(t)
args := append(append([]string{}, tt.args...), flagSet.flags...)
stdout, stderr, code := w.run(t, args...)
want := "Error: operation '" + tt.op + "' is not allowed in read-only mode\n"
if code != 1 {
t.Errorf("exit code = %d, want 1\nstdout:\n%s\nstderr:\n%s", code, stdout, stderr)
}
if stderr != want {
t.Errorf("stderr is not exactly the standard refusal\ngot: %q\nwant: %q", stderr, want)
}
if stdout != "" {
t.Errorf("stdout should be empty when the command is refused, got:\n%s", stdout)
}
w.assertUnchanged(t, before)
})
}
})
}
})
}
}
// TestDoctorDiagnosisWorksInReadonlyMode pins the other half of the contract:
// the gate keys on --fix/--clean alone, so every diagnosis mode still runs
// under --readonly. Diagnosing a sandboxed workspace is the whole point.
@ -143,6 +455,25 @@ func TestDoctorDiagnosisWorksInReadonlyMode(t *testing.T) {
}
}
// TestBackupStatusAndListWorkInReadonlyMode is the control for the backup and
// import gate: it keys on the commands that write, so `backup status` and
// `list` still run under --readonly, in both flavours.
func TestBackupStatusAndListWorkInReadonlyMode(t *testing.T) {
for _, flavour := range readonlyGateFlavours {
t.Run(flavour.name, func(t *testing.T) {
w := flavour.setup(t)
for _, args := range [][]string{{"backup", "status"}, {"list"}} {
t.Run(strings.Join(args, "_"), func(t *testing.T) {
stdout, stderr, code := w.run(t, append(append([]string{}, args...), "--readonly")...)
if code != 0 || strings.Contains(stderr, "not allowed in read-only mode") {
t.Errorf("bd %v under --readonly should run (exit %d):\nstdout:\n%s\nstderr:\n%s", args, code, stdout, stderr)
}
})
}
})
}
}
// TestDoctorMaintenanceSkippedInReadonlyMode is the readonly twin of
// TestDoctorMaintenanceSkippedDuringMigrationFreeze — see that test for why
// plain `bd doctor` had hidden writes at all, and for the shared-server setup.

View file

@ -1124,6 +1124,11 @@ is shown as not running, and the next bd command launches it.`,
if beadsDir == "" {
return HandleErrorWithHint(activeWorkspaceNotFoundError(), diagHint())
}
// A workspace in a format this build cannot open is refused before
// configfile.Load, which would first migrate a legacy config.json.
if err := checkDiscoveredWorkspaceFormat(beadsDir); err != nil {
return handleWorkspaceGuardError(err)
}
cfg, cfgErr := configfile.Load(beadsDir)
if cfgErr != nil {
return HandleError("loading config: %v", cfgErr)
@ -2004,6 +2009,11 @@ func showDoltConfig(testConnection bool) error {
return HandleErrorWithHint(activeWorkspaceNotFoundError(), diagHint())
}
// A workspace in a format this build cannot open is refused before
// configfile.Load, which would first migrate a legacy config.json.
if err := checkDiscoveredWorkspaceFormat(beadsDir); err != nil {
return handleWorkspaceGuardError(err)
}
cfg, err := configfile.Load(beadsDir)
if err != nil {
return HandleError("loading config: %v", err)

View file

@ -41,7 +41,7 @@ func bdDoltSeparate(t *testing.T, bd, dir string, args ...string) (string, strin
// -- push --
func TestDoltLocalOnly_Push_ExitsZeroWithMessage(t *testing.T) {
func TestEmbeddedDoltLocalOnly_Push_ExitsZeroWithMessage(t *testing.T) {
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run dolt.local-only embedded tests")
}
@ -62,7 +62,7 @@ func TestDoltLocalOnly_Push_ExitsZeroWithMessage(t *testing.T) {
}
}
func TestDoltLocalOnly_Push_LocalStoreCopy(t *testing.T) {
func TestEmbeddedDoltLocalOnly_Push_LocalStoreCopy(t *testing.T) {
// The push no-op message must include the "Your issues are stored locally" line.
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run dolt.local-only embedded tests")
@ -77,7 +77,7 @@ func TestDoltLocalOnly_Push_LocalStoreCopy(t *testing.T) {
}
}
func TestDoltLocalOnly_Push_JSON_DisabledStatus(t *testing.T) {
func TestEmbeddedDoltLocalOnly_Push_JSON_DisabledStatus(t *testing.T) {
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run dolt.local-only embedded tests")
}
@ -101,7 +101,7 @@ func TestDoltLocalOnly_Push_JSON_DisabledStatus(t *testing.T) {
// -- pull --
func TestDoltLocalOnly_Pull_ExitsZeroWithMessage(t *testing.T) {
func TestEmbeddedDoltLocalOnly_Pull_ExitsZeroWithMessage(t *testing.T) {
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run dolt.local-only embedded tests")
}
@ -122,7 +122,7 @@ func TestDoltLocalOnly_Pull_ExitsZeroWithMessage(t *testing.T) {
}
}
func TestDoltLocalOnly_Pull_JSON_DisabledStatus(t *testing.T) {
func TestEmbeddedDoltLocalOnly_Pull_JSON_DisabledStatus(t *testing.T) {
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run dolt.local-only embedded tests")
}
@ -146,7 +146,7 @@ func TestDoltLocalOnly_Pull_JSON_DisabledStatus(t *testing.T) {
// -- remote add --
func TestDoltLocalOnly_RemoteAdd_RefusesExitOne(t *testing.T) {
func TestEmbeddedDoltLocalOnly_RemoteAdd_RefusesExitOne(t *testing.T) {
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run dolt.local-only embedded tests")
}
@ -169,7 +169,7 @@ func TestDoltLocalOnly_RemoteAdd_RefusesExitOne(t *testing.T) {
}
}
func TestDoltLocalOnly_RemoteAdd_ErrorOnStderr(t *testing.T) {
func TestEmbeddedDoltLocalOnly_RemoteAdd_ErrorOnStderr(t *testing.T) {
// The refusal must go to stderr (not stdout) so agents can distinguish errors.
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run dolt.local-only embedded tests")
@ -189,7 +189,7 @@ func TestDoltLocalOnly_RemoteAdd_ErrorOnStderr(t *testing.T) {
// -- config round-trip --
func TestDoltLocalOnly_ConfigRoundTrip(t *testing.T) {
func TestEmbeddedDoltLocalOnly_ConfigRoundTrip(t *testing.T) {
// bd config set dolt.local-only true / unset must persist via config.yaml.
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run dolt.local-only embedded tests")
@ -215,7 +215,7 @@ func TestDoltLocalOnly_ConfigRoundTrip(t *testing.T) {
// -- bd dolt status --
func TestDoltLocalOnly_DoltStatus_ShowsDisabled(t *testing.T) {
func TestEmbeddedDoltLocalOnly_DoltStatus_ShowsDisabled(t *testing.T) {
// When dolt.local-only=true, bd dolt status must include the indicator line.
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run dolt.local-only embedded tests")

View file

@ -1,21 +1,19 @@
//go:build embeddeddolt && cgo
//go:build cgo
package main
import (
"bytes"
"encoding/json"
"os"
"os/exec"
"strings"
"testing"
)
// Integration tests for be-7eu1d: git-origin collision guard in bd dolt remote
// add and bd doctor (FR-06 to FR-09).
//
// TDD gate tests — these fail before the implementation exists. Run with
// BEADS_TEST_EMBEDDED_DOLT=1.
// Integration tests for be-7eu1d's git-origin collision guard in bd dolt
// remote add (FR-06, FR-07). Its bd doctor half (FR-08, FR-09:
// doctor.CheckDoltRemoteGitOrigin) is server-mode only: bd doctor runs none of
// its checks on an embedded workspace (GH#3794), so it cannot be driven here.
// remoteAdd runs "bd dolt remote add <args>" returning (stdout, stderr, error)
// with separate buffers. Delegates to bdDoltSeparate (dolt_local_only_embedded_test.go).
@ -34,25 +32,11 @@ func setGitOrigin(t *testing.T, dir, url string) {
}
}
// bdDoctorSeparate runs "bd doctor <args>" returning (stdout, stderr, error).
func bdDoctorSeparate(t *testing.T, bd, dir string, args ...string) (string, string, error) {
t.Helper()
fullArgs := append([]string{"doctor"}, args...)
cmd := exec.Command(bd, fullArgs...)
cmd.Dir = dir
cmd.Env = bdEnv(dir)
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
err := cmd.Run()
return stdout.String(), stderr.String(), err
}
// -- bd dolt remote add: collision with git origin --
// TestDoltRemoteAdd_GitOriginCollision_Exits1 asserts that adding a Dolt remote
// TestEmbeddedDoltRemoteAdd_GitOriginCollision_Exits1 asserts that adding a Dolt remote
// whose URL matches the git origin exits non-zero and prints the refusal message.
func TestDoltRemoteAdd_GitOriginCollision_Exits1(t *testing.T) {
func TestEmbeddedDoltRemoteAdd_GitOriginCollision_Exits1(t *testing.T) {
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded integration tests")
}
@ -75,9 +59,9 @@ func TestDoltRemoteAdd_GitOriginCollision_Exits1(t *testing.T) {
}
}
// TestDoltRemoteAdd_GitOriginCollision_RefusalMessageCopy verifies exact phrases
// TestEmbeddedDoltRemoteAdd_GitOriginCollision_RefusalMessageCopy verifies exact phrases
// from the UX spec (be-fxwbm §2.1) appear in the refusal output.
func TestDoltRemoteAdd_GitOriginCollision_RefusalMessageCopy(t *testing.T) {
func TestEmbeddedDoltRemoteAdd_GitOriginCollision_RefusalMessageCopy(t *testing.T) {
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded integration tests")
}
@ -103,9 +87,9 @@ func TestDoltRemoteAdd_GitOriginCollision_RefusalMessageCopy(t *testing.T) {
}
}
// TestDoltRemoteAdd_AllowGitOrigin_Exits0 asserts that --allow-git-origin
// TestEmbeddedDoltRemoteAdd_AllowGitOrigin_Exits0 asserts that --allow-git-origin
// bypasses the collision guard and exits 0.
func TestDoltRemoteAdd_AllowGitOrigin_Exits0(t *testing.T) {
func TestEmbeddedDoltRemoteAdd_AllowGitOrigin_Exits0(t *testing.T) {
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded integration tests")
}
@ -122,9 +106,9 @@ func TestDoltRemoteAdd_AllowGitOrigin_Exits0(t *testing.T) {
}
}
// TestDoltRemoteAdd_AllowGitOrigin_WarningOnStderr asserts the one-liner warning
// TestEmbeddedDoltRemoteAdd_AllowGitOrigin_WarningOnStderr asserts the one-liner warning
// from be-fxwbm §2.2 appears on stderr when --allow-git-origin is set.
func TestDoltRemoteAdd_AllowGitOrigin_WarningOnStderr(t *testing.T) {
func TestEmbeddedDoltRemoteAdd_AllowGitOrigin_WarningOnStderr(t *testing.T) {
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded integration tests")
}
@ -146,9 +130,9 @@ func TestDoltRemoteAdd_AllowGitOrigin_WarningOnStderr(t *testing.T) {
}
}
// TestDoltRemoteAdd_NoGitOrigin_ProceedsNormally asserts no refusal fires when
// TestEmbeddedDoltRemoteAdd_NoGitOrigin_ProceedsNormally asserts no refusal fires when
// the git repo has no 'origin' remote.
func TestDoltRemoteAdd_NoGitOrigin_ProceedsNormally(t *testing.T) {
func TestEmbeddedDoltRemoteAdd_NoGitOrigin_ProceedsNormally(t *testing.T) {
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded integration tests")
}
@ -167,9 +151,9 @@ func TestDoltRemoteAdd_NoGitOrigin_ProceedsNormally(t *testing.T) {
}
}
// TestDoltRemoteAdd_DifferentURL_ProceedsNormally asserts the guard does not
// TestEmbeddedDoltRemoteAdd_DifferentURL_ProceedsNormally asserts the guard does not
// fire when the Dolt remote URL is different from the git origin.
func TestDoltRemoteAdd_DifferentURL_ProceedsNormally(t *testing.T) {
func TestEmbeddedDoltRemoteAdd_DifferentURL_ProceedsNormally(t *testing.T) {
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded integration tests")
}
@ -190,10 +174,10 @@ func TestDoltRemoteAdd_DifferentURL_ProceedsNormally(t *testing.T) {
}
}
// TestDoltRemoteAdd_LocalOnly_FiresBeforeGuard verifies that when
// TestEmbeddedDoltRemoteAdd_LocalOnly_FiresBeforeGuard verifies that when
// dolt.local-only=true is set, the local-only refusal fires before the
// git-origin guard — the local-only guard takes priority (be-3v2ou ordering).
func TestDoltRemoteAdd_LocalOnly_FiresBeforeGuard(t *testing.T) {
func TestEmbeddedDoltRemoteAdd_LocalOnly_FiresBeforeGuard(t *testing.T) {
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded integration tests")
}
@ -218,130 +202,9 @@ func TestDoltRemoteAdd_LocalOnly_FiresBeforeGuard(t *testing.T) {
}
}
// -- bd doctor: Dolt remote matches git origin --
// TestDoctor_DoltRemoteMatchesGitOrigin_Warning verifies that bd doctor emits a
// warning when a Dolt remote URL matches the git origin.
func TestDoctor_DoltRemoteMatchesGitOrigin_Warning(t *testing.T) {
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded integration tests")
}
t.Parallel()
bd := buildEmbeddedBD(t)
dir, _, _ := bdInit(t, bd, "--prefix", "dw")
originURL := "file:///tmp/origin-collision-for-doctor"
setGitOrigin(t, dir, originURL)
// Add a Dolt remote that matches the git origin (using --allow-git-origin to bypass the guard).
bdDolt(t, bd, dir, "remote", "add", "--allow-git-origin", "origin", originURL)
stdout, _, _ := bdDoctorSeparate(t, bd, dir)
combined := stdout
// Doctor must surface the warning check.
if !strings.Contains(combined, "warning") && !strings.Contains(combined, "Warning") {
t.Errorf("bd doctor: expected warning when Dolt remote matches git origin\noutput:\n%s", combined)
}
if !strings.Contains(combined, "git origin") {
t.Errorf("bd doctor: expected 'git origin' in warning output\noutput:\n%s", combined)
}
}
// TestDoctor_DoltRemoteNoMatch_OK verifies that bd doctor does NOT emit a
// git-origin warning when the Dolt remote URL differs from the git origin.
func TestDoctor_DoltRemoteNoMatch_OK(t *testing.T) {
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded integration tests")
}
t.Parallel()
bd := buildEmbeddedBD(t)
dir, _, _ := bdInit(t, bd, "--prefix", "dn")
setGitOrigin(t, dir, "https://github.com/org/repo.git")
remoteDir := t.TempDir()
bdDolt(t, bd, dir, "remote", "add", "dolt-origin", "file://"+remoteDir)
stdout, _, _ := bdDoctorSeparate(t, bd, dir)
if strings.Contains(stdout, "Dolt remote matches git origin") {
t.Errorf("bd doctor: unexpected git-origin warning when URLs differ\noutput:\n%s", stdout)
}
}
// TestDoctor_NoGitOrigin_OK verifies that bd doctor shows OK for the git-origin
// check when no git origin is configured.
func TestDoctor_NoGitOrigin_OK(t *testing.T) {
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded integration tests")
}
t.Parallel()
bd := buildEmbeddedBD(t)
dir, _, _ := bdInit(t, bd, "--prefix", "ng")
// bdInit creates a git repo but no origin.
remoteDir := t.TempDir()
bdDolt(t, bd, dir, "remote", "add", "dolt-origin", "file://"+remoteDir)
stdout, _, _ := bdDoctorSeparate(t, bd, dir)
// Should not emit a warning for the git-origin check.
if strings.Contains(stdout, "Dolt remote matches git origin") {
t.Errorf("bd doctor: unexpected git-origin warning when no git origin\noutput:\n%s", stdout)
}
}
// TestDoctor_JSON_DoltRemoteMatchesGitOrigin_Warning verifies that
// bd doctor --json exposes the git-origin warning check with "status":"warning".
func TestDoctor_JSON_DoltRemoteMatchesGitOrigin_Warning(t *testing.T) {
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded integration tests")
}
t.Parallel()
bd := buildEmbeddedBD(t)
dir, _, _ := bdInit(t, bd, "--prefix", "dj")
originURL := "file:///tmp/origin-collision-for-json"
setGitOrigin(t, dir, originURL)
bdDolt(t, bd, dir, "remote", "add", "--allow-git-origin", "origin", originURL)
stdout, _, _ := bdDoctorSeparate(t, bd, dir, "--json")
// Output should be JSON array of checks.
var checks []map[string]interface{}
if err := json.Unmarshal([]byte(strings.TrimSpace(stdout)), &checks); err != nil {
// May be wrapped in an outer object — try extracting the checks array.
var outer map[string]interface{}
if jsonErr := json.Unmarshal([]byte(strings.TrimSpace(stdout)), &outer); jsonErr != nil {
t.Fatalf("bd doctor --json: not valid JSON: %v\noutput:\n%s", err, stdout)
}
if arr, ok := outer["checks"].([]interface{}); ok {
data, _ := json.Marshal(arr)
_ = json.Unmarshal(data, &checks)
}
}
found := false
for _, check := range checks {
name, _ := check["name"].(string)
if strings.Contains(name, "git origin") || strings.Contains(name, "Dolt remote") {
found = true
status, _ := check["status"].(string)
if status != "warning" {
t.Errorf("doctor JSON check %q: status = %q, want \"warning\"", name, status)
}
if _, hasFix := check["fix"]; !hasFix {
t.Errorf("doctor JSON check %q: missing \"fix\" field", name)
}
break
}
}
if !found {
t.Errorf("bd doctor --json: no git-origin check found in output\noutput:\n%s", stdout)
}
}
// TestDoltRemoteAdd_JSON_AllowGitOrigin_WarningOnStderr asserts that even in
// TestEmbeddedDoltRemoteAdd_JSON_AllowGitOrigin_WarningOnStderr asserts that even in
// --json mode, the override warning still appears on stderr (not stdout).
func TestDoltRemoteAdd_JSON_AllowGitOrigin_WarningOnStderr(t *testing.T) {
func TestEmbeddedDoltRemoteAdd_JSON_AllowGitOrigin_WarningOnStderr(t *testing.T) {
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded integration tests")
}

View file

@ -56,7 +56,7 @@ func lsRemoteRef(t *testing.T, remoteDir, ref string) string {
return fields[0]
}
func TestDoltRemoteResetData_GitBacked(t *testing.T) {
func TestEmbeddedDoltRemoteResetData_GitBacked(t *testing.T) {
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded integration tests")
}
@ -112,7 +112,7 @@ func TestDoltRemoteResetData_GitBacked(t *testing.T) {
}
}
func TestDoltRemoteResetData_UnknownRemote(t *testing.T) {
func TestEmbeddedDoltRemoteResetData_UnknownRemote(t *testing.T) {
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded integration tests")
}
@ -129,7 +129,7 @@ func TestDoltRemoteResetData_UnknownRemote(t *testing.T) {
}
}
func TestDoltRemoteResetData_CloudRemoteRefused(t *testing.T) {
func TestEmbeddedDoltRemoteResetData_CloudRemoteRefused(t *testing.T) {
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded integration tests")
}

View file

@ -13,7 +13,7 @@ import (
"github.com/steveyegge/beads/internal/storage"
)
// TestAutoPruneBoundsTheJournalAfterAMutatingCommand is the feature as a user
// TestEmbeddedAutoPruneBoundsTheJournalAfterAMutatingCommand is the feature as a user
// meets it: enable the journal, write, and the journal stays inside its floors
// without anyone running `bd events prune`.
//
@ -30,7 +30,7 @@ import (
// because the throttle's persisted watermark is never stamped while auto-prune
// is off, so the next command with it on is the first pass this workspace has
// ever run.
func TestAutoPruneBoundsTheJournalAfterAMutatingCommand(t *testing.T) {
func TestEmbeddedAutoPruneBoundsTheJournalAfterAMutatingCommand(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")
}
@ -117,12 +117,12 @@ func TestAutoPruneBoundsTheJournalAfterAMutatingCommand(t *testing.T) {
}
}
// TestAutoPruneLeavesAnUnboundedJournalAlone. Both floors at 0 is the documented
// TestEmbeddedAutoPruneLeavesAnUnboundedJournalAlone. Both floors at 0 is the documented
// way to keep every record, and it is also the configuration the truncation
// tests run under — so a maintenance pass that ignored it would quietly delete
// the history those tests (and any consumer that chose an unbounded ledger)
// depend on.
func TestAutoPruneLeavesAnUnboundedJournalAlone(t *testing.T) {
func TestEmbeddedAutoPruneLeavesAnUnboundedJournalAlone(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")
}
@ -158,7 +158,7 @@ func TestAutoPruneLeavesAnUnboundedJournalAlone(t *testing.T) {
}
}
// TestAutoPruneRespectsBdConfigSet drives the whole retention story through
// TestEmbeddedAutoPruneRespectsBdConfigSet drives the whole retention story through
// `bd config set` rather than the environment.
//
// The four events-journal keys are startup settings read through viper before
@ -167,7 +167,7 @@ func TestAutoPruneLeavesAnUnboundedJournalAlone(t *testing.T) {
// `bd config set events-journal true` reported success and changed nothing.
// A new key is one YamlOnlyKeys entry away from repeating it, and the symptom
// is invisible: retention that silently keeps whatever the default was.
func TestAutoPruneRespectsBdConfigSet(t *testing.T) {
func TestEmbeddedAutoPruneRespectsBdConfigSet(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")
}
@ -221,7 +221,7 @@ func TestAutoPruneRespectsBdConfigSet(t *testing.T) {
}
}
// TestAutoPruneDoesNotRunForReadOnlyCommands. The trigger is writer-pays, and
// TestEmbeddedAutoPruneDoesNotRunForReadOnlyCommands. The trigger is writer-pays, and
// three separate gates keep it that way — each one covered here by a command
// that would prune the journal without it:
//
@ -236,7 +236,7 @@ func TestAutoPruneRespectsBdConfigSet(t *testing.T) {
// - `bd migrate --dry-run` is a PREVIEW. It promised not to mutate and holds
// a write-refusing store; maintenance must not be the one write it
// performs.
func TestAutoPruneDoesNotRunForReadOnlyCommands(t *testing.T) {
func TestEmbeddedAutoPruneDoesNotRunForReadOnlyCommands(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")
}

View file

@ -34,7 +34,7 @@ func runBDOut(t *testing.T, bd, dir string, env []string, args ...string) (strin
return stdout.String(), stderr.String()
}
// TestDeleteJournalsTheRequestingActor is #5985's repro, verbatim: create two
// TestEmbeddedDeleteJournalsTheRequestingActor is #5985's repro, verbatim: create two
// beads with an edge between them, delete the blocker with an explicit --actor,
// and read the journal back. Both the delete record and the cascade dep_remove
// record must name that actor.
@ -42,7 +42,7 @@ func runBDOut(t *testing.T, bd, dir string, env []string, args ...string) (strin
// The whole route is exercised — cobra flag to journal column — because the
// actor is resolved, threaded through the role, and written by the storage
// seam, and a unit test at any one of those cannot see the drop at the next.
func TestDeleteJournalsTheRequestingActor(t *testing.T) {
func TestEmbeddedDeleteJournalsTheRequestingActor(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")
}
@ -92,13 +92,13 @@ func TestDeleteJournalsTheRequestingActor(t *testing.T) {
}
}
// TestEventsReadNoticesADisabledJournal pins the "nothing to read and no way to
// TestEmbeddedEventsReadNoticesADisabledJournal pins the "nothing to read and no way to
// tell why" fix. A workspace that never enabled the journal serves an empty
// export forever, which a consumer cannot distinguish from being caught up, so
// the read says so on stderr — and keeps stdout clean and the exit status zero,
// because exporting a historical ledger from a now-disabled workspace is
// legitimate.
func TestEventsReadNoticesADisabledJournal(t *testing.T) {
func TestEmbeddedEventsReadNoticesADisabledJournal(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")
}

View file

@ -118,7 +118,7 @@ func eventsJournalMaintenanceRunnerFor(plumbing any) issueops.EventsMaintenanceR
// with OpenForReadOnlyCommand, which is "otherwise a normal writable
// store", so nothing underneath refuses a maintenance delete. Drop this
// check and `bd list` prunes the journal — which
// TestAutoPruneDoesNotRunForReadOnlyCommands catches.
// TestEmbeddedAutoPruneDoesNotRunForReadOnlyCommands catches.
//
// Two more gates are specific to this trigger:
//

View file

@ -57,7 +57,7 @@ func TestProxiedServerServeActivatesTheEventsJournal(t *testing.T) {
}
}
// TestRoutedCreateJournalsIntoTheTargetWorkspace covers the cross-workspace
// TestEmbeddedRoutedCreateJournalsIntoTheTargetWorkspace covers the cross-workspace
// store: `bd create --repo <other>` opens a SECOND store for another workspace
// and writes the bead there.
//
@ -65,7 +65,7 @@ func TestProxiedServerServeActivatesTheEventsJournal(t *testing.T) {
// TARGET's own config.yaml, so a workspace that enabled the journal gets its
// mutations recorded no matter which directory bd was launched from — and the
// launching workspace, which enabled nothing, records nothing of its own.
func TestRoutedCreateJournalsIntoTheTargetWorkspace(t *testing.T) {
func TestEmbeddedRoutedCreateJournalsIntoTheTargetWorkspace(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")
}
@ -120,13 +120,13 @@ func TestRoutedCreateJournalsIntoTheTargetWorkspace(t *testing.T) {
}
}
// TestRoutedCreateHonorsTheEnvOverrideOverTheTargetsConfig is the precedence
// TestEmbeddedRoutedCreateHonorsTheEnvOverrideOverTheTargetsConfig is the precedence
// half. BD_EVENTS_JOURNAL is the documented way to turn the journal on for a
// process without editing a workspace, and a routed write is exactly where an
// operator reaches for it — so a target whose config.yaml says false must not
// be able to veto it. Getting this backwards makes the env var a suggestion,
// and the operator finds out by discovering an empty journal later.
func TestRoutedCreateHonorsTheEnvOverrideOverTheTargetsConfig(t *testing.T) {
func TestEmbeddedRoutedCreateHonorsTheEnvOverrideOverTheTargetsConfig(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")
}

View file

@ -89,15 +89,21 @@ var qualifiedActivationCalls = map[string]map[string]bool{
// scannedPackages are the directories searched for construction sites: every
// package that builds a store or provider for the bd binary, plus the standalone
// embedded-Dolt utility so it is accounted for rather than merely unnoticed.
// Each maps to the prefix its sites are keyed under.
// embedded-Dolt utility and the Go SDK's own opens (the repository root), so they
// are accounted for rather than merely unnoticed. Each maps to the prefix its
// sites are keyed under.
var scannedPackages = map[string]string{
".": "",
"doctor": "doctor/",
"doctor/fix": "doctor/fix/",
"../../internal/storage/embeddeddolt/cmd": "embeddeddolt-cmd/",
"../..": "sdk/",
}
// sdkOpenExemptionReason is the one reason the Go SDK's five opens share. It has
// to be true of both per-store switches, because the exemption list is shared.
const sdkOpenExemptionReason = "SDK entry point (library surface, not the bd binary): applies neither per-store switch, the events journal's or versioned history's; the bd binary's factories do"
// constructionExemptions are construction sites that legitimately do NOT
// activate the events journal, each with a reason. Keyed by
// "<pkg>/<file>:<Recv.Func>" so the two build-tag twins of a factory are
@ -172,6 +178,17 @@ var constructionExemptions = map[string]string{
// A standalone developer utility binary, not bd. It has no workspace config
// to read and never runs as part of a bd command.
"embeddeddolt-cmd/main.go:main": "standalone embeddeddolt debug utility, not the bd binary; no workspace config and no bd command context",
// The Go SDK's own opens (the repository root's beads package). They are a
// library surface that embedders call directly, and they build stores without
// applying either per-store switch. They are declared here so that a new SDK
// open is noticed rather than missed. Making them apply the switches would
// change the library's behavior for every embedder, so it is a separate change.
"sdk/beads.go:Open": sdkOpenExemptionReason,
"sdk/beads.go:OpenFromConfig": sdkOpenExemptionReason,
"sdk/beads.go:OpenGated": sdkOpenExemptionReason,
"sdk/beads_cgo.go:OpenBestAvailableWith": sdkOpenExemptionReason,
"sdk/beads_nocgo.go:OpenBestAvailableWith": sdkOpenExemptionReason,
}
func TestEveryStoreConstructionActivatesTheEventsJournal(t *testing.T) {
@ -235,6 +252,9 @@ func exemptionFor(key string) (exemption, reason string, ok bool) {
type constructionSite struct {
constructors []string
activates bool
// activatesVersionedHistory is the same question for the versioned-history
// guard, which reuses this scan (see versioned_history_construction_test.go).
activatesVersionedHistory bool
}
// scanStoreConstructionSites parses each scanned package and returns one entry
@ -364,10 +384,16 @@ func inspectConstructionSite(node ast.Node, imports map[string]string) *construc
if qualifiedActivationCalls[path][fun.Sel.Name] {
site.activates = true
}
if qualifiedVersionedHistoryActivationCalls[path][fun.Sel.Name] {
site.activatesVersionedHistory = true
}
case *ast.Ident:
if activationCalls[fun.Name] {
site.activates = true
}
if versionedHistoryActivationCalls[fun.Name] {
site.activatesVersionedHistory = true
}
}
return true
})

View file

@ -3,7 +3,6 @@
package main
import (
"bytes"
"encoding/json"
"fmt"
"os"
@ -16,7 +15,7 @@ import (
"github.com/steveyegge/beads/internal/storage"
)
// TestEventsTailReportsTruncationToTheCLI is the end-to-end guard for the
// TestEmbeddedEventsTailReportsTruncationToTheCLI is the end-to-end guard for the
// retention boundary as a consumer actually meets it: through the binary, not
// through the store API.
//
@ -27,7 +26,7 @@ import (
// that; this one fails if either path regresses. It also proves the whole
// config chain end to end: BD_EVENTS_JOURNAL turns the journal on, and the two
// BD_EVENTS_JOURNAL_RETAIN_* floors reach the prune.
func TestEventsTailReportsTruncationToTheCLI(t *testing.T) {
func TestEmbeddedEventsTailReportsTruncationToTheCLI(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")
}
@ -109,7 +108,7 @@ func TestEventsTailReportsTruncationToTheCLI(t *testing.T) {
}
}
// TestEventsTailFollowReportsTruncationOnTheStream covers the OTHER read call
// TestEmbeddedEventsTailFollowReportsTruncationOnTheStream covers the OTHER read call
// site: the --follow poll, which the one-shot test above cannot reach.
//
// A follower is the consumer most exposed to a prune — it is the one sitting
@ -120,7 +119,7 @@ func TestEventsTailReportsTruncationToTheCLI(t *testing.T) {
// it interrupts. The consumer on the other end is a line reader; a
// pretty-printed multi-line object in the middle of its input is unparseable,
// and it would see the stream stop with garbage after the last good record.
func TestEventsTailFollowReportsTruncationOnTheStream(t *testing.T) {
func TestEmbeddedEventsTailFollowReportsTruncationOnTheStream(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")
}
@ -163,7 +162,7 @@ func TestEventsTailFollowReportsTruncationOnTheStream(t *testing.T) {
follow := exec.Command(bd, "events", "tail", "--since", "0", "--limit", "1", "--follow", "--json")
follow.Dir = dir
follow.Env = env
var stdout, stderr bytes.Buffer
var stdout, stderr syncBuffer
follow.Stdout = &stdout
follow.Stderr = &stderr
if err := follow.Start(); err != nil {
@ -226,11 +225,11 @@ func TestEventsTailFollowReportsTruncationOnTheStream(t *testing.T) {
}
}
// TestEventsPruneHonorsRetainRowsFloorFromConfig proves the shipped defaults
// TestEmbeddedEventsPruneHonorsRetainRowsFloorFromConfig proves the shipped defaults
// reach the CLI: a `prune --before <huge>` on a workspace that configured no
// floors of its own must be stopped by the built-in retain-rows floor rather
// than deleting the whole journal and stranding its consumer.
func TestEventsPruneHonorsRetainRowsFloorFromConfig(t *testing.T) {
func TestEmbeddedEventsPruneHonorsRetainRowsFloorFromConfig(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")
}

View file

@ -47,9 +47,9 @@ func parseExportedIssues(t *testing.T, jsonl string) []*types.Issue {
return issues
}
// TestExportExcludeOwner_flag verifies that bd export --exclude-owner=<name>
// TestEmbeddedExportExcludeOwner_flag verifies that bd export --exclude-owner=<name>
// filters out issues created_by that identity from the export.
func TestExportExcludeOwner_flag(t *testing.T) {
func TestEmbeddedExportExcludeOwner_flag(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")
}
@ -86,9 +86,9 @@ func TestExportExcludeOwner_flag(t *testing.T) {
}
}
// TestExportExcludeOwner_config verifies that export.exclude_owners config
// TestEmbeddedExportExcludeOwner_config verifies that export.exclude_owners config
// filters issues without a command-line flag.
func TestExportExcludeOwner_config(t *testing.T) {
func TestEmbeddedExportExcludeOwner_config(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")
}
@ -115,8 +115,8 @@ func TestExportExcludeOwner_config(t *testing.T) {
}
}
// TestExportExcludeOwner_verbose verifies that --verbose emits a filtered count message.
func TestExportExcludeOwner_verbose(t *testing.T) {
// TestEmbeddedExportExcludeOwner_verbose verifies that --verbose emits a filtered count message.
func TestEmbeddedExportExcludeOwner_verbose(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")
}
@ -151,12 +151,12 @@ func TestExportExcludeOwner_verbose(t *testing.T) {
}
}
// TestAutoExportExcludeOwner_config is a regression test for the maphew review
// TestEmbeddedAutoExportExcludeOwner_config is a regression test for the maphew review
// of PR #4023 (be-e2nb): the export.exclude_owners safety net must also apply to
// the git-committed auto-export (.beads/issues.jsonl), not only to manual
// `bd export`. Before the fix, contributor/personal issues that the manual path
// excludes could still leak into git history and PRs via auto-export.
func TestAutoExportExcludeOwner_config(t *testing.T) {
func TestEmbeddedAutoExportExcludeOwner_config(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")
}

View file

@ -0,0 +1,102 @@
//go:build cgo
package main
import (
"bytes"
"encoding/json"
"errors"
"os"
"os/exec"
"slices"
"strings"
"testing"
)
// bdRunStreams runs one bd process in dir with the hermetic test environment
// and returns stdout, stderr and the exit status separately. A nonzero exit is
// returned, not fatal, so a caller can pin the status itself; only a process
// that could not be started fails the test here.
func bdRunStreams(t *testing.T, bd, dir string, args ...string) (stdout, stderr string, exit int) {
t.Helper()
cmd := exec.Command(bd, args...)
cmd.Dir = dir
cmd.Env = bdEnv(dir)
var outBuf, errBuf bytes.Buffer
cmd.Stdout, cmd.Stderr = &outBuf, &errBuf
if err := cmd.Run(); err != nil {
var ee *exec.ExitError
if !errors.As(err, &ee) {
t.Fatalf("bd %s did not run: %v", strings.Join(args, " "), err)
}
return outBuf.String(), errBuf.String(), ee.ExitCode()
}
return outBuf.String(), errBuf.String(), 0
}
// TestEmbeddedFormatJSONAliasMatchesJSON pins the hidden root --format alias
// (GH#2612): on show, list, ready and memories, `--format json` prints exactly
// what `--json` prints, byte for byte, and exits 0 like it.
//
// The alias is a root persistent flag, so any subcommand that registers a
// --format of its own shadows it (the GH#6278 hazard). `bd list` already has
// its own --format and passes `json` through by hand (list_input.go). A
// local --format added to show, ready or memories for another output
// format would turn `bd show ID --format json` into a refusal or into a
// different document. Both are regressions this test catches: it compares
// the whole of stdout, not a parse of it.
//
// Each command is checked in three spellings: `--format json` and
// `--format=json` after the subcommand, and `--format json` before it, where
// the flag is plainly the root's.
func TestEmbeddedFormatJSONAliasMatchesJSON(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", "fj")
id := bdCreateSilent(t, bd, dir, "Format alias parity", "--type", "task", "--description", "read through --format json")
bdRunOK(t, bd, dir, "remember", "the format alias is --json", "--key", "fj-alias")
for _, tc := range []struct {
name string
args []string
// mention is a value the --json document must contain, so two empty
// documents cannot match each other.
mention string
}{
{"show", []string{"show", id}, id},
{"list", []string{"list"}, id},
{"ready", []string{"ready"}, id},
{"memories", []string{"memories"}, "fj-alias"},
} {
t.Run(tc.name, func(t *testing.T) {
wantArgs := slices.Concat(tc.args, []string{"--json"})
want, wantErr, exit := bdRunStreams(t, bd, dir, wantArgs...)
if exit != 0 {
t.Fatalf("bd %s exited %d\nstdout:\n%s\nstderr:\n%s", strings.Join(wantArgs, " "), exit, want, wantErr)
}
if !json.Valid([]byte(want)) || !strings.Contains(want, tc.mention) {
t.Fatalf("bd %s did not print one JSON document naming %s:\n%s", strings.Join(wantArgs, " "), tc.mention, want)
}
for _, args := range [][]string{
slices.Concat(tc.args, []string{"--format", "json"}),
slices.Concat(tc.args, []string{"--format=json"}),
slices.Concat([]string{"--format", "json"}, tc.args),
} {
got, gotErr, exit := bdRunStreams(t, bd, dir, args...)
if exit != 0 {
t.Errorf("bd %s exited %d, want 0 like bd %s\nstdout:\n%s\nstderr:\n%s", strings.Join(args, " "), exit, strings.Join(wantArgs, " "), got, gotErr)
continue
}
if got != want {
t.Errorf("bd %s printed a different document from bd %s\n--format:\n%s\n--json:\n%s", strings.Join(args, " "), strings.Join(wantArgs, " "), got, want)
}
}
})
}
}

View file

@ -0,0 +1,326 @@
//go:build cgo
package main
import (
"bytes"
"context"
"errors"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"time"
)
// graphModeAdmissionFixture is a workspace whose metadata or format marker
// declares a format this build does not open.
type graphModeAdmissionFixture struct {
name string
// filename is the metadata file; "" lays down no metadata.
filename string
metadata string
// embedded adds the embedded Dolt root of a graph database. Without the
// guard, an ordinary bd opens that database as an Issue store and
// migrates it.
embedded bool
// marker adds the graph-preview-format sentinel graph-preview builds
// write before metadata.json.
marker bool
// refusal lists what the refusal must mention besides "this bd build
// does not support": the declared format and the start of its hint.
refusal []string
}
// write lays the fixture down under beadsDir and returns the metadata path,
// or "" when the fixture has no metadata.
func (f graphModeAdmissionFixture) write(t *testing.T, beadsDir string) string {
t.Helper()
if err := os.MkdirAll(beadsDir, 0o700); err != nil {
t.Fatal(err)
}
path := ""
if f.filename != "" {
path = filepath.Join(beadsDir, f.filename)
writeFile(t, path, []byte(f.metadata))
}
if f.embedded {
if err := os.MkdirAll(filepath.Join(beadsDir, "embeddeddolt", "beads_graph_0123456789abcdef0123456789abcdef", ".dolt"), 0o700); err != nil {
t.Fatal(err)
}
}
if f.marker {
writeFile(t, filepath.Join(beadsDir, "graph-preview-format"), []byte("link-preview-v9\n"))
}
if err := os.Chmod(beadsDir, 0o700); err != nil {
t.Fatal(err)
}
return path
}
func graphModeAdmissionFixtures() []graphModeAdmissionFixture {
graphModeRefusal := func(mode string) []string {
return []string{"graph_mode", mode, "use a bd build that supports graph_mode"}
}
var fixtures []graphModeAdmissionFixture
fixtures = append(fixtures, graphModeAdmissionFixture{
name: "metadata.json/link/embedded", filename: "metadata.json",
metadata: graphLinkWorkspaceMetadata, embedded: true, marker: true,
refusal: graphModeRefusal("link"),
})
for _, filename := range []string{"metadata.json", "config.json"} {
for _, mode := range []string{"link", "future-format"} {
fixtures = append(fixtures, graphModeAdmissionFixture{
name: filename + "/" + mode + "/server", filename: filename,
metadata: `{"backend":"dolt","dolt_mode":"server","graph_mode":"` + mode + `"}`,
refusal: graphModeRefusal(mode),
})
}
}
// Only the format marker declares these: graph init stopped before
// metadata.json, metadata.json was lost, or a bd that predates
// graph_mode rewrote it without the field.
markerRefusal := []string{"graph-preview-format", "restore metadata.json"}
fixtures = append(fixtures,
graphModeAdmissionFixture{
name: "marker/only", marker: true,
refusal: markerRefusal,
},
graphModeAdmissionFixture{
name: "marker/metadata-lost/embedded", embedded: true, marker: true,
refusal: markerRefusal,
},
graphModeAdmissionFixture{
name: "marker/metadata-stripped/embedded", filename: "metadata.json",
metadata: graphStrippedWorkspaceMetadata, embedded: true, marker: true,
refusal: markerRefusal,
},
graphModeAdmissionFixture{
name: "marker/dependency/server", filename: "metadata.json",
metadata: `{"backend":"dolt","dolt_mode":"server","graph_mode":"dependency"}`, marker: true,
refusal: markerRefusal,
},
)
return fixtures
}
// runGraphModeAdmissionBD runs bd in repoDir with a private HOME and no
// ambient BEADS_* selection, and returns its combined output and exit code.
func runGraphModeAdmissionBD(t *testing.T, bd, repoDir string, args ...string) (string, int) {
t.Helper()
return runGraphModeAdmissionBDEnv(t, bd, repoDir, nil, args...)
}
// runGraphModeAdmissionBDEnv is runGraphModeAdmissionBD run in dir with env
// added to bd's environment.
func runGraphModeAdmissionBDEnv(t *testing.T, bd, dir string, env []string, args ...string) (string, int) {
t.Helper()
// A refused run takes well under a second. An unrefused one (what these
// tests catch) goes on to create or open a database, which under load
// can approach 10s; the bound leaves room for it to fail on the
// assertion that names the regression rather than on the timeout.
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, bd, args...)
cmd.Dir = dir
cmd.Env = append(bdEnv(t.TempDir()),
"BEADS_DOLT_SERVER_MODE=0",
"BEADS_DOLT_SHARED_SERVER=0",
)
cmd.Env = append(cmd.Env, env...)
var output bytes.Buffer
cmd.Stdout = &output
cmd.Stderr = &output
err := cmd.Run()
if ctx.Err() != nil {
t.Fatalf("bd %s did not finish promptly: %v\n%s", strings.Join(args, " "), ctx.Err(), output.String())
}
var exitErr *exec.ExitError
switch {
case err == nil:
return output.String(), 0
case errors.As(err, &exitErr):
return output.String(), exitErr.ExitCode()
default:
t.Fatalf("bd %s: %v", strings.Join(args, " "), err)
return "", -1
}
}
// requireGraphModeRefusal fails unless bd args exited with the refusal of
// fixture's workspace format and its hint.
func requireGraphModeRefusal(t *testing.T, fixture graphModeAdmissionFixture, args []string, output string, code int) {
t.Helper()
if code != ExitUnsupportedWorkspaceFormat {
t.Fatalf("bd %s exit = %d, want %d (ExitUnsupportedWorkspaceFormat)\n%s",
strings.Join(args, " "), code, ExitUnsupportedWorkspaceFormat, output)
}
// --json renders the refusal as a JSON error, which escapes the quotes
// around the mode, so match its parts.
for _, want := range append([]string{"this bd build does not support"}, fixture.refusal...) {
if !strings.Contains(output, want) {
t.Fatalf("bd %s refusal does not mention %q:\n%s", strings.Join(args, " "), want, output)
}
}
}
// A refusal in a helper is insufficient: ordinary commands must reach it before
// metadata migration, version tracking, or an attempt to provision/open storage.
func TestGraphModeCLIRefusesLegacyStoreWithoutWorkspaceEffects(t *testing.T) {
bd := buildBDUnderTest(t)
commands := [][]string{
{"show", "beads/plan"},
{"list", "--json"},
{"create", "graph fence probe"},
{"context", "--json"},
{"where"},
{"dolt", "start"},
{"doctor", "--json"},
{"bootstrap", "--dry-run", "--yes"},
{"init", "--quiet", "--non-interactive", "--skip-hooks", "--skip-agents"},
{"init", "--force", "--quiet", "--non-interactive", "--skip-hooks", "--skip-agents"},
// What the installed git hooks run; their shim passes exit 16 on.
{"hooks", "run", "pre-commit"},
}
for _, fixture := range graphModeAdmissionFixtures() {
for _, args := range commands {
name := args[0]
if name == "init" && args[1] == "--force" {
name = "init-force"
}
t.Run(fixture.name+"/"+name, func(t *testing.T) {
repoDir := t.TempDir()
initGitRepoAt(t, repoDir)
beadsDir := filepath.Join(repoDir, ".beads")
metadataPath := fixture.write(t, beadsDir)
before := legacyUpgradeTreeDigest(t, beadsDir)
output, code := runGraphModeAdmissionBD(t, bd, repoDir, args...)
requireGraphModeRefusal(t, fixture, args, output, code)
if after := legacyUpgradeTreeDigest(t, beadsDir); after != before {
t.Fatalf("refused bd %s changed the workspace\n%s", strings.Join(args, " "), output)
}
if metadataPath != "" {
if got, err := os.ReadFile(metadataPath); err != nil || string(got) != fixture.metadata {
t.Fatalf("refused bd %s rewrote %s: %q, %v", strings.Join(args, " "), fixture.filename, got, err)
}
}
})
}
}
}
// Commands also reach a workspace they do not run in: create --repo, from
// another workspace or from none and as a dry run, --db and BEADS_DB,
// init --proxied-server, and bootstrap in a workspace with no metadata of its
// own, which takes the nearest ancestor's (and refuses a graph ancestor even
// when only its format marker declares it, rather than skip past it). Each must refuse a graph workspace
// the same way, before resolving it migrates a legacy config.json or anything
// opens its store.
func TestGraphModeOutsideEntryPointsRefuseWithoutWorkspaceEffects(t *testing.T) {
bd := buildBDUnderTest(t)
sourceDir, _, _ := bdInit(t, bd, "--prefix", "src")
outsideDir := t.TempDir()
entries := []struct {
name string
// run returns where bd runs, what it adds to bd's environment and
// bd's arguments, for a graph workspace in repoDir.
run func(t *testing.T, repoDir string) (dir string, env, args []string)
}{
{"create --repo from a workspace", func(t *testing.T, repoDir string) (string, []string, []string) {
return sourceDir, nil, []string{"create", "--repo", repoDir, "graph fence probe"}
}},
{"create --repo from outside", func(t *testing.T, repoDir string) (string, []string, []string) {
return outsideDir, nil, []string{"create", "--repo", repoDir, "graph fence probe"}
}},
{"create --dry-run --repo", func(t *testing.T, repoDir string) (string, []string, []string) {
// Without --parent the preview opens no target at all.
return sourceDir, nil, []string{"create", "--dry-run", "--repo", repoDir, "graph fence probe"}
}},
{"create --dry-run --parent --repo", func(t *testing.T, repoDir string) (string, []string, []string) {
// A dry run looks the parent up in the target's store.
return sourceDir, nil, []string{"create", "--dry-run", "--parent", "src-abc", "--repo", repoDir, "graph fence probe"}
}},
{"--db", func(t *testing.T, repoDir string) (string, []string, []string) {
return outsideDir, nil, []string{"--db", filepath.Join(repoDir, ".beads"), "list", "--json"}
}},
{"BEADS_DB", func(t *testing.T, repoDir string) (string, []string, []string) {
return outsideDir, []string{"BEADS_DB=" + filepath.Join(repoDir, ".beads")}, []string{"list", "--json"}
}},
{"init --proxied-server", func(t *testing.T, repoDir string) (string, []string, []string) {
return repoDir, nil, []string{"init", "--proxied-server", "--quiet", "--non-interactive", "--skip-hooks", "--skip-agents"}
}},
{"bootstrap below it", func(t *testing.T, repoDir string) (string, []string, []string) {
innerDir := filepath.Join(repoDir, "inner")
writeFile(t, filepath.Join(innerDir, ".beads", "config.yaml"), []byte("# bd workspace config\n"))
initGitRepoAt(t, innerDir)
return innerDir, nil, []string{"bootstrap", "--dry-run", "--yes"}
}},
}
for _, fixture := range graphModeAdmissionFixtures() {
for _, entry := range entries {
t.Run(fixture.name+"/"+entry.name, func(t *testing.T) {
repoDir := t.TempDir()
initGitRepoAt(t, repoDir)
beadsDir := filepath.Join(repoDir, ".beads")
metadataPath := fixture.write(t, beadsDir)
dir, env, args := entry.run(t, repoDir)
before := legacyUpgradeTreeDigest(t, beadsDir)
output, code := runGraphModeAdmissionBDEnv(t, bd, dir, env, args...)
requireGraphModeRefusal(t, fixture, args, output, code)
if after := legacyUpgradeTreeDigest(t, beadsDir); after != before {
t.Fatalf("bd %s changed the graph workspace\n%s", strings.Join(args, " "), output)
}
if metadataPath != "" {
if got, err := os.ReadFile(metadataPath); err != nil || string(got) != fixture.metadata {
t.Fatalf("refused bd %s rewrote %s: %q, %v", strings.Join(args, " "), fixture.filename, got, err)
}
}
})
}
}
}
// Commands that never open a store keep working in a workspace this build
// refuses, and leave it untouched.
func TestGraphModeWorkspaceAdmitsStorelessCommands(t *testing.T) {
bd := buildBDUnderTest(t)
var fixtures []graphModeAdmissionFixture
for _, fixture := range graphModeAdmissionFixtures() {
if fixture.name == "metadata.json/link/embedded" || fixture.name == "marker/only" {
fixtures = append(fixtures, fixture)
}
}
if len(fixtures) != 2 {
t.Fatalf("store-less fixtures = %d, want 2", len(fixtures))
}
for _, fixture := range fixtures {
for _, args := range [][]string{
{"version"},
{"--version"},
{"help"},
{"completion", "bash"},
} {
t.Run(fixture.name+"/"+strings.Join(args, " "), func(t *testing.T) {
repoDir := t.TempDir()
initGitRepoAt(t, repoDir)
beadsDir := filepath.Join(repoDir, ".beads")
fixture.write(t, beadsDir)
before := legacyUpgradeTreeDigest(t, beadsDir)
output, code := runGraphModeAdmissionBD(t, bd, repoDir, args...)
if code != 0 {
t.Fatalf("bd %s exit = %d, want 0\n%s", strings.Join(args, " "), code, output)
}
if strings.Contains(output, "this bd build does not support") {
t.Fatalf("store-less bd %s reported the workspace format:\n%s", strings.Join(args, " "), output)
}
if after := legacyUpgradeTreeDigest(t, beadsDir); after != before {
t.Fatalf("bd %s changed the workspace", strings.Join(args, " "))
}
})
}
}
}

View file

@ -0,0 +1,90 @@
//go:build cgo
package main
import (
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
)
// readGraphKeys returns the graph_* keys of a metadata.json and their values.
func readGraphKeys(t *testing.T, path string) map[string]any {
t.Helper()
data, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
var doc map[string]any
if err := json.Unmarshal(data, &doc); err != nil {
t.Fatalf("parse %s: %v\n%s", path, err, data)
}
keys := map[string]any{}
for key, value := range doc {
if strings.HasPrefix(key, "graph_") {
keys[key] = value
}
}
return keys
}
// The graph-mode fence must not change ordinary workspaces: one without the
// marker, and one whose metadata names the default "dependency" model
// explicitly, open and write as before, and a command that rewrites
// metadata.json keeps the marker exactly as it found it.
func TestEmbeddedGraphModeDependencyWorkspaceUnaffected(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)
for _, marker := range []string{"absent", "dependency"} {
t.Run(marker, func(t *testing.T) {
dir, beadsDir, _ := bdInit(t, bd, "--prefix", "gm")
metadataPath := filepath.Join(beadsDir, "metadata.json")
if marker != "absent" {
data, err := os.ReadFile(metadataPath)
if err != nil {
t.Fatal(err)
}
var doc map[string]any
if err := json.Unmarshal(data, &doc); err != nil {
t.Fatal(err)
}
doc["graph_mode"] = marker
data, err = json.MarshalIndent(doc, "", " ")
if err != nil {
t.Fatal(err)
}
if err := os.WriteFile(metadataPath, data, 0o600); err != nil {
t.Fatal(err)
}
}
wantKeys := readGraphKeys(t, metadataPath)
before, err := os.ReadFile(metadataPath)
if err != nil {
t.Fatal(err)
}
issue := bdCreate(t, bd, dir, "ordinary workspace issue", "--type", "task")
if out := bdList(t, bd, dir, "--json"); !strings.Contains(out, issue.ID) {
t.Fatalf("bd list --json does not show %s:\n%s", issue.ID, out)
}
if after, err := os.ReadFile(metadataPath); err != nil || string(after) != string(before) {
t.Fatalf("create/list changed metadata.json:\nbefore:\n%s\nafter:\n%s\n%v", before, after, err)
}
// upgrade ack rewrites metadata.json through configfile.Save.
if out, err := bdRunWithFlockRetry(t, bd, dir, "upgrade", "ack"); err != nil {
t.Fatalf("bd upgrade ack: %v\n%s", err, out)
}
if got := readGraphKeys(t, metadataPath); len(got) != len(wantKeys) || got["graph_mode"] != wantKeys["graph_mode"] {
data, _ := os.ReadFile(metadataPath)
t.Fatalf("metadata rewrite changed graph keys: got %v, want %v\n%s", got, wantKeys, data)
}
})
}
}

View file

@ -7,6 +7,8 @@ import (
"fmt"
"os"
"os/exec"
"regexp"
"sort"
"strings"
"sync"
"testing"
@ -403,3 +405,128 @@ func TestEmbeddedHistoryConcurrent(t *testing.T) {
}
}
}
// doltCommitHashPattern is a full Dolt commit hash: 32 characters of Dolt's
// base32 alphabet. It is what `bd show --as-of` takes, and a prefix is not.
var doltCommitHashPattern = regexp.MustCompile(`^[0-9a-v]{32}$`)
// issueVersionOnlyKeys are fields of a recorded version (`bd versions --json`,
// storage.IssueVersion) that neither the Dolt-commit history nor the Dolt AS OF
// read has.
var issueVersionOnlyKeys = []string{"local_revision", "epoch", "change_actor", "change_at", "attribution_status", "removed_restriction", "state_bytes"}
// TestEmbeddedHistoryAndShowAsOfReadDoltCommits pins what `bd history <id>` and
// `bd show <id> --as-of <ref>` read in an ordinary workspace whose store records
// versioned history, so both planes hold the same issue:
// - `bd history <id> --json` is the Dolt-commit history: an array, newest first,
// of {CommitHash, Committer, CommitDate, Issue} entries, each CommitHash a full
// Dolt commit hash and each Issue the row as that commit left it. No field of a
// recorded version appears, and the text output names the same full hashes.
// - `bd show <id> --as-of <hash>`, with a hash from `bd history`, is the Dolt AS OF
// read: the issue as that commit left it, in show's JSON shape (an array of
// issues), not a recorded version. A branch name is a ref too: --as-of main
// reads the branch head.
//
// Recorded versions are a separate plane with its own command (`bd versions`) and
// its own as-of read (R7.1, over issue_versions), which takes an instant or a
// version address and not a Dolt ref. Recording them must change neither answer.
func TestEmbeddedHistoryAndShowAsOfReadDoltCommits(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", "hd")
bdConfig(t, bd, dir, "set", "versioned-history.enabled", "true")
id := bdCreateSilent(t, bd, dir, "Before title", "--type", "task")
bdUpdate(t, bd, dir, id, "--title", "After title")
// Both planes hold this issue: versions were recorded for it.
var recorded struct {
Recording bool `json:"recording"`
Versions []json.RawMessage `json:"versions"`
}
if out, stderr, exit := bdRunStreams(t, bd, dir, "versions", id, "--json"); exit != 0 || json.Unmarshal([]byte(out), &recorded) != nil || !recorded.Recording || len(recorded.Versions) == 0 {
t.Fatalf("bd versions %s --json (exit %d) did not report recorded versions, so this test would not tell the planes apart\nstdout:\n%s\nstderr:\n%s", id, exit, out, stderr)
}
historyJSON := bdHistory(t, bd, dir, id, "--json")
var entries []map[string]json.RawMessage
if err := json.Unmarshal([]byte(historyJSON), &entries); err != nil {
t.Fatalf("bd history %s --json is not a JSON array: %v\n%s", id, err, historyJSON)
}
if len(entries) < 2 {
t.Fatalf("bd history %s --json has %d entries, want one for each of the create and the update:\n%s", id, len(entries), historyJSON)
}
type snapshot struct {
ID string `json:"id"`
Title string `json:"title"`
}
hashes := make([]string, len(entries))
titles := make([]string, len(entries))
for i, entry := range entries {
keys := make([]string, 0, len(entry))
for key := range entry {
keys = append(keys, key)
}
sort.Strings(keys)
if got := strings.Join(keys, ","); got != "CommitDate,CommitHash,Committer,Issue" {
t.Errorf("bd history entry %d has keys %s, want the Dolt-commit entry CommitDate,CommitHash,Committer,Issue", i, got)
}
if err := json.Unmarshal(entry["CommitHash"], &hashes[i]); err != nil || !doltCommitHashPattern.MatchString(hashes[i]) {
t.Errorf("bd history entry %d CommitHash %s is not a full Dolt commit hash", i, entry["CommitHash"])
}
var issue snapshot
if err := json.Unmarshal(entry["Issue"], &issue); err != nil || issue.ID != id {
t.Errorf("bd history entry %d Issue %s is not a snapshot of %s", i, entry["Issue"], id)
}
titles[i] = issue.Title
}
if titles[0] != "After title" || titles[len(titles)-1] != "Before title" {
t.Fatalf("bd history %s titles newest first are %q, want %q first and %q last", id, titles, "After title", "Before title")
}
for _, key := range issueVersionOnlyKeys {
if strings.Contains(historyJSON, `"`+key+`"`) {
t.Errorf("bd history %s --json carries %q, a field of a recorded version:\n%s", id, key, historyJSON)
}
}
text := bdHistory(t, bd, dir, id)
for _, hash := range hashes {
if !strings.Contains(text, hash) {
t.Errorf("bd history %s text output does not name the full commit hash %s:\n%s", id, hash, text)
}
}
// show --as-of reads the Dolt commit the history named.
first := hashes[len(hashes)-1]
asOfJSON := func(ref string) snapshot {
t.Helper()
out, stderr, exit := bdRunStreams(t, bd, dir, "show", id, "--as-of", ref, "--json")
var shown []map[string]json.RawMessage
if exit != 0 || json.Unmarshal([]byte(out), &shown) != nil || len(shown) != 1 {
t.Fatalf("bd show %s --as-of %s --json exited %d, want an array of one issue\nstdout:\n%s\nstderr:\n%s", id, ref, exit, out, stderr)
}
for _, key := range issueVersionOnlyKeys {
if _, ok := shown[0][key]; ok {
t.Errorf("bd show %s --as-of %s --json carries %q, a field of a recorded version:\n%s", id, ref, key, out)
}
}
var issues []snapshot
if err := json.Unmarshal([]byte(out), &issues); err != nil {
t.Fatalf("bd show %s --as-of %s --json: %v\n%s", id, ref, err, out)
}
return issues[0]
}
if got := asOfJSON(first); got.ID != id || got.Title != "Before title" {
t.Errorf("bd show %s --as-of %s (its first commit) read %+v, want the issue titled %q", id, first, got, "Before title")
}
if got := asOfJSON("main"); got.ID != id || got.Title != "After title" {
t.Errorf("bd show %s --as-of main read %+v, want the branch head's title %q", id, got, "After title")
}
human := bdShowRaw(t, bd, dir, id, "--as-of", first)
if !strings.Contains(human, "as of "+first) || !strings.Contains(human, "Before title") || strings.Contains(human, "After title") {
t.Errorf("bd show %s --as-of %s text output does not show the first commit's issue under that ref:\n%s", id, first, human)
}
}

View file

@ -21,7 +21,7 @@ import (
"github.com/steveyegge/beads/internal/storage/schema"
)
// TestPersistentPreRunLogsAndSkipsIdentityCheckForFreshEmbeddedWorkspace is
// TestEmbeddedPersistentPreRunLogsAndSkipsIdentityCheckForFreshEmbeddedWorkspace is
// the MINOR-criterion regression test for be-0gfcs round 2 (be-3bt2e): a
// brand-new workspace -- metadata.json present, but no embedded database on
// disk yet -- is the one previewErr case the identity check has always
@ -32,7 +32,7 @@ import (
// This exercises a real embedded-Dolt bootstrap (schema init on first open),
// so it is opt-in like the other embedded-dolt integration tests in this
// package: set BEADS_TEST_EMBEDDED_DOLT=1 to run it.
func TestPersistentPreRunLogsAndSkipsIdentityCheckForFreshEmbeddedWorkspace(t *testing.T) {
func TestEmbeddedPersistentPreRunLogsAndSkipsIdentityCheckForFreshEmbeddedWorkspace(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")
}
@ -120,7 +120,7 @@ func TestPersistentPreRunLogsAndSkipsIdentityCheckForFreshEmbeddedWorkspace(t *t
}
}
// TestIdentityGateRendersSchemaSkewFromForwardDriftedWorkspace pins the
// TestEmbeddedIdentityGateRendersSchemaSkewFromForwardDriftedWorkspace pins the
// preview→skew WIRE, which TestRefuseUnverifiablePreviewOpenRendersTypedErrors
// deliberately does not: that test hands refuseUnverifiablePreviewOpen a
// hand-built *schema.SchemaSkewError, so it pins the renderer in isolation.
@ -136,7 +136,7 @@ func TestPersistentPreRunLogsAndSkipsIdentityCheckForFreshEmbeddedWorkspace(t *t
//
// This bootstraps a real embedded-Dolt database, so it is opt-in on the same
// tier as the sibling above: set BEADS_TEST_EMBEDDED_DOLT=1 to run it.
func TestIdentityGateRendersSchemaSkewFromForwardDriftedWorkspace(t *testing.T) {
func TestEmbeddedIdentityGateRendersSchemaSkewFromForwardDriftedWorkspace(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")
}

View file

@ -55,10 +55,10 @@ func bdShowRevision(t *testing.T, bd, dir, id string) int64 {
func revStr(rev int64) string { return strconv.FormatInt(rev, 10) }
// TestIfRevisionAdvertisedOnFourVerbs pins T4.1: --if-revision is a real,
// TestEmbeddedIfRevisionAdvertisedOnFourVerbs pins T4.1: --if-revision is a real,
// documented flag on all four verbs A8 adds it to, not an undocumented side
// channel a caller has to discover by reading source.
func TestIfRevisionAdvertisedOnFourVerbs(t *testing.T) {
func TestEmbeddedIfRevisionAdvertisedOnFourVerbs(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")
}
@ -77,11 +77,11 @@ func TestIfRevisionAdvertisedOnFourVerbs(t *testing.T) {
}
}
// TestIfRevisionMatchAndMismatch pins T4.2 across all four verbs: a stale
// TestEmbeddedIfRevisionMatchAndMismatch pins T4.2 across all four verbs: a stale
// --if-revision token exits ExitGuardMismatch (13) and writes nothing at all
// (not the field, not the revision itself); the same token, once it is the
// issue's CURRENT revision, applies the write and the revision moves again.
func TestIfRevisionMatchAndMismatch(t *testing.T) {
func TestEmbeddedIfRevisionMatchAndMismatch(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")
}
@ -196,7 +196,7 @@ func TestIfRevisionMatchAndMismatch(t *testing.T) {
})
}
// TestIfRevisionDeletePreflightGoneIsPreconditionFailed pins mc-zndi7.81: `bd
// TestEmbeddedIfRevisionDeletePreflightGoneIsPreconditionFailed pins mc-zndi7.81: `bd
// delete`'s single-id path resolves the row with resolveAndGetIssueForMutation
// BEFORE calling deleter.Delete() and the per-id lock fence #7244 added. On a
// real Dolt sql-server, a same-token --if-revision racer that loses that fence
@ -211,7 +211,7 @@ func TestIfRevisionMatchAndMismatch(t *testing.T) {
// winning racer's delete would), then present that now-stale token. The
// pre-flight existence check must fail exactly the same way a mid-guard
// version mismatch does.
func TestIfRevisionDeletePreflightGoneIsPreconditionFailed(t *testing.T) {
func TestEmbeddedIfRevisionDeletePreflightGoneIsPreconditionFailed(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")
}
@ -392,7 +392,7 @@ func TestEmbeddedIfRevisionPreflightGoneIsPreconditionFailedOnEveryVerb(t *testi
})
}
// TestIfRevisionCascadeDelete pins mc-zndi7.76 (gap 4): a single named id with
// TestEmbeddedIfRevisionCascadeDelete pins mc-zndi7.76 (gap 4): a single named id with
// --cascade takes the SAME deleteBatch path a multi-id delete does
// (cmd/bd/delete.go:105, "len(issueIDs) > 1 || cascade"), which is the only
// way a single-id --if-revision request ever reaches deleteBatch's own
@ -405,7 +405,7 @@ func TestEmbeddedIfRevisionPreflightGoneIsPreconditionFailedOnEveryVerb(t *testi
// concurrent delete removed before deleteBatch resolves it is
// TestEmbeddedIfRevisionPreflightGoneIsPreconditionFailedOnEveryVerb's
// delete_cascade row.
func TestIfRevisionCascadeDelete(t *testing.T) {
func TestEmbeddedIfRevisionCascadeDelete(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")
}
@ -459,11 +459,11 @@ func TestIfRevisionCascadeDelete(t *testing.T) {
bdShowFail(t, bd, dir, child.ID)
}
// TestIfRevisionComposesWithIfAssigneeIfStatus pins T4.5: on `bd update`,
// TestEmbeddedIfRevisionComposesWithIfAssigneeIfStatus pins T4.5: on `bd update`,
// --if-revision composes with --if-assignee/--if-status as a conjunction —
// every guard present must hold, not just one of them, regardless of which
// guard happens to be the stale one.
func TestIfRevisionComposesWithIfAssigneeIfStatus(t *testing.T) {
func TestEmbeddedIfRevisionComposesWithIfAssigneeIfStatus(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")
}
@ -516,13 +516,13 @@ func TestIfRevisionComposesWithIfAssigneeIfStatus(t *testing.T) {
})
}
// TestIfRevisionRejectsLabelAndParentEdits pins T4.6: `bd update --if-revision`
// TestEmbeddedIfRevisionRejectsLabelAndParentEdits pins T4.6: `bd update --if-revision`
// (alone or composed with --if-assignee/--if-status) refuses when the ONLY
// edit riding with it is a label or parent change, because those edits do not
// run inside the guarded issues-row write. Refused before any write, exit 1
// (a flag-validation refusal, never 13 — 13 is reserved for an actual stale
// guard).
func TestIfRevisionRejectsLabelAndParentEdits(t *testing.T) {
func TestEmbeddedIfRevisionRejectsLabelAndParentEdits(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")
}
@ -562,12 +562,12 @@ func TestIfRevisionRejectsLabelAndParentEdits(t *testing.T) {
})
}
// TestIfRevisionMultiIDRejected pins T4.8 on the three verbs that accept more
// TestEmbeddedIfRevisionMultiIDRejected pins T4.8 on the three verbs that accept more
// than one id (assign is cobra.ExactArgs(2): id + assignee, so it can never
// carry a second id). A single --if-revision token names one row's version;
// refused before any write rather than applying it to only the first id a
// batch happens to resolve.
func TestIfRevisionMultiIDRejected(t *testing.T) {
func TestEmbeddedIfRevisionMultiIDRejected(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")
}
@ -633,14 +633,14 @@ func TestIfRevisionMultiIDRejected(t *testing.T) {
})
}
// TestRevisionRemintMatrix pins T4.10: the revision is a token over the
// TestEmbeddedRevisionRemintMatrix pins T4.10: the revision is a token over the
// issues-row write, not over "anything happened to this id". A field update,
// a metadata edit, a close and a reopen must each mint a fresh revision (so a
// caller who read one of those as "no-op" cannot keep replaying a now-stale
// --if-revision); a label edit, a dependency edit and the derived is_blocked
// flag must NOT, because none of those touch the issues-row write the token
// guards.
func TestRevisionRemintMatrix(t *testing.T) {
func TestEmbeddedRevisionRemintMatrix(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")
}

View file

@ -112,9 +112,9 @@ func gcClassifyAsPrecondition(out []byte, errText string) (ok bool, expected, cu
// cover, pinning the 2026-10 Opus-review BLOCKER fix end-to-end: gc's own
// classifier logic, not just bd's JSON shape in isolation, must recognize the
// refusal as a precondition with the caller's expected revision and bd's
// current one. The TestEmbedded name in an *_embedded_test.go file is what
// puts it in a CI lane: .github/scripts/embedded-test-shard.sh discovers
// tests by exactly that pair, and under any other name it skips everywhere.
// current one. The TestEmbedded name is what puts it in a CI lane:
// .github/scripts/embedded-test-shard.sh discovers tests by that prefix, and
// under any other name it skips everywhere.
func TestEmbeddedGCConditionalMatcherDecode(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")

View file

@ -0,0 +1,168 @@
//go:build cgo
package main
import (
"encoding/json"
"os"
"slices"
"strconv"
"strings"
"testing"
"github.com/steveyegge/beads/internal/types"
)
// ifRevisionStaleExit is a literal on purpose: the contract with gascity's
// bdstore_conditional.go classifier is the number 13, not whatever name the
// constant for it (ExitGuardMismatch) happens to have.
const ifRevisionStaleExit = 13
// decodeIfRevisionBodyExact decodes the flat machine body a refused
// --if-revision write puts on the last line of stderr, keeping numbers as
// json.Number. Revisions are int64 values well past 2^53, so comparing them
// as float64 would accept a neighbouring revision; a json.Number also proves
// the field is a JSON number and not a string.
func decodeIfRevisionBodyExact(t *testing.T, line string) map[string]any {
t.Helper()
dec := json.NewDecoder(strings.NewReader(line))
dec.UseNumber()
var body map[string]any
if err := dec.Decode(&body); err != nil {
t.Fatalf("decode the --if-revision refusal body: %v\nline: %s", err, line)
}
return body
}
// TestEmbeddedIfRevisionOrdinaryCAS pins the ordinary --if-revision
// compare-and-swap (#7203) end to end, as a gascity-style caller sees it:
//
// - a stale decimal token on update, close, assign and delete (preview and
// --force) exits 13 with a precondition_failed body on the last line of
// stderr naming the id and both revisions as JSON integers, prints
// nothing on stdout and writes nothing;
// - a token that is not a decimal exits 1 with the "invalid --if-revision"
// refusal, never 13, and writes nothing;
// - the current token applies on update, close, assign and delete, and
// each write that leaves the issue in place moves its revision on.
//
// A second meaning for the same flag (an opaque token in some other kind of
// workspace) must leave all of this unchanged in an ordinary one. This is
// the ordinary-workspace half of the fork's
// TestGraphPreviewIfRevisionOutsideLinkModeIsUpstreamCAS, ported onto this
// package's embedded helpers and extended from update/delete to close and
// assign.
func TestEmbeddedIfRevisionOrdinaryCAS(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", "ifrev")
id := bdCreateSilent(t, bd, dir, "Stale guard", "--type", "task", "--priority", "2")
stale := bdShowRevision(t, bd, dir, id)
bdRunOK(t, bd, dir, "update", id, "--notes", "bump", "--json")
current := bdShowRevision(t, bd, dir, id)
if current == stale {
t.Fatal("an unguarded update did not advance the revision")
}
staleToken := strconv.FormatInt(stale, 10)
for _, tc := range []struct {
name string
args []string
}{
{"update", []string{"update", id, "--priority", "3"}},
{"close", []string{"close", id}},
{"assign", []string{"assign", id, "worker"}},
{"delete preview", []string{"delete", id}},
{"delete force", []string{"delete", id, "--force"}},
} {
args := slices.Concat(tc.args, []string{"--if-revision", staleToken, "--json"})
stdout, stderr, exit := bdRunStreams(t, bd, dir, args...)
if exit != ifRevisionStaleExit {
t.Fatalf("stale --if-revision %s exited %d, want %d\nstdout:\n%s\nstderr:\n%s", tc.name, exit, ifRevisionStaleExit, stdout, stderr)
}
if stdout != "" {
t.Errorf("stale --if-revision %s printed on stdout, want nothing:\n%s", tc.name, stdout)
}
body := decodeIfRevisionBodyExact(t, lastJSONLine(t, stderr))
if body["code"] != ifRevisionCodePreconditionFailed || body["id"] != id {
t.Errorf("stale --if-revision %s reported %v, want code %q for %s", tc.name, body, ifRevisionCodePreconditionFailed, id)
}
if got := body["expected_revision"]; got != json.Number(staleToken) {
t.Errorf("stale --if-revision %s reported expected_revision %#v, want the JSON integer %s", tc.name, got, staleToken)
}
if got := body["current_revision"]; got != json.Number(strconv.FormatInt(current, 10)) {
t.Errorf("stale --if-revision %s reported current_revision %#v, want the JSON integer %d", tc.name, got, current)
}
if msg, _ := body["error"].(string); !strings.Contains(msg, "precondition failed") {
t.Errorf("stale --if-revision %s error text %q lacks \"precondition failed\"", tc.name, msg)
}
if got := bdShowRevision(t, bd, dir, id); got != current {
t.Fatalf("stale --if-revision %s wrote: revision %d -> %d", tc.name, current, got)
}
}
// A token that is not a decimal is a typo refused before any write, with
// exit 1 and not the guard's 13, in both output modes.
for _, base := range [][]string{
{"update", id, "--priority", "3"},
{"close", id},
{"assign", id, "worker"},
{"delete", id},
{"delete", id, "--force"},
} {
for _, mode := range [][]string{nil, {"--json"}} {
args := slices.Concat(base, []string{"--if-revision", "observed"}, mode)
stdout, stderr, exit := bdRunStreams(t, bd, dir, args...)
out := stdout + stderr
// The text refusal quotes the token; the --json one carries the
// same text JSON-escaped.
refused := strings.Contains(out, `invalid --if-revision "observed"`) ||
strings.Contains(out, `invalid --if-revision \"observed\"`)
if exit != 1 || !refused {
t.Errorf("bd %s exited %d, want exit 1 refusing the non-decimal token\nstdout:\n%s\nstderr:\n%s", strings.Join(args, " "), exit, stdout, stderr)
}
if strings.Contains(out, ifRevisionCodePreconditionFailed) {
t.Errorf("bd %s reported a stale revision for a token that is not one:\nstdout:\n%s\nstderr:\n%s", strings.Join(args, " "), stdout, stderr)
}
}
}
if got := bdShowRevision(t, bd, dir, id); got != current {
t.Fatalf("a refused non-decimal token wrote: revision %d -> %d", current, got)
}
// The current token applies, on each verb in turn.
revision := current
guarded := func(target string, args ...string) {
t.Helper()
bdRunOK(t, bd, dir, slices.Concat(args, []string{"--if-revision", strconv.FormatInt(revision, 10), "--json"})...)
next := bdShowRevision(t, bd, dir, target)
if next == revision {
t.Fatalf("a matching --if-revision on bd %s did not advance the revision", strings.Join(args, " "))
}
revision = next
}
guarded(id, "update", id, "--priority", "3")
if got := bdShow(t, bd, dir, id); got.Priority != 3 {
t.Errorf("matching --if-revision update did not apply: priority = %d, want 3", got.Priority)
}
guarded(id, "close", id)
if got := bdShow(t, bd, dir, id); got.Status != types.StatusClosed {
t.Errorf("matching --if-revision close did not apply: status = %s, want closed", got.Status)
}
bdRunOK(t, bd, dir, "delete", id, "--force", "--if-revision", strconv.FormatInt(revision, 10), "--json")
bdShowFail(t, bd, dir, id)
// assign gets an issue of its own: closing an issue assigned to someone
// other than the actor is refused without --force, whatever the guard.
other := bdCreateSilent(t, bd, dir, "Guarded assign", "--type", "task")
revision = bdShowRevision(t, bd, dir, other)
guarded(other, "assign", other, "worker")
if got := bdShow(t, bd, dir, other); got.Assignee != "worker" {
t.Errorf("matching --if-revision assign did not apply: assignee = %q, want worker", got.Assignee)
}
}

View file

@ -8,7 +8,7 @@ import (
"testing"
)
// TestIfRevisionOutranksReassignFenceCLI pins mc-zndi7.74 on the direct
// TestEmbeddedIfRevisionOutranksReassignFenceCLI pins mc-zndi7.74 on the direct
// (embedded) route: a stale --if-revision guard on an assignee edit must
// report precondition_failed/ExitGuardMismatch, never fall through to the
// bd-98s5c live-claim reassign fence's "already claimed" policy refusal --
@ -22,7 +22,7 @@ import (
// the now-live foreign claim and reports the plain policy refusal (exit 1)
// before the guarded write underneath ever gets a chance to report the
// correctly-ordered precondition failure (exit 13).
func TestIfRevisionOutranksReassignFenceCLI(t *testing.T) {
func TestEmbeddedIfRevisionOutranksReassignFenceCLI(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")
}

View file

@ -48,7 +48,7 @@ func proxiedRevStr(rev int64) string { return strconv.FormatInt(rev, 10) }
// TestProxiedServerIfRevisionOutranksReassignFence pins mc-zndi7.74 on the
// proxied-server route, the topology where this race actually happens: every
// shared-dolt-server clone writes through it. See
// TestIfRevisionOutranksReassignFenceCLI's doc for the full race shape —
// TestEmbeddedIfRevisionOutranksReassignFenceCLI's doc for the full race shape —
// this is the same scenario, proved against the real shared Dolt server
// instead of embedded Dolt.
func TestProxiedServerIfRevisionOutranksReassignFence(t *testing.T) {

View file

@ -147,14 +147,20 @@ func bulkLoadPoolReadTimeout(cmd *cobra.Command) time.Duration {
}
func runImport(cmd *cobra.Command, args []string) error {
// Explicit call, not inherited from CheckReadonly: runImport doesn't call
// CheckReadonly at all (a separate, pre-existing gap — readonlyMode
// doesn't gate bd import either), so it can't pick up the freeze check
// folded into CheckReadonly the way create/update/close/remember do.
// The path that makes this call load-bearing rather than redundant is
// `bd import --dry-run`: a preview sets useReadOnly, so it skips the early
// gate in PersistentPreRunE, and runImport is the only chokepoint left.
// Plain `bd import` is already stopped by that early gate.
// Strict --readonly refuses import, a --dry-run preview included (it
// refuses create --dry-run too). Guarded, unlike the write commands'
// unconditional call, because CheckReadonly also answers a migration freeze
// and does it by exiting the process. The freeze is answered below instead,
// by returning the error, so that cleanup still runs.
if readonlyMode {
CheckReadonly("import")
}
// The freeze check, not inherited from CheckReadonly for the reason above.
// It is load-bearing rather than redundant on `bd import --dry-run`: a
// preview sets useReadOnly, so it skips the early gate in
// PersistentPreRunE, and runImport is the only chokepoint left. Plain
// `bd import` is already stopped by that early gate.
if err := migrationFreezeGateFor(cmd, "import"); err != nil {
return err
}

View file

@ -84,7 +84,7 @@ func provisionChunkStore(t *testing.T) storage.DoltStorage {
// End-to-end against the real engine: a mid-import failure leaves a committed,
// queryable prefix, and re-running the same import converges — every row
// present, cross-chunk dependencies wired, no duplicated events.
func TestImportChunkedRealStoreResumeConverges(t *testing.T) {
func TestEmbeddedImportChunkedRealStoreResumeConverges(t *testing.T) {
requireEmbeddedDolt(t)
setImportChunkSize(t, 5)
recordImportPauses(t)
@ -179,7 +179,7 @@ func TestImportChunkedRealStoreResumeConverges(t *testing.T) {
// edges its import file declares must be visible too. This is the red-team
// ready-window finding: the previous two-phase layout committed every row
// dep-less first, so `bd ready` mid-import offered blocked work for dispatch.
func TestImportChunkedNoReadyWindowAtAnyFreezePoint(t *testing.T) {
func TestEmbeddedImportChunkedNoReadyWindowAtAnyFreezePoint(t *testing.T) {
requireEmbeddedDolt(t)
setImportChunkSize(t, 5)
recordImportPauses(t)
@ -251,7 +251,7 @@ func TestImportChunkedNoReadyWindowAtAnyFreezePoint(t *testing.T) {
// but the no-ready-window invariant must hold there too — otherwise the
// dependent commits ready-without-blocker for the rest of the import. Regression
// for the attempt-1 review finding.
func TestImportChunkedNoReadyWindowWithReadinessEdgeIntoCycle(t *testing.T) {
func TestEmbeddedImportChunkedNoReadyWindowWithReadinessEdgeIntoCycle(t *testing.T) {
requireEmbeddedDolt(t)
setImportChunkSize(t, 5)
recordImportPauses(t)
@ -339,7 +339,7 @@ func TestImportChunkedNoReadyWindowWithReadinessEdgeIntoCycle(t *testing.T) {
// Ordering the spawner inline with the waiter is not enough; every in-batch
// child of a waited spawner must be emitted no later than the waiter. Regression
// for the attempt-2 review blocker.
func TestImportChunkedWaitsForChildImportedLaterStaysBlocked(t *testing.T) {
func TestEmbeddedImportChunkedWaitsForChildImportedLaterStaysBlocked(t *testing.T) {
requireEmbeddedDolt(t)
setImportChunkSize(t, 5)
recordImportPauses(t)
@ -421,7 +421,7 @@ func (r *raceInjectingStore) CreateIssuesWithFullOptions(ctx context.Context, is
// the row away). The dependency pass must wire edges for every row phase 1
// accepted, regardless of later row-level updates, and must not clobber the
// concurrent write.
func TestImportChunkedConcurrentUpdateKeepsDeferredDeps(t *testing.T) {
func TestEmbeddedImportChunkedConcurrentUpdateKeepsDeferredDeps(t *testing.T) {
requireEmbeddedDolt(t)
setImportChunkSize(t, 5)
recordImportPauses(t)
@ -483,7 +483,7 @@ func TestImportChunkedConcurrentUpdateKeepsDeferredDeps(t *testing.T) {
// update racing the import must leave the blocking edge intact. With ordered
// inline wiring the row and its edge commit atomically, so no interleaving of
// row-level updates can separate them.
func TestImportChunkedConcurrentUpdateKeepsBlockingDeps(t *testing.T) {
func TestEmbeddedImportChunkedConcurrentUpdateKeepsBlockingDeps(t *testing.T) {
requireEmbeddedDolt(t)
setImportChunkSize(t, 5)
recordImportPauses(t)
@ -532,7 +532,7 @@ func TestImportChunkedConcurrentUpdateKeepsBlockingDeps(t *testing.T) {
// the pre-filter read and the row's chunk), the snapshot's deferred deps must
// stay out too. This is why the dependency pass cannot simply run everything
// with ConflictSkip: it must be restricted to rows phase 1 accepted.
func TestImportChunkedStaleRejectedRowKeepsDeferredDepsOut(t *testing.T) {
func TestEmbeddedImportChunkedStaleRejectedRowKeepsDeferredDepsOut(t *testing.T) {
requireEmbeddedDolt(t)
setImportChunkSize(t, 5)
recordImportPauses(t)
@ -593,7 +593,7 @@ func TestImportChunkedStaleRejectedRowKeepsDeferredDepsOut(t *testing.T) {
// straddling a chunk boundary must be wired, not skip-reported, and a
// same-bucket wisp -> wisp edge straddling the same boundary must survive as
// before. Every export→import used to lose such edges for good.
func TestImportChunkedMixedRegularWispCrossBucketEdgesWired(t *testing.T) {
func TestEmbeddedImportChunkedMixedRegularWispCrossBucketEdgesWired(t *testing.T) {
requireEmbeddedDolt(t)
setImportChunkSize(t, 5)
recordImportPauses(t)
@ -696,7 +696,7 @@ func TestImportChunkedMixedRegularWispCrossBucketEdgesWired(t *testing.T) {
// durable and the deferred one is not yet; re-running the same import must
// backfill it with nothing skip-reported, and a further run must be a no-op
// for the edges.
func TestImportChunkedCrossBucketBlocksEdgesResumeBackfills(t *testing.T) {
func TestEmbeddedImportChunkedCrossBucketBlocksEdgesResumeBackfills(t *testing.T) {
requireEmbeddedDolt(t)
setImportChunkSize(t, 4)
recordImportPauses(t)

View file

@ -5,6 +5,7 @@ import (
"context"
"errors"
"fmt"
"net"
"os"
"os/exec"
"os/user"
@ -226,6 +227,40 @@ func shouldInitSharedGlobalDB(sharedServer, sharedServerMode, gateway bool) bool
return (sharedServer || sharedServerMode) && !gateway
}
// externalServerUnreachableMessage returns the message for an --external init
// whose server could not be dialed, or "" when err is any other failure.
//
// --external declares the server managed outside bd, so init starts none. The
// store's own advice for a dead local server, "bd dolt start", would start the
// very server --external says bd must not, and the store words this failure
// differently per route (shared server, socket, remote host, auto-start pinned
// off). One message serves them all: it names the endpoint that was dialed and
// says that bd did not start a server.
//
// A dial to port 0 is the exception. The store leaves a zero port zero for
// auto-start to fill in, so it means nothing named a port: the address is a
// placeholder, not an endpoint. The message says so and how to name one, and
// offers no default, since on a shared machine whatever listens on a default
// port may belong to another project (GH#2098, GH#2372).
func externalServerUnreachableMessage(err error) string {
var opErr *net.OpError
if !errors.As(err, &opErr) || opErr.Op != "dial" {
return ""
}
if addr, ok := opErr.Addr.(*net.TCPAddr); ok && addr.Port == 0 {
return fmt.Sprintf("Error: failed to open Dolt store: %v\n\n"+
"--external declares the Dolt server externally managed, so bd did not start one, and no port was named for it.\n"+
"Name the server's port with --server-port or BEADS_DOLT_SERVER_PORT.\n", opErr)
}
endpoint := "the configured endpoint"
if opErr.Addr != nil {
endpoint = opErr.Addr.String()
}
return fmt.Sprintf("Error: failed to open Dolt store: %v\n\n"+
"--external declares the Dolt server at %s externally managed, so bd did not start one.\n"+
"Start that server, or point init at the right endpoint.\n", opErr, endpoint)
}
// warnHalfIdentifiedSubstrate reports a substrate carrying one identity marker
// and not the other.
//
@ -820,7 +855,7 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1):
if initProxiedServer {
if beadsDir := resolveInitBeadsDir(); beadsDir != "" {
if err := guardLegacyUpgradeWorkspace(beadsDir); err != nil {
return err
return handleWorkspaceGuardError(err)
}
}
if err := runInitProxiedServer(cmd, rootCtx, initProxiedServerInput{
@ -970,8 +1005,8 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1):
// before init's existing-workspace checks so even --force cannot create
// or rewrite state beside a source that has not been preserved.
if beadsDir := resolveInitBeadsDir(); beadsDir != "" {
if err := guardLegacyUpgradeWorkspace(beadsDir); err != nil {
return err
if err := guardLegacyUpgradeWorkspaceForInit(beadsDir, initServerMode); err != nil {
return handleWorkspaceGuardError(err)
}
}
@ -1554,7 +1589,9 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1):
}
// Build config. Beads always uses dolt sql-server.
// AutoStart is always enabled during init — we need a server to initialize the database.
// AutoStart is enabled during init — we need a server to initialize the database —
// except under --external: that server is managed outside bd, so bd must not start
// one of its own on the endpoint the caller named.
//
// Port resolution for init: use ONLY project-local sources (env var, port file)
// to prevent cross-project data leakage (GH#2336). DefaultConfig falls through
@ -1602,7 +1639,7 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1):
ProxiedServer: initProxiedServer,
CreateIfMissing: true, // bd init is the only path that should create databases
OpenedByInit: true, // shapes the identity-mismatch advice (GH#5558)
AutoStart: initServerMode && os.Getenv("BEADS_DOLT_AUTO_START") != "0",
AutoStart: initServerMode && !externalServer && os.Getenv("BEADS_DOLT_AUTO_START") != "0",
ServerTLS: initDoltServerTLSFromEnv(),
}
if serverHost != "" {
@ -1727,6 +1764,12 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1):
}
return &exitError{Code: 1}
}
if externalServer {
if msg := externalServerUnreachableMessage(err); msg != "" {
fmt.Fprint(os.Stderr, msg)
return &exitError{Code: 1}
}
}
fmt.Fprintf(os.Stderr, "Error: failed to open Dolt store: %v\n", err)
return &exitError{Code: 1}
}

View file

@ -49,11 +49,11 @@ func updateAgentFile(filename string, verbose bool, templatePath string, profile
}
newContent = string(data)
} else {
newContent = agents.EmbeddedDefault()
newContent = agents.EmbeddedDefaultWithOpts(opts)
}
// Replace the beads section with the requested profile.
// EmbeddedDefault() ships with profile:full; swap to the requested profile
// The embedded template ships with profile:full; swap to the requested profile
// (which defaults to minimal). Also handles legacy markers without profile metadata.
if strings.Contains(newContent, "BEGIN BEADS INTEGRATION") {
if replaced, changed, err := agents.ReplaceSectionWithOpts(newContent, profile, opts); err == nil && changed {

79
cmd/bd/init_agent_test.go Normal file
View file

@ -0,0 +1,79 @@
package main
import (
"os"
"path/filepath"
"strings"
"testing"
"github.com/steveyegge/beads/internal/templates/agents"
)
// TestUpdateAgentFileQuickReferenceFollowsRemote pins that a new AGENTS.md
// written by `bd init` lists `bd dolt push` in its Quick Reference exactly
// when its managed section does: only with a Dolt remote configured and the
// workspace not declared no-push. A custom --agents-template is the user's
// own text and is written as given.
func TestUpdateAgentFileQuickReferenceFollowsRemote(t *testing.T) {
for _, tc := range []struct {
name string
opts agents.RenderOpts
wantPush bool
}{
{name: "remote", opts: agents.RenderOpts{HasRemote: true}, wantPush: true},
{name: "no-remote", opts: agents.RenderOpts{}, wantPush: false},
{name: "no-push", opts: agents.RenderOpts{HasRemote: true, NoPush: true}, wantPush: false},
} {
t.Run(tc.name, func(t *testing.T) {
path := filepath.Join(t.TempDir(), "AGENTS.md")
if err := updateAgentFile(path, false, "", agents.ProfileMinimal, tc.opts); err != nil {
t.Fatalf("updateAgentFile: %v", err)
}
data, err := os.ReadFile(path)
if err != nil {
t.Fatalf("read %s: %v", path, err)
}
content := string(data)
begin := strings.Index(content, "<!-- BEGIN BEADS INTEGRATION")
if begin < 0 {
t.Fatalf("AGENTS.md has no managed section:\n%s", content)
}
if got := listsDoltPush(content[:begin]); got != tc.wantPush {
t.Errorf("Quick Reference lists `bd dolt push` = %v, want %v", got, tc.wantPush)
}
if got := listsDoltPush(content[begin:]); got != tc.wantPush {
t.Errorf("managed section lists `bd dolt push` = %v, want %v", got, tc.wantPush)
}
})
}
t.Run("custom-template", func(t *testing.T) {
dir := t.TempDir()
template := "# Ours\n\n```bash\nbd dolt push # our own reminder\n```\n"
templatePath := filepath.Join(dir, "template.md")
if err := os.WriteFile(templatePath, []byte(template), 0o644); err != nil {
t.Fatalf("write template: %v", err)
}
path := filepath.Join(dir, "AGENTS.md")
if err := updateAgentFile(path, false, templatePath, agents.ProfileMinimal, agents.RenderOpts{}); err != nil {
t.Fatalf("updateAgentFile: %v", err)
}
data, err := os.ReadFile(path)
if err != nil {
t.Fatalf("read %s: %v", path, err)
}
if string(data) != template {
t.Errorf("custom template was not written as given:\n got: %q\nwant: %q", data, template)
}
})
}
// listsDoltPush reports whether any line of s is a `bd dolt push` command.
func listsDoltPush(s string) bool {
for _, line := range strings.Split(s, "\n") {
if strings.HasPrefix(strings.TrimSpace(line), "bd dolt push") {
return true
}
}
return false
}

View file

@ -482,6 +482,39 @@ func TestEmbeddedInitABasic(t *testing.T) {
t.Errorf("issue_prefix: got %q, want %q", val, "alpha")
}
})
// The project's .claude/settings.json still carries the bare `bd prime`
// SessionStart and PreCompact hooks an older bd registered. init's Claude
// install migrates them, and --quiet drops the migration's "Removed
// <event> hook" lines like the rest of the installers' progress.
t.Run("quiet_legacy_claude_hooks", func(t *testing.T) {
dir := t.TempDir()
initGitRepoAt(t, dir)
settingsPath := filepath.Join(dir, ".claude", "settings.json")
if err := os.MkdirAll(filepath.Dir(settingsPath), 0o755); err != nil {
t.Fatalf("mkdir .claude: %v", err)
}
legacyHook := `[{"matcher": "", "hooks": [{"type": "command", "command": "bd prime"}]}]`
legacy := `{"hooks": {"SessionStart": ` + legacyHook + `, "PreCompact": ` + legacyHook + `}}`
if err := os.WriteFile(settingsPath, []byte(legacy), 0o644); err != nil {
t.Fatalf("seed settings.json: %v", err)
}
args := []string{"--prefix", "legacyhooks"}
if database, seeded := seededInitDatabase(args); seeded {
seedEmbeddedSchema(t, dir, database)
}
if out := runBDInit(t, bd, dir, args...); out != "" {
t.Errorf("bd init --quiet should print nothing, got:\n%s", out)
}
data, err := os.ReadFile(settingsPath)
if err != nil {
t.Fatalf("read settings.json: %v", err)
}
if got := string(data); !strings.Contains(got, `"bd prime --hook-json"`) || strings.Contains(got, `"bd prime"`) || strings.Contains(got, "PreCompact") {
t.Errorf("legacy hooks not migrated to the SessionStart --hook-json hook:\n%s", got)
}
})
}
func TestEmbeddedInitAForkAutoContributor(t *testing.T) {

View file

@ -0,0 +1,430 @@
//go:build cgo
package main
import (
"encoding/json"
"errors"
"fmt"
"io"
"net"
"os"
"os/exec"
"path/filepath"
"runtime"
"strconv"
"strings"
"sync"
"testing"
"time"
"github.com/steveyegge/beads/internal/configfile"
)
// `bd init --external` declares that the Dolt server is managed outside bd, so
// init must never start one. These tests own one boundary risk that no lower
// seam can show: init builds its dolt config by hand, so the flag reaches the
// auto-start decision only if init carries it there. They run the real bd
// binary against a dolt shim that records every launch, which makes the
// outcome observable without a real server and leaves nothing running.
// externalInitFixture is one fresh project plus a dolt shim for `bd init`
// attempts. The shim sits first on PATH, records every invocation and fails.
type externalInitFixture struct {
t *testing.T
repoDir string
home string
shimDir string
launches string
}
type externalInitResult struct {
output string // combined stdout and stderr
failed bool // bd exited non-zero
launches string // dolt invocations the shim saw, one per line
}
func newExternalInitFixture(t *testing.T) *externalInitFixture {
t.Helper()
if runtime.GOOS == "windows" {
t.Skip("the dolt shim is a POSIX shell script")
}
f := &externalInitFixture{t: t, repoDir: t.TempDir(), home: t.TempDir(), shimDir: t.TempDir()}
f.launches = filepath.Join(f.shimDir, "invocations")
shim := "#!/bin/sh\nprintf '%s\\n' \"$*\" >> \"$EXTERNAL_INIT_SHIM_LOG\"\nexit 1\n"
if err := os.WriteFile(filepath.Join(f.shimDir, "dolt"), []byte(shim), 0o755); err != nil {
t.Fatal(err)
}
initGitRepo(t, f.repoDir)
return f
}
// run executes bd in the project. autoStart is the value of
// BEADS_DOLT_AUTO_START, or "" to leave it unset: an unpinned environment is
// what most callers run in, so it is the one that matters here.
func (f *externalInitFixture) run(autoStart string, args ...string) externalInitResult {
f.t.Helper()
env := append(envWithoutBeadsStorageSettings(),
"HOME="+f.home,
"XDG_CONFIG_HOME="+filepath.Join(f.home, ".config"),
"BEADS_TEST_IGNORE_REPO_CONFIG=1",
"BD_DISABLE_METRICS=1",
"PATH="+f.shimDir+string(os.PathListSeparator)+os.Getenv("PATH"),
"EXTERNAL_INIT_SHIM_LOG="+f.launches,
)
if autoStart != "" {
env = append(env, "BEADS_DOLT_AUTO_START="+autoStart)
}
out, err := runExternalServerBD(f.t, f.repoDir, env, args...)
var exitErr *exec.ExitError
if err != nil && !errors.As(err, &exitErr) {
f.t.Fatalf("bd %s did not run: %v\n%s", strings.Join(args, " "), err, out)
}
launches, _ := os.ReadFile(f.launches)
return externalInitResult{output: out, failed: err != nil, launches: strings.TrimSpace(string(launches))}
}
// externalEndpoint is the server an --external init is pointed at.
type externalEndpoint struct {
flags []string // --server-host/--server-port, or --server-socket
network string // "tcp" or "unix"
addr string // host:port or the socket path, as bd reports it
}
func tcpEndpoint(port int) externalEndpoint {
return externalEndpoint{
flags: []string{"--server-host", "127.0.0.1", "--server-port", strconv.Itoa(port)},
network: "tcp",
addr: net.JoinHostPort("127.0.0.1", strconv.Itoa(port)),
}
}
func unixEndpoint(path string) externalEndpoint {
return externalEndpoint{flags: []string{"--server-socket", path}, network: "unix", addr: path}
}
// externalInitSocketPath returns an unused unix socket path. Socket paths are
// capped near 104 bytes and t.TempDir() nests too deeply under some runners.
func externalInitSocketPath(t *testing.T) string {
t.Helper()
dir, err := os.MkdirTemp("", "bdx")
if err != nil {
t.Fatal(err)
}
if len(filepath.Join(dir, "dolt.sock")) > 100 {
_ = os.RemoveAll(dir)
if dir, err = os.MkdirTemp("/tmp", "bdx"); err != nil {
t.Fatal(err)
}
}
t.Cleanup(func() { _ = os.RemoveAll(dir) })
return filepath.Join(dir, "dolt.sock")
}
// serveUnixProxy listens on a fresh unix socket and forwards each connection
// to target, so bd sees a reachable server at a socket path. The returned
// func reports how many connections bd made through it.
func serveUnixProxy(t *testing.T, target string) (string, func() int) {
t.Helper()
path := externalInitSocketPath(t)
ln, err := net.Listen("unix", path)
if err != nil {
t.Fatalf("listen on %s: %v", path, err)
}
t.Cleanup(func() { _ = ln.Close() })
var mu sync.Mutex
accepted := 0
go func() {
for {
client, err := ln.Accept()
if err != nil {
return
}
mu.Lock()
accepted++
mu.Unlock()
go func() {
defer client.Close()
upstream, err := net.Dial("tcp", target)
if err != nil {
return
}
defer upstream.Close()
done := make(chan struct{}, 2)
go func() { _, _ = io.Copy(upstream, client); done <- struct{}{} }()
go func() { _, _ = io.Copy(client, upstream); done <- struct{}{} }()
<-done // either side closing ends the session; the deferred closes release the other copy
}()
}
}()
return path, func() int { mu.Lock(); defer mu.Unlock(); return accepted }
}
// requireNoLaunch fails when bd tried to run dolt at all: an externally
// managed server is never started by bd, and the shim is how a start shows.
func requireNoLaunch(t *testing.T, res externalInitResult) {
t.Helper()
if res.launches != "" {
t.Errorf("bd launched dolt although the server is externally managed (dolt %s):\n%s",
strings.ReplaceAll(res.launches, "\n", "; dolt "), res.output)
}
}
// requireExternalUnreachableMessage checks the one wording an --external init
// gives for an endpoint it cannot reach: it names the endpoint, says the server
// is declared external and that bd did not start one, and never advises
// `bd dolt start`, which would start the server --external says bd must not.
func requireExternalUnreachableMessage(t *testing.T, output, endpoint string) {
t.Helper()
for _, want := range []string{endpoint, "externally managed", "did not start"} {
if !strings.Contains(output, want) {
t.Errorf("output does not contain %q:\n%s", want, output)
}
}
if strings.Contains(output, "bd dolt start") {
t.Errorf("output advises `bd dolt start`:\n%s", output)
}
}
func requireNothingListening(t *testing.T, network, addr string) {
t.Helper()
conn, err := net.DialTimeout(network, addr, time.Second)
if err == nil {
_ = conn.Close()
t.Errorf("something accepts connections on %s %s after init", network, addr)
}
}
// requireDoltRootEmpty fails when .beads/dolt holds anything: init leaves at
// most an empty marker directory for an external server, so any entry is a
// server root a local dolt created.
func requireDoltRootEmpty(t *testing.T, repoDir string) {
t.Helper()
entries, err := os.ReadDir(filepath.Join(repoDir, ".beads", "dolt"))
if errors.Is(err, os.ErrNotExist) {
return
}
if err != nil {
t.Fatal(err)
}
if len(entries) > 0 {
names := make([]string, 0, len(entries))
for _, e := range entries {
names = append(names, e.Name())
}
t.Errorf(".beads/dolt holds %v, which init did not put there", names)
}
}
// TestInitServerExternalDeadPortStartsNoServer is the end-to-end boundary for
// --external: a dead endpoint must fail loudly instead of making bd launch a
// dolt of its own on the port the caller named.
func TestInitServerExternalDeadPortStartsNoServer(t *testing.T) {
f := newExternalInitFixture(t)
ep := tcpEndpoint(freeLoopbackPort(t))
res := f.run("", append(append([]string{"init", "--quiet", "--server", "--external"}, ep.flags...),
"--prefix", "x", "--skip-hooks", "--skip-agents")...)
if !res.failed {
t.Errorf("bd init --server --external succeeded against a dead endpoint %s:\n%s", ep.addr, res.output)
}
requireNoLaunch(t, res)
requireExternalUnreachableMessage(t, res.output, ep.addr)
requireNothingListening(t, ep.network, ep.addr)
requireDoltRootEmpty(t, f.repoDir)
}
// TestInitServerExternalNoPortStartsNoServer is the --external boundary that
// rule 2c (#5934) cannot see: the argv and the environment name no port, so
// nothing but the flag declares the server external. A server init in that
// shape launches a repo-local dolt by design (see
// TestInitServerWithoutNamedPortStillStartsServer), so with --external it must
// fail instead, and say that bd did not start one. There is no endpoint to
// name, so the wording is checked without one: the child inherits
// BEADS_TEST_MODE, under which the store dials port 1 rather than leave an
// unnamed port at 0, so the port-0 wording itself is pinned by
// TestExternalServerUnreachableMessage.
func TestInitServerExternalNoPortStartsNoServer(t *testing.T) {
f := newExternalInitFixture(t)
res := f.run("", "init", "--quiet", "--server", "--external", "--prefix", "x", "--skip-hooks", "--skip-agents")
if !res.failed {
t.Errorf("bd init --server --external succeeded with no server named:\n%s", res.output)
}
requireNoLaunch(t, res)
requireDoltRootEmpty(t, f.repoDir)
for _, want := range []string{"externally managed", "did not start"} {
if !strings.Contains(res.output, want) {
t.Errorf("output does not contain %q:\n%s", want, res.output)
}
}
if strings.Contains(res.output, "bd dolt start") {
t.Errorf("output advises `bd dolt start`:\n%s", res.output)
}
}
// TestInitSharedServerExternalDeadPortStillFails pins the sibling route that
// already honors --external: the same dead endpoint under --shared-server
// exits non-zero without launching dolt. Without it the test above could pass
// because every init fails here, not because --server honors the flag.
func TestInitSharedServerExternalDeadPortStillFails(t *testing.T) {
f := newExternalInitFixture(t)
ep := tcpEndpoint(freeLoopbackPort(t))
res := f.run("", append(append([]string{"init", "--quiet", "--shared-server", "--external"}, ep.flags...),
"--prefix", "x", "--skip-hooks", "--skip-agents")...)
if !res.failed {
t.Errorf("bd init --shared-server --external succeeded against a dead endpoint %s:\n%s", ep.addr, res.output)
}
requireNoLaunch(t, res)
}
// TestInitServerWithoutNamedPortStillStartsServer pins the other half of the
// contract: a --server init that names no port is where bd starts a repo-local
// dolt by design, so the no-launch assertions above cannot pass merely because
// nothing can ever launch one. It names no port, in argv or in the environment
// (envWithoutBeadsStorageSettings drops every BEADS_DOLT_* variable): a named
// port is declared external by rule 2c (#5934) with or without --external, so
// it would launch nothing here either way.
func TestInitServerWithoutNamedPortStillStartsServer(t *testing.T) {
f := newExternalInitFixture(t)
res := f.run("", "init", "--quiet", "--server", "--prefix", "x", "--skip-hooks", "--skip-agents")
if res.launches == "" {
t.Errorf("bd init --server naming no port never reached dolt, so auto-start regressed:\n%s", res.output)
}
}
// TestInitExternalUnreachableMessage covers the wording across the routes an
// --external init can take. Every one of them gives the same message, whether
// auto-start is pinned off by the environment, the server is a shared one, or
// the endpoint is a socket.
func TestInitExternalUnreachableMessage(t *testing.T) {
cases := []struct {
name string
mode string
autoStart string
endpoint func(t *testing.T) externalEndpoint
}{
{"server host:port with auto-start pinned off", "--server", "0",
func(t *testing.T) externalEndpoint { return tcpEndpoint(freeLoopbackPort(t)) }},
{"shared-server host:port", "--shared-server", "",
func(t *testing.T) externalEndpoint { return tcpEndpoint(freeLoopbackPort(t)) }},
{"server socket", "--server", "",
func(t *testing.T) externalEndpoint { return unixEndpoint(externalInitSocketPath(t)) }},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
f := newExternalInitFixture(t)
ep := tc.endpoint(t)
res := f.run(tc.autoStart, append(append([]string{"init", "--quiet", tc.mode, "--external"}, ep.flags...),
"--prefix", "x", "--skip-hooks", "--skip-agents")...)
if !res.failed {
t.Fatalf("bd init succeeded against a dead endpoint %s:\n%s", ep.addr, res.output)
}
requireExternalUnreachableMessage(t, res.output, ep.addr)
})
}
}
// TestInitExternalProvisionerShape runs init with the argv a provisioner of an
// externally managed server uses, in both endpoint forms, with auto-start
// unset and pinned off, against a server that is up and one that is not. Every
// cell is a control: a port named with --server-port is already declared
// external by rule 2c (#5934), and a socket is never auto-started, so none of
// them launched dolt before init honored --external either. They pin that the
// provisioner shape keeps launching nothing, keeps failing against a dead
// endpoint, and still records the endpoint it was given. The reachable cells
// need the Dolt test server and skip without it.
func TestInitExternalProvisionerShape(t *testing.T) {
for _, form := range []string{"host-port", "socket"} {
for _, autoStart := range []string{"unset", "0"} {
for _, reachable := range []bool{false, true} {
state := "unreachable"
if reachable {
state = "reachable"
}
t.Run(fmt.Sprintf("%s/auto-start=%s/%s", form, autoStart, state), func(t *testing.T) {
runProvisionerCell(t, form, autoStart, reachable)
})
}
}
}
}
func runProvisionerCell(t *testing.T, form, autoStart string, reachable bool) {
t.Helper()
if reachable {
skipIfNoDolt(t)
}
f := newExternalInitFixture(t)
var ep externalEndpoint
var socketConnections func() int
switch {
case form == "host-port" && reachable:
ep = tcpEndpoint(testDoltServerPort)
case form == "host-port":
ep = tcpEndpoint(freeLoopbackPort(t))
case reachable:
var sock string
sock, socketConnections = serveUnixProxy(t, net.JoinHostPort("127.0.0.1", strconv.Itoa(testDoltServerPort)))
ep = unixEndpoint(sock)
default:
ep = unixEndpoint(externalInitSocketPath(t))
}
database := "provisioned"
if reachable {
database = uniqueTestDBName(t)
t.Cleanup(func() { dropTestDatabase(database, testDoltServerPort) })
}
args := append([]string{"init", "--init-if-missing", "--quiet", "--server", "--external"}, ep.flags...)
args = append(args, "-p", "prov", "--skip-hooks", "--skip-agents", "--database", database, f.repoDir)
pin := ""
if autoStart == "0" {
pin = "0"
}
res := f.run(pin, args...)
requireNoLaunch(t, res)
if !reachable {
if !res.failed {
t.Errorf("bd init succeeded against an unreachable endpoint %s:\n%s", ep.addr, res.output)
}
requireNothingListening(t, ep.network, ep.addr)
return
}
if res.failed {
t.Fatalf("bd init against the reachable server %s failed:\n%s", ep.addr, res.output)
}
requireDoltRootEmpty(t, f.repoDir)
data, err := os.ReadFile(filepath.Join(f.repoDir, ".beads", "metadata.json"))
if err != nil {
t.Fatalf("expected metadata.json after init: %v", err)
}
var meta configfile.Config
if err := json.Unmarshal(data, &meta); err != nil {
t.Fatalf("parse metadata.json: %v\n%s", err, data)
}
if form == "socket" {
if meta.DoltServerSocket != ep.addr {
t.Errorf("metadata.json dolt_server_socket = %q, want the socket init was given, %q", meta.DoltServerSocket, ep.addr)
}
if socketConnections() == 0 {
t.Errorf("bd never connected through the socket %s", ep.addr)
}
return
}
if meta.DoltServerHost != "127.0.0.1" || meta.DoltServerPort != testDoltServerPort {
t.Errorf("metadata.json names %s:%d, want the endpoint init was given, %s", meta.DoltServerHost, meta.DoltServerPort, ep.addr)
}
}

View file

@ -0,0 +1,97 @@
package main
import (
"errors"
"fmt"
"net"
"strings"
"testing"
)
// TestExternalServerUnreachableMessage pins which failures get the --external
// wording. Only a failed dial may: the message claims the server could not be
// reached, so any other open failure (an identity mismatch, a handshake that
// was reset) must keep its own text instead of being reported as "externally
// managed".
func TestExternalServerUnreachableMessage(t *testing.T) {
refused := errors.New("connect: connection refused")
dial := &net.OpError{
Op: "dial",
Net: "tcp",
Addr: &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 3307},
Err: refused,
}
tests := []struct {
name string
err error
wantEndpoint string // "" means the error is not rewritten
}{
{"dial error", dial, "127.0.0.1:3307"},
{
// The store wraps the dial error with %w and its own advice.
"dial error wrapped like the store does",
fmt.Errorf("Dolt server unreachable at 127.0.0.1:3307: %w\n\nThe Dolt server may not be running.", dial),
"127.0.0.1:3307",
},
{
"unix socket dial error",
&net.OpError{Op: "dial", Net: "unix", Addr: &net.UnixAddr{Name: "/run/dolt.sock", Net: "unix"}, Err: refused},
"/run/dolt.sock",
},
{
// A name that does not resolve has no address to report.
"dial error without an address",
&net.OpError{Op: "dial", Net: "tcp", Err: errors.New("no such host")},
"the configured endpoint",
},
{"read error after connecting", &net.OpError{Op: "read", Net: "tcp", Err: errors.New("connection reset by peer")}, ""},
{"not a network error", errors.New("project identity mismatch"), ""},
}
// Every rewritten message says the server is declared external and that bd
// did not start one, and never advises `bd dolt start`.
requireDeclaredExternal := func(t *testing.T, got string, wants ...string) {
t.Helper()
for _, want := range append(wants, "externally managed", "did not start") {
if !strings.Contains(got, want) {
t.Errorf("message does not contain %q:\n%s", want, got)
}
}
if strings.Contains(got, "bd dolt start") {
t.Errorf("message advises `bd dolt start`:\n%s", got)
}
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := externalServerUnreachableMessage(tt.err)
if tt.wantEndpoint == "" {
if got != "" {
t.Fatalf("message = %q, want none for an error that is not a failed dial", got)
}
return
}
requireDeclaredExternal(t, got, tt.wantEndpoint)
})
}
// A dial to port 0 is an init that was never told a port: the address is a
// placeholder, not the server's endpoint, so the message must not offer it
// as one. The first line quotes the dialled address, so it is cut out
// before looking.
t.Run("dial error with no port named", func(t *testing.T) {
noPort := &net.OpError{
Op: "dial",
Net: "tcp",
Addr: &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 0},
Err: refused,
}
got := externalServerUnreachableMessage(noPort)
if got == "" {
t.Fatal("message = none, want the --external wording for a failed dial")
}
requireDeclaredExternal(t, got)
if strings.Contains(strings.ReplaceAll(got, noPort.Error(), ""), ":0") {
t.Errorf("message offers port 0 as the endpoint:\n%s", got)
}
})
}

View file

@ -19,17 +19,35 @@ import (
)
// guardLegacyUpgradeWorkspace rejects the reviewed pre-Dolt and legacy-Dolt
// workspace shapes before command setup can track a version, migrate metadata,
// or construct a store. It intentionally classifies only metadata, regular
// SQLite files, and the bounded local version witness; storage internals stay
// behind the driver boundary.
// workspace shapes, and workspaces whose metadata declares a format this build
// cannot open (checkWorkspaceFormat), before command setup can track a version,
// migrate metadata, or construct a store. It intentionally classifies only
// metadata, regular SQLite files, and the bounded local version witness;
// storage internals stay behind the driver boundary. Render its refusals with
// handleWorkspaceGuardError.
func guardLegacyUpgradeWorkspace(beadsDir string) error {
return guardLegacyUpgradeWorkspaceForInit(beadsDir, false)
}
// guardLegacyUpgradeWorkspaceForInit is guardLegacyUpgradeWorkspace for a caller
// that has already resolved server intent from a source the workspace does not
// yet record: `bd init --server`, whose flag is the only place that choice lives
// until init has written it. The guard cannot see the flag, so initSelectsServer
// carries it in. It is consulted for exactly one thing, the empty-root admission
// below, and is deliberately not folded into the workspace's own server mode:
// that would also move a non-empty root with an unreadable witness onto the
// warn-and-open arm, and an embedded repository beside a non-empty .beads/dolt
// onto the refusing one.
func guardLegacyUpgradeWorkspaceForInit(beadsDir string, initSelectsServer bool) error {
if beadsDir == "" {
return nil
}
cfg, err := configfile.LoadForDiscovery(beadsDir)
// This guard admits only the ordinary Issue store. A workspace in another
// format is refused before any legacy classification, which could
// otherwise admit it, or report it as a legacy store to migrate.
cfg, err := loadAndCheckWorkspaceFormat(beadsDir)
if err != nil {
return fmt.Errorf("loading config: %w", err)
return err
}
if isHistoricalSQLiteWorkspace(beadsDir, cfg) {
return legacyUpgradeRefusal("historical SQLite workspace")
@ -75,6 +93,15 @@ func guardLegacyUpgradeWorkspace(beadsDir string) error {
// did not.
return nil
}
if initSelectsServer && !present && isEmptyDirectory(filepath.Join(beadsDir, "dolt")) {
// Init has already chosen a server, so this is the empty root the
// serverMode arm below admits for a workspace that records the choice: it
// holds no Dolt data a legacy release could have left, and bd makes it
// itself on use, so a retry after a first attempt that could not reach a
// server finds exactly this. A present witness, a root holding any entry,
// and every caller that does not pass the flag are decided as before.
return nil
}
if serverMode {
if !present && isEmptyDirectory(filepath.Join(beadsDir, "dolt")) {
// An empty .beads/dolt holds no Dolt data, so no legacy release
@ -249,9 +276,34 @@ func onlyLegacySQLiteEntries(beadsDir string, entries []os.DirEntry, databaseNam
// excludes vc.db, so this bounded fallback runs only after that discovery found
// no current workspace.
func guardUndiscoveredLegacyWorkspace() error {
for _, beadsDir := range undiscoveredWorkspaceCandidates() {
if err := guardLegacyUpgradeWorkspace(beadsDir); err != nil {
return err
}
}
return nil
}
// checkUndiscoveredWorkspaceFormat refuses a workspace in a format this build
// cannot open (checkWorkspaceFormat) that discovery passed over, such as one
// marked only by a legacy config.json, and nothing else. It reads metadata
// without migrating it.
func checkUndiscoveredWorkspaceFormat() error {
for _, beadsDir := range undiscoveredWorkspaceCandidates() {
if err := checkDiscoveredWorkspaceFormat(beadsDir); err != nil {
return err
}
}
return nil
}
// undiscoveredWorkspaceCandidates lists, nearest first, the .beads directories
// the undiscovered-workspace checks read: the one BEADS_DIR names or, without
// it, each .beads from the working directory up to the repository root and
// below BEADS_CEILING_DIRECTORIES.
func undiscoveredWorkspaceCandidates() []string {
if explicit := os.Getenv("BEADS_DIR"); explicit != "" {
beadsDir := beads.FollowRedirect(utils.CanonicalizePath(explicit))
return guardLegacyUpgradeWorkspace(beadsDir)
return []string{beads.FollowRedirect(utils.CanonicalizePath(explicit))}
}
cwd, err := os.Getwd()
@ -261,19 +313,18 @@ func guardUndiscoveredLegacyWorkspace() error {
dir := utils.CanonicalizePath(cwd)
boundary := utils.CanonicalizePath(git.GetRepoRoot())
bound := ceiling.For(dir)
var candidates []string
for {
if bound.Excludes(dir) {
return nil
}
if err := guardLegacyUpgradeWorkspace(filepath.Join(dir, ".beads")); err != nil {
return err
return candidates
}
candidates = append(candidates, filepath.Join(dir, ".beads"))
if boundary != "" && utils.PathsEqual(dir, boundary) {
return nil
return candidates
}
parent := filepath.Dir(dir)
if parent == dir {
return nil
return candidates
}
dir = parent
}

View file

@ -0,0 +1,87 @@
//go:build cgo
package main
import (
"os"
"path/filepath"
"slices"
"strconv"
"testing"
)
// TestInitServerFlagAdmitsEmptyDoltRootWithoutConfig reproduces the retry shape
// with nothing on disk that records the server choice: an empty .beads/dolt and
// neither config.yaml nor metadata.json, so the --server flag is the only place
// the intent lives. The legacy guard used to refuse that init as a legacy Dolt
// workspace, so the workspace was never created and no bd command could repair
// it.
func TestInitServerFlagAdmitsEmptyDoltRootWithoutConfig(t *testing.T) {
skipIfNoDolt(t)
env := externalServerTestEnv(t)
repoDir := t.TempDir()
initGitRepo(t, repoDir)
beadsDir := filepath.Join(repoDir, ".beads")
if err := os.MkdirAll(filepath.Join(beadsDir, "dolt"), 0o700); err != nil {
t.Fatal(err)
}
database := uniqueTestDBName(t)
t.Cleanup(func() { dropTestDatabase(database, testDoltServerPort) })
out, err := runExternalServerBD(t, repoDir, env, externalServerInitArgs(database)...)
if err != nil {
t.Fatalf("bd init --server over an empty .beads/dolt failed: %v\n%s", err, out)
}
assertCurrentVersionWitness(t, beadsDir)
}
// TestInitServerFlagRetryAfterFailedFirstAttempt replays the reported sequence: a
// first `bd init --server` that cannot reach a server fails after creating the
// local Dolt root, leaving an empty .beads/dolt and no witness, and the same
// command run again once the server is up must succeed instead of being refused
// as a legacy workspace over the root the first attempt made itself.
func TestInitServerFlagRetryAfterFailedFirstAttempt(t *testing.T) {
skipIfNoDolt(t)
env := externalServerTestEnv(t)
// The first attempt has to fail without starting a server of its own: one
// that started and then failed would leave a populated .beads/dolt, which
// the guard refuses by design. externalServerTestEnv pins
// BEADS_DOLT_AUTO_START=0 for exactly that, which keeps the attempt
// deterministic even once init's separate --external handling stops trying
// to start a per-project server. Fail here, naming the reason, if a change to
// that helper drops it.
if !slices.Contains(env, "BEADS_DOLT_AUTO_START=0") {
t.Fatal("externalServerTestEnv must set BEADS_DOLT_AUTO_START=0: the failed first attempt must not start a server of its own")
}
repoDir := t.TempDir()
initGitRepo(t, repoDir)
beadsDir := filepath.Join(repoDir, ".beads")
database := uniqueTestDBName(t)
t.Cleanup(func() { dropTestDatabase(database, testDoltServerPort) })
out, err := runExternalServerBD(t, repoDir, env,
externalServerInitArgs(database, "--server-port", strconv.Itoa(freeLoopbackPort(t)))...)
if err == nil {
t.Fatalf("precondition: bd init --server against an unreachable server succeeded:\n%s", out)
}
// The retry only has something to fix if the failed attempt left exactly
// this. Any other leftover is a finding about init, not a reason to loosen
// what follows.
entries, readErr := os.ReadDir(filepath.Join(beadsDir, "dolt"))
if readErr != nil || len(entries) != 0 {
t.Fatalf("precondition: the failed first attempt should leave an empty .beads/dolt, found %d entries (err %v)", len(entries), readErr)
}
if _, statErr := os.Stat(filepath.Join(beadsDir, localVersionFile)); !os.IsNotExist(statErr) {
t.Fatalf("precondition: the failed first attempt should leave no %s (stat err %v)", localVersionFile, statErr)
}
out, err = runExternalServerBD(t, repoDir, env, externalServerInitArgs(database)...)
if err != nil {
t.Fatalf("retrying bd init --server over the empty .beads/dolt the first attempt left failed: %v\n%s", err, out)
}
assertCurrentVersionWitness(t, beadsDir)
}

View file

@ -0,0 +1,143 @@
package main
import (
"fmt"
"os"
"path/filepath"
"testing"
)
// TestLegacyUpgradeGuardForInitAdmitsEmptyDoltRoot pins the one thing init's own
// intent unlocks. `bd init --server` resolves server mode from the flag, a source
// the workspace does not record until init has written it. A retry over the empty
// .beads/dolt that a failed first attempt leaves behind therefore looks like an
// embedded workspace with a local Dolt root, and the guard refuses it. Told what
// init already knows, the guard gives that root the admission a config-selected
// server workspace gets. Asked without it, in either form, it still refuses, so
// the admission cannot pass vacuously.
func TestLegacyUpgradeGuardForInitAdmitsEmptyDoltRoot(t *testing.T) {
warnings := captureLegacyUpgradeWarnings(t)
beadsDir := writeEmptyDoltRootServerWorkspace(t, "", "", "")
if err := guardLegacyUpgradeWorkspaceForInit(beadsDir, true); err != nil {
t.Fatalf("guardLegacyUpgradeWorkspaceForInit(dir, true) = %v, want nil", err)
}
if warnings.Len() != 0 {
t.Fatalf("guard warned about an absent witness: %q", warnings.String())
}
if err := guardLegacyUpgradeWorkspaceForInit(beadsDir, false); !isLegacyUpgradeRefusal(err) {
t.Fatalf("guardLegacyUpgradeWorkspaceForInit(dir, false) = %v, want migration refusal", err)
}
if err := guardLegacyUpgradeWorkspace(beadsDir); !isLegacyUpgradeRefusal(err) {
t.Fatalf("guardLegacyUpgradeWorkspace(dir) = %v, want migration refusal", err)
}
}
// TestLegacyUpgradeGuardForInitAdmissionStaysNarrow proves init's intent relaxes
// nothing beyond an empty, witness-less .beads/dolt. With it set, anything that
// could be legacy data still refuses, and the outcomes a broader reading of the
// flag would move (treating it as if the workspace itself selected server mode)
// stay where they are.
func TestLegacyUpgradeGuardForInitAdmissionStaysNarrow(t *testing.T) {
for _, entry := range []string{"beads", ".dolt", "stray-file", "symlink"} {
t.Run("root holding "+entry, func(t *testing.T) {
captureLegacyUpgradeWarnings(t)
beadsDir := writeEmptyDoltRootServerWorkspace(t, "", "", "")
path := filepath.Join(beadsDir, "dolt", entry)
var err error
switch entry {
case "stray-file":
err = os.WriteFile(path, nil, 0o600)
case "symlink":
if err = os.Symlink(t.TempDir(), path); err != nil {
t.Skipf("symlink capability unavailable: %v", err)
}
default:
err = os.Mkdir(path, 0o700)
}
if err != nil {
t.Fatal(err)
}
if err := guardLegacyUpgradeWorkspaceForInit(beadsDir, true); !isLegacyUpgradeRefusal(err) {
t.Fatalf("guardLegacyUpgradeWorkspaceForInit(dir, true) = %v, want migration refusal", err)
}
})
}
for _, version := range []string{"0.49.6", "0.62.0"} {
t.Run("pre-1.0 witness "+version, func(t *testing.T) {
captureLegacyUpgradeWarnings(t)
beadsDir := writeEmptyDoltRootServerWorkspace(t, "", "", version)
if err := guardLegacyUpgradeWorkspaceForInit(beadsDir, true); !isLegacyUpgradeRefusal(err) {
t.Fatalf("guardLegacyUpgradeWorkspaceForInit(dir, true) = %v, want migration refusal", err)
}
})
}
t.Run("blank witness over a non-empty root", func(t *testing.T) {
warnings := captureLegacyUpgradeWarnings(t)
beadsDir := writeEmptyDoltRootServerWorkspace(t, "", "", "")
if err := os.Mkdir(filepath.Join(beadsDir, "dolt", "beads"), 0o700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(beadsDir, localVersionFile), []byte("\n"), 0o600); err != nil {
t.Fatal(err)
}
// A workspace that selects server mode itself warns and opens over an
// unreadable witness. Init's intent must not move this root onto that arm.
if err := guardLegacyUpgradeWorkspaceForInit(beadsDir, true); !isLegacyUpgradeRefusal(err) {
t.Fatalf("guardLegacyUpgradeWorkspaceForInit(dir, true) = %v, want migration refusal", err)
}
if warnings.Len() != 0 {
t.Fatalf("guard took the unreadable-witness arm: %q", warnings.String())
}
})
t.Run("symlinked dolt root", func(t *testing.T) {
captureLegacyUpgradeWarnings(t)
beadsDir := writeEmptyDoltRootServerWorkspace(t, "", "", "")
root := filepath.Join(beadsDir, "dolt")
if err := os.Remove(root); err != nil {
t.Fatal(err)
}
if err := os.Symlink(t.TempDir(), root); err != nil {
t.Skipf("symlink capability unavailable: %v", err)
}
// hasLegacyDoltRoot does not follow a symlink, so the guard never takes
// such a root for a local Dolt root and it never reaches the empty-root
// admission. Init's intent has to leave its outcome exactly where every
// other caller finds it.
want := fmt.Sprint(guardLegacyUpgradeWorkspace(beadsDir))
if got := fmt.Sprint(guardLegacyUpgradeWorkspaceForInit(beadsDir, true)); got != want {
t.Fatalf("guardLegacyUpgradeWorkspaceForInit(dir, true) = %s, want %s (unchanged by init's intent)", got, want)
}
})
t.Run("embedded repository beside a non-empty root", func(t *testing.T) {
captureLegacyUpgradeWarnings(t)
beadsDir := writeEmptyDoltRootServerWorkspace(t, "", "", "")
repo := filepath.Join(beadsDir, "embeddeddolt", "beads", ".dolt")
if err := os.MkdirAll(repo, 0o700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(repo, "repo-entry"), []byte("opaque"), 0o600); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(beadsDir, "dolt", "stray-file"), nil, 0o600); err != nil {
t.Fatal(err)
}
// An embedded repository admits the workspace before server intent is
// consulted at all. Folding init's intent into the workspace's own mode
// would send this one to the refusing arm.
for _, initSelectsServer := range []bool{false, true} {
if err := guardLegacyUpgradeWorkspaceForInit(beadsDir, initSelectsServer); err != nil {
t.Fatalf("guardLegacyUpgradeWorkspaceForInit(dir, %t) = %v, want nil", initSelectsServer, err)
}
}
})
}

View file

@ -5,7 +5,6 @@ import (
"github.com/spf13/cobra"
"github.com/steveyegge/beads/internal/metrics"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/internal/ui"
"github.com/steveyegge/beads/issueops"
@ -64,8 +63,10 @@ Examples:
defer toCleanup()
dt := types.DependencyType(depType)
// bd link writes through the store's own dependency verb rather than
// the DependencyEditor role, so it asks the role's rule directly.
// link's own checks run before anything is written, and over http
// before the dial: the dotted-child rule (the role raises it too) and
// the type's length. Unlike `bd dep add`, link takes any type a
// workspace spells, so it never asks validateDependencyType.
if err := issueops.CheckDottedChildDependency(fromID, toID, dt); err != nil {
return HandleErrorRespectJSON("%v", err)
}
@ -74,13 +75,25 @@ Examples:
return HandleErrorRespectJSON("invalid dependency type %q: must be non-empty and at most %d characters", depType, types.MaxDependencyTypeLen)
}
dep := &types.Dependency{
IssueID: fromID,
DependsOnID: toID,
Type: dt,
opsCtx, err := issueOpsContext(ctx)
if err != nil {
return HandleErrorRespectJSON("%v", err)
}
// Read the titles while the resolution's reads are fresh, as `bd dep
// add` does: an edge changes neither title, and over http a lookup
// after the write would be two more round trips.
var fromTitle, toTitle string
if !jsonOutput {
fromTitle, toTitle = lookupTitle(fromID), lookupTitle(toID)
}
if err := fromStore.AddDependencyWithOptions(ctx, dep, currentActor(), storage.DependencyAddOptions{EmitEvent: true}); err != nil {
// The write goes through the DependencyEditor role, the route `bd dep
// add` takes, so it is served on every backend: a local store and an
// http workspace alike (the http client refuses the raw
// AddDependencyWithOptions by design). The role records the
// dependency_added event the raw verb's EmitEvent did.
edge := issueops.DependencyEdge{IssueID: fromID, DependsOnID: toID, Type: dt}
if err := addDependencyEdgesDirect(opsCtx, fromStore, []issueops.DependencyEdge{edge}, false); err != nil {
return HandleErrorRespectJSON("%v", err)
}
@ -104,7 +117,7 @@ Examples:
})
}
fmt.Printf("%s Linked: %s depends on %s (%s)\n",
ui.RenderPass("✓"), formatFeedbackIDParen(fromID, lookupTitle(fromID)), formatFeedbackIDParen(toID, lookupTitle(toID)), depType)
ui.RenderPass("✓"), formatFeedbackIDParen(fromID, fromTitle), formatFeedbackIDParen(toID, toTitle), depType)
return nil
},
}

View file

@ -811,6 +811,7 @@ func TestEmbeddedListSearchAndOutputFormats(t *testing.T) {
if !strings.Contains(out, "digraph") {
t.Errorf("dot output should contain 'digraph' header, got: %s", out)
}
assertDotCanonicalOrder(t, out)
})
t.Run("format_dot_output_error", func(t *testing.T) {

View file

@ -327,6 +327,50 @@ func TestListDisplayPrettyListHonorsSort(t *testing.T) {
t.Fatalf("tree siblings ignore --sort closed:\n%s", out)
}
})
t.Run("deps scheduling", func(t *testing.T) {
// At both levels the --deps tree orders (roots, and one parent's
// children): late depends on dep, so dep prints first although --sort
// closed alone would lead with the newer late; free has no edge, so
// --sort closed puts it ahead of dep, where priority would put it last.
oldest := time.Now().Add(-3 * time.Hour)
parentAt := time.Now().Add(-4 * time.Hour)
parent := &types.Issue{ID: "bd-parent", Title: "Parent", Status: types.StatusClosed, Priority: 2, IssueType: types.TypeEpic, ClosedAt: &parentAt}
rootDep := &types.Issue{ID: "bd-root-dep", Title: "Root dependency", Status: types.StatusClosed, Priority: 0, IssueType: types.TypeTask, ClosedAt: &oldest}
rootLate := &types.Issue{ID: "bd-root-late", Title: "Root dependent", Status: types.StatusClosed, Priority: 1, IssueType: types.TypeTask, ClosedAt: &newer}
rootFree := &types.Issue{ID: "bd-root-free", Title: "Root unlinked", Status: types.StatusClosed, Priority: 2, IssueType: types.TypeTask, ClosedAt: &older}
childDep := &types.Issue{ID: "bd-child-dep", Title: "Child dependency", Status: types.StatusClosed, Priority: 0, IssueType: types.TypeTask, ClosedAt: &oldest}
childLate := &types.Issue{ID: "bd-child-late", Title: "Child dependent", Status: types.StatusClosed, Priority: 1, IssueType: types.TypeTask, ClosedAt: &newer}
childFree := &types.Issue{ID: "bd-child-free", Title: "Child unlinked", Status: types.StatusClosed, Priority: 2, IssueType: types.TypeTask, ClosedAt: &older}
deps := map[string][]*types.Dependency{
rootLate.ID: {{IssueID: rootLate.ID, DependsOnID: rootDep.ID, Type: types.DepBlocks}},
childDep.ID: {{IssueID: childDep.ID, DependsOnID: parent.ID, Type: types.DepParentChild}},
childFree.ID: {{IssueID: childFree.ID, DependsOnID: parent.ID, Type: types.DepParentChild}},
childLate.ID: {
{IssueID: childLate.ID, DependsOnID: parent.ID, Type: types.DepParentChild},
{IssueID: childLate.ID, DependsOnID: childDep.ID, Type: types.DepBlocks},
},
}
issues := []*types.Issue{parent, rootDep, rootLate, rootFree, childDep, childLate, childFree}
out := captureStdout(t, func() error {
displayPrettyListWithDepsMode(issues, false, deps, "scheduling", false, false, "closed", "closed", false, nil)
return nil
})
// A dependency's id also appears on its dependent's annotation row; the
// first occurrence is still the dependency's own row whenever it prints first.
for _, want := range [][]string{
{rootFree.ID, rootDep.ID, rootLate.ID},
{childFree.ID, childDep.ID, childLate.ID},
} {
for i := 1; i < len(want); i++ {
before, after := strings.Index(out, want[i-1]), strings.Index(out, want[i])
if before < 0 || after < 0 || before > after {
t.Fatalf("--deps scheduling --sort closed: want %s before %s:\n%s", want[i-1], want[i], out)
}
}
}
})
}
func TestListDisplayPrettyList(t *testing.T) {

View file

@ -2,9 +2,11 @@ package main
import (
"bytes"
"cmp"
"fmt"
"io"
"os"
"slices"
"strings"
"text/template"
@ -38,7 +40,27 @@ func composeTruncationHint(render func(string) string, text string) string {
return "\n" + rendered + "\n"
}
// outputDotFormat renders the listed issues, and the dependency edges between
// them, as a Graphviz digraph.
//
// The bytes depend on the graph alone: nodes are declared in byte order of id,
// and each node's edges in byte order of target id, then type (the order
// issueops.EdgeReader pins). The page arrives in display order, by default
// priority, then created_at DESC at one-second precision, then id, so two
// equal-priority issues swapped places depending on whether they were created
// in the same second; and the proxied route's edge query orders by source
// only. Declaration order means nothing in the graph but steers Graphviz's
// layout and shows in every diff, so it is pinned here, as bd graph --dot pins
// its layers. --sort and --limit still choose which issues are listed.
//
// Byte order, not the utils.NaturalCompareIDs order --sort id uses: that
// comparator is not a total order (x-9 < x-10 < x-1a < x-9; bd-01 ties bd-1),
// so a sort under it could still depend on the order the page arrived in.
// Both sorts work on copies; the caller's slices keep their order.
func outputDotFormat(out io.Writer, issues []*types.Issue, depsByIssueID map[string][]*types.Dependency) error {
issues = slices.Clone(issues)
slices.SortFunc(issues, func(a, b *types.Issue) int { return cmp.Compare(a.ID, b.ID) })
w := &graphExportWriter{out: out}
w.println("digraph dependencies {")
w.println(" rankdir=TB;")
@ -82,7 +104,11 @@ func outputDotFormat(out io.Writer, issues []*types.Issue, depsByIssueID map[str
// Output edges with labels for dependency type
for _, issue := range issues {
for _, dep := range depsByIssueID[issue.ID] {
deps := slices.Clone(depsByIssueID[issue.ID])
slices.SortFunc(deps, func(a, b *types.Dependency) int {
return cmp.Or(cmp.Compare(a.DependsOnID, b.DependsOnID), cmp.Compare(a.Type, b.Type))
})
for _, dep := range deps {
// Only output edges where both nodes are in the filtered list
if issueMap[dep.DependsOnID] != nil {
// Color code by dependency type

View file

@ -2,9 +2,12 @@ package main
import (
"bytes"
"cmp"
"errors"
"fmt"
"io"
"regexp"
"slices"
"strings"
"testing"
@ -65,6 +68,117 @@ func TestOutputDotFormatExactBytes(t *testing.T) {
}
}
// TestOutputDotFormatCanonicalOrder pins that the DOT rendering is a function
// of the graph alone. The page it is handed is in display order (priority,
// then created_at DESC at one-second precision, then id), so the same two
// equal-priority issues arrive in either order depending on whether they were
// created in the same second; and the proxied route's edge read does not order
// one issue's edges. Every order of the page, with each issue's edges either
// way round, must print these bytes: nodes by id, edges by source, target and
// type, all in byte order (so dot-10 sorts before dot-2). It also pins that the
// caller's page and edge slices are not reordered.
func TestOutputDotFormatCanonicalOrder(t *testing.T) {
t.Parallel()
issues := []*types.Issue{
{ID: "dot-2", Title: "Two", Status: types.StatusInProgress, Priority: 0, IssueType: types.TypeBug},
{ID: "dot-10", Title: "Ten", Status: types.StatusOpen, Priority: 1, IssueType: types.TypeEpic},
{ID: "dot-1", Title: "One", Status: types.StatusClosed, Priority: 2, IssueType: types.TypeTask},
}
edges := map[string][]*types.Dependency{
"dot-2": {
{IssueID: "dot-2", DependsOnID: "dot-10", Type: types.DepRelated},
{IssueID: "dot-2", DependsOnID: "dot-unlisted", Type: types.DepBlocks},
{IssueID: "dot-2", DependsOnID: "dot-1", Type: types.DepBlocks},
},
"dot-1": {{IssueID: "dot-1", DependsOnID: "dot-10", Type: types.DepParentChild}},
}
const want = `digraph dependencies {
rankdir=TB;
node [shape=box, style=rounded];
"dot-1" [label="dot-1\n[task P2]\nOne\n(closed)", style="rounded,filled", fillcolor="lightgray", fontcolor="dimgray"];
"dot-10" [label="dot-10\n[epic P1]\nTen\n(open)", style="rounded,filled", fillcolor="white", fontcolor="black"];
"dot-2" [label="dot-2\n[bug P0]\nTwo\n(in_progress)", style="rounded,filled", fillcolor="lightyellow", fontcolor="black"];
"dot-1" -> "dot-10" [label="parent-child", color=blue, style=solid];
"dot-2" -> "dot-1" [label="blocks", color=red, style=bold];
"dot-2" -> "dot-10" [label="related", color=gray, style=dashed];
}
`
for _, perm := range [][]int{{0, 1, 2}, {0, 2, 1}, {1, 0, 2}, {1, 2, 0}, {2, 0, 1}, {2, 1, 0}} {
for _, reversed := range []bool{false, true} {
page := []*types.Issue{issues[perm[0]], issues[perm[1]], issues[perm[2]]}
pageEdges := map[string][]*types.Dependency{}
for id, deps := range edges {
deps = slices.Clone(deps)
if reversed {
slices.Reverse(deps)
}
pageEdges[id] = deps
}
wantPage := slices.Clone(page)
wantEdges := map[string][]*types.Dependency{}
for id, deps := range pageEdges {
wantEdges[id] = slices.Clone(deps)
}
var out bytes.Buffer
if err := outputDotFormat(&out, page, pageEdges); err != nil {
t.Fatalf("outputDotFormat: %v", err)
}
name := fmt.Sprintf("page order %v, edges reversed %v", perm, reversed)
if got := out.String(); got != want {
t.Errorf("%s: DOT output bytes differ\ngot:\n%s\nwant:\n%s", name, got, want)
}
if !slices.Equal(page, wantPage) {
t.Errorf("%s: outputDotFormat reordered the caller's page", name)
}
for id, deps := range wantEdges {
if !slices.Equal(pageEdges[id], deps) {
t.Errorf("%s: outputDotFormat reordered the caller's edges of %s", name, id)
}
}
}
}
}
// dotNodeDecl and dotEdgeDecl match the node and edge lines outputDotFormat
// writes.
var (
dotNodeDecl = regexp.MustCompile(`(?m)^ "([^"]+)" \[label=`)
dotEdgeDecl = regexp.MustCompile(`(?m)^ "([^"]+)" -> "([^"]+)" \[label="([^"]+)"`)
)
// assertDotCanonicalOrder is TestOutputDotFormatCanonicalOrder's check for a
// real `bd list --format dot` run: nodes in byte order of id, edges in byte
// order of source, target and type. The embedded and proxied list seeds mint
// their ids across five priorities, so a rendering that followed the page's
// priority order fails it.
func assertDotCanonicalOrder(t *testing.T, out string) {
t.Helper()
var nodes []string
for _, m := range dotNodeDecl.FindAllStringSubmatch(out, -1) {
nodes = append(nodes, m[1])
}
if len(nodes) < 2 {
t.Fatalf("dot output declares %d nodes, want every listed issue:\n%s", len(nodes), out)
}
if !slices.IsSorted(nodes) {
t.Errorf("dot output declares its nodes out of id order: %v", nodes)
}
type edge struct{ from, to, typ string }
var edges []edge
for _, m := range dotEdgeDecl.FindAllStringSubmatch(out, -1) {
edges = append(edges, edge{m[1], m[2], m[3]})
}
if !slices.IsSortedFunc(edges, func(a, b edge) int {
return cmp.Or(cmp.Compare(a.from, b.from), cmp.Compare(a.to, b.to), cmp.Compare(a.typ, b.typ))
}) {
t.Errorf("dot output declares its edges out of (source, target, type) order: %v", edges)
}
}
func TestOutputFormattedListExactBytes(t *testing.T) {
t.Parallel()
issues, deps := listOutputFixture()

View file

@ -495,6 +495,7 @@ func TestProxiedServerList(t *testing.T) {
if !strings.Contains(out, "digraph") {
t.Errorf("dot output should contain 'digraph' header, got: %s", out)
}
assertDotCanonicalOrder(t, out)
})
t.Run("format_digraph_output_error", func(t *testing.T) {

View file

@ -1,8 +1,10 @@
package main
import (
"slices"
"strings"
"testing"
"time"
"github.com/spf13/cobra"
"github.com/steveyegge/beads/internal/types"
@ -83,6 +85,48 @@ func TestOrderSiblingsByDeps_OutOfGroupEdgeIgnored(t *testing.T) {
}
}
// closedSibling builds a sibling closed hoursAgo hours before a fixed instant,
// so --sort closed (newest first) orders it independently of priority and ID.
func closedSibling(id string, priority, hoursAgo int) *types.Issue {
at := time.Date(2026, 1, 1, 12, 0, 0, 0, time.UTC).Add(-time.Duration(hoursAgo) * time.Hour)
return &types.Issue{ID: id, Priority: priority, ClosedAt: &at}
}
func TestOrderSiblingsByDeps_ReadySetFollowsCallerCompare(t *testing.T) {
// b depends on a. Newest-closed first is b, u, a, v; priority order is
// v, a, u, b. The initial ready set {a, u, v} must follow the caller's
// compare (u, a, v), and once a frees b the re-sorted ready set must put
// the newer b ahead of v.
a := closedSibling("pa-a", 1, 3)
b := closedSibling("pa-b", 3, 1)
u := closedSibling("pa-u", 2, 2)
v := closedSibling("pa-v", 0, 4)
deps := map[string][]*types.Dependency{"pa-b": {schedDep("pa-b", "pa-a")}}
got := idsOf(orderSiblingsByDeps([]*types.Issue{b, a, v, u}, deps, compareIssuesForTree("closed", false)))
want := []string{"pa-u", "pa-a", "pa-b", "pa-v"}
if !slices.Equal(got, want) {
t.Fatalf("--sort closed ready set: got %v, want %v", got, want)
}
}
func TestOrderSiblingsByDeps_CycleFallbackFollowsCallerCompare(t *testing.T) {
// x <-> y cycle: x wins on priority and ID, but y closed more recently, so
// the cycle fallback under --sort closed must emit y first.
x := closedSibling("pa-x", 0, 2)
y := closedSibling("pa-y", 1, 1)
deps := map[string][]*types.Dependency{
"pa-x": {schedDep("pa-x", "pa-y")},
"pa-y": {schedDep("pa-y", "pa-x")},
}
got := idsOf(orderSiblingsByDeps([]*types.Issue{x, y}, deps, compareIssuesForTree("closed", false)))
want := []string{"pa-y", "pa-x"}
if !slices.Equal(got, want) {
t.Fatalf("--sort closed cycle fallback: got %v, want %v", got, want)
}
}
func TestDepEdgeDisplay(t *testing.T) {
cases := []struct {
name string

View file

@ -31,6 +31,7 @@ import (
"github.com/steveyegge/beads/internal/doltserver"
"github.com/steveyegge/beads/internal/hooks"
"github.com/steveyegge/beads/internal/httpclient"
"github.com/steveyegge/beads/internal/initprocs"
"github.com/steveyegge/beads/internal/metrics"
"github.com/steveyegge/beads/internal/migration"
"github.com/steveyegge/beads/internal/molecules"
@ -1578,6 +1579,9 @@ var rootCmd = &cobra.Command{
}
}
if err := guardLegacyNoStoreCommand(cmd, beadsDir); err != nil {
if isUnsupportedWorkspaceFormat(err) {
return handleWorkspaceGuardError(err)
}
isMigrationCommand := false
for current := cmd; current != nil; current = current.Parent() {
if current.Name() == "migrate" {
@ -1637,7 +1641,7 @@ var rootCmd = &cobra.Command{
prepareSelectedCommandContext(bd, true)
refreshBoundCommandConfig(cmd)
if guardErr := guardLegacyUpgradeWorkspace(bd); guardErr != nil {
return HandleError("%v", guardErr)
return handleWorkspaceGuardError(guardErr)
}
cfg, cfgErr := configfile.LoadForDiscovery(bd)
if cfgErr != nil || cfg != nil && (cfg.IsDoltProxiedServerMode() ||
@ -1658,7 +1662,7 @@ var rootCmd = &cobra.Command{
dbPath = bd
}
} else if guardErr := guardUndiscoveredLegacyWorkspace(); guardErr != nil {
return HandleError("%v", guardErr)
return handleWorkspaceGuardError(guardErr)
}
}
@ -1743,7 +1747,7 @@ var rootCmd = &cobra.Command{
prepareSelectedCommandContext(beadsDir, true)
refreshBoundCommandConfig(cmd)
if guardErr := guardLegacyUpgradeWorkspace(beadsDir); guardErr != nil {
return HandleError("%v", guardErr)
return handleWorkspaceGuardError(guardErr)
}
// Workspace operation gate: every command that reaches this point
@ -2782,7 +2786,7 @@ func isBootstrapPreviewErr(err error) bool {
// Extracted from the gate's default arm so both halves are directly testable
// without standing up a forward-drifted workspace; the wire itself is pinned on
// the embedded tier by
// TestIdentityGateRendersSchemaSkewFromForwardDriftedWorkspace.
// TestEmbeddedIdentityGateRendersSchemaSkewFromForwardDriftedWorkspace.
func refuseUnverifiablePreviewOpen(previewErr error) error {
if handleFreshCloneError(previewErr) {
return SilentExit()
@ -2878,6 +2882,7 @@ func validateWorkspaceIdentity(ctx context.Context, s storage.DoltStorage, beads
}
func main() {
initprocs.Done()
// BD_NAME overrides the binary name in help text (e.g. BD_NAME=ops makes
// "ops --help" show "ops" instead of "bd"). Useful for multi-instance
// setups where wrapper scripts set BEADS_DIR for routing.

View file

@ -25,8 +25,10 @@ import (
// workspace and then deletes them from the project. Those are ordinary bead
// mutations in another workspace, so they belong in that workspace's events
// journal if it has one enabled — and the setting is read from there, not from
// the workspace bd was launched in.
// the workspace bd was launched in. The same goes for its issue-version history,
// which the store's own settings row decides.
func openMigrationPlanningStore(ctx context.Context, planningBeadsDir string) (s storage.DoltStorage, err error) {
defer func() { s, err = activateVersionedHistoryStore(ctx, s, err) }()
defer func() { s, err = activateEventsJournalStore(planningBeadsDir, s, err) }()
return dolt.New(ctx, &dolt.Config{
Path: doltserver.ResolveDoltDir(planningBeadsDir),

View file

@ -46,9 +46,9 @@ func setupContributorRouting(t *testing.T, bd, dir string) string {
return planningDir
}
// TestMigratePersonal_noopWhenEmpty verifies that migrate-personal with no
// TestEmbeddedMigratePersonal_noopWhenEmpty verifies that migrate-personal with no
// matching issues exits 0 and reports nothing to migrate.
func TestMigratePersonal_noopWhenEmpty(t *testing.T) {
func TestEmbeddedMigratePersonal_noopWhenEmpty(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")
}
@ -71,9 +71,9 @@ func TestMigratePersonal_noopWhenEmpty(t *testing.T) {
}
}
// TestMigratePersonal_movesIssues verifies that migrate-personal moves issues
// TestEmbeddedMigratePersonal_movesIssues verifies that migrate-personal moves issues
// matching the current git identity to the planning repo.
func TestMigratePersonal_movesIssues(t *testing.T) {
func TestEmbeddedMigratePersonal_movesIssues(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")
}
@ -119,9 +119,9 @@ func TestMigratePersonal_movesIssues(t *testing.T) {
_ = planningDir
}
// TestMigratePersonal_abortOnNoConfirm verifies that without --yes, the command
// TestEmbeddedMigratePersonal_abortOnNoConfirm verifies that without --yes, the command
// prompts and aborts when stdin signals no confirmation (EOF).
func TestMigratePersonal_abortOnNoConfirm(t *testing.T) {
func TestEmbeddedMigratePersonal_abortOnNoConfirm(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")
}
@ -162,13 +162,13 @@ func TestMigratePersonal_abortOnNoConfirm(t *testing.T) {
}
}
// TestMigratePersonal_preservesComments is a regression test for the maphew
// TestEmbeddedMigratePersonal_preservesComments is a regression test for the maphew
// review of PR #4023 (be-e2nb): migrate-personal must copy comments as
// structured rows (ImportIssueComment) so they survive in the planning repo.
// The pre-fix code used AddComment, which records an event-style entry that
// GetIssueComments never returns — silently dropping the migrated issue's
// comments.
func TestMigratePersonal_preservesComments(t *testing.T) {
func TestEmbeddedMigratePersonal_preservesComments(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")
}
@ -211,14 +211,14 @@ func TestMigratePersonal_preservesComments(t *testing.T) {
}
}
// TestCopyIssueRelations_preservesCommentWithTimestamp is the in-process proof
// TestEmbeddedCopyIssueRelations_preservesCommentWithTimestamp is the in-process proof
// for the maphew review of PR #4023 (be-e2nb). The full migrate-personal command
// can't run in the embedded harness because its planning store uses the
// server-based Dolt store, so this drives the helper directly against two
// embedded stores: a comment must land in the destination as a structured row
// (returned by GetIssueComments) preserving its original timestamp, not be lost
// as an event-style AddComment entry.
func TestCopyIssueRelations_preservesCommentWithTimestamp(t *testing.T) {
func TestEmbeddedCopyIssueRelations_preservesCommentWithTimestamp(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")
}

View file

@ -13,7 +13,7 @@ import (
"github.com/steveyegge/beads/internal/storage/schema"
)
// TestMigrateSchema_IdentityMismatchRefusesBeforeApplying reproduces be-0gfcs:
// TestEmbeddedMigrateSchema_IdentityMismatchRefusesBeforeApplying reproduces be-0gfcs:
// bd migrate schema's workspace-identity guard (validateWorkspaceIdentity)
// runs AFTER the shared pre-run has already opened the store and let the
// smart gate auto-apply a pending schema migration as a side effect. The
@ -22,7 +22,7 @@ import (
// schema_migrations. The fix must make the identity check run before (or
// otherwise gate) that auto-apply, so a refused migrate leaves the schema
// cursor untouched.
func TestMigrateSchema_IdentityMismatchRefusesBeforeApplying(t *testing.T) {
func TestEmbeddedMigrateSchema_IdentityMismatchRefusesBeforeApplying(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")
}

View file

@ -743,8 +743,8 @@ func TestLabelAddBlockedDuringMigrationFreeze(t *testing.T) {
// Plain `bd import` is stopped by the early gate in PersistentPreRunE, like
// any other write. The `--dry-run` row is the one that pins runImport's OWN
// call: a preview sets useReadOnly, so it skips the early gate, and runImport
// never calls CheckReadonly — delete the check from import.go and only this
// row goes red. It also pins the claim the PreRunE comment makes about
// calls CheckReadonly only under strict --readonly, so its freeze check is the
// only one left — delete that check from import.go and only this row goes red. It also pins the claim the PreRunE comment makes about
// previews being re-blocked at the per-command chokepoint, which for import is
// exactly that call and nothing else.
func TestImportBlockedDuringMigrationFreeze(t *testing.T) {

View file

@ -13,11 +13,11 @@ import (
"github.com/steveyegge/beads/internal/validation"
)
// TestSpawnMolecule_PreservesStepLabels verifies that a cooked formula with
// TestEmbeddedSpawnMolecule_PreservesStepLabels verifies that a cooked formula with
// per-step labels results in spawned issues whose labels are persisted to the
// database. Regression for labels being silently dropped by cloneSubgraph in
// the same shape as the metadata bug fixed by gastownhall/beads#3341.
func TestSpawnMolecule_PreservesStepLabels(t *testing.T) {
func TestEmbeddedSpawnMolecule_PreservesStepLabels(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")
}
@ -74,9 +74,9 @@ func TestSpawnMolecule_PreservesStepLabels(t *testing.T) {
}
}
// TestSpawnMolecule_SubstitutesTemplatedStepFields is the cook -> pour
// TestEmbeddedSpawnMolecule_SubstitutesTemplatedStepFields is the cook -> pour
// regression test for GH#5110 (labels, metadata) and GH#5754 (assignee).
// TestSpawnMolecule_PreservesStepLabels above fixed labels being dropped
// TestEmbeddedSpawnMolecule_PreservesStepLabels above fixed labels being dropped
// entirely, but its labels carry no {{vars}}, so the missing substitution went
// unnoticed: the labels ARE carried through - just literal, which silently
// stops matching every label query downstream.
@ -85,7 +85,7 @@ func TestSpawnMolecule_PreservesStepLabels(t *testing.T) {
// spawned bead unclosable by the actor that poured it, so the molecule can
// never advance - which is what the AssigneeMatches assertion pins, not just
// the string value.
func TestSpawnMolecule_SubstitutesTemplatedStepFields(t *testing.T) {
func TestEmbeddedSpawnMolecule_SubstitutesTemplatedStepFields(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")
}

View file

@ -281,12 +281,12 @@ func primeFirstDiff(got, want string) string {
// subprocess parity tests. The TestEmbedded prefix is deliberate and
// load-bearing in both directions: the fast `./...` lanes run
// -skip '^TestEmbedded' (pr.yml, main.yml), and .github/scripts/embedded-test-shard.sh
// discovers shard members by grepping ^func TestEmbedded in *_embedded_test.go.
// discovers shard members by grepping ^func TestEmbedded in cmd/bd/*_test.go.
// So they run in the full embedded tier, which ci-embedded-tier.sh enables
// unconditionally for merge_group and pushes to main — i.e. in the merge queue
// before this can land, not on every PR push. Renaming them out of the prefix
// moves ~30s of subprocess work into every short lane; renaming the file out of
// *_embedded_test.go drops them from the shard runner entirely.
// moves ~30s of subprocess work into every short lane and drops them from the
// shard runner entirely.
//
// TestEmbeddedPrimeChangeDirPrimesTarget is the issue's repro end to end
// (#5509): from repo-a, `bd -C repo-b prime` must emit repo-b's PRIME.md,

View file

@ -238,12 +238,12 @@ func TestEmbeddedPruneDryRunAndFilters(t *testing.T) {
})
}
// TestPrune_protectsBeadCitedByCustomStatusBead is a regression test for the
// TestEmbeddedPrune_protectsBeadCitedByCustomStatusBead is a regression test for the
// maphew review of PR #4023 (be-e2nb): reference-aware prune must scan beads in
// active *custom* statuses, not only the built-in non-closed statuses. A closed
// bead cited by a bead in an active custom status must be protected from prune,
// exactly like one cited by a built-in open bead.
func TestPrune_protectsBeadCitedByCustomStatusBead(t *testing.T) {
func TestEmbeddedPrune_protectsBeadCitedByCustomStatusBead(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")
}

View file

@ -179,6 +179,9 @@ This is useful for agents executing molecules to see which steps can run next.`,
return nil
}
if jsonOutput && readyJSONPrintsNoTotal(activeStore) {
return runReadyJSONWithoutTotal(ctx, activeStore, filter)
}
if jsonOutput {
// The page and the size of the whole ready set come back from ONE
// read transaction: the total rides the page's own ID query, so a
@ -430,6 +433,65 @@ var blockedCmd = &cobra.Command{
},
}
// readyJSONPrintsNoTotal reports whether `bd ready --json` should skip sizing
// the whole ready set. Without BD_JSON_ENVELOPE the total only decorates the
// stderr hint. A local store takes it in the page's own transaction, so the
// hint keeps it there; a remote backend pays a second request
// (countReadyWork) for it, so the hint goes without.
func readyJSONPrintsNoTotal(activeStore storage.DoltStorage) bool {
return !jsonEnvelopeEnabled() && storeIsRemoteBackend(activeStore)
}
// runReadyJSONWithoutTotal lists one row past the limit, which says whether
// the limit hid anything: all the hint needs. A cap at or below the limit
// would count that extra row against it, so such a listing keeps the counted
// path and its refusal exactly as before.
func runReadyJSONWithoutTotal(ctx context.Context, activeStore storage.DoltStorage, filter types.WorkFilter) error {
limit := filter.Limit
var results []*types.IssueWithCounts
var total int
var err error
if limit > 0 && filter.MaxRows > 0 && filter.MaxRows <= limit {
results, total, err = activeStore.GetReadyWorkWithCountsAndTotal(ctx, filter)
} else {
if limit > 0 {
filter.Limit = limit + 1
}
results, err = activeStore.GetReadyWorkWithCounts(ctx, filter)
total = len(results)
}
if err != nil {
if capErr := handleMaxRowsError(err); capErr != nil {
return capErr
}
return HandleErrorRespectJSON("%v", err)
}
truncated := limit > 0 && len(results) >= limit && total > limit
if len(results) > limit && limit > 0 {
results = results[:limit]
}
if results == nil {
results = []*types.IssueWithCounts{}
}
if err := outputJSON(results); err != nil {
return err
}
if truncated {
fmt.Fprintf(os.Stderr, "%s Use --limit 0 for all, or --limit N to raise the cap.\n", readyHiddenHint(len(results)))
}
return nil
}
// readyHiddenHint is the truncation hint for a page whose total is unknown:
// how many rows are shown, and that the limit hid more.
func readyHiddenHint(shown int) string {
noun := "issues"
if shown == 1 {
noun = "issue"
}
return fmt.Sprintf("Showing %d ready %s; more matched but were hidden by --limit.", shown, noun)
}
// readyTotal sizes the whole ready set for the request `bd ready` just listed
// a page of, through the store's own ReadyCounter accessor.
//

View file

@ -0,0 +1,138 @@
package main
import (
"context"
"encoding/json"
"strings"
"testing"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/types"
)
// readyPageFake serves GetReadyWorkWithCounts from a fixed ready set and
// records the filters it was asked for. Its embedded DoltStorage is nil, so any
// other read panics and the test says so.
type readyPageFake struct {
storage.DoltStorage
ready []*types.IssueWithCounts
limits []int
totalCalls int
}
func (f *readyPageFake) IsRemoteBackendStore() bool { return true }
func (f *readyPageFake) GetReadyWorkWithCounts(_ context.Context, filter types.WorkFilter) ([]*types.IssueWithCounts, error) {
f.limits = append(f.limits, filter.Limit)
if filter.Limit > 0 && filter.Limit < len(f.ready) {
return f.ready[:filter.Limit], nil
}
return f.ready, nil
}
func (f *readyPageFake) GetReadyWorkWithCountsAndTotal(_ context.Context, filter types.WorkFilter) ([]*types.IssueWithCounts, int, error) {
f.totalCalls++
if filter.Limit > 0 && filter.Limit < len(f.ready) {
return f.ready[:filter.Limit], len(f.ready), nil
}
return f.ready, len(f.ready), nil
}
func readyRows(n int) []*types.IssueWithCounts {
rows := make([]*types.IssueWithCounts, n)
for i := range rows {
rows[i] = &types.IssueWithCounts{Issue: &types.Issue{ID: "bd-" + string(rune('a'+i)), Title: "t", Status: types.StatusOpen}}
}
return rows
}
func runReadyJSONWithoutTotalForTest(t *testing.T, s storage.DoltStorage, filter types.WorkFilter) ([]types.IssueWithCounts, string) {
t.Helper()
stdioMutex.Lock()
defer stdioMutex.Unlock()
var err error
stdout, stderr := captureStdio(t, func() {
err = runReadyJSONWithoutTotal(context.Background(), s, filter)
})
if err != nil {
t.Fatalf("runReadyJSONWithoutTotal: %v\nstderr: %s", err, stderr)
}
var rows []types.IssueWithCounts
if err := json.Unmarshal([]byte(stdout), &rows); err != nil {
t.Fatalf("stdout is not a JSON array: %v\n%s", err, stdout)
}
return rows, stderr
}
// TestReadyJSONOnARemoteBackendAsksForNoTotal pins `bd ready --json` against a
// remote backend with no envelope: one listing one row past the limit, never
// the counted listing (which costs a remote store a countReadyWork request),
// and a hint that says more exist without saying how many.
func TestReadyJSONOnARemoteBackendAsksForNoTotal(t *testing.T) {
t.Run("truncated", func(t *testing.T) {
s := &readyPageFake{ready: readyRows(5)}
rows, stderr := runReadyJSONWithoutTotalForTest(t, s, types.WorkFilter{Limit: 2})
if len(rows) != 2 {
t.Fatalf("printed %d rows, want the 2 the limit allows", len(rows))
}
if len(s.limits) != 1 || s.limits[0] != 3 || s.totalCalls != 0 {
t.Fatalf("listings asked for limits %v and %d counted listings, want one listing of 3 and none counted", s.limits, s.totalCalls)
}
if !strings.Contains(stderr, "Showing 2 ready issues; more matched but were hidden by --limit.") {
t.Fatalf("stderr = %q, want the truncation hint without a total", stderr)
}
})
t.Run("whole set", func(t *testing.T) {
s := &readyPageFake{ready: readyRows(2)}
rows, stderr := runReadyJSONWithoutTotalForTest(t, s, types.WorkFilter{Limit: 2})
if len(rows) != 2 || stderr != "" {
t.Fatalf("rows = %d, stderr = %q; want both rows and no hint", len(rows), stderr)
}
})
t.Run("unlimited", func(t *testing.T) {
s := &readyPageFake{ready: readyRows(3)}
rows, stderr := runReadyJSONWithoutTotalForTest(t, s, types.WorkFilter{})
if len(rows) != 3 || stderr != "" || len(s.limits) != 1 || s.limits[0] != 0 {
t.Fatalf("rows = %d, stderr = %q, limits = %v; want every row, no hint, one unlimited listing", len(rows), stderr, s.limits)
}
})
t.Run("cap at the limit keeps the counted listing", func(t *testing.T) {
s := &readyPageFake{ready: readyRows(5)}
rows, stderr := runReadyJSONWithoutTotalForTest(t, s, types.WorkFilter{Limit: 2, MaxRows: 2})
if len(rows) != 2 || s.totalCalls != 1 || len(s.limits) != 0 {
t.Fatalf("rows = %d, counted = %d, limits = %v; want the counted listing alone", len(rows), s.totalCalls, s.limits)
}
if !strings.Contains(stderr, "Showing 2 ready issues; more matched") {
t.Fatalf("stderr = %q, want the truncation hint without a total", stderr)
}
})
}
// TestReadyJSONPrintsNoTotalOnlyWithoutTheEnvelopeOnARemoteBackend pins when
// the total is skipped: the envelope prints it as pagination.total, and a local
// store takes it in the page's own transaction for the stderr hint.
func TestReadyJSONPrintsNoTotalOnlyWithoutTheEnvelopeOnARemoteBackend(t *testing.T) {
remote := &readyPageFake{}
local := &routingSettingsFake{}
t.Setenv("BD_JSON_ENVELOPE", "")
if !readyJSONPrintsNoTotal(remote) {
t.Error("remote backend without the envelope: want the total skipped")
}
if readyJSONPrintsNoTotal(local) {
t.Error("local store: want the total kept")
}
t.Setenv("BD_JSON_ENVELOPE", "1")
if readyJSONPrintsNoTotal(remote) {
t.Error("remote backend with the envelope: want the total kept for pagination.total")
}
}
func TestReadyHiddenHintAgreesInNumber(t *testing.T) {
if got := readyHiddenHint(1); got != "Showing 1 ready issue; more matched but were hidden by --limit." {
t.Errorf("readyHiddenHint(1) = %q", got)
}
if got := readyHiddenHint(2); got != "Showing 2 ready issues; more matched but were hidden by --limit." {
t.Errorf("readyHiddenHint(2) = %q", got)
}
}

Some files were not shown because too many files have changed in this diff Show more