Commit graph

108 commits

Author SHA1 Message Date
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
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
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
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
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
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
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
Jim Wordelman
ce70b261c5
storage: add participation_generation (migration 0070) and the versioned-history write fence (#6943)
* schema+storage: restore 0068, move participation_generation to 0070 (be-blvmg)

MAYOR RULING 2026-09-29 on tracker be-waare: migration 0068 shipped to
origin/main as attribution_status-only (be-v33pa). be-h89oq's lineage had
appended participation_generation steps 4-5 to that same file while it was
still unmerged, which check-migration-hygiene.sh Check C correctly rejects
once 0068 is frozen on main. This restores 0068 to origin/main's exact
content and re-homes the participation_generation column (issues + wisps,
design section 16.3 steps 4-5, be-dt74u amendment) in a new migration 0070,
with its clone-local ignored/0028 twin for wisps. Ports back the
participation_generation write-fence consumer code (RecordVersionInTx in
internal/storage/issueops/version_history.go and its callers) and the
dualwrite contract tests that exercise it.

RED: the CLI-bundle direct-DDL override for 0070's guarded PREPARE/ALTER
pair is not yet registered in cli_migrations.go, so
TestBundleMigrationsWithPreparedALTERAreOverriddenOrJustified,
TestMigration0070AddsParticipationGeneration, and
TestAllMigrationsSQLUsesDirectDDLForKnownCLIIncompatibilities fail --
correctly: a fresh CLI-built bundle would silently omit the column
(dolthub/dolt#11345) while a runtime-migrated store has it.

git diff origin/main -- internal/storage/schema/migrations/0068_*.sql is
empty, confirming 0068 is untouched.

Agent-Signature: model=claude-sonnet-5; reasoning=high

* schema: register CLI-bundle direct-DDL override for migration 0070 (be-blvmg)

GREEN: adds cliMigration0070AddParticipationGeneration and its dispatch
entries (cliCompatibleMigrationSQL, cliSubstituteAssumesWispTables), the
same pre-2.3 Dolt CLI PREPARE/ALTER escape hatch 0067's wisps.current_revision
and 0068's attribution_status already use (dolthub/dolt#11345). Makes
TestBundleMigrationsWithPreparedALTERAreOverriddenOrJustified,
TestMigration0070AddsParticipationGeneration, and
TestAllMigrationsSQLUsesDirectDDLForKnownCLIIncompatibilities pass: a
fresh CLI-built bundle now carries participation_generation on both
issues and wisps, matching what a runtime-migrated store gets.

scripts/check-migration-hygiene.sh checks A-D pass; 0068 remains
byte-identical to origin/main.

Agent-Signature: model=claude-sonnet-5; reasoning=high

* build: bazel-sync BUILD.bazel for migration 0070 files (be-blvmg)

make bazel-sync (gazelle) picked up two files the RED commit added that
the hand-ported BUILD.bazel hadn't listed yet: 0070's embedded .up.sql in
the go_library embedsrcs and migration_0070_add_participation_generation_test.go
in the go_test srcs.

Agent-Signature: model=claude-sonnet-5; reasoning=high

* test(feat): red — Fix: enable history before fixtures in TestDualWriteDeleteNeighborRewriteRidesTheDeletesDoltCommit — PR #6943's §16.2b write fence leaves its flag-off neighbor legacy, so the delete mints 0 rows (stacked on 44418b3) (refs be-fyaja)

* feat: green — Fix: enable history before fixtures in TestDualWriteDeleteNeighborRewriteRidesTheDeletesDoltCommit — PR #6943's §16.2b write fence leaves its flag-off neighbor legacy, so the delete mints 0 rows (stacked on 44418b3)

(refs be-fyaja)

* test(conformance): pin that a wisp reaching the issues plane begins its history (be-31mnz)

Review feedback on #6943, blocker 1: with the flag on, a promoted wisp is
never versioned. None of the five RunParticipationGeneration* cases reaches
a promotion, so nothing caught it.

Two contract cases, wired on all three legs:

- RunParticipationGenerationWispPromotionBeginsHistory: create a wisp with
  the flag on, promote it, and require a stamped participation_generation,
  one version row, and +1 on the next update.
- RunParticipationGenerationWispPersistenceMoveBeginsHistory: the same
  check for a persistence-mode update (bd update --persistent). This mints
  at a different site than promotion on every leg: the guarded update's one
  end-of-update mint on dolt and embeddeddolt, and
  MoveIssuePersistenceInTx's own on uow.

"Wisp" is in the names because this contract already says "promoted" in
R2.3's sense (ProceedsForPromotedRecord), which is a different operation.
The fixture gains CreateWisp, PromoteWisp and MovePersistent closures, and
each leg's FixtureKitIsWired checks them.

Red at this commit on the embedded leg: after the arrival there are 0 rows
and participation_generation is NULL, and after the update there are still
0 rows. A flag-on durable create goes 1 -> 2 in the same store.

* fix(issueops): mint a wisp's first issues-plane version create-shaped (be-31mnz)

Review feedback on #6943, blocker 1. A promotion, or a persistence move out
of the wisps table, inserts a new issues row. A wisp never declares
participation (FR-8), so that row's participation_generation is NULL. Both
sites minted through the update-shaped RecordVersionInTx, and the section
16.2b fence read the NULL as legacy and skipped the mint. Nothing stamps the
column later, so every later update skipped too, and a record created with
versioned history on was never versioned.

These sites now use RecordVersionForCreateInTx, which stamps the column and
mints version 1, as a create on the issues plane does:

- PromoteFromEphemeralInTx (promote.go).
- MoveIssuePersistenceInTx's move out of the wisps table.
- ExecuteUpdate's one end-of-update mint (execution.go), when its
  persistence patch did that move. This is the site bd update --persistent
  reaches on the dolt and embeddeddolt legs, and the review did not list
  it. PersistenceMoveResult.EnteredIssuesPlane tells ExecuteUpdate which
  entry point to use.

One site the review named stays update-shaped on purpose:
MoveIssuePersistenceInTx's same-plane repair, which clears a stray wisp
flag on a row already in issues. That row keeps its own
participation_generation. A row created with the flag on still mints. A
legacy row stays legacy, because a repair is an ordinary write and R2.3
says an ordinary write does not promote it. A create-shaped mint there
would stamp the legacy row and start versioning it.

* docs(schema): 0070 must precede turning versioned history on (be-31mnz)

Review note on #6943 (schema skew). The write fence reads
participation_generation on every flag-on mint of an issues-plane row. On a
store that has not applied 0070 the read fails, and the mutation fails with
it instead of skipping. The migration header now says so, and says that the
flag-off path (the default) returns before the read, so a store below 0070
writes exactly as before.

Comment only. 0070 is not on main, so check-migration-hygiene's frozen-file
check does not apply to it, and no test pins its bytes.

* test(dolt): a persistence repair keeps the row's own participation (be-31mnz)

Pins why MoveIssuePersistenceInTx's same-plane repair stays update-shaped
while promotion and a move out of the wisps table became create-shaped (the
previous commit). The repair clears a stray wisp flag on a row that already
lives in issues, so the row keeps its own participation_generation.

TestPersistenceRepairKeepsTheRowsOwnParticipation runs the repair with
versioned history on for a legacy row (created with the flag off) and a
participating row (created with it on), through both repair entry points:
MoveIssuePersistenceInTx and a guarded update with a persistence patch. They
mint at different sites. The legacy row must stay NULL and mint nothing,
since R2.3 says an ordinary write does not promote it. The participating row
must mint one version. participation_generation must not change in either
case.

It fails if the repair mint is create-shaped, which would stamp and start
versioning the legacy row.

* test(dolt): a delete's rewrite of a legacy neighbor mints nothing (be-31mnz)

Folded in from bee's R1 on #6961, note 1. Once
TestDualWriteDeleteNeighborRewriteRidesTheDeletesDoltCommit started creating
its neighbor with history on, nothing covered a delete whose neighbor was
created with history off. Under the section 16.2b fence, the expected result
for that case is different: the rewrite still runs, but it mints nothing.

TestDualWriteDeleteSkipsALegacyNeighborsRewrite creates the fixtures with
history off, turns history on, and force-deletes the cited target. It then
checks four things: the rewrite ran (ReferencesUpdated=1), the neighbor has
no issue_versions rows, its participation_generation is still NULL, and
dolt_status is clean for issue_versions, store_epoch and issues.

* test(embeddeddolt): batch-created rows are stamped with the participation generation

A batch create writes its rows first and mints each created row's first
version last, after the creation-time edges land. The mint has to stay
create-shaped for rows the batch inserted (stamping participation_generation
from the store epoch) and update-shaped for rows it only upserted over
(skipped while the row is a legacy row), so the per-row isNew has to survive
the deferral to the batch's final mint pass.

Pin that on the embedded engine:

- brand-new explicit-id rows are stamped with the store epoch and get one
  version row each, and match the same input run one row at a time with the
  batch-create fast paths off (5 rows, and 250 rows across three INSERT
  statements);
- a legacy row the batch upserts over keeps a NULL participation_generation
  and gets no version row, while the new rows beside it are stamped;
- with versioned history off, no row is stamped and no version row is written.

* ci(bazel): enroll the participation-generation tests in the embedded shards

The embedded-Dolt shard manifest has to name every top-level Test* in
internal/storage/embeddeddolt, or the exact-once coverage check fails.
The two participation-generation fence tests were written before that
check landed on main, and the batch-create stamping test is new, so none
of the three is listed yet. Add them to the 15-shard block as the
generator's incremental output: three inserted lines, no existing
assignment moves.

Also list the new batch-create test file in the embeddeddolt_test srcs,
in sorted position, so the Bazel target compiles it alongside the Go
build. Its imports are already among that target's deps.

Rebase note (maintainer): on current main the embedded storage manifest
uses a 40-shard block; the generator's incremental output placed these
three tests in shards 18, 19 and 39 and re-sorted one existing shard-12
line.

* fix(issueops): keep a created row's updated_at when its first version is minted

Minting a version is bookkeeping. It must not change a user-visible column
of the row it versions.

The create-shaped mint stamps participation_generation with an UPDATE of the
issues row. issues.updated_at is ON UPDATE CURRENT_TIMESTAMP, so an UPDATE
that changes any other column and does not name updated_at rewrites it with
the clock. Before the stamp, a row's first mint left current_revision at its
column default of 1, so the UPDATE changed nothing and the clause never
fired. The stamp moves participation_generation from NULL to the store
epoch, so the clause fires on every row whose first version is minted and
replaces the updated_at an import supplies.

Set updated_at to itself in the stamp, as the blocked-state recompute in
issueops/blocked_state.go already does, so the timestamp the row was created
with survives. Add a regression that batch-creates rows with a supplied
updated_at and requires both the stamp and the unchanged timestamp.

* test(createbatchequiv): re-record the digests the participation-generation fence moves

The fence does not re-mint rows that predate the stamp: a row whose
participation_generation is still NULL gets no new version when a batch
touches it. Main mints one, so six recorded entries move.

The issue_versions entry of five scenarios loses the versions main mints
for rows that predate the stamp: three rows in small, all eleven in
depadd, all fifteen in waitsfor, four in import458 and two in
import458-reject-stale. In depadd, eq-db1 and eq-dl are the only rows
main mints more than once, and each of those mints moves their updated_at
off the fixture date. The fence skips them, so the two rows keep the
fixture date and join the issues_updated_at entry.

No other table, list or counter digest changes, and the fast and per-row
bodies already agree in every scenario. The digests were recorded with
the embedded backend. The doc comment on GoldenDirEnv now says which
entries were re-recorded.

* test(storage): waive the participation-generation contracts on the http leg

main's #7247 (6d21d337ad, "a served http conformance leg") registered a
fourth leg, http, after this PR's original base. The PR's seven
RunParticipationGeneration* entrypoints are neither wired nor waived there,
so TestEveryLegWiresEveryRoleContract/http fails on the rebased branch.

ParticipationGenerationFixture toggles the store's own versioned-history
write flag and reads the raw participation_generation column back: store
write-fence bookkeeping (design §16.2b), not a publicops role the HTTP
client serves. Waive the seven cases on http with a named reason, the same
waiver the donnabox fork carries (09e7ce05af), and keep the gap visible
until a supported HTTP surface is designed and tested.

go test ./internal/storage/ -run TestEveryLegWiresEveryRoleContract now
passes on dolt, embeddeddolt, http and uow.

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

* fix(issueops): decide the fence's plane by the table that holds the row

recordVersionInTx chose the plane from the row's flags (IsWisp: Ephemeral
|| NoHistory) and then read participation_generation from the issues table
only. A wisps-TABLE row can carry neither flag, so it passed the IsWisp
return and the issues read failed with sql.ErrNoRows, aborting the whole
mutation whenever versioned history is on. Two producers:

  - bd mol squash clears an ephemeral root's flag in place
    (UpdateIssue {"wisp": false}, after the root's close, in the squash's
    one transaction); update.go and the uow repository's Update both mint
    after it unconditionally.
  - import's "wisp_plane" marker (WispPlaneOverride = &true, flags false)
    routes the row to wisps, and the batch create mints it create-shaped.

On origin/main the same paths do not fail but mint a stray issue_versions
row for a wisps-table row, an FR-8 leak (wisps are never versioned).

Fix: no issues row means nothing to version. ErrNoRows on the
participation_generation read now returns nil (no version, no error) for
update- and create-shaped calls alike. That read is the right signal and
IsActiveWispInTx is not: GetIssueInTx has already resolved the row, so
ErrNoRows on the issues read can only mean "not in issues", which is
exactly the question the fence has to answer before it stamps or advances
an issues row. It costs no extra query. IsActiveWispInTx asks the inverse
question ("is it in wisps?") with one more query per mint, and it folds
every error, including a transient one, into "not a wisp".

Tests come first, as three new conformance contracts with three new
ParticipationGenerationFixture hooks (ClearWispFlag, SquashWispRoot,
CreateUnflaggedWisp). They are wired on the dolt, embeddeddolt and uow legs
as subtests of each leg's TestParticipationGenerationFence (no new
top-level test, so the shard manifests do not change) and waived on http
with participationGenerationRawStoreWaiverReason:

  RunParticipationGenerationWispFlagClearMintsNothing      (create wisp,
      UpdateIssue {"wisp": false}: no error, 0 versions)
  RunParticipationGenerationWispRootSquashMintsNothing     (close +
      UpdateIssue {"wisp": false} in one transaction: no error, 0 versions)
  RunParticipationGenerationUnflaggedWispCreateMintsNothing (CreateIssues
      with WispPlaneOverride=&true, flags false: no error, 0 versions)

Red before the fix, green after, run both ways:
  embeddeddolt (BEADS_TEST_EMBEDDED_DOLT=1): all three FAIL with
    "versioned history: read participation_generation for pg-...: sql: no
    rows in result set"; all three PASS after.
  uow: all three FAIL with the same error; all three PASS after.
  dolt (BEADS_TEST_DOLT_SERVER=local): WispRootSquash and UnflaggedWispCreate
    FAIL with the same error; both PASS after. WispFlagClear passes both
    ways on this leg. The store-level wisp update (updateWisp) runs in a
    transaction versioned history never scopes, so it never reaches the
    mint. For the same reason the leg's SquashWispRoot hook turns the events
    journal on for its one transaction: that pins the wisp writes to the
    scoped regular transaction, as in a journal-enabled workspace, so that
    case does reach the seam.

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

* fix(issueops): a create stamps participation even when the row is flagged no-history

A create-shaped mint (RecordVersionForCreateInTx) of a brand-new
ISSUES-TABLE row that carries NoHistory or Ephemeral returned at the IsWisp
check before the isCreate stamp, so participation_generation stayed NULL
although the row was created with versioned history on.

Import produces exactly that row: bd-r9uce keeps a promoted no-history
wisp's durable row on the issues plane with its stray no_history=true
(import_shared.go applyImportWispPlane: WispPlaneOverride = &false). When
bd update --persistent later repairs the flag, it is a same-plane normalize
whose mint is update-shaped by design (persistence.go: "A row created with
the flag on proceeds; a legacy row stays legacy"). The NULL column made the
fence read the row as legacy, so the repair and every later update were
fenced and the row was never versioned. origin/main versions it after the
repair (0, then 1, then 2 rows).

Fix: on a create-shaped call, a flagged row that the issues table holds
gets participation_generation stamped from store_epoch.epoch, the same
source the minting stamp uses, read in the same transaction. No version is
minted and updated_at is kept (SET ..., updated_at = updated_at), then the
call returns. Update-shaped calls on flagged rows still return before any
read. The table check from the previous commit now runs ahead of the IsWisp
branch for create-shaped calls, so a flagged wisps-table row (the common
wisp create) still mints and stamps nothing. That costs a create-shaped
call on a flagged wisp one primary-key miss on issues, and only while
versioned history is on. The store_epoch read/seed moves into
readStoreEpochInTx so both stamps share it.

Tests first:
  - New conformance contract
    RunParticipationGenerationNoHistoryIssueCreateDeclaresParticipation and
    hook CreateNoHistoryIssue. Wired on dolt, embeddeddolt and uow as a
    TestParticipationGenerationFence subtest and waived on http. With
    history on: create {NoHistory: true, WispPlaneOverride: &false} gives
    participation_generation non-NULL and 0 versions. The persistent repair
    (MovePersistent) then gives 1 version, and an update-shaped edit
    (MutateExisting, a title edit) gives 2.
  - New subtest
    TestCreateBatchParticipationGeneration/NoHistoryRowIsStampedUnversionedAndKeepsTheCallersUpdatedAt
    (embeddeddolt): a batch of such rows with a supplied updated_at comes
    out stamped, unversioned, and with updated_at unchanged.

Red before the fix, green after, run both ways:
  dolt (BEADS_TEST_DOLT_SERVER=local), embeddeddolt
  (BEADS_TEST_EMBEDDED_DOLT=1), uow: the contract FAILS on all three legs
    ("participation_generation for pg-no-history-create is NULL ...", then
    "= 0 after the persistent repair, want 1", then "went from 0 to 0 ...
    want exactly +1"). It PASSES on all three after.
  embeddeddolt subtest: FAILS before the fix ("store_epoch has no row after
    the batch, so nothing stamped the 5 rows"). With the fix minus the
    updated_at = updated_at clause it FAILS on every row's updated_at. It
    PASSES with the full fix.
No new top-level Test*, so the shard manifests do not change. The
createbatchequiv goldens are unchanged: the dolt and embeddeddolt
equivalence tests pass.

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

* docs: fix comments the rebase left stale

Comment-only.

- createbatchequiv.GoldenDirEnv said "One deliberate behavior change since
  ... nothing else moved" and then listed a second re-record, the
  participation-generation fence's. It now says there are two deliberate
  changes, puts each in its own paragraph, and scopes "nothing else moved"
  to apply.json, the only golden the first change touched.
- issueops CreateIssueResult.isNew and deferredVersion still described one
  write path. After main's #7205, a row written by deferredCreates'
  multi-row INSERT reaches finishCreateIssueInTx(..., true) directly
  (create_batch_cache.go flush) and never passes through InsertIssueIfNew
  or CreateIssueInTxWithResult. isNew is InsertIssueIfNew's result on the
  per-row path and always true for a multi-row-INSERT row. deferredVersion
  is filled from both paths.

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

* test(issueops): pin the create/update shape split in the version guard

TestEveryVersionedEntryPointMints counts RecordVersionInTx and
RecordVersionForCreateInTx as one seam. A create-shaped site that fell back
to the update-shaped entry therefore stayed green, though the fence then
reads the new row's NULL participation_generation as legacy and the record
is never versioned. The reverse case also stayed green: an update path that
reached the create-shaped entry would stamp an existing legacy row and
promote it, which R2.3 forbids.

Add the split to the structural guard. It is two small tests over the same
journalscan fixpoint and mintVersion edge discipline, with no AST changes:

- TestCreateShapedEntryPointsMintCreateShaped: the create-shaped mint sites
  (finishCreateIssueInTx, CreateIssuesInTxWithContext,
  PromoteFromEphemeralInTx, moveIssuePersistenceInTx, executeUpdate) must
  each call RecordVersionForCreateInTx themselves. A delegate is not enough
  here, because executeUpdate runs its move with mintVersion=false and a
  batch switches finishCreateIssueInTx's mint off at run time. Every
  create-shaped entry point, the delegates and #7205's
  deferredCreates.flush included, must reach it.
- TestUpdateShapedEntryPointsNeverMintCreateShaped: every other
  versionedEntryPoint must not reach RecordVersionForCreateInTx. The
  exception is ApplyBatchInTx, which runs create and update items together
  and is listed as mixed with a reason.

Mutation-checked, each probe reverted afterwards. executeUpdate's
EnteredIssuesPlane mint, PromoteFromEphemeralInTx's mint, or the batch's
deferred create-shaped mint switched to RecordVersionInTx: each fails the
create half. update.go's end-of-update mint switched to
RecordVersionForCreateInTx: fails the update half for UpdateIssueInTx and
every entry point that writes through it.

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

* test(issueops): hold the dual-shape mint sites to both halves of the split

f006c871c5 listed executeUpdate, moveIssuePersistenceInTx,
finishCreateIssueInTx and CreateIssuesInTxWithContext (and the
ExecuteUpdate/MoveIssuePersistenceInTx/create wrappers that delegate to
them) as create-shaped, so TestUpdateShapedEntryPointsNeverMintCreateShaped
skipped them. Each one also mints update-shaped, on its existing-row or
same-plane branch, which is the common path: a guarded update of an
existing row, the bd update --persistent repair of an issues-plane row's
flags, a create or batch create that resolved to a row already there.
Switching that branch to RecordVersionForCreateInTx stamped a legacy row
out of legacy (R2.3), and every guard stayed green.

Split the lists by what each function actually mints:

- versionCreateShapedMintSites keeps only the pure create-shaped site,
  PromoteFromEphemeralInTx. It must call RecordVersionForCreateInTx and
  must not call RecordVersionInTx.
- versionDualShapeMintSites names the four, each with its two branches.
  TestDualShapeMintSitesCallBothEntries requires each to call BOTH entries
  directly. A delegate does not count, for the same mintVersion=false and
  DeferVersionMint reasons as before.
- versionCreateShapedEntryPoints keeps PromoteFromEphemeralInTx and
  deferredCreates.flush, which passes isNew=true for every row.
- versionDualShapeEntryPoints replaces versionMixedShapeEntryPoints. It
  holds ApplyBatchInTx and the create, persistence-move and guarded-update
  entries that delegate to a dual-shape site, each with a reason. Each must
  reach both entries transitively.

The update half skips the create-shaped and dual-shape entry points, as
before. The update-shaped branch inside a dual-shape site is now the new
test's to pin.

Mutation-checked in a throwaway worktree. Switching the update-shaped mint
to RecordVersionForCreateInTx at execution.go:301, persistence.go:97,
create.go:260 or create.go:499 now fails
TestDualShapeMintSitesCallBothEntries for that site. Before this commit,
the whole issueops package stayed green under each of these switches.

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

* test(httpclient): run the participation-generation fence over the served wire

edd3b72a1a waived all eleven ParticipationGeneration contracts on the http
leg, saying the client had "no write flag to toggle and no raw column to
read". That reason was wrong. served_dualwrite_history_test.go already
flips the reference store's VersionedHistoryConfigurer and reads its raw
columns, with the client driving the mutation. The waiver also hid the
one harness that runs the fence behind the update a connected workspace
actually sends. Every store leg's MutateExisting is store.UpdateIssue,
but the served Lifecycle.Update reaches the guarded update,
ExecuteUpdate.

Add served_participation_generation_test.go on the same pattern:

- Bound to the client: Mutate is Lifecycle.Create, MutateExisting is
  Lifecycle.Update, MovePersistent is the persistence-mode
  Lifecycle.Update that bd update --persistent sends, and PromoteWisp is
  issueops.Promote over the client's Reader/Lifecycle/Commenter, the
  entry bd promote dials over http.
- Bound to the reference store, as before: SetFlag, the CreateWisp seed,
  and the raw reads.

TestServedParticipationGenerationFence runs seven cases:
CreateWithFlagOnStampsAValue, CreateWithFlagOffLeavesLegacyNull,
SkipsUpdateOnLegacyRecord, ProceedsForPromotedRecord,
FenceIgnoresSchemaSkewHatch, WispPromotionBeginsHistory and
WispPersistenceMoveBeginsHistory. All seven pass, and no case turned up a
server-side fence bug.

Four cases stay waived, now with a reason that names the actual wire gap
(participationGenerationWireGapWaiverReason):

- WispFlagClearMintsNothing: the in-place {"wisp": false} is an untyped
  UpdateIssue, and IssuePatch.Persistence moves the row instead.
- WispRootSquashMintsNothing: it needs RunInTransaction. That and
  UpdateIssue are both on the client's unsupported allowlist (D8).
- UnflaggedWispCreateMintsNothing and
  NoHistoryIssueCreateDeclaresParticipation: both need WispPlaneOverride,
  which every create shape on the wire drops
  (roleIgnoredCreateIssueMembers).

The new file is listed in httpclient_test's srcs. The served lane deals
unpinned tests round-robin, so no shard manifest names it.

Mutation-checked in a throwaway worktree. With execution.go:301 (the
guarded update's update-shaped mint) switched to
RecordVersionForCreateInTx, SkipsUpdateOnLegacyRecord and
FenceIgnoresSchemaSkewHatch fail here ("version row count for
hpg-legacy-skip went from 0 to 1"). The embeddeddolt and uow
Participation|DualWrite|Version suites stay green under the same probe.

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

* test(conformance): an update never stamps a legacy no-history row

7c00d65fa6 made the seam write participation_generation on a flagged
(NoHistory or Ephemeral) issues-table row when the call is create-shaped.
Only the early `if IsWisp(issue) && !isCreate { return nil }` keeps an
update-shaped call out of that branch, and nothing pinned it. The new
contract and its subtest covered only the positive, create-shaped side.
With the early return dropped, an ordinary update stamped a legacy
no-history row out of legacy (R2.3), and every suite stayed green.

Add RunParticipationGenerationLegacyNoHistoryIssueStaysLegacy beside
NoHistoryIssueCreateDeclaresParticipation as its negative twin:

1. Create the no-history issues-table row with the flag OFF.
2. Turn the flag on and run MutateExisting. participation_generation must
   stay NULL, with 0 versions and current_revision unchanged.
3. Run MovePersistent, the bd update --persistent repair that clears the
   flag in place. The repair is update-shaped too, so the same three
   things must still hold.

Wired on all four legs: dolt, embeddeddolt, uow and http. On http the
case exercises the client's Lifecycle.Update and persistence update.
Their precondition, the flag-off no-history create, is seeded through
the reference store, because no client create can land that row in the
issues table. That gap is also why the case whose SUBJECT is that create
stays waived on http.

Mutation-checked in a throwaway worktree, with the early return made
`if false && IsWisp(issue) && !isCreate`. The new case fails on all four
legs and is the only case that fails:
"participation_generation for pg-no-history-legacy = 1 after an
update-shaped mutation with the flag on, want NULL" (dolt server leg,
embeddeddolt, uow and http). At tip it passes on all four.

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

* docs(issueops): say which table and which mint the fence comments mean

Comment and doc corrections. No code changes.

- RecordVersionForCreateInTx's doc comment covered a flagged issues-table
  row but not a wisps-table row. A row the wisps table holds mints and
  stamps nothing, whatever its flags say: there is no issues row to stamp
  (FR-8). That holds for an ordinary wisp create and for import's
  unflagged "wisp_plane" row.
- The no-history stamp branch said the bd update --persistent repair mints
  update-shaped "(MoveIssuePersistenceInTx)". That is true only on the
  unit-of-work path. On dolt and embeddeddolt the repair goes through the
  guarded update: executeUpdate runs moveIssuePersistenceInTx with
  mintVersion=false and mints once at its own end. The fixture's
  MovePersistent doc already says this.
- VERSIONED-BEADS-WRITE-PATHS.md row 13 still credited the whole wisp
  exclusion to `RecordVersionInTx returns on IsWisp` and called every case
  a NO-OP. After ec52d29030, the table holding the row decides its plane:
  only an update-shaped call on a flagged wisp returns on IsWisp. Every
  other wisps-table row, including an unflagged one, is excluded by the
  issues-table participation_generation read, which finds no row. After
  7c00d65fa6, a create-shaped call on a flagged issues-table row is
  stamped but not versioned, so the row says that too.

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

* test(conformance): the wisps-table cases check the row is still a wisp

runWispTableRowMintsNothing asserted 0 versions but never checked its own
precondition, that the wisps table still holds the row. Suppose a step
moved the row onto the issues plane through an update-shaped mint. That
mint would hit the new row's NULL participation_generation and be fenced,
so the count stayed 0 and the case passed without saying anything about
a wisps-table row.

- Add an InWispsTable hook to ParticipationGenerationFixture and bind it
  on dolt, embeddeddolt and uow as a raw wisps-table count. The
  wisps-table body now Fatals if the row is not in the wisps table after
  its steps. Each leg's KitIsWired test checks the hook. On http it
  stays nil with the other wisps-table hooks, whose cases are waived
  there.
- The dolt ClearWispFlag hook now bites. A bare store.UpdateIssue on a
  wisp goes through updateWisp, whose transaction versioned history never
  scopes. So WispFlagClearMintsNothing passed on dolt with or without the
  ec52d29030 fix, as that commit's message admits. The hook now runs the
  lone flag clear in a RunInTransaction with the events journal on: the
  journal-enabled shape the SquashWispRoot hook already uses.
- Both hooks go through a new withEventsJournal helper. It restores the
  store's previous journal setting rather than unconditionally setting it
  to false afterwards, which assumed the store started with the journal
  off.

Mutation-checked in throwaway worktrees:
- With version_history.go at ec52d29030^, dolt's WispFlagClearMintsNothing
  now fails ("read participation_generation for pg-flag-clear: sql: no
  rows in result set"). It used to pass there.
- Embedded ClearWispFlag rerouted as a flag-off persistence move followed
  by a flag-on title update: the case fails on the new precondition ("is
  not in the wisps table after flag-clear"). With the precondition
  disabled, the same probe passes.

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

* fix(storage): review fixups for the participation_generation fence

The review of d17b716115 approved the PR with no required changes and
raised four minors and three nits. Each one below says what changed and
why, or why it did not.

Minor 1, the upsert create's new-or-existing choice was untested. The
unit-of-work create that is not CreateOnly (bd batch, bd todo, tracker
sync and mol port) inserts through an upsert, and db.Insert's existed
probe picks the mint's shape; forcing it either way shipped green. The
new uow TestParticipationGenerationUpsertCreate pins all three outcomes:
a new row is stamped and begins its history, a legacy row the upsert
resolves to stays legacy with no version, and a participating row mints
exactly one more. No served-route case is added because every served
create is CreateOnly (uow createParams), so the http wire cannot reach
this branch. The cmd/bd proxied-server batch and todo creates call this
same use-case method.

Minor 2, an update-shaped mint still lets issues.updated_at move
through ON UPDATE CURRENT_TIMESTAMP. Not changed here. The maintainer
listed it on the PR as follow-up (2), and the approving review of
d17b716115 accepted carrying it as a follow-up. It does not change
the fence's contract as pinned.

Minor 3, the depadd and waitsfor goldens had been re-recorded to zero
issue_versions rows. Their seeds run with history off, so every seeded
row was legacy and the harness stopped checking the dependency-add,
close and reopen mints. Both scenarios now stamp their seeded
issues-table rows after the seed (stampParticipation; wisps stay
unstamped). Their goldens are back to main's pre-fence files byte for
byte: depadd mints 11 version rows and waitsfor 15. The fenced legacy
outcome stays pinned by small, import458 and import458-reject-stale. A
run scenario that mints no version row now fails rather than recording
an empty digest.

Minor 4, PromoteFromEphemeralInTx always minted create-shaped. When the
issues plane already held the id (the dual presence GH#4455 records),
its upsert resolved to that row and the create-shaped mint stamped a
legacy record (R2.3). It now keeps InsertIssueIfNew's isNew and mints
update-shaped for an existing row, as finishCreateIssueInTx does. The
version guard lists it as a dual-shape mint site and entry point, and
PromoteOverDualPresenceKeepsLegacy pins the behavior at run time.

Nit 1: with versioned history off, db.Insert skips the existed probe,
since both mint entries return before reading anything. A create costs
the round trips it did before the fence.

Nit 2: the MINT COST comment now counts the fence read (about 6 to 7
round trips) and no longer says the snapshot reads current_revision;
the fence read can select it for #6379's ordinal seed. Moving that read
now would only add a column nothing consumes yet.

Nit 3: the http leg's participation-generation wire-gap waiver opens as
PENDING and names the wire mutation that would retire each case.

Validation, in a scrubbed env with -tags=gms_pure_go on embedded and
server Dolt (all pass, none skipped):
- uow: TestParticipationGenerationFence, its FixtureKitIsWired check
  and TestParticipationGenerationUpsertCreate with its 4 subtests.
- embeddeddolt: the create-batch equivalence parts (small/depadd,
  apply/waitsfor), the parts-coverage guard, the large scenarios, and
  the fence and kit.
- dolt: TestCreateBatchFastPathsMatchPerRow_Dolt, the fence,
  FenceIgnoresSchemaSkewHatch and the kit.
- httpclient: TestServedParticipationGenerationFence.
- TestEveryLegWiresEveryRoleContract, the issueops structural guards,
  and the issueops, storage and domain/db packages.

Eleven mutants, graded in 13 runs, each fail the test meant to catch
them:
- upsert always create-shaped or always update-shaped;
- the probe guard inverted;
- promote always create-shaped or always update-shaped;
- the seed left unstamped;
- the dependency-add, close or reopen mint dropped;
- two on-disk single-entry promotes.

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(storage): a wisp upsert must not stamp a legacy issues twin

domain/db's Insert chose the mint shape of its upsert (the create that
is not CreateOnly) from an existence probe of the target table. For a
wisps-table insert that probe asks the wrong plane: the seam snapshots
the issues table first (GetIssueInTx), so when the issues plane already
held the id as a legacy row, the wisp create took the create-shaped
mint and stamped and versioned that untouched twin. An ordinary wisp
write promoted a legacy record, which R2.3 forbids. bd mol port and the
proxied mol and wisp writers call CreateWisp this way. It is latent
until versioned history is enabled (#6661).

A wisps-table insert never creates an issues row, so it now mints
update-shaped, without the probe. The fence leaves a legacy twin alone,
a wisp-only id still mints nothing through either entry (FR-8), and a
participating twin mints the one version main already minted for it.
Insert's comment now records that last case: the dual presence
predates the fence, and this upsert does not refuse it the way
issueops' create path does.

TestParticipationGenerationUpsertCreate gains
WispOverLegacyIssuesRowKeepsItLegacy, which fails against the previous
dispatch (twin stamped, one version row). Also from review: the version
shape guard names the dual-shape site its parse cannot see, and the
row-lock exemption comment counts all three of the seam's UPDATE issues
statements.

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: Julian Knutsen <julianknutsen@users.noreply.github.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-18 13:10:57 +00:00
gascity-eddie[bot]
4a67d0d028
fix(bootstrap): cut the host part before stripping userinfo (mc-gcmer) (#7616)
* fix(bootstrap): cut the host part before stripping userinfo (mc-gcmer)

urlHostname stripped userinfo through the first "@" anywhere in the URL,
before cutting out the host part, so an "@" in a path, query or fragment
picked the host: https://my-dolt.example.com/x@github.com/path read as
github.com. isGitCodeRepoURL then called it a forge, and doltRemoteURL
rewrote what is really a Dolt remotesapi URL to git+https:// (the GH#3339
class). The SCP branch made the same split, so both
my-dolt.example.com:org/x@github.com:db and the local path
./backups/me@github.com:db read as github.com too.

Cut the host part first, then strip userinfo through its last "@":

- scheme URLs: the authority, ending at the first "/", "?" or "#". That is
  the host net/url dials, and Dolt's earl.Parse hands scheme URLs to
  net/url. Taking the last "@" matches net/url too, so
  https://a@b@github.com/org/db is now a forge, as Dolt would dial it,
  instead of going raw to the remotesapi client (the #4421 class).
- SCP: everything before the first ":", unless a "/" comes first (a local
  path) - the split doltremote.FromGitURL makes.

TestIsGitCodeRepoURL gains the path/query/fragment-@, SCP path-@,
local-path-@ and last-@ cases, 7 of them red before this change, plus
userinfo controls in both URL forms that stay green.

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(bootstrap): scrub credentials from the Bootstrap failed message (mc-gcmer)

An unencoded "#" or "?" in a sync.remote password ends the URL's
authority early, so urlHostname no longer reads the remote as a forge and
bootstrap clones it as configured. The clone error then carries the URL,
password included, twice: sanitizeURL passes through a URL net/url cannot
parse, and Dolt's "invalid remote url:" repeats it. Scrub the error with
scrubURLCredentials where "Bootstrap failed:" prints it.
TestEmbeddedBootstrapCloneFailureScrubsCredentials pins this; it fails
against the pre-fix binary for both "pa#ss" and "pa?ss", and the new test
is registered in the embedded shard manifest.

Also add a forgeSyncRemoteForms row for multi-@ userinfo without a .git
suffix, so the routing pin covers a URL only its host can make a forge.
The row fails with the base urlHostname.

Review: PR #7616 synthesis F1 (minor) and F5 (nit).

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 <338826946+gascity-eddie[bot]@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 18:07:50 +00:00
Julian Knutsen
4450fe99bb
feat(http): bd blocked over bd serve (blocked.list), plus bd blocked --flags [--raw] (#7649)
* feat(http): bd blocked over bd serve (blocked.list) through issueops.BlockedLister

`bd blocked` refused against an HTTP workspace: it called the legacy
GetBlockedIssues, which the HTTP backend stubs as unsupported. It now runs
one role on every route, and bd serve publishes that role.

- Role: issueops.BlockedLister.ListBlocked(BlockedRequest{ParentID, Labels,
  LabelsAny, ExcludeLabels}) -> BlockedResult{Items}. One body,
  internal/storage/issueops.ExecuteListBlockedInTx over the unchanged
  GetBlockedIssuesInTx; labels normalized in the role (BlockedFilter);
  Items never nil and in a total order (priority, created_at desc, id).
- Legs: DoltStore (read tx), EmbeddedDoltStore (read conn), uow (read unit
  of work through the use case's GetBlockedIssues, so the
  external-dependency uow decorator applies). Census: storage.DoltStorage
  gains BlockedLister(); HookFiringStore passes it through (a read),
  telemetry wraps it, uow.notifyingProvider, externaldeps.uowProvider and
  httpapi.timedProvider build it.
- externaldeps.Store.BlockedLister is built over its own GetBlockedIssues,
  so local `bd blocked` output is unchanged. Over a remote store it takes
  the server's listing when the server advertises
  policy.external_dependencies, else decorates the server's listing here
  through EdgeReader and BatchGetter (decorateBlocked, factored out of
  GetBlockedIssues).
- Wire: GET /v0/beads/blocked (listBlockedIssues; parent, label,
  label_any, exclude_label) answering BlockedPage {items, has_more} with
  the new x-go-type-pinned BlockedIssue schema, behind the new
  blocked.list token. apigen and the wire-shape golden regenerated; the
  golden diff is additive only, so wire_revision stays 2.
  Config.BlockedLister is a required role, wired in bd serve.
- Client: httpclient.Store.BlockedLister dials through Store.dispatch, so
  an older server is refused BEFORE the dial with *wire.CapabilityError
  naming blocked.list. The legacy Store.GetBlockedIssues rides the role
  (page and row cap applied to its answer) and leaves the unsupported
  shell. Divergence ledger row F-blocked retired.
- CLI: `bd blocked` takes BlockedLister() from the store on the direct
  routes and from the provider's BlockedListerSource on the proxied route;
  runBlockedProxiedServer is deleted. --json output is the same rows in
  the same order, [] when empty.

Tests: backend/conformance RunBlockedLister (10 cases: direct blocker,
child attributed to its blocked parent, closed blocker, wisp plane, pinned
status, parent filter, label filters with normalization, order, empty
slice, request not mutated) on dolt, embedded, uow and the served HTTP
client; httpapi handler tests (mapping, unknown/repeated params,
projection, capability); httpclient stub tests (pre-dial refusal naming
the token, encoding, projection, legacy door paging); skew and vocabulary
counts; TestE2E_BlockedOverHTTP (served `bd blocked --json` equals the
local command's after mapping ids and timestamps, member order included,
external blocker named, older-server refusal with no dial); corpus
gc-blocked re-marked and gc-blocked-parent added, both pending until the
reference server advertises blocked.list.

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

* fix(blocked): pin server-side external decoration, refuse has_more, serve the legacy door over http

Review fixes for the blocked.list slice.

- Server-side external decoration is now pinned on the compositions bd
  serve answers from. TestWrapUOWProviderBlockedListerNamesExternalBlockers
  lists through the wrapped unit-of-work provider's own BlockedLister
  accessor (the bd serve provider path) and requires an external-only row
  and a mixed row to carry their external: refs; building that lister over
  the inner provider fails it. TestServedBlockedListerCarriesExternalRefs-
  WhenTheServerEnforces serves the store-shaped composition
  (externaldeps.Store.BlockedLister, policy advertised) and requires the
  operation's own answer, through the undecorated client role, to carry the
  refs, and the client's decorated chain to return it unchanged; serving
  the inner store's lister fails it.
- The client refuses an answer reporting has_more with the new typed
  httpclient.TruncatedListingError instead of returning a short listing:
  the operation has no cursor, and a caller reads a missing row as
  unblocked. The legacy door inherits it.
- externaldeps.Store.GetBlockedIssues over an http store reads the extra
  sources through the served roles (EdgeReader, BatchGetter) instead of the
  raw GetIssuesByIDs / GetDependencyRecordsForIssues the http backend
  refuses, and the decoration skips the source read when there is nothing
  to load. The legacy door on the CLI chain (bd mol stale, the wisp
  commands) now answers over http in both policy modes;
  TestServedLegacyGetBlockedIssuesThroughTheDecorator pins it, paging
  included. bd ready --explain still refuses on its other raw reads; the
  CHANGELOG says so.
- Docs: the spec and the retired F-blocked ledger row state that the
  listing is unpaged, bounded by the client's 32 MiB response limit
  (refused, never read in part), and that has_more is refused.
- Contract: new cases for waits-for and conditional-blocks blockers, no
  type exclusions (gate, epic), and a stale flag with no nameable blocker
  (on the legs that can write the column: dolt, embedded; skipped
  elsewhere with the reason). Order seeds explicit created_at values with
  five rows tied on priority and created_at, two of them wisps, so only the
  id tiebreak orders them; dropping the tiebreak now fails every run.

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

* feat(blocked): bd blocked --flags, the blocked flag per id from stdin

`bd blocked --flags [--json]` reads ids from stdin, one per line (blank
lines and repeats ignored), and prints the blocked flag bd holds for each:
with --json, [{"id","is_blocked"}] in the order the ids were first given,
omitting an id that names no row on either plane, [] for no input. It is
the readiness column a consumer otherwise had to read with `bd sql`, so no
such consumer needs a local-only command.

It is the FLAG, not the listing: `bd blocked` narrows the stored flag to
rows it can name a blocker for, and --flags does not, so a row whose flag
is set with no nameable blocker reads true here and is absent from the
listing. Where the external-dependency policy applies, an unsatisfied
external: blocker sets the flag, as it keeps the row out of `bd ready`.

One library entry on every route: issueops.BlockedFlags over the route's
BlockingAnnotator (the store's accessor on dolt, embedded and HTTP, the
provider's on the proxied route). Over HTTP that is listBlockingAnnotations
with is_blocked behind dependencies.blocking.isBlocked; a server without
that token is refused before the dial, naming it. No wire change. The
listing's filter flags are refused with --flags rather than ignored.

Tests: TestE2E_BlockedFlagsOverHTTP (served JSON equals the local command's
after mapping ids to titles, unknown id omitted, repeat collapsed, [] on
empty stdin, filters refused; a stale-flagged row with no blocker reads
true and is absent from `bd blocked --json`, which fails if --flags is
derived from the listing; an older server's handshake refused naming the
token with no dial); TestProxiedServerBlocked/flags_reads_ids_from_stdin on
the proxied route; corpus gc-blocked-flags, pending until the reference
server advertises the token. CHANGELOG entry.

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

* feat(blocked): bd blocked --flags --raw, the stored is_blocked column

`bd blocked --flags --raw [--json]` answers the stored is_blocked column
for each id read from stdin, exactly what reading is_blocked from the issues
and wisps tables returns, without the external-dependency policy: a row
blocked only by an unsatisfied external: ref reads false (the policy-aware
--flags reads true), and a stale flag reads true either way. Same output
shape as --flags. This lets a consumer move off a `bd sql` read of the
column with no change in what it reads. The default --flags is unchanged.

The role is taken from beneath every decorator: storage.UnwrapStore on the
direct routes, uow.UnwrapProvider on the proxied route. Over HTTP the
innermost store is the http client, whose annotation read is the server's
answer: against a server that does not advertise
policy.external_dependencies that answer is the column, and --raw is
served. A server that advertises it decorates the flag it answers, the v0
wire has no member asking it for the column, and the decorated flag cannot
be turned back into the column client-side, so --raw against such a server
is refused before the annotation read, naming the token, rather than
answered with the decorated flag. --raw without --flags is refused.

Tests: TestE2E_BlockedFlagsOverHTTP/raw_is_the_stored_column (served --raw
equals local --raw; the externally-blocked-only row reads true with --flags
and false with --raw on both; locally blocked rows agree; a stale-flagged
row reads true in both modes; --raw without --flags exits 1; a server
advertising the policy refuses --raw with no annotation request);
TestProxiedServerBlocked/flags_raw_is_the_stored_column; corpus
gc-blocked-flags-raw (pending until the reference server advertises
dependencies.blocking.isBlocked). Routing --raw through the decorated
annotator fails the e2e. CHANGELOG entry.

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

* docs(changelog): bd blocked --flags --raw is for the local and proxied routes

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

* test(blocked): give the e2e gate-kid its own priority; document --flags answers closed ids

TestE2E_BlockedOverHTTP seeded gate-parent and gate-kid at one priority, so
when both landed in the same second their order fell to the generated ids,
which differ between the local and the served workspace: the comparison
failed intermittently. gate-kid now has its own priority. Ten runs on the
embedded lane pass.

bd blocked --flags answers a closed id too, with its stored flag; a SQL read
of the column filtered on status <> 'closed' leaves it out. Said in the
command's doc and the CHANGELOG.

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

* fix(blocked): apply label filters to external-only blocked rows

The external-dependency policy appends a row blocked only by an
unsatisfied external: ref after the label query has run, so --label,
--label-any and --exclude-label never judged it: bd blocked and
GET /v0/beads/blocked listed it whatever its labels, on every route.
Both decorators now filter those rows by the request's labels. The uow
decorator reads them through GetMany, chunked at MaxGetManyIDs, so their
labels are hydrated; GetIssuesByIDs left them empty, which also printed
them unlabelled on the proxied route.

Review fixes (adopt-pr apply-fixes, iteration 1):
- major #1: label filters on external-only rows in the store and uow
  decorators, with absence-asserting arms in the unit, served httpclient
  (server- and client-enforced policy), e2e and proxied tiers; the spec
  and the role doc say such rows are narrowed like every other row.
- minor #2: the policy.external_dependencies token prose names the
  blocked listing (spec, routes.go, regenerated types.gen.go).
- minor #6: SERVE_RUNBOOK and the allowUnlimited comment record the
  blocked listing's unbounded whole-set answer and why.
- minor #10: BlockedLister telemetry-outermost and typed-unsupported pins
  beside the ReadyCounter pair, plus the externaldeps wrap pin.
- nit #9: F-blocked names --flags --raw's refusal against a server that
  applies the policy (ledger.go and the regenerated ledger doc).
- nit #11: the remote BlockedLister no longer builds a local lister it
  then discards.

Review fixes (adopt-pr apply-fixes, iteration 2; the review approved at
940 with one minor and two nits, none gating):
- minor (the --flags refusal list was unpinned): the new
  TestBlockedFlagsRefusesEveryListingFilter pins blockedFlagFilterFlags
  to the flags blockedCmd registers, in both directions. Every
  registered flag except --flags and --raw must be refused, and every
  entry must name a registered flag. The test walks Flags() rather than
  LocalFlags(), so it does not merge the root's persistent flags into
  blockedCmd, and it skips inherited root flags and cobra's --help.
  Mutants:
  - four fail it: a new filter flag left off the list, a dropped
    entry, a misspelled entry, and --raw added to the list;
  - a simulated earlier in-process run (merged root flags plus --help)
    stays green, and fails once either skip is removed.
- nit (the remote branch's span): the remote BlockedLister comment now
  says why that lister is not wrapped again. The inner lister already
  carries telemetry's span, so wrapping would nest a second span of the
  same name. The comment also says what runs outside that span.
- nit (duplicated order comparator): left as is. finishBlockedIssues
  predates this PR, so merging the two sorts would refactor existing
  code with no review pass left after this one.

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

---------

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-17 12:29:13 +00:00
Julian Knutsen
601be8a6bf
feat(list): bd list's remaining filters over http behind issues.list.filters (#7647)
* feat(list): bd list's remaining filters over http behind issues.list.filters

Over http every `bd list` filter beyond the created bounds and the title,
id and no-assignee scope refused (time bounds, priority range, text and external-ref
matches, spec, label pattern/regex, exclude-type, no-parent, no-labels,
empty-description, pinned/no-pinned, deferred, overdue, mol/wisp type).
The library entry already applied all of them: issueops.Reader.List via
workapi.BuildListFilter, shared by the CLI and the handler. This adds
only the wire.

- Server: GET /v0/beads/issues decodes 29 new optional parameters
  (listFilterParams, decode only; countIssues' names where it already
  spells the filter) into the existing ListRequest, behind one new
  behavior token, issues.list.filters. mol_type/wisp_type are closed
  enums refused by name (an empty value too). wire_revision stays 2;
  apigen and the wireshape golden are regenerated (additive only).
- Every RFC 3339 bound the listing and count decode is normalized to UTC,
  so an offset-bearing bound selects what its Z twin does on a zone-less
  timestamp column.
- workapi.BuildListFilter refuses PinnedFlag with NoPinnedFlag
  (ErrValidation, the CLI's own sentence) instead of letting PinnedFlag
  win; over http that is a 400 on no_pinned.
- Client: the encoder sends the members (encode.ListFiltersMembers, one
  list read by the encoder, the pre-dial gate and a spec-parity test).
  Against a server not advertising the token, httpReader.List refuses
  before dialing with ErrUnsupported naming issues.list.filters. The 29
  E-ListRequest ledger refusal rows retire; the ledger doc is updated;
  skew flag mappings added.
- Tests: handler decode/parity/enum/UTC/malformed/pinned-pair tests;
  encode member/gate/spec parity and bound encoding; per-member
  ride-behind-token and pre-dial skew refusal; two new Reader contract
  cases on every leg (dolt, embedded, uow, served): the eight time
  bounds at exact boundaries (strict, whole-second truncation, NULL never
  matches, +02:00 equals UTC) and one in/out row per remaining family;
  three served Reader cases unparked; TestE2E_ListFilterParityOverHTTP
  (served == embedded, masked server refuses naming the token, no dial);
  five corpus shapes marked pending until the reference server profile
  advertises the token.

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

* feat(list): exclude_status on listIssues, the 30th issues.list.filters member

issueops.ListRequest gains ExcludeStatus: statuses to leave out of a
listing, appended to the default exclusions (never re-admitting what they
hide), comma-separated or repeated, and validated against the workspace's
statuses by the same rule CountRequest.ExcludeStatus uses (an unknown name
is ErrValidation). The rule moves into one shared function,
workapi.ParseExcludeStatus, called by both builders. With AllFlag it reads
the active set without enumerating every status, so an http-backed caller
can list O(active) rows instead of the whole history.

- Server: listIssues decodes a repeatable `exclude_status` under the same
  issues.list.filters token (no new token); an unknown name is a 400 on
  exclude_status. apigen and the wireshape golden are regenerated
  (additive).
- Client: the encoder sends it and it joins encode.ListFiltersMembers, so
  the pre-dial gate asks for the token.
- It is refused together with ReadyFlag, like the other members the ready
  query cannot carry.
- No `bd list --exclude-status` flag yet (it would need the CLI docs
  regenerated); the member is reachable through the library and the wire.

Tests: builder unit test (append, AllFlag, comma split, unknown name);
handler decode and 400; encoder, round-trip and gate; Reader contract
cases on every leg (active set under AllFlag, repeated and comma values,
adds to the defaults, narrows an explicit Status, unknown name refused).

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

* fix(list): label_regex compile errors are 400s; review polish for list filters

- An invalid `label_regex` on GET /v0/beads/issues, /v0/beads/ready and
  /v0/beads/ready:count is now `400 invalid_argument` (`invalid_value` on
  `label_regex`) instead of `500 internal`. The database still compiles
  the pattern in its own dialect; a request that sent a regex and earned
  the engine's "regular expression is invalid" refusal is attributed to
  the parameter (failRegexReadErr). The same text on a request with no
  regex stays a server fault.
- mol_type and wisp_type refuse each other's vocabulary (tests pin
  `mol_type=heartbeat` and `wisp_type=swarm`), so the call-site
  allowlist, not just the spec enum, is covered.
- exclude_status with a workspace custom status: leg tests on the
  embedded store and over the served wire (accepted and applied; a name in
  no vocabulary refused). ReaderFixture cannot configure custom statuses,
  so these sit beside the count's twin rather than in the contract.
- The search e2e gains a positive arm: --desc-contains returns exactly the
  row whose description carries the token.
- Docs: `all` plus `exclude_status` keeps every status not named (pinned,
  hooked and custom done/frozen included unless named), not "the active
  set"; label_regex documents its 400. A corpus source line is made
  neutral; a test message says 30.

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

* fix(list): compose issues.list.filters with the --title-contains fold

#7631, now on main, folds `bd list --title-contains` onto listIssues
`title` and refuses the TitleContains left over from a --title and
--title-contains pair that differs, because the listing then had one
title parameter. This branch publishes `title_contains` behind
issues.list.filters, so that leftover now rides it beside `title` and
the server applies both. Neither half is dropped, and against a server
without the token the pre-dial gate refuses, naming issues.list.filters.

- encode.FoldTitleContains still runs first; its doc now says where a
  differing pair goes.
- Tests: the fold table expects `title` plus `title_contains` for a
  differing pair, including the ſ/s pair strings.EqualFold would match;
  the differing-pair refusal names issues.list.filters; the
  list_filters_test sweep pairs its TitleContains probe with a differing
  TitleSearch, since a lone one asks only for issues.list.title; the e2e
  differing-pair refusal becomes a listFilterShapes row that answers
  exactly child-a over http and embedded, and refuses before dialing
  without the token.
- The gc-polecat-closed-after corpus shape's pending reason also names
  issues.list.title. The CHANGELOG --title-contains entry no longer
  lists the differing pair and --closed-after as refused.

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

* build(bazel): auto-sync BUILD files

Applied from the bazel-sync-patch artifact of https://github.com/gastownhall/beads/actions/runs/39013611268
(`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.

* fix(list): serve --priority-max in search parity, refuse the parent pair

The proxied tier's search parity table still expected a remote
`bd search --priority-max 1` to refuse, because listIssues could not
carry it. This branch serves priority_max behind issues.list.filters,
so the remote route answered and the dolt-race shard went red in
TestProxiedServerSearchRoutesAgree. The row now expects the answer on
every route. It was the last wireCan=false row; the branch stays, with
a comment, for the next flag listIssues cannot carry.

- ParentID with NoParent: a served listing now carries no_parent beside
  parent, and ANDing the two answered only the edge-less rows under the
  parent's dotted id. BuildListFilter refuses the pair with
  ErrValidation, in the sentence bd list and BuildCountFilter already
  use, so issueops.Reader.List refuses it on every backend and the
  listing answers 400 on no_parent. Pinned by a builder test, a reader
  conformance case (dolt, embedded, uow, served http) and two httpapi
  tests.
- POST /v0/beads/issues:claimNext shares the ready listing's
  label_regex but answered a pattern the database cannot compile with
  500. It now gives the listing's 400 invalid_value on label_regex,
  through the helper the listing's mapping is split into.
- The descendant walk's ledger rows said listIssues publishes no
  parameter for members it now serves behind issues.list.filters. They
  now say the walk does not send them yet, and that --flat or --json
  asks listIssues directly. The ExcludeStatus, Pinned and ExcludeTypes
  rows, the parentwalk.go header, the walk table's doc and two walk test
  comments are corrected the same way, and the ledger doc is
  regenerated. parentWalkRefusals notes that a member moved off the list
  must check issues.list.filters itself, because the walk dials past
  the listing's pre-dial gate.
- Spec: the listing's no_parent documents the pair's 400, the count's
  exclude_status no longer says it has no listing counterpart, and
  claimNext's label_regex documents its 400. types.gen.go is
  regenerated. Comment-only: countFilters, and readyScopeFields'
  ExcludeStatus entry.
- CHANGELOG and README say the default `bd list --parent` tree view
  does not carry the new filters yet; the label_regex entry names
  claimNext, and a Changed entry records the parent-pair refusal.

Second review pass: docs and comments only, no behavior change.

- The prose copies of the issues.list.filters member set now match
  ListFiltersMembers: CapIssuesListFilters and wire.CapListFilters name
  the status exclusion, and the spec's capabilities text names
  label-regex.
- Every time bound on the listing and the count goes through
  q.timestamp, which normalizes it to UTC, and sqlbuild compares it
  strictly at whole-second precision. listIssues' created_before and
  created_after, and countIssues' created, updated and closed bounds,
  now say so in the words the new listing bounds use. The count's
  updated bounds also say what they filter, and its closed bounds say
  that a NULL closed_at never matches. types.gen.go is regenerated.
- README and CHANGELOG: `--flat` or `--json` applies the filters to the
  parent's direct children, not its whole subtree.
- The 29 listRefusal rows this branch serves stay deleted rather than
  kept as retired rows, as #7550 deleted its TitleSearch, IDFilter and
  NoAssignee rows when it served them. The CHANGELOG now says the rows
  are removed, not retired.

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>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-10-17 11:21:18 +00:00
Julian Knutsen
ae693ef7cc
fix(http): bd gate create, add-waiter and discover over a connected HTTP workspace (#7621)
* fix(http): gate create, add-waiter and discover through the library roles

bd gate create, bd gate add-waiter and bd gate discover wrote through the
legacy CreateIssue, AddDependency and map-based UpdateIssue, which the http
store does not implement, so over a connected HTTP workspace each failed
before any gate member reached the wire. They now run through the roles on
every route (direct, proxied server, http):

- gate create is ONE Lifecycle.Create carrying the gate members and a
  reverse blocks edge from the blocked issue to the new gate: atomic on
  every route, one createIssue over http behind issues.create.gates. The
  proxied-server route's private unit of work is gone; it uses the same
  role.
- gate add-waiter reads through Reader.Get, deduplicates, and writes the
  whole waiter list through Lifecycle.Update guarded by the row version it
  read, retrying up to three times on ErrVersionMismatch, so concurrent
  adders cannot lose each other's waiter. Over http: issues.update.gates.
- gate discover lists through issueops.ListGates and records the run ID
  through the same Lifecycle await_id patch gate check makes; bd close's
  gh:run persist (updateGateAwaitID) takes the same path.
- Against a server without the token, each refuses before any write,
  naming the token.
- gate discover skips template gates, as gate check already does, instead
  of recording a run ID on a proto every later pour copies.

Tests: unit tests for the one-Create shape, the refusal, the add-waiter CAS
retry, and discover over ListGates with its template skip;
backend/http TestE2E_GatesOverHTTP (advertised and masked); four served
corpus shapes, pending until the reference server advertises the gate
tokens (verified to pass against a profile that does). CHANGELOG.

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

* fix(gate): add-waiter backs off under contention; discover fails on a failed write

Review follow-ups to the gate CLI port.

- gate add-waiter's guarded write retried three times with no wait, so a
  convoy of workers registering on one gate at once failed all but a few
  (the proxied route's old unit of work had served them all). Each retry
  now waits a jittered, doubling backoff (10 ms to 400 ms, drawn from
  [d/2, d)), for at most 20 writes. The bound is attempts, not wall time:
  under a loaded server one round takes seconds, and a wall-clock budget
  failed the convoy after two or three rounds. A cancelled wait stops the
  loop. TestProxiedServerGateAddWaiterConvoy (direct SQL and
  proxied, real Dolt server) and TestE2E_GatesOverHTTP's concurrent case
  run 11 simultaneous adders (one duplicate): all exit 0, every waiter
  present once.
- gate discover counts only the gates whose run ID was recorded and exits
  non-zero when any matched gate's write failed; it used to print the
  refused gate as updated and exit 0. TestE2E_GatesOverHTTP covers
  discover with and without issues.update.gates (fake gh).
- TestServedGateCheckOverAwaitTypedGates masks issues.update.gates itself,
  so upgrading reference_server.json does not turn its gh:run case into a
  different test.
- The discover listing test asserts closed gates are not listed.
- CHANGELOG: discover's template skip and add-waiter's template refusal
  are behavior changes on the local routes; gate create refuses
  a negative --timeout; gate create/add-waiter follow dolt.auto-commit and
  use the role's commit messages; the proxied create no longer journals
  dependency_added.

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-17 02:15:07 +00:00
Julian Knutsen
47d5db39ff
feat(http): bd heartbeat over bd serve (issues.heartbeat), and close the re-arm orphan-lease race (#7600)
* feat(roles): issueops.Heartbeater role on the dolt, embedded and uow legs

Adds issueops.Heartbeater.Heartbeat(HeartbeatRequest{Actor, IssueID}) ->
HeartbeatResult{IssueID, Holder, HeartbeatAt, LeaseExpiresAt, Rearmed},
the lease refresh behind `bd heartbeat`, as its own role with its own
accessor.

- One body: internal/storage/issueops.ExecuteHeartbeatInTx validates
  (*HeartbeatFieldError for a blank/over-long actor or empty id), refuses
  a wisp, then runs RenewLeaseInTx, which is HeartbeatIssueInTx's body
  reporting the renewal. HeartbeatIssueInTx is now a wrapper, so the legacy
  HeartbeatIssue legs answer the same text and sentinels.
- The refresh is fenced on the holder AND on the live claim: after the
  holder-fenced UPDATE, a read in the same transaction requires the issue
  to be in_progress under the holder (the `update leases set` prefix and
  the one IF() the Postgres dialect rewrites are unchanged; a Postgres port
  should expect more serialization retries from that read). A refusal deletes the caller's orphaned lease
  row, and the legs commit that refusal.
- A refresh writes only the lease row: no row_lock, version, updated_at,
  event, journal entry, Dolt commit or hook. A re-arm (a live hand-doled
  claim with no lease row the caller holds) is recorded as a mutation:
  row_lock reminted, updated_at stamped, a lease_rearmed event, a journal
  entry, a version, a Dolt commit (LeaseRearmVersionCommit) and on_update.
  The remint makes a re-arm collide with a racing release or close instead
  of leaving an orphaned lease on an open or closed issue (a pre-existing
  race on every Dolt route). Rearmed is true only when a row was created:
  a same-second refresh (0 changed rows on embedded Dolt) or a holder
  spelled differently refreshes the existing row in place and keeps its
  granted_at/granted_node. Reported times are rounded to whole seconds,
  the stored values; the binds stay unrounded so a same-second refresh is
  never a 0-row UPDATE on Dolt.
- Typed refusals: an absent id is ErrNotFound; a foreign holder is
  *LeaseConflictError{Holder} wrapping ErrAlreadyClaimed; a wisp
  (Ephemeral) or no live claim is *LeaseConflictError wrapping the new
  ErrLeaseNotHeld, which also matches ErrNotClaimable.
- Legs: DoltStore and EmbeddedDoltStore through the issue-operation
  funnel (DOLT_ADD of the named tables, then DOLT_COMMIT -m, after the SQL
  commit); uow.NewHeartbeater through the new uow.RunTxScoped: a refresh or
  a refusal commits with the plain SQL COMMIT (no working-set scan, no Dolt
  commit, nothing another writer left uncommitted is swept), and a re-arm
  commits through the new ScopedCommitter (DOLT_ADD of exactly its tables,
  DOLT_COMMIT -m, never -Am). The legacy HeartbeatIssue doors commit a
  re-arm the same way and keep a refusal's orphan delete, and the
  proxied-server `bd heartbeat` route runs the role's body with the same
  scoped commit.
- Census: storage.Storage gains Heartbeater(); HookFiringStore wraps it
  (fires on_update for a re-arm only, RoleFiresHooks knows it), telemetry
  wraps it, httpapi.timedProvider, uow.notifyingProvider (records a re-arm)
  and externaldeps.uowProvider build it; the journal and version guards
  list the heartbeat family as entry points; the httpclient unsupported
  shell is regenerated and Heartbeater sits on its unsupported allowlist
  until the wire lands.

Conformance: RunHeartbeater* (18 cases) on dolt, embedded dolt and uow:
refresh post-state with the stored times pinned to the result; no
row_lock/current_revision/updated_at/events/journal/issue_versions/
version-control/hook change; a guarded write with the pre-heartbeat
revision still lands; foreign holder refused against an aged lease;
refused after close/release/reclaim/status move; wisp refused; hand-doled
claim re-armed as a mutation; same-second heartbeat is not a re-arm;
orphaned leases on released, closed and reassigned issues refused and
deleted; a refresh and a refusal against a dirty working set make no
commit and leave the other writer's change uncommitted, and a re-arm
commits only its own tables; absent id; request rules; no request mutation. The http leg is
waived until the wire lands.

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

* feat(httpapi): POST /v0/beads/issues/{id}:heartbeat behind issues.heartbeat

Publishes issueops.Heartbeater on bd serve as heartbeatIssue, the served
lease refresh behind `bd heartbeat`.

- Spec: the operation, HeartbeatIssueRequest {actor} and
  HeartbeatIssueResponse {id, holder, heartbeat_at, lease_expires_at,
  rearmed}; no `revision` (a refresh writes nothing to the row) and no
  expected_version (the fence is the holder and the live claim).
  issues.heartbeat joins the capability vocabulary and lease_not_held
  (409) the Problem.code list; `reason: ephemeral` qualifies it for a
  wisp. apigen and the wire-shape golden are regenerated; the golden diff
  is additive only, so wire_revision stays 2.
- Server: route row on the custom-method dispatcher, handleHeartbeat in
  heartbeat.go (claim's actor rules via bodyActor, unknown member and
  query refusals), Config.Heartbeater as a required role (sourceRoles,
  roleSourceNames, the per-request uow.HeartbeaterSource accessor).
  failHeartbeat maps *LeaseConflictError typed fields: a foreign holder
  is the claim's conflict shape (already_claimed + assignee +
  issue_status); no live claim, a wisp included, is the new
  lease_not_held (+ issue_status, + reason: ephemeral for a wisp), matched
  before the generic arms so ErrLeaseNotHeld's ErrNotClaimable never
  surfaces as not_claimable. Its detail names the one state the refusing
  transaction found (closed, open and not claimed, an ephemeral wisp, ...).
- bd serve wires the role from its peeled store (serveRoleSource gains
  Heartbeater); the serve stub stores, the corpus and e2e harnesses, the
  served harness and the encode oracle bind it.
- Wire client vocabulary: OpHeartbeatIssue/issues.heartbeat and
  MethodHeartbeat are CLASSIFIED (the capability set-equality gate),
  ReasonEphemeral is pinned to the server's, and lease_not_held rebuilds
  *LeaseConflictError{Status, Ephemeral} wrapping ErrLeaseNotHeld in the
  native words (the code-table set-equality gate). No accessor yet.

Tests: heartbeat_test.go (request mapping and projection, edge refusals,
every role refusal with its code, members and state-specific detail, the
code row, the capability). The served-http Heartbeater leg
(served_heartbeater_test.go, 18 cases) runs the contract against a real
bd serve through a test-local dial over the store's own dispatch, and the
http-leg waivers are deleted.

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

* feat(http): bd heartbeat over http through httpclient.Heartbeater

The client leg of the served lease refresh, and `bd heartbeat` on the
role for every route.

- httpclient.Store.Heartbeater (heartbeater.go) dials POST
  /v0/beads/issues/{id}:heartbeat through Store.dispatch, so
  issues.heartbeat is preflighted: an older server is refused BEFORE the
  dial with *wire.CapabilityError naming the token (unwraps to
  *storage.ErrUnsupported{Capability: "issues.heartbeat"}); it never falls
  back to a re-claim or a metadata stamp.
- The role's request rules are restated before the dial
  (validateHeartbeatRequest, pinned to
  storeops.ValidateHeartbeatRequest): blank/over-long actor, empty id, each
  a *HeartbeatFieldError.
- Problem mapping: already_claimed (which the shared table rebuilds as the
  claim's ClaimConflictError) becomes *issueops.LeaseConflictError naming
  the holder and wrapping ErrAlreadyClaimed, in the native words ("issue
  already claimed by <holder>"); lease_not_held already arrives as
  LeaseConflictError (Ephemeral from `reason`); not_found is ErrNotFound;
  invalid_argument on `actor` is the role's field error.
- Idempotent: true, the one write this client marks replayable (a repeat
  only moves the expiry later; a replay after a reclaim fails the fence).
- Legacy Store.HeartbeatIssue rides the role. Both leave the generated
  shell and completeness_test's unsupported allowlist.
- `bd heartbeat` takes Heartbeater() from the resolved store on the direct
  routes (dolt, embedded, http) and from the provider's HeartbeaterSource
  on the proxied route (exact id resolution in a read unit of work, then
  the role); runHeartbeatProxiedServer and heartbeat_proxied_server.go are
  deleted. Success output and exit codes are unchanged; refusal text
  changes per route (see CHANGELOG).

Tests: heartbeater_test.go (stub server: preflight refusal naming the
token with no POST, request/answer projection, each refusal's typed
mapping including the wisp's reason, the 503 replay, pre-dial validation,
validator parity, the legacy door). served_heartbeater_test.go runs the
18-case contract through env.subject.Heartbeater(), with
HookedHeartbeater wired off a HookFiringStore. TestE2E_HeartbeatOverHTTP:
real bd against an in-process serve: holder ok with revision and
updated_at unchanged and a guarded write with the pre-heartbeat revision
landing; a non-holder refused against an aged lease that stays untouched;
closed, wisp and unclaimed refused, each naming its own state; an older
server's handshake refused naming issues.heartbeat with no write. Corpus
shapes gc-heartbeat, -non-holder, -closed, -wisp pending until
reference_server.json advertises the token. CHANGELOG entry for the whole
track, including the orphaned-lease race fix.

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/38875641041
(`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.

* fix(heartbeat): roll back a no-issue refusal; restate refresh vs re-arm

Review fixes for #7600 (adopt-pr apply-fixes, iterations 1-2).

Legacy HeartbeatIssue doors commit a refusal only when it read the issue.
The dolt and embedded HeartbeatIssue callbacks committed every
LeaseRenewalRefusal, including Found=false (the issue read failed). That
refusal deletes nothing, but it can follow a fast-path UPDATE that
already extended an orphan lease row's expiry, so committing it kept the
extension. issueops.LeaseRenewalRefusalCommits now gates the commit on
Found, the rule the Heartbeater role's HeartbeatRefusalCommits applies.
New tests on both legs pin both arms: a no-issue orphan's expiry is
unchanged, and a released issue's orphan is deleted.

Refresh vs re-arm contract docs. Comments, Long help, the OpenAPI spec
and the generated apigen still said every heartbeat writes only the
lease row, makes no Dolt commit and fires no hook. A re-arm is recorded
as a mutation: it remints the revision, records an event and a version
entry, commits once (LeaseRearmVersionCommit) and fires on_update
through the wrapping hook decorator. Restated in domain, uow, issueops,
storage.go (why RoleFiresHooks answers true, so bd serve takes the
heartbeater off a peeled store), cmd/bd heartbeat and serve, httpapi,
httpclient, the spec (apigen regenerated), and the conformance and
contract-test docs.

Minor review findings:
- The 409 already_claimed and lease_not_held details now end "nothing
  on the issue was written": the refusal may have deleted and committed
  the caller's orphan lease row.
- docs/multi-agent/federation.md and the CHANGELOG entry describe the
  spelling-mismatch heartbeat: the row is refreshed in place and keeps
  granted_at and granted_node; only a re-arm stamps this node. The
  embedded spelling test pins both columns, and the lease.go comments
  say "refreshed in place" instead of "re-arms".
- The refusal's orphan delete judges the holder under actorMatches, as
  the in-place refresh does (iteration 2). It matched holder = ? on the
  actor as sent, so a dead claim's orphan held under another spelling
  of the caller (gastown.mayor, heartbeat as gastown__mayor) survived
  the refusal until TTL. The refused closure now reads the row's holder
  and deletes that stored holder only when actorMatches(holder, actor).
  Both TestHeartbeatIssueCommitsARefusalOnlyWhenItReadTheIssue twins
  gain a cross-spelling arm (row deleted) and a control: another
  identity's row (gastown.dog-3) survives.

Not changed: `bd heartbeat --json` still omits `rearmed`, since adding
it changes a CLI JSON contract (follow-up). The federation.md paragraph
post-dates the v1.2.2 docs pin, so documenting this main-only behaviour
there is a maintainer call under
engdocs/decisions/2026-07-17-docs-release-pin.md section 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>

* fix(uow): run the scoped re-arm's Dolt commit after the SQL commit

The proxied-server heartbeat commits a re-arm with doltServerTx.CommitScoped,
which ran DOLT_ADD per table and DOLT_COMMIT('-m') INSIDE the open
transaction, before the SQL COMMIT. DOLT_ADD stages whole tables from the
session's transaction root, so that Dolt commit was built from the re-arm's
start snapshot: an issues row another session changed while the re-arm was
open (a write still only in the working set, as in batch mode or before that
writer's own Dolt commit) was staged at its old value, and HEAD disagreed
with the rows every reader sees. This is the LatentLabsSpace/NEXUS#92
ordering the DoltStore funnel (runIssueOperationTxWithMessage) already
avoids, and the review's major finding on this PR.

CommitScoped now commits the SQL transaction first, then stages exactly the
named tables (plus the versioned-history tables) and makes the Dolt commit on
the same pinned connection, the uow twin of doltAddAndCommitPostTx:

- a serialization failure of the SQL COMMIT is still returned, so
  RunTxScoped replays the unit of work;
- the Dolt commit runs detached on its own budget and replays only conflicts
  that leave nothing behind: serialization failures and Dolt's 1105
  "@autocommit transaction rolled back" (new isDoltAutocommitRollbackError,
  mirroring the DoltStore classifier of the same name);
- nothing staged, or "nothing to commit", is not an error: a concurrent
  writer's Dolt commit already took the row. A "nothing to commit" past the
  staged check is logged, as the funnel logs it, so the missing audit line
  is explicable;
- any other failure is logged, never returned. The data is committed, and
  returning it would make RunTxScoped replay a committed re-arm, which would
  then report a refresh. The session is poisoned rather than pooled, since
  its state is unknown. uow records no metrics, so that log line is the
  drop's only signal; bd.db.post_tx_commit_dropped counts only the funnel's.

Statements go through schema.DrainCall, retiring the local drainCall fork
(review nit).

Tests: five sqlmock tests pin the order (SQL COMMIT before any DOLT_ADD),
the swallow-and-poison path, the 1105 retry, the returned serialization
failure and the empty-commit tolerance; each fails against the previous
CommitScoped. TestIsDoltAutocommitRollbackError carries the DoltStore
classifier's table over to the uow copy, plus the prefix boundary; dropping
the prefix branch, the prefix's period, the 1105 check or the type check
each fails a case. TestHeartbeaterRearmKeepsAConcurrentWrite is the
real-Dolt regression: a change to another issues row made while the
re-arm's transaction is open must be at HEAD after the re-arm's Dolt
commit. Its working-set-only writer fails on the old ordering (dolt
2.1.8); the writer that Dolt-commits its own change passes on both and is
kept as coverage.

Review follow-ups folded in (comments, a file move and a test; the
absorption log line above is the only behaviour change among them):

- the freshRowLock invariant and its row_lock_guard_test.go mirror name the
  re-arm as the one deliberate remint without a lifecycle-field change,
  load-bearing for the release/close collision;
- httpclient: "a write is never retried" (wire/client.go, stall_retry.go)
  and "only a read's answer is yes" (dispatch.go) now allow for the
  Idempotent heartbeat, and httpHeartbeater and issueops.HeartbeatResult
  document that a replayed heartbeat can report Rearmed false after a
  committed re-arm, with the guarded write's revision check as the backstop;
- the proxied route moves back to cmd/bd/heartbeat_proxied_server.go, the
  file family cmd/bd/AGENTS.md prescribes;
- the ScopedCommitter and RunTxScoped docs no longer say every other
  writer's uncommitted change stays out of the commit: a staged table is
  committed whole, so such a change to a named table rides in the re-arm's
  commit, as it does in the funnel, and only other tables keep theirs;
- commitStagedTables says its drop is log-only, the absorption is logged,
  and the uow classifier gets its table test (see Tests).

Not folded in: the base-owned IssueUseCase.Heartbeat /
IssueSQLRepository.HeartbeatIssue door, dead in production since the
proxied route moved to the Heartbeater role. Its one caller is the
notifying hook-parity test (uow/notifying_test.go), and moving that case
onto the Heartbeater means re-deriving its RenewLease hook semantics, so it
is left for a follow-up.

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: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: Eddie the Engineer <338826946+gascity-eddie[bot]@users.noreply.github.com>
2026-10-16 22:38:23 +00:00
gascity-eddie[bot]
91a72ef7b5
fix(mol): route bond operand resolution like show/update/close (closes #4714) (follow-up to #4720) (#7622)
* fix(mol): route bond operand resolution like show/update/close (closes #4714)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Three non-blocking notes from the Aug 16 review:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Review fixes for #4720.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

---------

Co-authored-by: Rody Vilchez <102562850+R0SEWT@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Co-authored-by: matt wilkie <maphew@gmail.com>
Co-authored-by: Eddie the Engineer <julianknutsen@users.noreply.github.com>
Co-authored-by: Eddie the Engineer <338826946+gascity-eddie[bot]@users.noreply.github.com>
2026-10-16 21:10:12 +00:00
Julian Knutsen
169c5fc499
perf(list): read only the listed issues' dependency edges (#7591)
* perf(list): read only the listed issues' dependency edges

`bd list`'s text renderings (the default tree, --deps, --parent, --format
and --watch) loaded every dependency record in the workspace through
GetAllDependencyRecords to draw one page. On a local store that is one
query. Over a connected HTTP workspace it is a walk of the whole workspace:
every issue id at 200 per request, then every id's edges at 100 per
request. `bd list --limit 20` against the ~3.8k-issue maintainer-city
workspace made 62 sequential requests and took ~5.7 s at ~50 ms a round
trip, where `bd list --json` makes 5.

Every rendering reads only edges a listed issue owns. The tree nests a
child under a parent only when both are listed, and looks the edge up
under the child. Sibling ordering, the --deps annotations and the gate
decoration read the listed node's own edges, and --format prints edges
between listed issues. An unlisted issue's edge onto a listed one, or a
parent off the page, is never read. listDependencyRecords reads exactly
those edges through the EdgeReader role, which every backend serves (the
http store refuses the raw GetDependencyRecordsForIssues batch method).
Over http that is one anchored listDependencies request per 100 listed
ids.

Through a logging proxy in front of the production bd serve, list
--limit 20 goes from 62 requests / 5.7 s to 6 / 0.49 s with
byte-identical output; every changed mode (--deps, --deps=all, --format
digraph/dot, --sort, --status, --ready, --limit 200, --limit 0, --parent)
prints the same bytes as before. On a local store a default page is as
fast or faster; a listing that covers most of a large durable store pays
batched reads instead of one table scan (+0.07 s at 1,000 rows, +0.46 s
at 4,000 on embedded Dolt).

Tests:
- backend/http TestE2E_ListTextRenderingsReadOnlyTheListedIssuesEdges:
  over a served workspace, the tree, --deps=all, a --limit cut, the
  --parent tree and --format digraph each make one listDependencies
  request naming exactly the listed ids, and at most one request more
  than the --json page. Failing first: the old read enumerated every id
  (all=true) and anchored the hidden closed issue too.
- cmd/bd: the page read equals GetAllDependencyRecords restricted to the
  page on Dolt server and embedded stores (both planes, every edge type,
  gates, external refs), and every text rendering prints the same bytes
  from either map; a runListCore spy pins one page read and no
  store-wide read; pure tests over an adversarial fixture (edges unlisted
  issues own pointing at listed ones, parents off the page, dotted
  children, a parent-child cycle) guard the renderers.

Refs: ga-nrnrlr.5

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>

* test(http): seed the list page-edges e2e with one graph apply

TestE2E_ListTextRenderingsReadOnlyTheListedIssuesEdges ran 26 s on
http_served_test's round-robin shard in CI, which made that shard the
embedded lane's longest test action (172 s). Most of it was subprocesses:
five creates and a close to seed, plus a --json budget run per case.

The fixture is now one `bd create --graph` plus the close (the batch
create cannot carry a closed row's closed_at over the wire), and one
`bd list --json` run is the budget for every page case, since its request
count does not depend on the page size. 16 subprocesses become 9. All
five cases still fail against the old GetAllDependencyRecords call
sites: each edge read anchors the hidden closed issue, and the four page
cases make 7 requests against the --json page's 5.

Refs: ga-nrnrlr.5

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: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-16 16:05:24 +00:00
Julian Knutsen
dff9492c61
fix(http): gate check records a bead gate's sighting through Lifecycle.Update (#7604)
* fix(http): gate check's bead sighting goes through Lifecycle.Update (issues.update)

The bead-gate sighting was written through the legacy map-based
UpdateIssue, which the http store does not implement, so the refusal
happened client-side and no issues.update was ever sent: every open bead
gate with an open target failed on every sweep over HTTP.

- recordSeen and the gh:run await_id persist now go through the Lifecycle
  role (updateGateThroughLifecycle): a single-key metadata set for the
  sighting, an AwaitID patch for the run. The http client still refuses the
  await_id patch before the dial (W-IssuePatch.AwaitID); the gate's error now
  names the await_id update instead of a Go method.
- backend/http/corpus TestServedGateCheckOverAwaitTypedGates seeds
  await-typed gates in the served store and proves, through the reference
  proxy: --dry-run writes nothing, timers close, the bead sighting persists,
  merged gh:pr gates close, and the gh:run persist refuses by name with
  await_id untouched.
- CHANGELOG corrected.

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

* fix(cmd/bd): gate check skips template gates; narrow the await_id reword

Review fixes for the gate-check sighting change.

- A persisted proto's gates (bd cook --persist) are templates, and
  issueops.ListGates lists them with the open gates. bd gate check now
  leaves them out of its listing's query: GateListRequest gains
  ExcludeTemplates, which only listOpenGatesWith sets, and it adds
  `template=false` to the expression, so the cut at --limit counts only
  the gates that remain. bd gate list leaves it unset and still lists
  templates. Dropping them from the page after the cut would let a page
  of a proto's gates (newer than the live ones at the same priority)
  fill --limit: the sweep would print "No open gates found." and exit 0
  with the live gates unchecked. filterCheckableGates, which both the
  direct and the proxied-server routes select through, keeps the skip
  as a backstop. Before this, each route mishandled templates in its
  own way:
  - Direct route: the Lifecycle role refused the sighting and await_id
    writes, so the sweep failed every time, after a gh:run template had
    already queried GitHub. In a local workspace, an expired template
    timer gate was closed in the proto.
  - Over HTTP: bd serve refused the close with 409 template_read_only.
  - Proxied-server route: the template timer gate was closed and a
    sighting was stamped on the template bead gate, silently.
- persistGateCheckAwaitID rewords only the HTTP wire's
  W-IssuePatch.AwaitID refusal. The new message names the run, await_id
  and the bd serve URL, and advises checking the gate in a local
  workspace: giving it a numeric run ID would be the same await_id edit
  the wire refuses. The error chain is kept, so *storage.ErrUnsupported
  and the ledger row stay reachable. Every other error comes back as the
  role raised it, including a capability the server does not advertise
  (#7589's issues.update.gates) and a local backend's ErrUnsupported.
  Before, every ErrUnsupported got the same sentence.
- Tests:
  - Unit: the template skip for every type filter; a sweep over template
    gates beside a live one; ListGates putting `template=false` in the
    query under ExcludeTemplates, and gate check's listing setting it;
    the reword and its chain; the pass-through cases; the sighting patch
    matching its map form.
  - Embedded: a cooked proto's gh:run, bead and timer gates are
    untouched, and gh is never run. With --limit 1 behind that proto's
    gates, a live expired timer gate is checked and closed.
  - Proxied-server: template timer and bead gates stay open and
    unstamped. With --limit 1 behind two newer template timer gates, the
    live one is checked and closed.
  - Served: the template gates are untouched, and the gh:run error names
    the server. --dry-run --limit 3 behind three template gates checks
    three live gates.
  - Each --limit case first shows, through bd gate list, that a template
    leads the listing.
  - Against the PR-head bd, the embedded, proxied and served template
    cases fail. Against a bd that skips templates after the cut, the
    three --limit cases fail, printing "No open gates found." and
    exiting 0.
- bd_test gains the //internal/httpclient{,/encode} deps (gazelle-checked).
  The embedded shard manifest lists both TestEmbeddedGateCheck* tests.
  The CHANGELOG notes the template skip, that templates take no row of
  --limit, and the new wording.

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 <adopt-pr@gascity.com>
2026-10-16 15:14:53 +00:00
Alex
fefcdf6533
fix(delete): resolve ids exactly, never by prefix abbreviation (#7375)
* test(delete): pin that a stale id never deletes the issue it prefixes (be-ksd)

bd delete resolves each id through the abbreviation-tolerant resolver
(resolveAndGetIssueForMutation -> utils.ResolvePartialID). When the exact
id is absent, that resolver falls through to leading-prefix abbreviation,
so an id that was already deleted resolves to a different issue whose id
it happens to begin, and --force deletes that issue.

The shape is ordinary: hash length is adaptive (3 to 8 characters) so a
grown store holds short ids beside longer ones, --id makes any shape, and
a hierarchical child's id always extends its parent's. On a fixture, after
fx-t00003 was deleted, bd delete fx-t00003 resolved to fx-t000031; a
re-run of a finished --from-file list with --force --quiet deleted two
issues it never named, silently.

The test drives deleteCmd in-process against a stub DoltStorage (no cgo,
no Dolt server) and records every request handed to the Deleter role. It
covers the single-id --force path, the preview, a deleted parent's id with
an orphaned child, the --from-file batch path, and an abbreviation of one
and of two live issues; each refusal must say delete needs the full id
and name the ids the input matches. An over-refusal guard checks that
exact ids (full, bare hash, child, batch) still delete exactly what they
name. The six refusal cases fail at this commit; the guard passes.

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

* fix(delete): resolve ids exactly, never by prefix abbreviation (be-ksd)

bd delete's direct route resolved each id with the abbreviation-tolerant
resolver, so an id that no longer exists resolved to the surviving issue
whose id it begins, and --force deleted that issue. Both of its resolution
sites now use resolveAndGetIssueForMutationExact (#5393's exact sibling,
until now used only by bd comment): the inline single-id path and
deleteBatch, which --from-file, multiple ids and --cascade take.

The resolver cannot tell a stale full id from an abbreviation. Hash length
is adaptive with store size, so one store holds 3- to 8-character ids side
by side and "fx-t00003" is both a valid full id and a valid abbreviation
of "fx-t000031". The rule therefore has to be per command, the way #5393
made it for bd comment. Delete is exact on both preview and --force: the
preview prints the next command to run ("To proceed, run: bd delete
fx-t000031 --force"), so a tolerant preview hands the caller the wrong
deletion to confirm.

This matches the team-server route, which passes ids to issueops.Deleter
unresolved, and DeleteRequest.IDs' own contract ("IDs ARE EXACT"). The
partial-ID notice (#6302) did not protect this path: --quiet silences it,
and a --force --quiet re-run of a finished --from-file list deleted two
issues it never named.

The refusal says what to do: "bd delete needs the full issue id: no issue
has the id "t000", which is the start of fx-t000031". To name the matches,
ResolvePartialIDExact now returns *utils.AbbreviatedIDError, which carries
the input and the sorted matches, wraps ErrAbbreviatedIDNotAllowed and
keeps the old error text, so bd comment's errors.Is checks and messages
are unchanged.

Cost: bd delete <abbreviation> is refused, naming the full ids, so the
caller retypes one. Exact ids, bare full hashes, child, cross-prefix and
routed ids resolve as before. The other deleteBatch callers (cleanup, wisp
gc, mol burn) pass full ids read from the store, so nothing changes for
them except under a race, where they now refuse instead of reaching a
neighbor. Reads and other writes keep abbreviation.

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

* docs(ids): say bd delete requires the full id, like bd comment (be-ksd)

The Working with IDs section named bd comment as the one command that
refuses abbreviations and said every other mutation keeps them. bd delete
now requires the exact id too, so the section covers both, says why a
delete reaches the wrong issue so easily (an already-deleted id is still
the start of its child's id, or of a longer hash), and adds the bd delete
lines to the example block. Best Practices #1 names both commands.

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

* docs(changelog): link the bd delete exact-id entry to #7375 (be-ksd)

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

* fix(delete): report a gone parent's id as a lost race under --if-revision (be-ksd)

Review-loop iteration 1 for #7375: a maintainer fixup on top of the
contributor's branch.

Major (codex+claude): a guarded `bd delete --if-revision` whose target
was deleted, and whose id is still the start of a surviving id (a gone
parent with a live <parent>.1 child), exited 1 with the abbreviation
refusal. Any other gone target gets the documented lost race
(precondition_failed, exit 13), and gascity's conditional deletes
switch on that code, so a benign race read as a hard failure.

- reportIfRevisionTargetGone (the single-id path) also takes
  utils.ErrAbbreviatedIDNotAllowed as a gone target: under delete's
  exact resolution that id names no row either.
- The refusal is a typed error, deleteAbbreviationError, that unwraps
  to storage.ErrNotFound beside the *utils.AbbreviatedIDError, so the
  --cascade caller of deleteBatch classifies it through
  reportIfRevisionFailure the same way. errors.New(msg) dropped every
  sentinel.

Minor (claude), taken: the refusal leads with the not-found fact,
`issue "t000" not found: bd delete needs the full issue id, and "t000"
is only the start of fx-t000031`, so gascity's isBdNotFound reads an
already-gone full id that begins a survivor's id as the idempotent
not-found it reads for any other gone id. The CHANGELOG entry quotes
the new text and the --if-revision outcome.

Minor (gemini), declined: threading the source command into the
refusal's wording. deleteBatch's other callers (bd cleanup, wisp gc,
mol burn) pass store-minted full ids that no user retypes, and the text
now leads with "issue X not found", which holds for every caller.

Tests:
- TestDeleteIfRevisionGoneIDThatPrefixesAnotherIssue: single id,
  --json, --cascade and --cascade --json each exit 13 with "precondition
  failed: issue no longer exists" and the precondition_failed body,
  never the refusal text, and the guarded write never runs. Two
  no-survivor rows are the plain gone id they must match.
- TestReportIfRevisionTargetGone: abbreviation rows, guarded and not.
- TestDeleteRefusesStaleIDThatPrefixesAnotherIssue also asserts the
  refusal says "not found".
- TestEmbeddedIfRevisionDeletePreflightGoneParentIsPreconditionFailed,
  end to end on embedded Dolt: delete a parent, its child survives and
  `bd show <parent>` resolves to it; a guarded delete of the parent
  exits 13 on the single-id and --cascade paths and leaves the child.
  The TestEmbedded name is what puts it in a CI lane; its line in
  embedded-cmd-test-shards.txt is the generator's incremental --write.

Mutation checks, each reverted afterwards: dropping the
ErrAbbreviatedIDNotAllowed match fails the single-id cases and the
abbreviation_guarded row; dropping ErrNotFound from Unwrap fails the
--cascade cases; dropping "not found" from the text fails every
refusal case; reverting both fixes fails both embedded legs (exit 1,
the refusal text, no "precondition failed").

Validation: the focused delete and if-revision tests; the embedded pair
under BEADS_TEST_EMBEDDED_DOLT=1; the scripts shard-manifest policy
tests and the generator's --check; gofmt; git diff --check. The full
./cmd/bd and ./internal/utils packages (-short, BEADS_TEST_SKIP=dolt)
pass but for TestRunApplyAllOK, which fails only because this worktree
sets core.hooksPath=/dev/null ("mkdir /dev/null: not a directory") and
passes with core.hooksPath overridden.

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 <noreply@anthropic.com>
Co-authored-by: Eddie the Engineer <julianknutsen@users.noreply.github.com>
2026-10-16 11:25:54 +00:00
Julian Knutsen
9c4b3d8bab
perf(externaldeps): annotate a page's blocking state in one pass, not one IsBlocked per id (#7556)
* perf(externaldeps): annotate a page's blocking state in one pass, not one IsBlocked per id

The external-dependency BlockingAnnotator overlaid IsBlocked on the
backend's answer one item at a time. Each IsBlocked made several reads
(the stored flag, both edge tables, the blockers' statuses), read the
item's own edges again, and resolved its external refs on its own, so a
foreign project was opened once per item. Over a remote serve,
listBlockingAnnotations cost 9-20 ms per id, and a 1,400-id refresh took
about 12 s.

The annotator now reads the whole page once:
- the local half through a new optional storage.BlockersBatchStore,
  IsBlockedWithBlockersBatch, backed by
  issueops.IsBlockedWithBlockersBatchInTx (the stored flags, the blocked
  ids' blocking edges from both tables, one status read). The dolt and
  embedded dolt stores implement it, and a store without it still gets
  one IsBlocked per id;
- the external half from ONE read of the page's own edges, whose refs
  are resolved together, so each foreign project is opened at most once
  per request.

The answer per id is IsBlocked's, unchanged: a blocked item's BlockedBy
is the local live blockers, then the unsatisfied refs. Both reads now
order a source's blocking edges by (depends_on_id, type). The single
read had no ORDER BY, so its order was the table's, which is a UUID key
on these tables.

Tests:
- TestBlockingAnnotatorReadsAPageOnce pins 1 own-edge read, 1 foreign
  open, 1 batch read and 0 per-id reads for 40 ids. On the old body it
  failed with 40, 30, 0 and 40.
- TestBlockingAnnotatorFallsBackPerIDWithoutTheBatchRead covers a store
  without the batch read.
- TestPolicyBlockingAnnotatorBatchEqualsPerItem (embedded dolt) compares
  the batched answer, and IsBlockedWithBlockersBatch, against the
  per-item path by deep equality. It covers local blockers of every
  blocking type, closed and pinned blockers, parent-chain blocking,
  waits-for and conditional-blocks gates on both planes, satisfied,
  unsatisfied and unconfigured external refs, a non-blocking external
  edge, local plus external, a free row and a missing id.
- TestPolicyBlockingAnnotatorForeignOpensAreSublinear logs N=10 at 1.9 s
  per-item vs 0.26 s batched, and N=40 at 7.5 s vs 0.29 s. Foreign opens
  go from N to 1.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(dolt): pin server-mode IsBlockedWithBlockersBatch against IsBlocked

Review apply-fixes for #7556, iteration 1. Two minors are taken here, the
merge conflict is left to the pre-approval rebase, and two items are
declined. All changes are a test and a doc comment; no runtime code moves.

Taken: server-Dolt test for the batch arm (Test Evidence Quality)
- TestIsBlockedWithBlockersBatchMatchesPerRow runs the DoltStore arm that
  bd serve and server-backed bd list take, which no test executed before.
  It compares each id's entry with IsBlocked through reflect.DeepEqual.
  The fixture reuses the embedded fixture's shapes as the raw store sees
  them: blocks, a parent-child chain (the list is nil), waits-for,
  conditional-blocks, a wisp source and a wisp blocker, closed and pinned
  blockers, and external refs (blocks and related), which the raw store
  drops. It also covers a free row, a missing id and repeated ids. Two more
  cases reach code the embedded test does not:
  - one id that exists in both issues and wisps, with an edge in each table;
  - 210 blocked ids with 210 distinct blockers, more than queryBatchSize
    (200).
- Mutants were applied to the PR's code with the test binaries rebuilt.
  Five fail the new test and pass the existing embedded
  TestPolicyBlockingAnnotator* tests:
  - edge-chunk: read only the first edge chunk;
  - status-chunk: read only the first status chunk;
  - no-dedup: drop the repeated-id check;
  - table-order: read wisp_dependencies first;
  - server-wrapper: the DoltStore wrapper returns an empty map.
  A sixth mutant, no-order (drop ORDER BY), fails both the new test and the
  existing embedded batch-equals-per-item test.

Taken: BlockersBatchStore doc (Contract and Interface Fidelity)
- The doc now says the interface answers for the raw store alone, with no
  external-dependency policy applied. It is meant to be called from inside
  that policy's decorator, not probed through UnwrapStore by a caller that
  holds the decorated store.

Deferred to the pre-approval rebase: conflict with #7552 (role_accessors.go)
- This change does not rebase. On a scratch merge with main 70887e708a,
  this resolution was validated:
  - keep this PR's
    state := states[id]; if state.blocked { BlockedBy = state.blockers };
  - nest #7552's IncludeIsBlocked flag (IsBlocked = boolPtr(true)) inside
    that branch;
  - keep boolPtr.
- Results on that merged tree:
  - go vet: clean;
  - go test ./internal/storage/externaldeps/: 66 pass, including
    TestBlockingAnnotatorFlagsUnsatisfiedExternalRef;
  - embedded BlockingAnnotator|IsBlocked tests: 22 pass;
  - served httpclient Blocking|Blocked|ExternalDependency|Ready tests with
    BEADS_HTTP_TEST_REQUIRED=1: 96 pass, plus 4 known-divergence skips that
    predate this change.

Declined
- Duplication (route blockedStates' external half through
  blockingStateFromRecords): this refactors contributor code, adds the
  "external dependencies: resolve blockers:" error prefix, and is not
  test-only. Recorded as a follow-up.
- Pattern Drift nit (move the guards next to their methods, rewrap the
  AnnotateBlocking comment): optional churn next to the conflict region.
  Recorded as a follow-up.

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 <noreply@anthropic.com>
2026-10-14 11:52:37 +00:00
Julian Knutsen
eaed71fbba
fix(http): bd promote over http through issueops.Promote and issues.update.persistence (S21b) (#7554)
* fix(http): bd promote over http through issueops.Promote and issues.update.persistence (S21b)

`bd promote` refused over a connected HTTP workspace: it called the raw
PromoteFromEphemeral, which the http backend stubs, and updateIssue's patch
did not publish persistence. MC's PR-intake formula
(mol-normalized-issue-pr-v1) runs `gc bd promote <id> --reason ...`, so this
blocked the HTTP cutover.

- One library entry, issueops.Promote(ctx, PromoteRoles{Reader, Lifecycle,
  Commenter}, PromoteRequest{Actor, IssueID, Reason, Provenance}): read the
  row, refuse a non-wisp (*NotAWispError, the sentence bd promote always
  printed), move it with ONE Lifecycle.Update whose patch is Persistence =
  persistent (the role's atomic plane move: same id, labels, deps, events and
  comments carried), then write the promotion comment (a comment failure is
  reported, the promotion stands). A no-op move is a lost race and reports
  NotAWispError without a second comment.
- cmd/bd: the direct route runs it over the store's own role accessors, so a
  connected http workspace and a local one take the same entry. The history
  label is "bd: promote <id>" where the store carries caller labels.
- bd serve: IssuePatchBody.persistence (persistent|ephemeral|no_history,
  anything else a 400 naming patch.persistence) on PATCH
  /v0/beads/issues/{id}, behind the new additive behavior token
  issues.update.persistence. wire_revision unchanged. Spec, apigen and the
  wire-shape golden regenerated; the handler only decodes and passes it to
  the role.
- httpclient: Lifecycle.Update sends patch.persistence only to a server
  advertising the token, and otherwise refuses BEFORE the dial with
  *wire.CapabilityError naming it (unwraps to *storage.ErrUnsupported with
  Capability set). The batchApply item still refuses it
  (W-IssuePatch.Persistence now reads "ON issues:batchApply").
- Conformance: RunLifecycleUpdatePersistentPromotesAWisp on dolt, embedded,
  uow and the served http leg; the served
  PersistentPreservesUnversionedClass case is unparked.
- Served e2e TestE2E_PromoteOverHTTP: the mc-promote shape end to end
  (label kept, comment written, one PATCH, re-promote refused), and under
  the MC server mask a pre-dial refusal naming the token with no write.
- Corpus: mc-promote stays pending, relabelled SRV-1 with the reference
  profile's exact refusal (the 1.3.0 server lacks issues.update.persistence).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(promote): run the proxied-server route through issueops.Promote (bd-4y73m9)

The adoption review found (major) that the proxied-server route still
promoted through the old engine, IssueUseCase.PromoteWisp in one
transaction with the comment, while the PR's docs said every route runs
issueops.Promote. Converge rather than reword: runPromoteProxiedServer
resolves the id, then runs issueops.Promote over the provider's own
notifying role accessors (proxiedIssueReader, proxiedIssueLifecycle,
proxiedCommenter), the entry the direct route runs. Both routes now share
promoteFailure (the error mapping) and reportPromotion (the comment
warning and the output), so neither contract can drift.

What a script sees change on the proxied-server route:
- the move is the persistence branch of Lifecycle.Update, so the child
  counter moves with the row: a promoted parent's next
  `bd create --parent` mints .3 after .1/.2 instead of failing with
  "issue already exists";
- on_update fires twice, for the move and for the comment, as on the
  direct route (it fired once, for the comment);
- a promotion is two Dolt commits, "bd: promote <id>" and
  "bd: comment <id>" (it was one);
- a comment that cannot be written leaves the promotion standing behind
  a warning, as on every other route, instead of rolling it back;
- a dual-plane id is refused rather than merged, the update role's
  template guard applies, and a lost race reads "<id> is not a wisp
  (already persistent)".

The PromoteWisp exemption in TestRecordingIssueUseCaseCoversItsSurface
stays, with its reason corrected: no route calls PromoteWisp now, and
its DoltStorage twin fires no hook either. The doc comments on the old
engine (PromoteFromEphemeral on DoltStore and the db layer, PromoteWisp)
no longer say bd promote uses it.

CHANGELOG: the promote entry now names what a script can see on the
direct and proxied-server routes: the hook firings, the comment row
`bd comments` lists, the child-counter carry, the two-commit shape, and
a comment failure that warns instead of rolling back.

Tests:
- TestEmbeddedPromoteMovesAWispParent promotes a wisp parent with .1/.2
  children, a dependency and a comment under a counting on_update hook:
  the hook fires twice, the dependency and the children's parent edge
  survive, `bd comments` lists the old comment and the promotion reason,
  and the next child is .3. At the pre-PR base it fails (the hook fired
  0 times).
- The proxied journey pins the two commits, and new subtests pin the
  child counter (the child_counters row, next child .3) and the two hook
  firings. Against the contributor head each fails: one commit, no
  counter row and a failing create, one firing.

Review iteration 2:
- TestEmbeddedPromoteMovesAWispParent gets its row in the embedded cmd
  shard manifest (shard 64 of 100, from the generator's incremental
  --write). Without it //scripts:go_test_sources_test fails both the
  NotStale and the bare-write guard, and the generator's --check fails.
- notifying.go no longer lists the promotion comment as a divergence.
  The direct route now writes that comment through st.Commenter(),
  which HookFiringStore wraps, so an embedded promote fires on_update
  for it (TestEmbeddedPromoteMovesAWispParent counts both firings). The
  list counts four, and the empty-commit note becomes the fifth item.
- batchapplier.go no longer says persistence is absent from both patch
  bodies: the update body publishes it behind issues.update.persistence,
  and only batchApply refuses it (W-IssuePatch.Persistence).
- Three comments still tied promotion to the old engine: the
  conformance fixture's PromoteWisp no longer claims to do what
  `bd promote` does, the CLI differential's promote scenario names
  issueops.Promote, and export_source's wisp-relations note names
  issueops.MoveIssuePersistenceInTx.
- The Promote unit test compares the whole update patch with
  reflect.DeepEqual. The helper it replaces checked 9 of the patch's 22
  members, so a Promote that also set Description passed it.

Review iteration 3:
- A refused persistence move answered 500 `internal` over http and
  emitted request_error, though the caller could fix the request. The
  role now returns two refusals as ErrValidation, so bd serve answers
  400 invalid_argument and the client maps that back to ErrValidation:
  an unversioned row asked for ephemeral or no_history (the role wraps
  types.ErrUnversionedWispMove, a new sentinel NormalizePersistenceMode
  returns for that case alone, with its message unchanged), and a
  demotion of a row with retained snapshots. A row that breaks its own
  persistence invariants still answers 500.
- RunLifecycleUpdateWispModesRefuseAnUnversionedRow pins the refusal on
  every leg (dolt, embedded dolt, the unit of work, served http): both
  wisp modes match ErrValidation and leave the row durable, unversioned
  and off the wisp plane. Without the wrap the dolt leg fails, and the
  served leg fails on "answered 500 internal".
- TestMoveIssuePersistenceInTxRefusesDemotionWithRetainedSnapshots is
  the first test of the snapshot refusal, and fails without its wrap.
  The unversioned unit test now requires both sentinels. The types tests
  pin the sentinel, its unchanged message, and that no row-invariant
  error matches it: checking the unversioned class ahead of the
  invariant checks fails them.
- CHANGELOG: the promote entry counts five script-visible changes, the
  fifth being the lost-race refusal sentence, and says the two refusals
  now answer 400 over bd serve and gain a `validation failed: ` prefix
  locally.
- NotAWispError's doc comment records that a no-history wisp is refused
  too: the gate reads the Ephemeral flag, as bd promote always has, and
  `bd update --persistent` is the move for that row.

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 <noreply@anthropic.com>
2026-10-14 05:51:53 +00:00
Julian Knutsen
873162dafa
ci(bazel): dolt-int gates server-storage + cmd-dolt in mode remote (item 5 A2) (#7535)
* ci(bazel): dolt-int gates the server-storage and cmd-dolt tiers in mode remote (item 5 A2)

In mode remote, folds bazel-server-storage (--config=doltserver-integration)
and bazel-cmd-dolt (--config=doltserver-cmd) into one bazel-dolt-int job
(--config=dolt-int), following the dolt-race pattern from #7514. The
members have different gating categories (server-storage plain-gated,
cmd-dolt flag-gated/advisory), so the union carries continue-on-error: true
and a bespoke --label-scoped Shard balance step. All other modes keep the
two lanes running unchanged. Action keys are byte-identical between the
member configs and the union (17 + 46 = 63 TestRunner actions), so cached
results carry over either direction and a revert is a safe rollback.

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

* fix(bazel): dolt-int per-tier results, integration gating, key-parity wording (review)

Coordinator review of #7535 found three must-fixes: integration:"off" was
ignored in remote mode (the union's members already honor it); job-level
continue-on-error made a server-storage-only failure read success on
push/nightly/dispatch, where main stays red; and the PR's key-parity claim
overstated byte-identical actionKeys when only the remote action digest
(not the local actionKey) is unaffected by moving --test_env/--test_arg
onto the targets' own env/args.

Fixes:
- bazel-dolt-int's if now adds `&& inputs.integration != 'off'`, matching
  the members (#7491's review); bazelLaneRunModes and
  TestBazelDoltIntArmsExactlyOnePerMode cover the "off" case.
- Job-level continue-on-error removed; only the `bazel test` step carries
  it, and a new always() "Classify tier results" step
  (tools/bazel/classify_tier_results.py, with its own unit tests and a Go
  wrapper) computes server_storage_result/cmd_dolt_result from the BEP and
  decides job.status per-tier. Confirmed with bazel-gate.sh/ci-gate.sh on
  synthetic empty-output inputs that a dead job still fails the gate.
- Corrected the local-actionKey-vs-remote-digest wording in .bazelrc,
  bazel.yml's job comment and CI_REQUIRED_CHECK_TOPOLOGY.md.
- Should-fix: test step 23->25 / job 58 minutes with reasoning; --label
  coverage added to shard_budget_test.py; stale lane comment fixed in
  tests/regression/BUILD.bazel:46; TestBazelDoltIntSoleRunIsInTheUnion's
  docstring corrected (members bake sole-run's line in directly, never via
  --config=sole-run).

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

* fix(bazel): fail-closed classify, per-tier check_testcases, pinned argv (review)

Final review round for PR #7535 (maintainer-city-c3, bee-ghosttrack,
julianknutsen):

- classify_tier_results.py now fails every tier shut (exit 1) on a
  non-PASSED label outside every --tier list, so a newly tagged target
  added without updating the step's --tier args cannot silently read as
  success (must-fix 1). Its --tier/--check label sets are policy-tied to
  the BUILD files' own tag sets by a new
  TestBazelDoltIntTierLabelsMatchTheTags.
- A missing or non-integer --rc (a timed-out or cancelled test step)
  takes the same fail-everything-shut branch instead of crashing argparse
  with no outputs written (bee-ghosttrack's should-fix 2).
- check_testcases.py gained a repeatable --label flag, and bazel.yml's
  shared "Every target and shard ran tests" step is split into check-ss
  and check-cd, each continue-on-error and folded into its own tier via
  classify's new --check NAME=OUTCOME, so a zero-testcase cmd-dolt shard
  no longer reddens the job on push/nightly (must-fix 2).
- classify's run: argv is now pinned by exact equality
  (bazelDoltIntClassifyRun), and every flag except --tier/--check is
  --StoreOnce; a repeated --tier/--check name or an unrecognized flag is
  now a hard parser error (must-fix 3).
- "Upload test logs" now also fires on steps.test.outcome == 'failure',
  not just failure() (must-fix 4).
- shard_budget.py --label now fails closed (::error, exit 1) on a label
  with no executed shard in the BEP at all, instead of silently reporting
  "no sharded test target executed two or more shards" (should-fix 3,
  carried across both review rounds).
- Updated engdocs/TESTING.md, CI_REQUIRED_CHECK_TOPOLOGY.md, .bazelrc and
  scripts/bazel_dolt_int_test.go/ci_workflow_test.go comments for the
  nits: stale "Advisory (continue-on-error: true)" wording, the
  bazelUnionHasFlagGatedMember comment's stale claim about bazel-dolt-int,
  "byte-identical" without specifying remote action digest vs. local
  actionKey, and "is unset" vs. ci-gate.sh's actual "was skipped" branch
  for an empty union output.

Verified: python3 -I on all four tools/bazel/*_test.py (classify 29,
check_testcases 7, shard_budget 19) green; GOTOOLCHAIN=go1.26.7 go test
./scripts/... green; bazel --nohome_rc test //scripts:scripts_test
--config=ci green.

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

* fix(bazel): shard_budget --label fail-closed only on a truly unknown label

The previous commit's fail-closed --label check compared against
read_shard_durations, which only records executed (non-cached) shards, so
a target whose every shard was a cache hit this run had zero entries and
was wrongly treated the same as a --label typo. This was not caught by
the new tests (none exercised an all-cached target) and broke this PR's
own dolt-int CI run: bazel-dolt-int's Shard balance step went red on
//internal/storage/dolt:dolt_server_full_test with "no executed shard for
it", even though that target was correctly, fully cache-hit.

Fix: a new read_tested_labels() reads every label with any testResult
event (cached or executed), and --label's fail-closed check now tests
against that set instead of read_shard_durations. A fully-cached target
still legitimately reports "nothing to judge" through evaluate(); only a
label absent from the BEP altogether is now an error. Added the missing
test row (every shard cached) that would have caught this before push.

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

* test(bazel): pin bazel-dolt-int's Upload test logs if-condition

A full 42-mutation re-run for PR #7535's second review round found that
nothing pinned this job's own "Upload test logs" if-condition (must-fix 4):
the other lanes' upload-logs steps are each pinned, but bazel-dolt-int's
(unlike dolt-race, a brand-new job) had no equivalent assertion, so a future
accidental revert to the old failure()-only condition would go uncaught.

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

---------

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-13 09:17:54 +00:00
Julian Knutsen
ec55baa425
fix(http): bd show --current, recompute-blocked and search over http through issueops entries (S6e/S25/S26) (#7528)
* fix(show): --current through issueops.FindCurrentIssue over the Querier role; no swallowed refusal (S6e)

Over http `bd show --current` printed the WRONG issue, exit 0.
resolveCurrentIssueID asked the raw SearchIssues method for the actor's
in_progress and then hooked work; the http backend refuses that method, the
refusal was taken for "nothing found", and the command fell back to the
last-touched issue. The proxied route had its own copy of the lookup, read
inside its unit of work, with the same swallow.

One library entry now: issueops.FindCurrentIssue(ctx, Querier, actor). It
asks the Querier role (queryIssues over http, which every deployed server
publishes) for `status=<s> AND assignee="<actor>"`, limit 1 — exactly the
raw filter, answered in the store's default order, so the same row comes
first on every backend — in_progress, then hooked. A failed read is an
error; "" (two reads that answered and found nothing) is the only miss. The
actor is a quoted, escaped query value; the query language reads
`assignee=none`/`null` as "unassigned", so such an actor (or an empty one)
is not asked about.

Both CLI routes call it with their route's Querier (store.Querier() or the
proxied provider's) through one cmd/bd helper; what stays in the CLI is the
actor and the last-touched fallback (a workspace file). The proxied route
resolves --current before it opens its unit of work, and its duplicate
in-transaction lookup is deleted.

Tests: issueops unit tests (order, failure is an error on either read,
quoting, unaskable actors, each expression evaluates to exactly the raw
filter); cmd/bd fallback tests; served e2e TestE2E_ShowCurrentOverHTTP
(in-progress beats a later-touched issue, hooked when nothing is in
progress, last-touched only when neither). Against the old code the e2e
fails with exactly the reported bug.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(recompute-blocked): one library entry, storage.RecomputeBlocked; a no-op on a remote backend (S25)

`bd recompute-blocked` refused over http ("storage backend does not support
is_blocked recompute"), and gc's BdStore.RecomputeBlocked issues it.

is_blocked is server-derived. Every write a remote client makes is committed
by the server's own store, which keeps the flag under
issueops.BlockedStateInvariant's local-write clause (targeted, inside the
write's transaction; a Postgres-family server has no full recompute at all
and runs a no-op readiness strategy for the same reason). A client cannot
leave the flag stale and holds no copy of it. The invariant's merge clause
(a recompute skipped after a pull, bd-6dnrw.37; a migration that over-set
it, beads#7037) happens to the SERVER's database, and its repair is this
command in the server's workspace.

So the decision is in the library, not the CLI: storage.RecomputeBlocked
(internal/storage/blocked_recomputer.go) is the one entry every backend goes
through. A local store (storage.BlockedRecomputer) recomputes its column; a
store implementing storage.ServerMaintainedBlockedState — the http client,
whose BlockedStateMaintainedByServer answers true — recomputes nothing and
reports MaintainedBy "server". No wire operation: a whole-column rewrite any
bearer of a workspace credential could trigger, for state no client can have
caused, is not one to publish. The proxied route keeps its pinned-connection
plumbing around the same versioncontrolops body the stores run.

--json keeps rows_corrected (gc requires the member; wh-bridge-sync reads the
exit code) as 0 and adds maintained_by: "server"; the text says where the
repair runs.

Tests: storage unit tests (local repair runs, server-maintained wins even
over a local repair and runs none, neither refuses); served e2e
TestE2E_RecomputeBlockedOverHTTP (exit 0, JSON shape, text, ready set
unchanged). With the server-maintained branch disabled the e2e fails with
the old refusal.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(search): every bd search route through Reader.List with issueops.SearchListRequest; listIssues `q` behind issues.list.search (S26)

`bd search` called the raw SearchIssues method with its text, which the http
backend refuses ("partial-id search is not available over HTTP"), and its
direct and proxied routes each mapped the flags onto a storage filter by
hand. No served operation could carry search's meaning (title OR id contains
the text, case-insensitively; an id-shaped text also matches exact id, id
prefix and external ref): TitleSearch is title-only and the query language
has no title-or-id predicate.

The library entry is issueops.Reader.List:
- issueops.ListRequest gains Query, SearchIssues' free-text argument as a
  member. Both Reader bodies (workapi/storereader and the uow reader) pass it
  to SearchIssuesWithCounts where they passed "". It narrows and lifts no
  default exclusion; the ready arm refuses it (readyScopeFields).
- issueops.SearchListRequest(query) is search's scope as a request: Query,
  every status (AllFlag), every kind of row (the four Include*), and the
  store's default order (SortBy priority), so --limit keeps the rows a raw
  read kept.
- CLI: ONE runSearch for the direct, proxied and remote routes. One builder
  (searchListRequest) maps the flags onto SearchListRequest; the route only
  picks the reader (store.IssueReader() or the proxied provider's).
  --sort/--reverse reorder the page as before. search_proxied_server.go and
  its hand-built filter are deleted, and search leaves the forbidigo
  filter-writing exemption.
- Server: GET /v0/beads/issues decodes `q` into ListRequest.Query and calls
  the same Reader role, behind the new issues.list.search behavior token
  (spec parameter cites it; additive, no wire_revision bump; apigen and the
  wire-shape digest regenerated).
- Client: the encoder maps Query to `q`; httpReader.List refuses a request
  carrying Query BEFORE dialing, with ErrUnsupported{Capability:
  issues.list.search}, unless the handshake advertises it — never a round
  trip an old server would 400, never the unsearched listing passed off as
  the search. CapListSearch mirrors the server token. Flags listIssues
  publishes nothing for are put on the request so the encoder refuses them
  rather than widening the search.

Tests: Reader contract case RunReaderListQueryMatchesTheTitleOrTheID (also
pins SearchListRequest's scope) on all four legs — dolt, embedded dolt, uow,
served http (label-scoped, so the served leg runs it as written); handler
test that `q` reaches the seam as the search text, not TitleSearch; client
tests for `q` and the pre-dial refusal (zero dials); round-trip and
vocabulary gates; TestSearchRoutesAgree runs the same twelve flag sets on
the direct, proxied and remote routes and requires identical answers
(remote is bd serve over the proxied database, so ids and order too); served
e2e TestE2E_SearchOverHTTP. The remote legs skip with the
SearchIssuesWithCounts refusal until S6c's externaldeps reader passthrough is
underneath (loud refusal, never an empty or wrong answer); with S6c
cherry-picked all three routes agree.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* build: resync BUILD srcs and the embedded storage shard manifest for S6e/S25/S26

gazelle picks up cmd/bd/show_current.go, cmd/bd/search_remote.go, the three
backend/http e2e files and internal/httpclient/list_search_test.go; the
embedded storage shard manifest gains
TestEmbeddedReaderListQueryMatchesTheTitleOrTheID
(scripts/ci/gen_embedded_storage_shard_manifest.py 15 --weights=duration
--write).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* style: gofmt list_show_filter_modes.go (trailing blank line)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(backend/http/corpus): drop the show --current and recompute-blocked marks S6e and S25 retire

With S26 folded in, `bd show --current` resolves through
issueops.FindCurrentIssue over the Querier role and `bd recompute-blocked`
goes through storage.RecomputeBlocked (a no-op on a remote backend), so
gc-show-current and gc-recompute-blocked lose their pending marks.
mc-search stays pending, relabelled S6c+SRV-1: bd search now asks listIssues
with q behind issues.list.search, which the reference server profile does
not advertise, so the client refuses before dialing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(cmd/bd): split the bd search route agreement into the embedded and proxied lanes

TestSearchRoutesAgree skipped unless BEADS_TEST_EMBEDDED_DOLT=1, then ran
its proxied and remote legs only under BEADS_TEST_PROXIED_SERVER=1, and
its name matched neither lane's discovery (TestEmbedded* in
*_embedded_test.go, TestProxiedServer*/TestServerMode*). No CI lane ran
it, which main's #7468 guard (TestProxiedGatedTestsRunInTheProxiedLane)
now fails on.

Split it:
- TestEmbeddedSearchRoutesAgree (search_routes_embedded_test.go): the
  direct route, embedded lane.
- TestProxiedServerSearchRoutesAgree (search_routes_proxied_test.go): the
  proxied route and the remote route (bd serve over the proxied
  workspace), gated only on BEADS_TEST_PROXIED_SERVER. The remote route
  must still answer the proxied one row for row, ids and order included,
  and refuse the flag listIssues cannot carry.

Neither lane can run the other's workspace, so the shared helper
(search_routes_parity_test.go: the seed, the twelve flag sets, and
checkSearchRoute) holds every route to one expected answer per flag set;
agreeing with it is agreeing with each other. The remote leg's "needs
S6c" skip is gone: S6c is on main, so a refusal now fails.

Both manifests regenerated incrementally (embedded 100-shard block, shard
71; proxied 34-shard block, shard 23). Bazel: bd_embedded_part2_test
(--config=embedded) and bd_proxied_test (--config=doltserver-proxied)
pass and run the new tests; //scripts:go_test_sources_test passes.
Swapping the title-sort expectation fails both routes of the proxied
test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(search): keep an infra type's durable rows, expand --type aliases, fail the S26 e2e on refusal (bd-1ejjv6)

Review fixes for #7528, attempt 1: the three majors and three minors of
the synthesis.

`bd search --type <infra type>` dropped the type's durable rows (a
promoted wisp, an issue retyped after it was created), exit 0. The shared
listing (workapi.BuildListFilter) narrowed an infra --type to its
ephemeral rows unconditionally, so SearchListRequest's IncludeEphemeral
did not bring back what raw SearchIssues used to return. The narrowing
now applies only without IncludeEphemeral, in BuildListFilter and in the
count lockstep (applyCountIncludeInfra), and the http parent-walk
recognizer reads an infra type's Ephemeral back as the include_ephemeral
intent. This also fixes `bd list --type <infra type> --include-ephemeral`
and GET /v0/beads/issues, which shipped the narrowing in v1.3.1. Pinned by
workapi tests and by template, gate, wisp and promoted-message rows in the
Reader conformance Query case (new ReaderFixture.PromoteWisp) on the
dolt, embedded, uow and served backends; the issueops Reader/Counter docs
and the openapi descriptions say the same.

`bd search --type` handed the raw string to the Reader: an alias (feat,
mol, mr, ...) answered nothing and an unknown type an empty result. It is
now expanded with utils.NormalizeIssueType as `bd list` does, and an
unknown type exits 1. The help text and the CHANGELOG say so, and the
CHANGELOG also records the additive comments_omitted field in
`bd search --json` rows.

TestE2E_SearchOverHTTP skipped on the very SearchIssuesWithCounts refusal
it exists to catch; it now fails. The route agreement seeds "kinded"
template, gate, wisp and promoted-message rows and pins the alias, the
unknown-type refusal and the infra rows on the direct, proxied and remote
routes.

Minors: the CHANGELOG states the proxied `bd show --current` miss
fallback; the CommentsOmitted contract names `bd search --json`; the
storage.RecomputeBlocked and `bd recompute-blocked` comments name the
deliberate --proxied-server bypass.

Validation: go vet and gofmt on every changed package; make api-check;
workapi, issueops, httpclient/encode, types and storage unit tests; the
Reader conformance on dolt, embedded, uow and served; the embedded and
proxied route agreements (remote included), the embedded search tests,
TestProxiedServerSearch, TestProxiedServerRecomputeBlocked, the http e2e
search/show/recompute tests; docs flag, freshness and docsync checks; and
a hand-run bd search/list/count against a scratch workspace.

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 <noreply@anthropic.com>
2026-10-13 04:12:54 +00:00
Julian Knutsen
a2d43e6792
fix(mol): molecule reads, auto-close and close --continue over http through issueops entries (S16) (#7513)
* fix(create): let a remote backend mint the --parent child id

`bd create --parent` always called the raw GetNextChildID first, which the
http backend does not serve, so every child create on a remote workspace
refused before writing anything. The Lifecycle role already mints
<parent>.<n> for a create that carries a ParentID and no id of its own, on
every backend and inside the create's own transaction; conformance
RunIssueOperationsCreateUnderAParentMintsTheNextChildID pins it on every leg,
the served one included (and the bd-enterprise postgres leg the MC server
runs). So the create route needs no new capability token: on a registered
Remote backend the client skips the raw reservation and lets the server mint.
The local route keeps its reservation so its Dolt commit staging is
unchanged, and an explicit --id beside --parent is still refused up front.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(mol): molecule reads, auto-close and close --continue over issueops roles

Over the http backend three molecule paths failed, and two of them
silently:

- `bd mol current` / `bd mol progress` without an id answered "no molecules"
  because the in_progress listing (a raw SearchIssues shape) and the parent
  walk (raw GetDependencyRecordsForIssues) were refused and the refusal was
  swallowed; with an id they refused on raw GetMoleculeProgress.
- The molecule auto-close after `bd close` never ran: findParentMolecules
  swallowed the same refused edge read into "not part of a molecule".
- `bd close --continue` claimed the next step in a raw RunInTransaction.

The direct route now reads molecules through roleMolStore, which answers
through roles every backend serves: EdgeReader (batched at the wire's 100
anchors) for the parent walk, BatchGetter for the roots (Get per id where a
server does not publish issues.batchGet), Relations for the step rows (full
rows; the raw dependents read over http is getIssue's shallow projection,
which zeroed step assignees) and the progress counts, and Reader.List for the
in_progress/hooked listings. The auto-close closes the root through
Lifecycle.Close, and the --continue claim is one Lifecycle.Update guarded by
ExpectedStatus=open.

No refusal is swallowed any more: findParentMolecules, the molecule finders
and the hooked scan return their errors; `mol current/progress` report them;
the auto-close stays best effort but warns on stderr; AdvanceToNextStep only
moves on to the next ready step when the claim LOST a race (status mismatch,
not claimable, already claimed) and returns anything else. The one heuristic
still skipped is the id-pattern heal in loadDescendants, and only for an
ErrUnsupported backend that cannot express an id-prefix search; other
failures now surface. `mol current`/`mol progress` leave the
types.IssueFilter forbidigo hole, since they no longer build a filter.

gc does not depend on bd's molecule auto-close: it runs its own
(cmd/gc/molecule_autoclose.go, from the bd on_close hook and the
controller's bead-close events). Its worker prompts do run `bd mol current`.

Served e2e (TestE2E_MoleculesOverHTTP): create --parent mints <root>.1/.2,
mol current <id> is non-empty with the full in-progress step, mol progress
counts, close --continue auto-advances, closing the last step auto-closes
the root. `mol current` without an id now refuses out loud on this stack
(asserted: never an empty list); its non-empty assertion is skipped until
S6c (externaldeps reader passthrough) is underneath.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(mol): list molecule candidates with the four wire knobs, drop the S6c skip

On top of S6c the in_progress listing behind 'bd mol current' (no id)
reaches the v0 wire encoder, which refuses ListRequest.IncludeAllTypes.
Ask for templates, gates, infra and ephemeral rows explicitly, which the
wire publishes, and run the 'mol current without an id' served case.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(issueops): one library entry each for molecule auto-close, advance and reads

The molecule rules lived only in cmd/bd, in copies that disagreed: two
auto-close implementations that closed the root through different
library entries outside the step close's transaction, a `close
--continue` claim that set no assignee and could take a step another
agent held on the direct and http routes, and three progress counts.
Every molecule rule now has one implementation in the public issueops
package, composed over three roles every backend serves (BatchGetter,
Relations, EdgeReader): MoleculeRoots, LoadMolecule, AnalyzeMolecule,
ViewMolecule, ReadMoleculeProgress, ActiveMoleculeIDs,
CompletedMolecule. Membership is the parent-child edge.

Auto-close: CloseRequest.AutoCloseMolecule and
CloseBatchRequest.AutoCloseMolecule (opt-in, so gc's own auto-close is
not doubled) close the molecule root a close completed IN THE SAME
TRANSACTION, unforced and guarded on the root revision read there:
storageissueops.CloseCompletedMoleculeInTx on the store backends (the
role bodies bound to the caller's tx, TxMoleculeReader) and
uow.CloseCompletedMoleculeInUOW on the unit of work. It replays on an
idempotent re-close, reports the root on CloseResult/CloseOutcome
.AutoClosedMolecule, and a root its own close policy refuses stays open
and is reported (MoleculeAutoCloseRefusal) without failing the step.

Advance: a new MoleculeStepper role (storage.DoltStorage accessor,
uow.MoleculeStepperSource) whose one implementation,
issueops.NewMoleculeStepper, claims the next ready step through the
Claimer (Lifecycle.Update's Claim for a wisp step): assignee set, a step
another actor holds skipped, never taken.

HTTP: closeIssue/batchCloseIssues carry auto_close_molecule behind the
issues.close.autoCloseMolecule behavior token, and POST
/v0/beads/issues/{id}:advanceMolecule (issues.advanceMolecule) serves
the stepper. Handlers only decode, call the role and encode. The client
sends the member and dials the operation only where advertised; against
an older server it DEGRADES rather than refuses — it runs the same
library rule over its own roles (issueops.CloseCompletedMolecule after
the close, NewMoleculeStepper for the advance), so the outcome is the
same in more round trips. The capability fallbacks that lived in
cmd/bd move into the client: BatchGetter answers one getIssue per id
without issues.batchGet, and EdgeReader splits past the operation's 100
anchors.

Conformance: RunMolecule* on dolt, embedded, uow and http (the http leg
twice: served, and against a server with the tokens struck out).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(cmd/bd): molecule commands and create --parent through the library entries

`bd close`, `bd close --continue`, `bd mol current`, `bd mol progress`,
`bd ready --mol` and `bd create --parent` now call the one library entry
for each rule on every route (direct, proxied server, remote):

- close (batch, --if-revision, proxied) sets CloseRequest/
  CloseBatchRequest.AutoCloseMolecule and only reports what the library
  closed in the step close's transaction. autoCloseCompletedMolecule,
  autoCloseProxiedCompletedMolecule and closeCompletedMoleculeRoot are
  gone, and so is the separate post-close write.
- --continue is the route's MoleculeStepper role: a real claim (the
  assignee is set) that skips a step another actor holds. Before, the
  direct and http routes flipped the status only and could take it.
  AdvanceToNextStep, ClaimStepIfOpen and its two implementations are
  gone.
- mol current / mol progress / ready --mol read through
  issueops.ViewMolecule, ReadMoleculeProgress, ActiveMoleculeIDs and
  LoadMolecule/AnalyzeMolecule over the route's roles. Over http this
  fixes the missing step assignee on `ready --mol` (corpus mark
  mc-ready-mol). The proxied route's SearchIssues fallback, the role
  store, the third progress count and the cmd/bd copy of the readiness
  analysis are deleted; only presentation stays here.
- create --parent asks the create role to mint the child id on every
  route (the local CLI reservation is gone) and to inherit the parent's
  labels (InheritLabelsFromParent) inside the create. The dry-run
  preview still shows the labels, and a failed label read there is
  reported, not swallowed.

TestProxiedServerMoleculeLifecycleAgreesOnEveryRoute runs one molecule
lifecycle through the real binary on the direct, proxied and remote
(`bd connect` to `bd serve`) routes and requires the same rows and the
same JSON on all three. The served e2e now also pins the held-step skip,
the claimed step's assignee and the full rows of `ready --mol`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(httpclient): refuse molecule auto-close and advance before dialing an older server

The client used to DEGRADE against a server without
issues.close.autoCloseMolecule / issues.advanceMolecule: it closed the step
without the member and ran a second, client-side copy of the auto-close
(issueops.CloseCompletedMolecule) in its own transactions, and composed the
stepper over its own roles. That kept two executions of each rule alive.
Now the rule runs in ONE place, the server's library: a close or batch close
that sets AutoCloseMolecule, and an Advance, refuse before anything is dialed
with the typed capability error (storage.ErrUnsupported, Capability naming the
token). The composed single-item batch leg now carries the member too.

- issueops.CloseCompletedMolecule (the role-composed form) is gone.
  MoleculeRootClose is the one root close request (unforced, the auto-close
  reason, the session, guarded on the root revision read), and both
  in-transaction bodies (storage issueops CloseCompletedMoleculeInTx, uow
  CloseCompletedMoleculeInUOW) build from it.
- MoleculeView.Ready is `bd ready --mol`'s list (every analysis-ready node,
  hydrated), so ready --mol and mol current derive from ViewMolecule alone.

Tests: unit pre-dial refusal and member pins (httpclient molecule_test.go),
TestServedMoleculeRefusesAgainstAnOlderServer (step stays open, nothing
claimed) replacing the degraded contract arm.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(cmd/bd): ask for the molecule auto-close only where the route serves it

The refuse-before-dialing client made every `bd close` over http fail
against a server that does not advertise issues.close.autoCloseMolecule
(an older bd serve, or the MC server shape, whose orchestrator owns the
molecule lifecycle): the CLI always set AutoCloseMolecule.
storage.ServesMoleculeAutoClose answers, through every decorator, whether a
store's closes may carry the flag (MoleculeAutoCloseProber, implemented by
httpclient.Store from its handshake; every local backend serves it). The
direct batch close and the --if-revision close set the flag from it; the
proxied route always serves it. Against a silent server the close goes out
without the member and the server's side owns the auto-close.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(backend/http): scope the advertised-policy check to reads before the close

The close policy check is the client-side policy's last chance: it runs
before the close request, so only the reads up to that request count. A
read after the close (the old-server molecule notice reads the closed
step's edges) is not the external-dependency policy.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(backend/http/corpus): drop the six marks S16 and S19 retire

With the molecule library entries underneath, mol current (with and
without an id, json and text), mol progress and ready --mol read through
issueops.LoadMolecule over the roles, and create --parent lets the server
mint the child id. Those six shapes pass on the reference profile.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(cmd/bd): never silent against a server without the molecule tokens

Against a server that advertises neither issues.close.autoCloseMolecule
nor issues.advanceMolecule (an older bd serve, or one whose orchestrator
owns the molecule lifecycle):

- `bd close --continue` closed the step and only then found the advance
  refused, leaving the step closed and the next step unclaimed. It now
  asks storage.ServesMoleculeAdvance (a MoleculeAdvanceProber the http
  store answers from its handshake; local backends always serve it)
  BEFORE the close and refuses up front, saying nothing was closed.
- `bd close` went out without auto_close_molecule and said nothing. When
  the closed step belongs to a molecule (issueops.MoleculeRoot), a notice
  on stderr now names the molecule and the missing token: its auto-close
  is the server's to run. The batch and --if-revision closes both say it.

The served e2e masks both tokens out of the handshake and checks the
up-front refusal (the step stays open) and the notice; the httpclient
unit test pins ServesMoleculeAdvance to the handshake.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(cmd/bd): mol show through issueops.LoadMolecule on every route

`bd mol show` still loaded the molecule through cmd/bd's
loadTemplateSubgraph (raw GetIssue, GetDependentsWithMetadata and
GetDependencyRecords, plus an id-pattern child probe), while mol current,
mol progress and ready --mol read through the library. It now loads
through issueops.LoadMolecule over the route's molecule roles (the direct
store's, or the proxied provider's), so membership is the parent-child
edge everywhere and the http route reads through roles the server serves.
The served e2e checks mol show's root and step count.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs: the molecule auto-close fails the step's close on a non-policy error; stale comments

CloseRequest.AutoCloseMolecule and CloseCompletedMoleculeInTx now say what
changed when the auto-close moved into the close's transaction: a root
close the close policy refuses still leaves the root open and is reported,
but any other failure (a storage error, a lost race on the root's revision)
fails the step's close with it, where the CLI used to close the root
afterwards and only warn.

Stale: the advanceMolecule vocabulary entry said the client composes the
stepper over its own roles when unserved (it refuses before dialing), and
the graph-create collision probe called itself best-effort by transport
(the http GetIssue miss is storage.ErrNotFound like every other store's).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(changelog): the molecule tokens and the S16/S19 behaviours

Entries for issues.close.autoCloseMolecule and issues.advanceMolecule, the
issueops molecule entries, the auto-close inside the step's close (and a
non-policy failure of it failing the close), the real claim behind
close --continue, the molecule reads on every route, the notice and the
up-front --continue refusal against a server without the tokens, and
create --parent / mol reads over http.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(httpclient): regenerate unsupported_gen.go for MoleculeStepper

The PR adds MoleculeStepper() to storage.DoltStorage (200 -> 201
methods). httpclient implements it by hand, but the generated shell's
trailer still counted 200, so
//internal/storage/unsupportedgen:unsupportedgen_test
(TestGeneratedShellIsFresh) failed in Bazel / test and
Bazel / integration, turning CI Gate / Required red.

Regenerated with `go generate ./internal/httpclient`; the only change
is the trailer count (143 of 201 methods generated; 58 left).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(molecule): auto-close refusals, write skew, close --json, docs

Review fixes for #7513, numbered as in each iteration's review
synthesis.

Iteration 1:

F1: a close guard's refusal of the root (TemplateReadOnlyError,
PinnedError, CloseNotAssigneeError) is an auto-close refusal, like the
close policy's: the root stays open and is reported, and the step's
close stands. Pinned by the new conformance case
RunMoleculeGuardedRootKeepsTheStepClose on dolt, embedded, uow and the
served http client.

F2: two closes that finish a molecule's last two steps in concurrent
transactions each read the other's step as open, so neither closed the
root and both committed. Every auto-close now rewrites the root's
coordination cell before it decides the root (local_metadata
molecule-coordination/v1/<shard>, the dependency coordination idiom and
sharding with a FreshRowLock value), in both twins
(CloseCompletedMoleculesInTx and CloseCompletedMoleculesInUOW). Two
deciders of one root now conflict at commit (1213), and the retry reads
the winner's close and closes the root. This is the synthesis's option
(c), applied through a coordination cell instead of the root row; it
needs no post-commit second transaction and no engine lock. The
deterministic two-transaction regression fails without the touch and
passes with it on dolt and uow; the concurrent-close tests end with the
root closed in every round, reported by exactly one close.

F3: the auto-close checks the root's eligibility before walking any
step, MoleculeStepsClosed stops at the first open step, and a batch
decides each root once and reports it on the first item under it.

F4: ErrVersionMismatch on the root is not a refusal; it fails the
step's close with it. The classifier unit test pins this. A conformance
case cannot stage that race deterministically through the public roles.

F5: storage.ServesMoleculeAdvance answers (bool, error), and bd close
--continue refuses before closing anything when the handshake cannot be
read.

F6: the CHANGELOG and the stepper and batch-closer doc comments say
what the code does.

F7: the unserved-auto-close notice fires only when the close left an
auto-closing molecule with every step closed and its root open
(issueops.CompletedMolecule): again on a re-close, once per root in a
batch, never for a step under an ordinary epic or an unfinished
molecule. Proxied mol show, mol current and mol progress again report a
read unit of work that cannot be opened as itself, not as a molecule
that was not found.

F8: the write-ledger comment says the close is refused before dialing.
The dead FirstClosed/LastClosed guards in mol progress pre-exist on main
and are left as they are.

Iteration 2:

F1: on the proxied route, bd ready --mol reported a read unit
of work it could not open twice: once as itself, then as "molecule
'<id>' not found", which under --json is a second error document on
stdout. It now returns moleculeNotResolved, as mol show, mol current and
mol progress do. TestProxiedReadyMolReportsAnUnopenableReadOnce drives
runMoleculeReady with a provider whose NewUOW fails and wants one Error:
line, or one JSON document; both subtests fail with the old return.

F2: the coordination cell serializes every concurrent close of a step
under an open auto-closing root, not only the closes that finish the
molecule. That is the price of deciding the root in the step's
transaction, so it is documented (TouchMoleculeCoordinationInTx, the
UOW twin, CloseRequest.AutoCloseMolecule, the CHANGELOG) and pinned on
dolt and uow: two sibling closes with a third step still open conflict
(both commit when the touch is removed, on either twin), and a six-step
fan-out closes every step through the store's retry, with the root
closed and reported by exactly one close. The synthesis's alternative,
a post-commit recheck by any close that read a step open, is not taken:
it is a second, best-effort transaction after the step's commit, the
shape this PR exists to remove.

F3: MoleculeRootClose's doc no longer promises that a step reopened
between the completion read and the root close fails the step's close.
The guard is the root's RowVersion, which a step reopen never writes;
the doc now says what the guard covers and that this race goes
undetected (it is inherited from the CLI's old post-commit auto-close).

F4: the user docs describe the auto-close. docs/workflows/molecules.md
replaces "Closing the last child does not close the molecule root"
with which roots close and which stay open, the refusal warning, the
unserved-server note and the --json members, and documents the claiming
--continue and parent-child step membership;
docs/reference/json-schema.md gains a bd close --json section. These
are main-only behaviors on pages pinned to v1.2.2 (docs/cli-docs.pin):
a maintainer call against §1 of
engdocs/decisions/2026-07-17-docs-release-pin.md, as in #6508, #5855,
#5997 and #5092. The auto-close itself shipped in v1.2.2
(cmd/bd/close.go autoCloseCompletedMolecule), so the old sentence was
already wrong at the pin. docs/cli-reference/ is generated from the
pinned release and is not hand-edited; the bd close and bd mol show
help texts carry the same facts and reach it at the next pin bump.

F5: bd close --json reports the auto-close. The entry of a close that
completed a molecule gains auto_closed_molecule (the root it closed) or
molecule_auto_close_refusal (why the root stayed open), the HTTP API's
names, on the direct, proxied and --if-revision routes. The members sit
beside the issue's own rather than wrapping the output in an object the
way --suggest-next does: an object would change the output's shape
exactly when a close completes a molecule and break every consumer that
reads an array, while members leave each entry decoding as the closed
issue, compose with `closed` under the flag objects, and leave a plain
close's bytes unchanged. Pinned on the embedded and proxied tiers
(TestEmbeddedCloseJSONReportsMoleculeAutoClose, TestProxiedServerClose2B
json_reports_*, and both --if-revision replay tests), all red without
the change.

F6: cmd/bd's BeadsTemplateLabel is issueops.MoleculeTemplateLabel, so
the template commands and molecule membership cannot drift apart.

F7: the UOW twin's revision probe says that it writes nothing,
and the BatchCloseRequest.auto_close_molecule spec description has its
verb back (apigen regenerated, no drift).

Iteration 3:

F1: on the unit-of-work route (bd serve, the proxied CLI), a refused
root's molecule_auto_close_refusal and warning carried the use case's
and repository's wrapping ("close <id>: db:
IssueSQLRepository.CloseChecked <id>: ...") around the refusal, where
the tx twin and the docs give the refusal alone. Both twins now report
it through RefusedMoleculeAutoClose, which answers the refusing guard's
or policy's own sentence. RunMoleculeRefusedRootKeepsTheStepClose,
RunMoleculeGuardedRootKeepsTheStepClose and the embedded and proxied
close --json tests want that exact sentence; the uow conformance leg
and the proxied test fail without the unwrap.

F2: the docs no longer promise ErrVersionMismatch for a write to the
root that races its auto-close. The root's read and its revision check
share one transaction snapshot, so that write conflicts with the root
close at commit and the retry decides the root again; the close fails
only if it still conflicts when its retry budget runs out
(MoleculeRootClose, IsMoleculeAutoCloseRefusal,
CloseRequest.AutoCloseMolecule, the tx twin's comment, the CHANGELOG
and the OpenAPI description, apigen regenerated).

F3: TestEmbeddedCloseJSONReportsMoleculeAutoClose moves above
TestEmbeddedCloseConcurrent's doc comment, which documents its own test
again.

F4: bd mol progress counting direct steps while the auto-close counts
every descendant predates this PR; it is left for a follow-up.

F5: cmd/bd's molReader drops GetMoleculeProgress, which nothing called
once mol progress read through issueops.ReadMoleculeProgress.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 19:50:34 +00:00
Julian Knutsen
3e7705a2cd
fix(bazel): remove host-go dep from compact GC test; drop frozen shard blocks (#7478)
* fix(bazel): remove host-go dep from compact GC test; drop frozen shard blocks

Replace the ungated `go build` in compact_gc_target_test.go's dolt-stand-in
fixture with a Bazel-built go_binary (cmd/bd:compact_gc_fixture) wired via
rlocationpath env + data, mirroring the existing preflight_go_fixture
pattern. Falls back to `go build` only when not running under Bazel
(bazeltest.IsBazel()). Also gate test_repo_beads_guard_test.go's `go env
GOCACHE`/`GOMODCACHE` probes on !bazeltest.IsBazel(), since they previously
ran unconditionally in every cmd/bd TestMain.

Separately, delete the legacy 20-shard embedded-cmd and 15-shard
proxied-cmd "frozen" manifest blocks in .github/scripts/*-test-shards.txt:
their only consumers were pr-risk.yml fork/push jobs that have since
migrated to bazel.yml. Update gen_embedded_cmd_shard_manifest.py and
gen_proxied_shard_manifest.py to drop the frozen-block rendering/guard
logic and default to the live Bazel-only shard counts (100 and 34),
and refresh stale comments/docs (cmd/bd/BUILD.bazel,
scripts/shard_manifest_test.go, engdocs/TESTING.md,
engdocs/CI_REQUIRED_CHECK_TOPOLOGY.md) that still described the deleted
blocks. Verified no other BUILD/.github/scripts references read them.

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

* build(bazel): auto-sync BUILD files

Applied from the bazel-sync-patch artifact of https://github.com/gastownhall/beads/actions/runs/38069936930
(`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.

* fix(bazel): gate remaining host-go calls; fix shard-manifest --weights footgun

Address PR #7478 review findings (bee-ghosttrack):

- scripts/ci/lib/test-env.sh: skip the GOCACHE/GOMODCACHE `go env` probes
  when TEST_SRCDIR is set, so scripts/test.sh's beads_test_env_enter never
  shells out to a bare `go` when reached from a Bazel-run go_test (e.g.
  //scripts:shell_scripts_test's TestTestScriptPrebuiltTestBinaryContract),
  where a farm masks host go/dolt to exit 127. Nothing on that path needs a
  cache directory.
- scripts/ci/fmt-check.sh: describe_gofmt() no longer calls a PATH `go`
  under Bazel. It now resolves BEADS_TEST_GO (the hermetic SDK go already
  wired into scripts/prlintmake:prlintmake_test's env) via TEST_SRCDIR, and
  skips the version-reporting arm entirely when that isn't set (e.g.
  scripts/repochecks:fmt_test), rather than ever touching a possibly-masked
  PATH `go`.
- Verified with a PATH stub (go/dolt scripts that log and exit 127) via
  `bazel --nohome_rc test --config=prcore //scripts/... //cmd/bd:bd_test
  --test_env=PATH=<stubdir>:/usr/bin:/bin:/usr/local/bin`: 26/26 targets
  pass, zero stub invocations logged.
- gen_proxied_shard_manifest.py / gen_embedded_cmd_shard_manifest.py:
  default --weights to duration now that the manifests' only remaining
  blocks are duration-packed (the legacy inits-packed blocks were deleted
  alongside the PR Risk fork/push jobs that read them). Previously the bare
  `--write` default (inits) silently clobbered the live block's duration
  header and repacked with the wrong cost model; --check couldn't see it.
  Added TestProxiedShardManifestBareWriteIsIdempotent and
  TestEmbeddedCmdShardManifestBareWriteIsIdempotent to pin a bare --write
  as a no-op against the committed files.
- cmd/bd/compact_gc_target_test.go: resolve the non-Bazel fallback fixture
  path from this file's own directory (runtime.Caller) instead of the test
  binary's working directory.
- Refresh stale comments in .github/workflows/bazel.yml,
  scripts/shard_manifest_test.go, scripts/pr_risk_bazel_coverage_test.go,
  and scripts/embedded_shard_count_test.go that still described the deleted
  legacy 20/15-shard blocks and their retired fork/push jobs in the present
  tense.
- Confirmed cmd/bd/BUILD.bazel's compact_gc_fixture go_binary (implicit
  pure/race defaults) still passes TestRunCompactDoltTargetsOnlyAuthorizedActiveDatabase
  under `bazel test //cmd/bd:bd_test`.

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

---------

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-10-10 19:24:21 +00:00
Julian Knutsen
1b7bf9b191
fix(cmd/bd): guarded close/update/assign that lose to a delete at pre-flight report precondition_failed (#7465)
* fix(cmd/bd): guarded close/update/assign that lose to a delete at pre-flight report precondition_failed

A --if-revision close, update or assign racing a `bd delete` can observe
the winning delete at two points: inside its guarded write (classified
precondition_failed / exit 13 via classifyIfRevisionFailure's
storage.ErrNotFound branch) or at its pre-flight resolution
(resolveAndGetIssueForMutation on the direct route, the advisory pre-read
on the proxied update/assign routes), which returned an unclassified
"no issue found matching" exit 1. Which one a loser hits depends only on
whether the delete commits before or after it resolves the id, so
TestSharedServerDeleteIfRevisionSingleWinner/delete_vs_close and
delete_vs_update flaked under load. mc-zndi7.81 (#7256) closed the same
gap for delete's own pre-flight only.

reportIfRevisionTargetGone now maps a pre-flight not-found under an active
--if-revision guard to the guard envelope on every verb and route (delete
refactored onto it); unguarded commands keep their not-found exit 1.

Fixes ga-vnycm2.10.

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

* test(cmd/bd): name the proxied target-gone test into the proxied lane's TestProxiedServer* prefix

TestProxiedIfRevisionTargetGoneIsPreconditionFailed skips unless
BEADS_TEST_PROXIED_SERVER=1, which only the proxied lane sets, and that
lane selects TestProxiedServer*/TestServerMode* by name: as named it ran in
no CI lane (ga-vnycm2.43). Renamed and placed in the 34-shard manifest block.

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

* fix(cmd/bd): classify pre-flight-gone reopen and cascade-delete targets

Review fixes for #7465, review-loop iteration 1.

The PR makes a guarded write whose pre-flight resolution finds the row
already deleted report precondition_failed (exit 13) on close, update and
assign, and documents that rule for every guarded verb. Two guarded paths
still turned the lost delete race into an unclassified exit 1:

- `bd reopen --if-revision`, on both routes. The direct loop's
  resolveAndGetIssueForMutation failure and the proxied
  reopenProxiedResolve pre-read now go through reportIfRevisionTargetGone,
  as the other verbs do. The proxied caller returns the already-reported
  exit error unchanged (isReportedExit), so the outcome prints once.
- `bd delete --cascade --if-revision` on the direct route. deleteBatch
  built its missing-id error with fmt.Errorf("issues not found: ..."),
  which carries no sentinel, so the caller's reportIfRevisionFailure could
  not classify it. It now returns issueops.NotFoundError, the error the
  delete role's own existence probe returns (delete_role.go). The text is
  identical, and the error unwraps to storage.ErrNotFound. This reuses the
  existing typed error instead of adding a guarded-only wrap.

ifRevisionFlagHelp's comment and reportIfRevisionTargetGone's doc now name
all five guarded verbs and the cascade path.

Tests:

- Rename TestIfRevisionPreflightGoneIsPreconditionFailedOnEveryVerb to
  TestEmbeddedIfRevisionPreflightGoneIsPreconditionFailedOnEveryVerb. The
  embedded lane only discovers `func TestEmbedded*`
  (.github/scripts/embedded-test-shard.sh), so under the old name it
  skipped in every CI lane. It is added to embedded-cmd-test-shards.txt
  (100 65), and the manifest generator's --check passes at 100.
- The embedded table and its proxied twin,
  TestProxiedServerIfRevisionTargetGoneIsPreconditionFailed, gain reopen,
  delete and delete_cascade rows. The embedded table also gains an
  unguarded cascade-delete row that pins the unchanged "issues not found:
  <id>" text at exit 1. The deterministic cascade case lives in this
  CI-run table rather than in TestIfRevisionCascadeDelete, which the
  embedded lane does not discover; that test's doc points here.
- The proxied table now asserts that no raw "not found" text leaks past
  the guard envelope. A new unguarded_assign_still_not_found subtest pins
  the proxied assign pre-read's unguarded wording and exit 1.

Each code fix was mutation-checked. Reverting reopen.go,
reopen_proxied_server.go or delete.go to the PR head fails exactly one
row of its table (embedded reopen, proxied reopen and embedded
delete_cascade respectively), and every other row still passes. The fixed
build passes both full tables locally, the proxied one against a local
dolt 2.2.0 sql-server. A manual --json smoke of the direct reopen and
cascade-delete paths exits 13 with the standard precondition_failed body,
expected_revision included.

PR body corrections for finalize (description only, no code):
- The rule now covers five verbs (delete, close, update, assign, reopen)
  plus delete --cascade, not four.
- The embedded test is now
  TestEmbeddedIfRevisionPreflightGoneIsPreconditionFailedOnEveryVerb.
- The proxied test is
  TestProxiedServerIfRevisionTargetGoneIsPreconditionFailed (renamed in
  009b9b629b), and it runs in //cmd/bd:bd_proxied_test shard 7 of 34. The
  coverage-gap note's "(the new test included)" no longer applies to it.

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>
2026-10-10 16:33:19 +00:00
Julian Knutsen
3b0aa1be58
ci(bazel): run every BEADS_TEST_PROXIED_SERVER-gated cmd/bd test in the proxied lane (+ guard) (#7468)
* ci(bazel): run every BEADS_TEST_PROXIED_SERVER-gated cmd/bd test in the proxied lane

proxied-test-shard.sh selects the proxied lane's tests by name prefix
(TestProxiedServer*/TestServerMode*), and BEADS_TEST_PROXIED_SERVER=1 is set
only by //cmd/bd:bd_proxied_test. Seven cmd/bd tests skip without that
variable but are named outside the prefix, so they ran in no CI lane:

  TestProxiedDeleteIfRevisionSingleWinner
  TestProxiedIfRevision{CloseMismatchRefuses,CloseReplaysMoleculeAutoClose,
    CloseWarnsOnForcedOpenChildren,DeleteMatchAndMismatch,
    OutranksReassignFence}
  TestHistoryRemoteSupportedDirectAndProxiedParity

Rename them into the TestProxiedServer* prefix (the repo's existing
convention, see if_revision_proxied_integration_test.go) and place them
incrementally in the 34-shard manifest block. The prefix stays the
selection rather than widening to TestProxied*, which would pull ~33
ungated unit tests into the lane as duplicates.

Running them exposed real rot: the history parity test had been broken
since #7436 scoped shared-server projects to a per-database user, because
its `bd dolt remote remove` needs DOLT_REMOTE. It now uses
newSharedProxiedRootProject, like the other remote-removing tests #7436
moved.

Guard: TestProxiedGatedTestsRunInTheProxiedLane (//scripts:
go_test_sources_test) walks cmd/bd's test call graph for any top-level test
that reaches an `os.Getenv("BEADS_TEST_PROXIED_SERVER") != "1"` gate and
fails unless proxied-test-shard.sh lists it in some shard;
TestProxiedGatedTestsDetector pins the walk against a fixture.

Fixes ga-vnycm2.43.

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

* test(scripts): indent the gated-test detector's fixture so equivalence.py does not count it

tools/bazel/equivalence.py finds a package's tests with a line-anchored
^func TestX(t *testing.T) scan, so the fixture's TestDirect..TestUngated
read as scripts tests Bazel never ran (EQUIVALENCE: FAIL on Bazel / test).

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-10 13:51:34 +00:00
Julian Knutsen
eb204363c9
ci(bazel): add advisory dolt-race shadow lane (item 5 phase 1) (#7464)
* ci(bazel): add advisory dolt-race shadow lane (item 5 phase 1)

Add --config=dolt-race, the union of --config=doltserver and
--config=doltserver-proxied with one tag filter for both tiers, and an
advisory bazel-dolt-race job that runs it beside bazel-doltserver and
bazel-proxied. The shadow measures one client per group of lanes against
the two lanes it would replace before any cutover (item 5 slice A1a).

The job runs in mode remote on pull_request and merge_group events only.
It has job-level continue-on-error, no job or workflow_call output, and no
gate names it, so it cannot change CI Gate or PR Risk Gate. Its
ci-analytics step is copied verbatim with LANE=dolt-race, and rrc seeds
the new config.

Policy tests pin the config as the exact union of its members' lines (tag
filter aside), the job's run modes and events, its advisory shape, the
analytics lane map and the rrc command list. aquery shows every member
target's TestRunner action (actionKey, argv, env, inputs, outputs) is
unchanged under the union config.

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(bazel): give the dolt-race shadow timeout headroom; fix gate-wait wording

Review follow-up on the advisory bazel-dolt-race job (maintainer-city-c3,
findings 1, 2 and 5):

- Raise the job's timeout-minutes from 30 to 35. continue-on-error covers
  a failed or timed-out step, but not a job GitHub cancels at its own
  timeout, which could make the bazel call non-success and turn CI Gate
  red. TestBazelDoltRaceShadowIsAdvisory now reads both timeouts from the
  workflow and requires job >= test step + 10 (and a step timeout at all).
- Correct the docs and comments: the shadow cannot fail the gate, but
  CI Gate still waits for it, because its needs on the bazel call
  completes only when every job in it has finished.
- Correct the checks comment: check_testcases covers every target in the
  union, including the dolt-server tier its own lane never checked.

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(bazel): bound every dolt-race shadow step; job timeout covers their sum

Review follow-up (S1): a hang in any bazel-dolt-race step without a
timeout would run into the job's own timeout, and a job GitHub cancels
there is not covered by continue-on-error. Every step now has a
timeout-minutes, and the job's timeout covers their sum:

- checkout 5, rrc read 1, setup-bazel 10, flaky query 5, checks 3 each,
  test-log upload 3. The test step (25) and the analytics steps (3, 2)
  keep bazel-proxied's values; bazel-proxied sets no timeout on the
  others, so these bound them.
- The step timeouts sum to 60 minutes, so the job timeout goes from 35 to
  65.
- TestBazelDoltRaceShadowIsAdvisory now requires a timeout on every step
  and job >= sum(step timeouts) + 5, read from the workflow, alongside the
  existing job >= test step + 10.

Also cite the farm maintainer's confirmation of NativeLink 1.7.1's
in-flight Execute dedupe in the job comment.

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(bazel): keep dolt-race shadow timeout under the merge queue's

Tighten the shadow's non-test step budgets so the job timeout (step sum
+ 5) is 55 minutes, and pin that it stays below the 60-minute merge
queue check timeout: CI Gate waits for the shadow, so a hung shadow
must not drop a group from the queue.

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-10 10:13:49 +00:00
Bee
11b5d3271e
docs(proxied): name the Close3/Close4 legacy pins and fix the Close3 doc comment (#7173 follow-up) (#7382)
* docs(proxied): name the Close3/Close4 legacy pins and fix the Close3 doc comment (#7173 follow-up)

Two non-blocking findings from the #7173 adoption review (bd-vrdrew,
bd-dars9p), both in bee's code, neither addressed in that PR:

- The doc comment on TestProxiedServerClose3 still called it "the second
  half of TestProxiedServerClose"; after the second split it is the middle
  of the three parents (Close, Close3, Close4). Say so, and name Close4
  as its own second half.

- In the frozen 15-shard block of .github/scripts/proxied-cmd-test-shards.txt
  the lines `15 13 TestProxiedServerClose3` and `15 2 TestProxiedServerClose4`
  sat inside the shard-1 and shard-7 groups (#7173's last commit moved the
  pins from 1 and 7 to 13 and 2 without moving the lines), and the header's
  "Deliberate exception (Oct 2026)" paragraph did not name them. The two
  lines now sit alphabetically inside their own shard groups, the header
  names them with the reason and the measured times, and the generator's
  hand-pin paragraph (scripts/ci/gen_proxied_shard_manifest.py) names them
  too so the two texts stay in step. The lines were inert either way:
  proxied-test-shard.sh matches each line by field.

No test moves shard: the 15-shard block's line set is unchanged apart from
order (sorted diff empty) and the 30-shard block is byte-identical.

Verified: gofmt -l (clean); go vet ./cmd/bd/ (exit 0);
gen_proxied_shard_manifest.py 30 --weights=duration --check (exit 0,
heaviest 435.1s est, unchanged); 15 --check reports the same 30 hashed
names missing as main (the frozen block is expected to fail it);
proxied-test-shard.sh list-only: Close3 on 13/15, Close4 on 2/15, neither
on 1/15 or 7/15; go test ./scripts/ -run 'Shard|Manifest|Coverage' ok 38.6s.

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

* docs(proxied): count CloseB in the Close3 comment; say why shard 5 got no pin

Maintainer fixup from the adoption review of #7382 (bd-g6pyb0), on top
of bee's commit, which stays as written. Comment and manifest-header
text only: no test body, shard assignment or routing changes.

- TestProxiedServerClose3's doc comment called it "the middle of the
  three parents TestProxiedServerClose was split into (Close, Close3,
  Close4)". That held at the PR's original base, but #7418, on main
  since, moved five of Close's eleven cases into a new
  TestProxiedServerCloseB, so the 23 bd-init subtests of the pre-#7173
  TestProxiedServerClose now sit in four parents: Close 6, CloseB 5,
  Close3 6, Close4 6 (their union is exactly the pre-#7173 set, no
  duplicates). The comment now says Close3 was split off Close, names
  all four parents, and keeps "Its own second half is
  TestProxiedServerClose4."

- The frozen 15-shard block's header said #7173 pinned Close3 and
  Close4 onto "the two lightest shards of that PR's own run (6m51s and
  7m57s)". On that run (37206446441, at 765248af5) shard 5 was lighter
  still, at 5m50s; #7173 passed over it on purpose, because it was
  light only because those 12 subtests had just left it and putting
  Close3 back would recreate most of the set that timed out. The header
  now says "other than shard 5 itself" and gives that reason.

This commit also supersedes the parts of the parent commit's message
that the rebase onto c21880105f outdated:

- "after the second split it is the middle of the three parents (Close,
  Close3, Close4)": four parents now, as above.
- "the 30-shard block is byte-identical": the Bazel-only block is 34
  shards now (#7418 made it 44, #7436 34), and that block is
  byte-identical to the base's.
- "gen_proxied_shard_manifest.py 30 --weights=duration --check (exit 0,
  heaviest 435.1s est, unchanged)": with no 30-shard block left, that
  command now exits 1 ("has no block for total_shards=30"). Its current
  form, 34 --weights=duration --check, exits 0 with the heaviest shard
  at 196.1 s est., the same before and after this commit.
- "15 --check reports the same 30 hashed names missing as main": it now
  reports 53, the same set as against the base's manifest.

Verified: git diff --check clean; gofmt -l clean (the Go change is
comment-only); with '#' lines stripped as proxied-test-shard.sh strips
them, the manifest is identical before and after;
gen_proxied_shard_manifest.py 15 --check and 34 --weights=duration
--check print the same output before and after (exit 1 with 53
missing; exit 0, heaviest 196.1 s); BEADS_TEST_SHARD_LIST_ONLY=1
proxied-test-shard.sh lists for 1, 2, 7 and 13 of 15 are unchanged
(Close3 on 13, Close4 on 2, neither on 1 or 7); go test ./scripts/ -run
'Shard|Manifest|Coverage' ok (21 top-level tests, none skipped).

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 Fable 5.1 <noreply@anthropic.com>
Co-authored-by: Eddie the Engineer <julianknutsen@users.noreply.github.com>
2026-10-10 05:28:43 +00:00
Bee
9f5028c78e
test(show): run --comments-tail through every show route; CHANGELOG bullet under Added (#6618 follow-ups) (#7383)
Follow-ups from the #6618 adoption review, neither addressed there:

- bd-6gl9h7 (Test Evidence Quality): no committed test ran `bd show` with
  --comments-tail set. show_comments_tail_test.go calls printComments and
  renderWatchComments directly, so passing 0 at any of the three call
  sites (show.go direct, show_display.go --watch,
  show_proxied_server.go / show_proxied_watch.go proxied) still passed the
  suite. TestEmbeddedShowCommentsTail (direct, direct --watch) and
  TestProxiedServerShowCommentsTail (proxied, proxied --watch) now run the
  built binary through each route over the same three comments with
  --comments-tail 1, and check the elision line, the surviving newest
  comment, the absence of both hidden ones, the off state (0 and a cap
  above the count) byte-identical to the flag's absence, the negative
  usage error, and --json --include-comments untouched.

  Mutating each call site to pass 0 fails the matching route tests
  (direct: direct_tail_1 + watch_tail_1; proxied: proxied_tail_1 +
  proxied_watch_tail_1) and nothing else.

  The off-state comparison strips the "💡 Tip:" line maybeShowTip may
  append after a direct text render (a per-run probability roll behind a
  per-tip frequency gate, independent of the flag); without that, the
  first render of a fresh store can carry the tip and the comparison
  fails on it.

  The embedded half lives in a *_embedded_test.go file because
  gen_embedded_cmd_shard_manifest.py discovers TestEmbedded* only there;
  both tests are registered in their shard manifests (--write, then
  --check rc 0 at 50 and 30) and in cmd/bd's go_test srcs.

- bd-l6f1r7 (Release Safety): the CHANGELOG bullet for the flag sat under
  "### Fixed" in [Unreleased]; it is now the first bullet under the
  section's "### Added".

Ran (GOTOOLCHAIN=go1.26.7): go vet ./cmd/bd/; gofmt -l; go test ./scripts/
-run 'Shard|Manifest|Coverage'; embedded leg
(BEADS_TEST_EMBEDDED_DOLT=1) -run TestEmbeddedShowCommentsTail -count=3:
15/15 subtests PASS; proxied leg (BEADS_TEST_PROXIED_SERVER=1,
BEADS_TEST_DOLT_SERVER=local, dolt 2.2.0, -tags gms_pure_go) -run
TestProxiedServerShowCommentsTail: 5/5 PASS, 0 SKIP.

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-10 02:50:41 +00:00
Julian Knutsen
f53010a23b
ci(bazel): remote repo contents cache: main-push seed, lane readers, nightly verify (#7453)
Port gascity's remote repo contents cache wiring (gascity #7467, #7478) to
bazel.yml, gated on the repository variable RBE_REPO_CONTENTS_CACHE
(unset/off: nothing; seed: rrc-seed on push to main; canary: + bazel-test
reads; on: + every test lane reads). Mode remote only.

- rbe job: an rrc step turns the variable into the rrc output.
- Readers: the eight test lanes append startup
  --experimental_remote_repo_contents_cache and common
  --loading_phase_threads=64 to .bazelrc.local before Set up Bazel.
- rrc-seed (push to main, id-token: write): a 30-minute
  rbe-rrc-writer-beads certificate from rbe-west's mint
  (.github/scripts/rrc-writer-credential.sh), then every lane's command
  (.github/scripts/rrc-lane-commands.txt) with --nobuild, --remote_cache
  only and --remote_upload_local_results (.github/scripts/rrc-run-lanes.sh).
- rrc-verify (schedule/dispatch, issues: write): cold fetch of every lane
  and tools/bazel/rrc_verify.py against the cache; a mismatch opens an
  rrc-verify issue.
- pr.yml, nightly.yml and bazel-farm.yml grant id-token: write and
  issues: write on their bazel.yml call (startup_failure otherwise);
  TestBazelWorkflowCallersGrantEveryRequestedPermission guards it.

rrc-writer-credential.sh, rrc_verify.py and rrc_verify_test.py are byte
copies of gascity's, pinned by sha256.

Refs ga-vnycm2.29.

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-10 02:50:26 +00:00
Julian Knutsen
d15958a5eb
fix(issueops): enforce the dotted-child dependency rule on every leg (#7424)
* fix(issueops): enforce the dotted-child dependency rule on every leg

The refusal of an explicit edge from a dotted-id child to its own ancestor
(bd-abc.1 -> bd-abc; only the parent-child edge to the immediate dotted
parent is allowed) lived only in cmd/bd (isDisallowedHierarchicalDependency).
HTTP dependencies:add, batch:apply dep_add items and `bd create --graph`'s own
edges skipped it.

It is now one library rule, issueops.CheckDottedChildDependency, returning
*issueops.DottedChildDependencyError (unwraps to ErrValidation, same message
the CLI printed):
- ValidateAddDependenciesRequest applies it, so DependencyEditor refuses on
  dolt, embedded, uow and the server behind httpapi (400 invalid_argument);
- both BatchApplier bodies (issueops and uow) apply it to each dep_add item on
  the resolved ids, so a key bound to a minted dotted child is refused too;
- the HTTP client checks it before the dial, as it does self-dependency, so
  the typed error survives the wire.

cmd/bd keeps no copy: single-edge dep add / dep --blocks rely on the role;
bd link (still on the store verb) and the --file bulk reporter call the
library rule. CLI output is byte-identical (checked against origin/main).

Conformance: RunDependencyEditorRefusesADottedChildGatedOnItsOwnParent and
RunBatchApplyRefusesADottedChildGatedOnItsOwnParent wired on dolt, embedded,
uow and http, plus a raw-wire served test past the client check and handler
mapping cases.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(batch): refuse a dotted child gated on its own ancestor in bd batch

Review fixup for PR #7424 (iterations 1 and 2).

Major: a bd batch script line `dep add bd-abc.1 bd-abc` still wrote the
edge this PR refuses everywhere else, on both backends. Neither batch
dispatch writes through the DependencyEditor role that enforces the
dotted-child rule: the classic arm calls storage.Transaction.AddDependency
and the proxied arm the unit of work's AddDependencies verb. Both arms now
build the edge with one helper, batchDepAddEdge, which keeps the default
type and the arity and type errors, and asks
publicops.CheckDottedChildDependency the way bd link does. A refused line
rolls the whole batch back.

Tests: TestBatchDepAddEdge (default and explicit types, arity and type
errors, three refusals typed *DottedChildDependencyError matching
ErrValidation, and the immediate parent-child edge allowed), and
TestProxiedServerBatchDepAddRefusesADottedChildGatedOnItsParent (classic
and proxied: the refusal names line 2, rolls back an earlier update line
and writes no edge, and `dep add C P parent-child` still lands exactly
one), registered in the proxied shard manifest. A mutant that drops the
rule from the shared helper fails both; one that bypasses the helper in
the proxied arm alone fails the proxied leg.

Minors:
- For a child whose parent-child edge is already stored (a
  `bd create --parent` child) the rule answers ahead of the hierarchy and
  type conflicts, so an HTTP caller now gets 400 invalid_argument where it
  got 409 dependency_cycle (blocking types) or dependency_exists (any
  other type). Documented in the DependencyEditor role doc, the CHANGELOG
  entry and the httpapi batch-apply test comment, and pinned by a
  stored-hierarchy phase in the DependencyEditor and BatchApplier
  dotted-child conformance contracts on every leg; a mutant that drops the
  rule gets the hierarchy conflict instead (409 dependency_cycle on the
  wire).
- The bd create --graph dry-run note now says the live create may also
  refuse an edge that gates a dotted-id child on its own ancestor.
- The DottedChildDependencyError comment says the message is kept verbatim
  and says "deadlock" whatever the type.

Not changed: bd relate (relates-to does not schedule) and the edges a
create writes with its issue (bd create --deps/--waits-for, and over
HTTP an explicit dotted id with a non-immediate ParentID) still write
through paths that skip the rule. The scheduling shapes need an explicit
dotted id or a grandparent target. Follow-up bd-25s1wh tracks moving the
rule down to the domain/store add verbs, with a structural bypass for
reparent and template edges.

Iteration 2 (minor): the CheckDottedChildDependency doc no longer implies
bd link and bd batch are the only writers outside the roles. It names
bd relate and the create edges as not applying the rule yet and cites
bd-25s1wh.

Complexity (cyclomatic/cognitive): runBatchOp 23/35 -> 21/31,
runBatchOpUOW 28/48 -> 26/44, batchDepAddEdge 5/4. Touching them brings
both pre-existing dispatch switches into the measured set; splitting them
is out of scope here.

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

* docs(issueops,httpapi): document the dotted-child 400 and widen its gap list

Review fixup for PR #7424 (relaunch, iteration 1, minors).

- The OpenAPI spec now describes the wire change this PR makes. The
  dependencies:add and issues:batchApply 400 vocabularies name an edge
  from a dotted-id child to its own ancestor (anything but the
  parent-child edge to its immediate parent; param `edges` and `items`).
  dependencies:add says why that is request-intrinsic, and both 409s say
  it is never dependency_cycle or dependency_exists, even for a child
  whose parent-child edge is stored. Response descriptions only: the
  generated types and the wireshape digest are unchanged (make api-check).
- The CheckDottedChildDependency doc no longer reads as a complete list of
  the writers that skip the rule. Besides bd relate and the create edges
  it names bd duplicate, bd supersede, bd duplicates --auto-merge (its
  related link and its reparenting) and the tracker engine's
  createDependencies, and says the molecule, template and swarm writers
  are unaudited. bd-25s1wh's notes carry the widened scope, including
  `bd duplicate bd-a.1 --of bd-a`.

Declined (nit): unifying the root issueops import alias across the PR's
cmd/bd files. batch.go is the one file that imports both issueops
packages, so one of them needs an alias there; it uses publicops, the
repo's usual alias for the root package, and aliasing the other side
instead would rewrite base-owned lines.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 22:56:46 +00:00
Julian Knutsen
72a3d8039d
ci(bazel): embedded storage tier to 40 shards; split its two slowest tests (#7440)
//internal/storage/embeddeddolt:embeddeddolt_embedded_test became the
embedded lane's floor once the cmd tier was split (CI on #7438: 20 shards,
220s max, 162s median). Its tests are serial, so a shard's wall time is the
sum of its tests; measured on rbe-west with the whole lane running (as CI
runs it), its 20 shards took 110-161s.

- TestCreateBatchFastPathsMatchPerRow_Embedded (111s) runs
  createbatchequiv's scenarios as two top-level tests (small+depadd,
  apply+waitsfor) through a new createbatchequiv.RunNamed; the same
  scenarios and checks. TestCreateBatchEquivalencePartsCoverEveryScenario
  fails unless the parts name every createbatchequiv.Run scenario exactly
  once.
- TestWithPeerAuth_WarnsWhenStoredPeerSuppressesAmbientPassword (81s, eight
  cases each opening its own store) runs its table as two top-level tests,
  cases 1-4 and 5-8; cases and assertions unchanged.
- Durations re-measured on rbe-west under the whole lane's load; the
  Bazel-only block is now 40 shards (LPT heaviest = the heaviest single
  test, TestLifecycleCloseReopenContract ~71s). One target: 40 is under
  Bazel's 50-shard cap, so no offset split.

rbe-west, `bazel test //... --config=embedded --nocache_test_results`:
storage shards max 161s -> 89s, median ~118s -> 63s.

Bead: ga-vnycm2.28

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-09 21:21:20 +00:00
Julian Knutsen
0d865460b1
ci(bazel): split the slow embedded cmd tests and run the cmd block as 2x50 shards (#7438)
//cmd/bd:bd_embedded_test was the embedded lane's floor: at Bazel's 50-shard
cap per rule, each shard's wall time was its slowest top-level test, and
~40 tests ran 65-130s on rbe-west.

- 34 slow TestEmbedded* functions are split into 89 smaller top-level
  functions. Subtests and table cases are moved verbatim: no assertion,
  flag or data changes, the same t.Run set per file, the same skip guard and
  t.Parallel. Subtests that read state earlier ones left stay together, in
  order; each new function repeats the shared setup it needs.
- The manifest's cmd/bd block is now 100 shards, run by two targets:
  bd_embedded_test (shards 1-50) and the new bd_embedded_part2_test
  (51-100), through go_test_manifest_shard.sh --shard-offset/--shard-total.
  check_shard_coverage.py takes SHARDS@OFFSET/TOTAL and fails unless the
  targets' ranges tile the block exactly once, so every test runs in exactly
  one shard of one target; the policy tests read both rules' ranges from
  cmd/bd/BUILD.bazel.
- Durations re-measured on rbe-west with the split tests and repacked. The
  frozen legacy 20-shard block drops the renamed names (no workflow reads
  it; new names hash-distribute as before).

Not split: the *Concurrent stress tests (their bd subprocesses queue on the
workspace's single writer lock: TestEmbeddedUpdateConcurrent is ~100
serialized bd commands), TestEmbeddedPurgeWispsPlaneRetention (one stateful
sequence), and the MaxRowsList* tests (setup is 21 sequential creates every
subtest reads).

rbe-west, both targets, --nocache_test_results: slowest shard 138-163s ->
109s (TestEmbeddedUpdateConcurrent alone; every other shard <=86s), median
80-84s -> 40s, shard-seconds 4.1-4.4k -> 4.2k, critical path 213-306s ->
113s.

Bead: ga-vnycm2.17

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-09 20:30:52 +00:00
Julian Knutsen
1531a31760
ci(bazel): halve the embedded cmd tier's cost (seeded bd init schema, no race exit sleep, concurrency-aware packing) (#7437)
//cmd/bd:bd_embedded_test sits at Bazel's 50-shard cap and was the embedded
lane's floor (shards 62-250s). Measured on rbe-west, every shard's wall time
was its single slowest top-level test, and most of a test's time was `bd
init` (~20s under -race: one Dolt commit per schema migration) plus a fixed
1s per bd subprocess exit (the race runtime's atexit_sleep_ms).

- bdInit seeds .beads/embeddeddolt/<db> from a per-process schema template
  (an empty database with every migration applied, made once per shard by a
  non-race build of internal/storage/embeddeddolt/cmd) before running the
  real `bd init`, which then skips the migration chain and does everything
  else itself (identity, prefix, config, hooks, agent files, git commit).
  Only for argument lists it understands (--prefix/--database plus
  --quiet/--skip-hooks/--skip-agents/--non-interactive), and it checks the
  result is the seeded embedded database. BEADS_TEST_FRESH_INIT=1 turns it
  off. The TestEmbeddedInit* tests run their own init and are unaffected.
- GORACE=atexit_sleep_ms=0 on the target: the bd subprocesses no longer
  sleep 1s before exiting. A race they hit while running still fails the
  command as before.
- TestEmbeddedInitSelectedExcludeRouting (serial, t.Setenv, 7 full inits,
  ~113s) is split into ...Stealth and ...Fork top-level functions; same
  cases, same assertions.
- The generator packs with a model of the shard process (pack_concurrent):
  tests without a top-level t.Parallel run one after another, the rest
  share -test.parallel=4. The durations are re-measured on rbe-west.

rbe-west, `bazel test //cmd/bd:bd_embedded_test --config=embedded
--nocache_test_results`: test-seconds 20.2k -> ~10.3k, shard-seconds
8.0k -> ~4.2k, slowest shard 243s -> 138s / 163s (two runs, before the
repack).

Bead: ga-vnycm2.17

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-09 19:20:33 +00:00
Julian Knutsen
6d27a4f96e
fix(issueops): enforce the close guards on every close leg (#7425)
* fix(issueops): enforce the close guards on every close leg

The template read-only guard, the pin guard and the assignee authority
fence (be-035) lived only in cmd/bd (validateIssueClosable), so a close
through bd serve, issues:batchClose, a batch:apply close item or a library
caller of Lifecycle.Close / BatchCloser / BatchApplier closed what bd close
refused.

They now run inside the close's own transaction in CloseIssueCheckedInTx
(enforceCloseGuardsInTx), the body every checked close shares (dolt,
embedded, uow, and the server behind httpapi), for a target that is not
already closed:
- a template refuses with *issueops.TemplateReadOnlyError (no bypass);
- unless Force (CloseRequest, CloseBatchRequest, CloseItem) is set, a pinned
  issue refuses with *issueops.PinnedError and another actor's bead with
  *issueops.CloseNotAssigneeError (matches ErrNotOwner).

Wire: 409 template_read_only, issue_pinned and not_assignee (holder in
`assignee`, also on a batch-close outcome); the client rebuilds the typed
errors. The decision is one exported pure rule over the pre-image,
issueops.CheckClosable (internal/storage/issueops), which the in-tx guard
calls; bd close's direct and proxied preflights call it too, ahead of gate
satisfaction under the same already-closed skip, so bd close output, refusal
order and exit codes are unchanged (validateIssueClosable is gone). bd close
--if-revision now applies the guards too.

Conformance: RunLifecycleCloseEnforcesTheCloseGuards,
RunBatchCloserItemsAnswerToTheCloseGuards and
RunBatchApplyCloseItemsAnswerToTheCloseGuards on dolt, embedded, uow and
http, plus handler mapping tests, a CheckClosable table test, and a cmd/bd
test pinning that the guards outrank gate satisfaction.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(httpclient): send force on the raw close; scope the close guards

Review fixes for #7425 (adopt-pr bd-0h0ao4, iterations 1 and 2).

The raw close keeps parity over http. httpclient.Store.CloseIssue maps the
off-role raw close onto the role's closeIssue op and sent force=false.
With the guards in the role, a pinned or claimed target then refused (409
issue_pinned / not_assignee) on http only: dolt, embedded and proxied run
the raw close as issueops.CloseIssueInTx, which applies neither the guards
nor close policy. The molecule auto-close, `bd gate resolve`,
`bd todo done` and `bd human dismiss` all make that call, and its
signature carries no force a caller could pass. It now sends force. Over
http that also stops applying close policy to the raw close, which it did
at base and no other backend does; parity is the point, so that goes too.
The template guard has no bypass on the wire, so a template still refuses
the raw close over http where the other backends close it; no raw caller
is known to close one. TestServedRawCloseKeepsParityWithTheOtherBackends
closes both pin spellings, a held bead and a parent with an open child
through Store.CloseIssue and requires the template refusal; with force
back to false it fails on 409 issue_pinned.

The close guards stay on the close verbs. A status update that crosses
into the done category (`bd update -s closed`, PATCH, a batchApply update
item) still answers to close policy only, so it closes a pinned issue or
another actor's bead on every backend, as it did before this PR. Guarding
it changes what the update legs admit and needs its own refusal mapping on
PATCH and batchApply, so it is left for a follow-up; the update.go and
domain/db comments now say the exclusion is deliberate.

CHANGELOG: the entry moves from Fixed to Changed as BREAKING, is scoped to
the close operations, names the two paths the guards do not cover, and
adds a Migration line (send force or reclaim; templates are never
closable). Docs: the OpBatchCloseIssues item codes, the CloseIssueChecked
and CloseIssueOptions.Force docs (storage, dolt, embeddeddolt), the
oracle-a scenario strings that named the retired validateIssueClosable,
and the TestCloseCheckOne_CloseGuardsOutrankGateSatisfaction doc, which
claimed a proxied route it does not drive.

Iteration 2: the wire contract says what force waives. The OpenAPI
`force` members of CloseIssueRequest, BatchCloseRequest and ApplyCloseItem
said force bypasses close policy "and nothing else"; it also waives the
pin and the assignee guard, and never the template guard. The batchClose
"only two answers" paragraph now says the same, and types.gen.go is
regenerated (`make api-gen`). "Close guards" names the close operations
instead of "every route to a close" and adds that a status update into
the done category is not one, and the PATCH done-crossing paragraph says
a patch is never refused `issue_pinned` or `not_assignee`. The conformance
comments that quoted the old Force sentence (batch_apply_contract.go,
batch_closer_contract.go, lifecycle_close_reopen_contract.go) quote the
current docs, and the batch_apply failure message no longer says Force
does nothing else. CHANGELOG: a `close` line of `bd batch` is named among
the raw closes, and "a template is never closable" becomes "the close
operations never close a template, forced or not". The storage interface
CloseIssue gains a doc that states its HTTP exception.

TestCloseGuardRefusalsPrintTheGuardSentenceOnEveryRoute pins the sentence
`bd close` prints for each guard (template, pin, assignee) through each
printer (closeDirectRefusal, closeDirectTypedRefusal, closeProxiedRefusal,
closeProxiedTypedRefusal), with the refusal bare, wrapped by the use case
and the SQL repository, or inside a served problem envelope. One pinned
refusal also goes through closeProxiedOutcomes and closeProxiedFailures,
where the stderr line and the `--json` error field must both be the
sentence. Six overlay mutants fail it: closeGuardRefusal recognizing no
guard, or not the pin, and each of the four printers skipping its call to
closeGuardRefusal.

Not done here: a CLI test that `--if-revision` exits 1 on a guard refusal,
not ExitGuardMismatch. External PR #7372 carries per-id fence tests for
that route (6 of 7 pass at this head); they are better absorbed with
credit than rewritten.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 18:30:42 +00:00
Julian Knutsen
7896abbfa8
ci(bazel): scope the proxied lane's shared-server projects to their own database (44 -> 34 shards) (#7436)
* ci(bazel): scope the proxied lane's shared-server projects to their own database (44 -> 28 shards)

//cmd/bd:bd_proxied_test spends nearly all its time in `bd init
--proxied-server` against the shard's shared dolt sql-server. Measured
where that goes (dolt query log): of ~2,031 statements per init, the ~220
INFORMATION_SCHEMA queries (migration guards and pre-repair probes) are
~80% of server time at a handful of databases, the 81 DOLT_COMMITs only
~0.5s. Dolt evaluates INFORMATION_SCHEMA by walking every database the
session can see, so as root each init cost the server ~1.2 CPU-seconds
more per database already on it (locally 6.7 CPU-s with 1 database, 21
with 11): a shard's k-th init paid for the k-1 projects before it.

- proxied_shared_harness_test.go: newSharedProxiedProject now provisions
  the database server-side (root creates it plus a passwordless user of
  the same name with ALL on it and nothing else) and inits with
  --proxied-server-external-user, so each project's sessions see one
  database. newSharedProxiedRootProject keeps the old root/bd-creates-it
  shape for the four tests that need a server-wide privilege (DOLT_REMOTE
  remove, CREATE DATABASE, one compact statement); a run with the server
  log in test outputs showed no other denied statement.
- Dropping finished databases instead was tried and rejected: a DROP
  DATABASE fails other sessions' in-flight INFORMATION_SCHEMA queries
  ("no root value found in session"), ~35 init failures per run.
- No assertion changed. The bd-creates-the-database path stays covered
  by the root variant, the managed-local and non-shared init tests.
- proxied_test_durations.json re-measured (two rbe-west runs): 19,618 ->
  6,345 cost-seconds. 44 -> 28 shards, LPT-packed to ~227 per shard.

rbe-west, --nocache_test_results (BEP attempt durations): before 44
shards, sum 6,063s, max 186s; scoped users at 44 shards, sum 2,337s, max
68s; at 20 shards, sum 1,950s, max 136s.

Bead: ga-vnycm2.16

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

* ci(bazel): proxied lane 28 -> 34 shards for a <=100s slowest shard

PR CI at 28 shards (~227 packed cost each): 2,285 shard-seconds, median
78s, but max 113s; equally packed shards spread up to 1.45x the median.
34 shards (~187 each) targets a slowest shard under 100s.

Bead: ga-vnycm2.16

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-09 18:22:08 +00:00
Julian Knutsen
470ec832b5
feat(roles): LeaseReclaimer role, POST issues:reclaim, and bd reclaim on both routes (S9) (#7412)
* feat(roles): LeaseReclaimer role and POST issues:reclaim (S9)

Adds issueops.LeaseReclaimer.Reclaim(ReclaimRequest{Actor, OlderThan,
Filter}) -> ReclaimResult{Reclaimed []ReclaimedLease{ID, PreviousOwner,
Revision}}, the stale-lease sweep behind `bd reclaim`, on every leg:

- dolt, embedded dolt and the unit-of-work provider all run one body,
  internal/storage/issueops.ExecuteReclaimInTx over
  ReclaimExpiredLeasesInTx, and record one version commit per sweep that
  reverted anything through the issue-operation funnel (so a deferred
  version commit on the context is honored);
- each reverted row's fresh row_lock is published as its revision, so a
  former holder's guarded write fails with ErrVersionMismatch;
- an id that is not a stale lease (absent, live, unheld) is left out of
  Reclaimed, never an error; the id scope is capped at 1000
  (*TooManyReclaimIDsError, counted as sent);
- the hook decorator fires on_update once per reverted row (and the
  proxied notifying provider records one update per row); telemetry
  wraps it like every role.

bd serve publishes it as POST /v0/beads/issues:reclaim behind the new
issues.reclaim capability (httpapi.Config.LeaseReclaimer, required like
every role). Spec, apigen and the wire-shape golden are regenerated;
the change is additive and wire_revision is unchanged. The HTTP client
leg dials it (wire vocabulary, capability preflight, local validation
in the role's order).

Conformance: RunLeaseReclaimer* (12 cases: revert post-state, the
revision race, live lease, grace window, id scope with absent/live ids,
empty answer, assignee/label scopes re-homed from reclaim_scope.go,
recovery event attribution, on_update once per row, refusals, the cap
boundary, no request mutation) wired on dolt, embeddeddolt, uow and the
served http leg, and so held by the leg lock. Handler tests cover the
member mapping, the projection, every handler refusal by name and the
role's refusals reaching the wire.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(bd): bd reclaim runs the LeaseReclaimer role on both routes (S9)

`bd reclaim` takes issueops.LeaseReclaimer off the decorated store on the
direct route (so a connected HTTP workspace dials issues:reclaim instead
of refusing) and off the proxied provider's own accessor on the proxied
route, replacing the raw ReclaimExpiredLeases calls and
runReclaimProxiedServer. Visible changes: --json entries carry the
reverted row's new `revision`, the workspace's on_update hook fires once
per reverted row, and the version commit is the role's own
("bd: reclaim N expired lease(s)", honoring dolt.auto-commit through the
context the way bd prune does).

Tests: an embedded direct-route CLI test (scoped sweep with a live and an
absent id, revision, one version commit, on_update once) and the proxied
reclaim integration test now asserts the revision.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(roles): S9 review LOWs: one validator, field attribution, overflow bound

- The library's ValidateReclaimRequest is the one definition of a valid
  reclaim: it now also refuses a blank assignee/label/label-any/exclude
  entry, and every refusal but the id cap is a *issueops.ReclaimFieldError
  naming its field. The httpapi handler no longer checks blank entries
  itself; failReclaimErr names the member the role's error is about
  (`ids` for the cap) instead of blaming `ids` for every validation. The
  HTTP client's restatement matches, pinned field by field.
- older_than_seconds is refused at >= MaxInt64/1e9: that float rounds to
  2^63 ns, which wrapped negative under the old > check.
- New contract case RunLeaseReclaimerRefusesABlankScopeEntry on all four
  legs; handler tests for field attribution and the overflow boundary.
- CHANGELOG names the 1000-id cap on bd reclaim --id and is rewrapped; the
  client's grace-window precision comment no longer claims exactness.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(roles): S9 review: regenerate the unsupported shell, cgo-tag the embedded contract, one actor spelling

- go generate ./internal/httpclient: the new accessor moves the partial-shell
  trailer to 145 of 200.
- lease_reclaimer_contract_test.go gets //go:build cgo like its siblings, so
  the pure-Go lane compiles.
- The library trims the actor before attributing, matching the handler, so
  " alice " is attributed the same on every route.

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

* fix(roles): S9 review minors: bound the reclaim actor on every leg, pin any_replica, validate before the uow

Review minors on #7412, each in code this PR adds.

- The reclaim actor lands on every reverted row's recovery event, in a
  VARCHAR(255) column, but ValidateReclaimRequest never bounded it: a
  256-character actor passed validation on the dolt, embedded-dolt and
  unit-of-work legs and failed the sweep with the backend's own
  "Error 1105: string '...' is too large for column 'actor'" on the first
  row it would have reverted (all three legs answer exactly that with the
  bound below removed). The shared validator now holds the trimmed actor to
  types.MaxFieldLen, as claimIssueInTx does, so it is a *ReclaimFieldError
  for `actor` on every leg. The HTTP client restates the rule, and the parity
  test covers both sides of it. bd serve already refused it through the
  claim's name rules. The role's Actor and REFUSALS docs name the bound, and
  the conformance case runs it on all four legs.
- ValidateReclaimRequest's doc no longer says bd serve's handler leaves every
  rule to it: it names the three wire rules the handler adds of its own.
- TestReclaimSendsAnyReplicaOnlyWhenAsked pins the one filter member that
  widens a sweep: the client sends any_replica only when the caller set it.
- The unit-of-work leg validates before opening its unit of work, as the dolt
  and embedded-dolt legs do; TestLeaseReclaimerRefusesBeforeOpeningAUOW pins
  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: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 14:56:32 +00:00
Julian Knutsen
c4c66d42a2
ci(bazel): rebalance the proxied-server tier on rbe-west measurements (30 -> 44 shards) (#7418)
//cmd/bd:bd_proxied_test's 30-shard block was packed from a local capture
of each test's <testsuite time>, which for a t.Parallel test spans the time
it sat paused behind its shard's other tests. Cheap tests that waited
looked as heavy as the shard, so the "balanced" block ran 38-286s per shard
in CI (356s on rbe-west).

- scripts/ci/proxied_test_durations.json: re-measured on rbe-west (two
  --nocache_test_results runs), each test's cost the sum of its leaf
  tests' <testcase time>, averaged over both runs.
- Measured where a test's time goes: nearly all of it is
  `bd init --proxied-server` against the shard's dolt sql-server (~2,000
  statements, 81 DOLT_COMMITs, ~6-12 server CPU-seconds per init), one per
  subtest. Top-level tests with ~20 such subtests ran up to ~350s alone,
  above any shard budget, so the fifteen heaviest are split into two or
  three top-level functions (TestProxiedServerUpdate/-UpdateB/-UpdateC,
  ...). Each subtest is moved verbatim; the split functions repeat the
  original's preamble.
- 30 -> 44 shards, LPT-packed to <=430 cost-seconds per shard.

rbe-west, --nocache_test_results: before 30 shards, max 356s, 5,671
shard-seconds; after 44 shards, max 159s (median 138s), 5,883
shard-seconds.

Bead: ga-vnycm2.3

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-09 08:53:35 +00:00
Julian Knutsen
b162e0a482
ci(bazel): cut embedded/test lane long shards (served template, bulk seed, rebalance) (#7416)
* ci(bazel): cut embedded/test lane long shards (served template, bulk seed, rebalance)

Embedded lane (bazel-embedded):
- RunBatchGetterAcceptsExactlyTheCap seeds its 1000 issues through a new
  optional BatchGetterFixture.CreateIssues hook (one write) instead of 1000
  single-row commits. Wired for the embedded, served and dolt-server legs;
  the UOW leg keeps the per-row fallback. Same rows, same GetMany
  assertions. TestBatchGetterContract 199s -> ~7s and
  TestServedBatchGetterContract 204s -> ~7s on rbe-west.
- The served-surface harness (newServedEnv) copies one per-process,
  freshly initialized reference workspace instead of initializing an
  embedded Dolt schema per case, the same pristine-template pattern
  internal/storage/embeddeddolt's tests already use (bd-7q32v).
  //internal/httpclient:httpclient_served_test: 3,713 -> ~1,200
  shard-seconds; 24 -> 16 shards; heaviest shard 390s -> ~108s.
- //internal/storage/embeddeddolt:embeddeddolt_embedded_test: re-measured
  every test on rbe-west (scripts/ci/embedded_storage_test_durations.json)
  and repacked 15 -> 20 shards (packed heaviest ~110s; was 352s in CI).

Test lane (bazel-test):
- //internal/httpclient:httpclient_test: unsharded (137-228s) -> 2 shards
  (76s / 97s measured).

Bead: ga-vnycm2.3

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

* test(dolt): seed the BatchGetter cap case without prefix validation

The dolt-server leg's shared test store is configured with prefix "test",
so the batch CreateIssues path's prefix validation refused the fixture's
bge-* ids (the per-row CreateIssue the other seeds use does not validate).

Bead: ga-vnycm2.3

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

* ci(bazel): shard //internal/storage/embeddeddolt:embeddeddolt_test 9 ways

At 8 round-robin shards one shard drew the package's three heaviest tests
(153s on rbe-west in this PR's test lane); 9 spreads them.

Bead: ga-vnycm2.3

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-09 08:02:40 +00:00
Julian Knutsen
533f95295a
feat(httpclient): BatchApplier over HTTP — handshake cap, dep_add lineage on the wire, gc mappings (S5) (#7265)
* feat(httpclient): carry DepAddItem.HasSpawner/ThreadID over the wire

The http leg's batchApply wire shape dropped a dep_add item's HasSpawner
and ThreadID fields -- an edit the caller believed landed. Extend the
wire body (ApplyDepAddItem.has_spawner/thread_id), gate sending either
field on a new additive behavior capability
(issues.batchApply.depAddLineage / CapBatchApplyDepAddLineage) so a
client refuses locally before dialing an older server instead of
silently dropping graph lineage, and wire the storage-layer spawner-id
stamping (StampWaitsForSpawnerID) through both the dolt and uow legs
that already had the fields but never stamped them. wire_revision and
min_client are unchanged; the golden digest and openapi spec are
regenerated.

Also fixes three generic bijection/vocabulary gates this change was
missing: write_ledger_test.go's applyBatch/item/dep_add carriage table,
and the literal behaviorCapabilities lists in
internal/httpapi/server_test.go and
internal/httpclient/wire/vocabulary_test.go.

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

* test(httpclient/wire): pin the item-count gate at 356 items

Add TestApplyBatchAt356ItemsWithoutTheCapabilityRefusesBeforeDialing,
exercising internal/storage/batchfixtures.Shape356's exact item count
-- the design's primary measured large-batch-apply shape -- rather than
only the floor+1/ceiling+1 boundaries the existing cases pin. The gate
is content-agnostic (it never looks past len(body.Items)), so a
synthetic plan here is behaviorally identical to a real Shape356 plan
for this one check; realistic-content coverage follows in the next
commit.

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

* test(httpclient): prove a 356-item Shape356 plan commits atomically or leaves zero rows

Add two tests against the real served stack using
batchfixtures.Shape356's realistic, heterogeneous content (102 creates,
136 blocks edges, 102 tracks-to-root edges, 16 assign updates):

- TestServedBatchApplyShape356CommitsAtomically applies the full plan
  once and verifies every create landed with a bound key, matching the
  issues table row-for-row.
- TestServedBatchApplyShape356PlusAStaleGuardLeavesZeroRows appends a
  357th item guarding the pre-existing root issue with a deliberately
  stale ExpectedVersion. Because the root is untouched by the other 356
  items, this exercises the real server-side precondition_failed round
  trip (rather than the static same-request-row ErrValidation rule),
  asserting errors.Is(err, issueops.ErrVersionMismatch) and that none of
  the 356 creates landed -- the "never chunk" ceiling: an all-or-nothing
  request that fails on its last item must leave nothing behind.

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

* test(httpclient): close S5 review HIGH findings (lineage gate, thread_id, gc mappings)

2026-10 Opus review on the S5 batch-apply slice found the wire change
correct but coverage missing:

- HIGH-1: refuseUnservedDepAddLineage (batchapplier.go) had no coverage
  at all -- deleting it passed every existing test. Add a test pinning
  that HasSpawner or ThreadID on a server without
  issues.batchApply.depAddLineage refuses *storage.ErrUnsupported
  before dialing, and that a plan touching neither field still dials.

- HIGH-2: thread_id was never asserted end to end. Add
  RunBatchApplyCarriesThreadIDOntoTheStoredEdge to the shared
  conformance package, wire it onto the dolt, embeddeddolt and uow
  legs, and add the http leg's own case
  (TestServedBatchApplyCarriesThreadIDOntoTheStoredEdge), which is the
  one case that proves the field survives both the client's encode and
  the server's decode at once.

- HIGH-3: DESIGN Sec 3.8 ("Guarded writes: no new roles") documents two
  gc mappings onto BatchApplier that had no coverage: an update carrying
  a metadata patch plus ExpectedVersion followed by a close in one
  request (CloseWithMetadataIfMatch, atomic -- a stale version leaves
  zero changes), and a keyed create/MetadataRefs/dep_add
  (parent-child included)/trailing-update plan (ApplyGraphPlan). Document
  both compositions on the BatchApplier interface and add http-leg tests
  for each.

Mutation-verified: removing the lineage gate call, dropping thread_id on
the client's encode, and dropping it on the server's decode each now
fail a test that previously passed unconditionally.

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

* fix(httpclient): nil-guard snapshot consumers, fix spec wording, sync Bazel

2026-10 Opus review MED/LOW findings on the S5 batch-apply slice:

- LOW-6: Store.snapshot returns (nil, nil) when a Store has neither a
  wire nor a cached handshake. Store.Counter() does not call roleWire
  first (unlike Sweeper/BatchApplier), so this is reachable through the
  ordinary public accessor and a scoped count would panic on
  snap.Capabilities. Nil-guard every snapshot() consumer
  (batchapplier.go, counter.go, sweeper.go) so a nil snapshot is treated
  as "nothing advertised" and falls through to the capability refusal.
  Add TestCounterRefusesScopeGracefullyWithNoTransportAndNoSnapshot,
  mutation-verified to panic without the guard.

- LOW-7: the ApplyDepAddItem spec comment said an old server would
  "silently ignore" has_spawner/thread_id; it answers its own 400 for
  an unknown member. Fix the wording and regenerate apigen/types.gen.go.

- MED-4: internal/httpclient/BUILD.bazel was missing
  served_batch_apply_large_test.go, expected_revision_contract_test.go,
  served_dualwrite_history_test.go and the
  //internal/storage/batchfixtures dep. Sync with gazelle (confirmed
  idempotent) and go_srcs.py --check.

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

* fix(storage): carry thread_id on a same-type dep re-add; bound batch thread_id

A same-type re-add of an existing dependency compared and rewrote only
metadata, so on both write legs (issueops.addDependencyInTx and the uow
dependency repository) a re-add naming a new ThreadID was read as
change-free and the thread was dropped, and a metadata-plus-thread re-add
stored the metadata without the thread. Both arms now read the stored
thread_id through one shared rule, issueops.ReAddedDependencyThread: a
named thread the row does not carry is a change (UPDATE, replacement-edge
journal entry, exactly one version, #5898 leg 2), and a re-add naming no
thread keeps the stored one, so callers that never carry a thread cannot
erase it. The journal's EventDep has no thread member, so a thread-only
re-add journals the same payload as the original add; the source's version
snapshot is what records the new thread, and the comments on both arms now
say so instead of promising a complete replacement edge.

planApplyBatchDepAdd bounds DepAddItem.ThreadID with CheckFieldLen, so an
over-long thread id is ErrValidation before any database work on every
leg, as the http leg's decode already refuses it, instead of an opaque
mid-transaction "string too long" on the local legs. Only the length bound
is shared: the http leg's control-character refusal stays http-only.

The HasSpawner/ThreadID docs now name the producer that actually sets
HasSpawner (an embedder lowering a graph plan, e.g. gc's ApplyGraphPlan
mapping) instead of bd create --graph, and drop the CHANGELOG reference
that had no entry behind it.

New conformance cases, wired on dolt, embeddeddolt, uow and served:
RunBatchApplyCarriesThreadIDOntoAnExistingEdge,
RunBatchApplyRefusesAThreadIDLongerThanItsColumn and
RunDependencyEditorSameTypeReAddWithChangedThreadMintsOneVersion.

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

* ci(shards): add the re-add thread test to the embedded storage shard manifest

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

* ci: trigger the first PR CI run now that the base is main

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

* fix(httpclient): gate has_spawner to waits-for edges; refuse empty thread_id

Review iteration 1 fix-up for #7265 (synthesis F1, F2, F4, F5, F6, F7).

F2: the client's CapBatchApplyDepAddLineage gate refused HasSpawner on
every edge type, but the role reads the flag on a waits-for edge only
(StampWaitsForSpawnerID is a no-op off one). An embedder plan setting it
on, say, a blocks edge works against every existing server, yet this
client refused it during a mixed-version rollout. depAddNamesSpawner now
holds the role's own rule: the flag is gated and encoded on a waits-for
edge only, and dropped elsewhere, which loses nothing the role would
store. ThreadID stays gated on every edge type, since a thread is stored
on all of them. The "spawner flag on any other edge type" subtest is
restored to an unadvertising server and now also asserts the flag is
dropped from the body, and
TestApplyBatchRefusesUnservedDepAddLineageBeforeDialing gains a
ThreadID-on-blocks case. The W-DepAddItem.HasSpawner ledger row and the
regenerated engdocs/design/http-divergence-ledger.md say the same.

F5: the document gives thread_id minLength: 1, but the decoder read an
empty string as no thread. applyDepAddItem now refuses a present, empty
thread_id with 400 invalid_value naming items[i].dep_add.thread_id, as
it does an empty type; an absent one still names no thread. New
TestApplyBatchRefusesAnEmptyThreadID; the documented-body test now
forwards has_spawner and thread_id as well.

F1: bd create --graph does set HasSpawner (buildGraphApplyBatchRequest,
on the embedded and proxied legs, since #7209), so the DepAddItem doc
names both producers again and the conformance doc's CHANGELOG pointer
is restored; the [Unreleased] entry behind it is on the base.

F4: the CapBatchApplyDepAddLineage comment said an older server would
silently drop the members; it answers either one with
400 invalid_argument/unknown_parameter.

F6: the create-edge ledger comment said no operation publishes a thread
member; batch apply's dep_add item now does.

F7: TestServedBatchApplyGcApplyGraphPlan adds a waits-for item carrying
HasSpawner and ThreadID and reads the stored row back, pinning
metadata.spawner_id to the resolved spawner and the thread on the
served leg.

F3 (the journal's EventDep carries no thread member) is not addressed
here.

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

---------

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
Co-authored-by: Eddie the Engineer <adopt-pr@gascity.com>
2026-10-09 01:05:39 +00:00
Julian Knutsen
5126de8c1a
perf(bd): no git subprocesses on read-only commands (in-process repo discovery, lazy actor, backup probe) (#7400)
* perf(git): locate the repository in-process instead of running git rev-parse

Every bd invocation resolved the process-wide git context (beads directory
discovery reads it) with `git rev-parse --git-dir --git-common-dir
--show-toplevel`: one git subprocess per bd call before any work. Tools that
call bd hundreds of times (gascity's doctor issues ~250 bd calls per run)
paid it on every call.

On Linux, initGitContext now first runs discoverGitInProcess, which mirrors
Git's discovery walk (physical cwd, .git as directory or gitfile, bare-dir
check, filesystem-boundary stop) and produces byte-for-byte what rev-parse
prints for ordinary repositories (top and subdirectories), linked worktrees
(absolute or relative gitfile, symlinked targets), submodules (core.worktree
pointing back at the gitfile's directory), nested repositories and no
repository. Both answers feed one shared normalization
(gitContextFromRevParse), so downstream values are unchanged.

It declines, and git runs exactly as before, whenever it cannot prove the
answer: GIT_DIR / GIT_WORK_TREE / GIT_COMMON_DIR / GIT_CEILING_DIRECTORIES /
GIT_DISCOVERY_ACROSS_FILESYSTEM / GIT_OBJECT_DIRECTORY / GIT_CONFIG_PARAMETERS
/ GIT_CONFIG_COUNT in the environment; a symlinked .git, an invalid gitfile
or git directory, a cwd inside a git directory; repository config with
core.worktree (other than the submodule shape), core.bare, extensions,
include directives, a format version above 1 or unmodeled syntax; any path
not owned by the effective uid (safe.directory is git's to evaluate), or
root under sudo. darwin and windows keep the subprocess (case folding and
ownership semantics).

Tests compare discoverGitFrom with real `git rev-parse` output across those
layouts, pin every decline case, and check the resulting cached context
equals the subprocess-derived one.

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

* perf(cli): resolve the git user.name actor fallback only when needed

PersistentPreRunE assigned `actor = getActorWithGit()` for every command,
which, with no --actor / BEADS_ACTOR / BD_ACTOR / config actor, runs
`git config user.name`: the second git subprocess of every bd call, paid
by read-only commands that never consult the actor.

The pre-run now calls deferActorGitFallback, which marks an empty actor as
pending; currentActor (and getActorWithGit, getActor) resolve it on first
use with the unchanged priority order and store it in the global and the
CommandContext copy, as the eager assignment did. Command code reads the
actor through currentActor() instead of the raw global (a mechanical
rewrite of every read site the compiler reported; writes, the flag binding
and the pre-run config binding keep the raw variable). setActor cancels a
pending fallback. The telemetry span's bd.actor attribute is still set, but
only for a recording span, so a noop span does not force the lookup.

With the in-process repository discovery from the previous commit, a
read-only `bd list` / `bd show` now starts no git process at startup, in
the main checkout and in a linked worktree; a write asks git for user.name
once (bd create previously asked once, now still once) and records the same
value. Measured on 50 sequential `bd list` calls: 100 -> 0 git execs
(embedded and proxied-server workspaces, main checkout and worktree).

TestEmbeddedReadOnlyCommandsSpawnNoGit counts git execs through a PATH shim;
TestDeferredActorGitFallback pins the deferral semantics.

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

* fix(git): decline in-process discovery on any config line git might read differently

Review follow-ups to the in-process repository discovery.

- The repository config scanner was looser than git: a config starting with
  a UTF-8 BOM followed by `[core] worktree = /other` made git report /other
  while discovery returned the cwd repository, and `[ core ]` or `!!! = x`
  (which git refuses) were accepted. scanGitConfig (gitconfig_linux.go) now
  skips a leading BOM exactly as git does and accepts only a narrow grammar:
  blank/comment lines, `[section]` / `[section "sub"]` headers at column 0,
  and `key` / `key = value` lines inside a section, with values free of
  backslashes and unbalanced quotes. Any other line declines to git.
- Walk from getcwd(2) (syscall.Getwd), as git does, instead of os.Getwd,
  which trusts $PWD when it names the same inode (bind-mount aliases).
- Resolve relative gitfile and commondir targets without filepath.Join's
  lexical Clean, so "link/.." resolves physically like git's realpath.
- A mount-boundary stop reports its own reason in the not-a-repository
  error.
- Tests: every decline case (BOM + core.worktree, malformed headers and
  keys, keys before a section, escapes, continuations, bare repositories,
  a commondir inside .git, ...) now also checks that what startup derives
  equals git's answer; BOM and CRLF/comment configs are equivalence cases;
  the no-repository case must be answered in-process instead of skipping;
  a $PWD alias test pins the getcwd walk.
- The exec-count test drops every GIT_* variable except the config-file
  selectors, so a runner exporting GIT_CONFIG_PARAMETERS & co. cannot make
  it fail spuriously.
- Comment the two places that touch the raw actor before the deferral.

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

* perf(backup): decide embedded auto-backup's git-remote probe without git

In an embedded workspace whose backup.enabled is unset, maybeAutoBackup
asks isBackupAutoEnabled -> primeHasGitRemote after every command, reads
included. That built a RepoContext (`git -C .beads rev-parse
--git-common-dir`) and ran `git remote`: two git processes per read even
after the startup calls were gone. The throttle cannot short-circuit it:
without a remote no backup ever runs, so there is no backup state to
throttle on.

Both probes are now answered in-process when provable, and the subprocess
remains the fallback, so the decision and every warning/notice downstream
of it are unchanged:

- internal/beads getGitCommonDirForPath uses git.CommonDirInProcess (the
  discovery walk from the given directory, git's spelling).
- primeHasGitRemote uses git.HasRemoteInProcess in the same directory
  primeGitCmd would run git in (primeGitDir, factored out). It answers only
  when every config file `git remote` reads -- system (GIT_CONFIG_SYSTEM, or
  /etc/gitconfig and <prefix>/etc/gitconfig of the git on PATH), global
  (GIT_CONFIG_GLOBAL, or XDG and ~/.gitconfig) and the repository's own --
  is absent or within scanGitConfig's grammar and include-free, no
  GIT_CONFIG_PARAMETERS/COUNT/GIT_CONFIG or discovery override is set, and
  no legacy .git/remotes or .git/branches entries exist. A remote seen only
  in a system-config candidate declines. Remote names outside
  [A-Za-z0-9._-] decline.

Tests compare HasRemoteInProcess with `git remote` (no remote, local,
worktree, submodule, remote.pushDefault only, global remote, no repo) and
pin the declines (global include, malformed global, command-line config);
CommonDirInProcess is compared with `git -C dir rev-parse
--git-common-dir`. TestEmbeddedReadOnlyCommandsSpawnNoGit now runs with
backup.enabled at its default, with and without a git remote, and still
expects zero git processes for list/show.

Agent-Signature: claude-code-claude-opus-5-5-medium 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-08 20:08:24 +00:00
Bee
c3a97e172d
show/list: render a derived GATED decoration when an open gate holds the bead (#6606)
* wy-j2upyy: render the derived GATED decoration on bd show and bd list

A bead an open gate blocks is excluded from `bd ready` but rendered
`[P2 · OPEN]` by `bd show` and with a plain ○ by `bd list`, so the human
surfaces disagreed with the readiness query.

The decoration is DERIVED, never stored: no status write, no --status
filter change, no existing JSON field reshaped.

- internal/types/gated.go: IsActiveGate, the ONE predicate — a gate-typed
  dependency reached over a blocking edge (blocks / conditional-blocks /
  waits-for) whose status is neither closed nor pinned. That is the
  is_blocked recompute's blocking leg restricted to gates, so a rendered
  GATED and a `bd ready` exclusion cannot disagree. GateDescription /
  GateReason own the reason's round trip with `bd gate create`.
- bd show: `[P2 · OPEN · GATED]` plus one `Gated by: <id> (<type>[:
  <reason>][, awaiting <await-id>])` line per gate, beside Deferred:. The
  dependency read the DEPENDS ON section already made is hoisted, so the
  decoration costs no extra query.
- bd list: ⊘ in the glyph column (circle family, distinct from ○ and ❄),
  and a legend entry when the page carries one. Batched by id set —
  at most two extra queries per listing, one in the tree view where the
  edge map is already loaded.
- --json: additive `gated_by: [{id,type,reason}]` on the detail view,
  omitted when empty; documented in the OpenAPI IssueDetails schema.

Tests (red first): cmd/bd/gated_render_embedded_test.go drives real
bd show/list/--json over an embedded rig — gated, resolved, deferred+gated,
JSON additivity — plus pure unit tests for the predicate and formatters.

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

* wy-j2upyy: document the additive gated_by field in the JSON schema reference

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

* wy-j2upyy: cover the flat list route's own batched gate read

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

* wy-j2upyy: make GATED the readiness rule's gate clause, both halves

The adversarial review found the "one predicate shared with bd ready" claim
false on two axes, and both were reproducible by hand:

BLOCKER 1 — waits-for is not the status rule. The is_blocked recompute applies
"target not closed and not pinned" only to its blocks / conditional-blocks
legs; the waits-for leg goes through waitsForGateBlockedSQL, a fanout over the
target's open parent-child children (or an also_blocks spawner). A plain
`bd dep add X G -t waits-for` onto an open childless gate therefore leaves X
in `bd ready` while every new surface called it GATED. Mirroring that leg in
Go would be a second implementation of a rule the database owns, so the edge
clause now names the two legs it really mirrors (types.IsGateEdge) and the
test that pinned the wrong direction is flipped.

BLOCKER 2 — the subject half was missing and spelled three different ways.
unmarkAllBlockedSQL forces is_blocked=0 for a closed or pinned subject
whatever its edges say, so `bd ready` never withholds one on a gate's account;
show and workapi filtered nothing, cmd/bd/gated.go filtered closed only, and
list_format.go filtered closed at two more sites. A force-closed bead rendered
[CLOSED · GATED] with gated_by on show while list showed a plain row — show
and list disagreeing about one bead, which is the drift this was meant to
prevent. The clause is now types.SubjectCanBeGated, asked once in
types.GatesHolding (which replaces ActiveGates and takes the subject) and once
in the listing helper that has no hydrated deps; the formatters re-ask the SAME
exported predicate rather than inventing a fourth spelling.

SHOULD 3 — agent mode computed the gate reads and threw them away, in every
CLAUDE_CODE seat, i.e. the population that filed the bug. Decorating it is the
real fix, so gatesByIssueID now returns the gate IDS and formatAgentIssue
carries "gated by: <id>" in the parenthetical it already prints. A gate is
also a blocker, so its id appears under both "blocked by" and "gated by": the
first says what to wait on, the second says which of those nobody can clear by
doing more work. --long and --format render no gate and no longer pay for the
reads.

NOTE 5 — a pinned+gated row kept ⊘ instead of 📌; with the subject clause a
pinned bead is not gated at all, so the pin survives by construction.
NOTE 6 — the cost comments claimed "two queries" / "exactly ONE"; the id-set
readers are a few round trips each. The bound that is real (per page, never
per row) is what the comments now say.

Tests, red-first: the flipped waits-for case; TestGatesHoldingSubjectStatus and
TestSubjectCanBeGated (open/in_progress/deferred yes, closed/pinned/nil no);
TestFormatIssueCompactGated and TestFormatAgentIssueGated; and four embedded
arms — a waits-for edge that bd ready lists and no surface decorates, a
force-closed subject and a pinned subject that render nothing and publish no
gated_by, and the agent line naming its gate. Each was watched to fail against
the pre-fix predicate before it passed.

Ran: go test ./internal/types/ -run 'TestGateIsHolding|TestGatesHolding|
TestSubjectCanBeGated|TestGateDescriptionRoundTrip|TestGateRefsProjection';
go test ./cmd/bd/ -run 'TestFormat*Gated|TestFormatIssueCompact*|
TestFormatDependencyInfoWithParent|TestListRoles*|TestDisplayPrettyList*';
BEADS_TEST_EMBEDDED_DOLT=1 go test ./cmd/bd/ -run TestEmbeddedGatedRendering
(11/11 subtests); gofmt -l (empty), go vet and golangci-lint on cmd/bd,
internal/types, internal/ui, internal/workapi; scripts/ci/pr-policy.sh.

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

* wy-j2upyy: render GATED on the proxied `bd show` text route

SHOULD 4 of the review, and required for this rig: the constellation runs
proxied-server, where `bd show --json` already carried gated_by (uow
issue_reader -> workapi.BuildIssueDetails) while the TEXT renderer called the
plain formatters. The same bead read two ways from the same server disagreed.

proxiedRenderIssue now hoists the outgoing-edge read it already did for the
DEPENDS ON section above the header — the gates are the gate-typed subset of
that very set, so the decoration costs no extra query — and passes them to
formatIssueHeaderWithGates / formatIssueMetadataWithGates. The proxied LIST
routes were wired in the previous commit.

TestProxiedServerGatedRendering covers all five text surfaces plus the JSON
one beside them (header + Gated by line, pretty glyph, compact glyph + "gated
by", agent line, and a closed subject that renders nothing). Watched red first
with the proxied decoration stubbed out: four of six subtests failed, and the
--json arm passed, which is exactly the asymmetry the review reported.

Ran: BEADS_TEST_PROXIED_SERVER=1 go test ./cmd/bd/
-run TestProxiedServerGatedRendering -count=1 (6/6, 37.8s).

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

* wy-j2upyy: put cmd/bd/state.go on the shared "Reason:" marker

NOTE 7 of the review: types' gateReasonMarker was not gate-private —
cmd/bd/state.go wrote the same "\n\nReason: " into state-change EVENT
descriptions from its own literal. No live collision (events are not
gate-typed), but the constant's doc claimed GateReason returns "" for every
gate not made by `bd gate create`, and that is false for any description
carrying the marker.

The previous commit exported the constant as types.ReasonMarker, reworded
GateReason to say what the pair really guarantees (a round trip, not a
provenance check) and pinned the honest behavior in
TestGateDescriptionRoundTrip. This commit is the second writer: state.go now
builds its event description from the same constant, so the two cannot drift
apart by accident.

Ran: go build ./...; go test ./internal/types/ -run TestGateDescriptionRoundTrip
-count=1; gofmt -l cmd/bd/state.go (empty); go vet ./cmd/bd/.

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

* wy-j2upyy: alias types.GateRef in package backend

gated_by on IssueDetails makes GateRef reachable from the public backend
contract; TestPublicSurfaceComplete requires every such type to carry an
alias here.

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

* wy-j2upyy: build(bazel): register gated.go and its tests in cmd/bd and internal/types

The rebase onto e766da5ed carried the new source files but not their
BUILD.bazel entries, so every Bazel lane failed to compile internal/types
(undefined: GateRef). This is CI's own bazel-sync patch for 9ad7eb96c3,
applied unchanged.

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

* wy-j2upyy: compute gated_by AFTER the dependencies read in BuildIssueDetails

The be-lpi merge (#6352) moved src.Dependencies() below the cardinality
counts so the unresolvable-edge delta reads count-first. That hunk merged
cleanly, which left details.GatedBy computed on the still-nil slice, and
both CI shards' show_json…carries_gated_by subtests went red (PR Risk
Embedded Dolt Cmd 20/20, Proxied Dolt Cmd 4/15 at d21237f3dc).

Move the GatedBy line to directly after details.Dependencies = deps, still
before the BriefDeps trim that rewrites the slice, and pin the ordering with
a workapi unit test over both DetailSource seams and BriefDeps on/off (red
on the pre-fix code, green after).

Ran: go test ./internal/workapi; go vet ./internal/workapi;
BEADS_TEST_EMBEDDED_DOLT=1 go test ./cmd/bd -run TestEmbeddedGatedRendering;
BEADS_TEST_PROXIED_SERVER=1 go test ./cmd/bd -run TestProxiedServerGatedRendering.

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

* ci: register #6606's gated-rendering tests and gated_by wire shape with main's generated gates

Maintainer fixup for adopt-pr #6606. The adopted head merges the PR head
(c43eb567d2) into main (800d43eb8d). The PR's merge-base (02f05340f6)
predates three generated artifacts on main that every PR adding a cmd/bd
tier test or a wire member has to keep current, so the merged tree is red
on them even though the PR's own CI cannot see them:

- .github/scripts/embedded-cmd-test-shards.txt: the Bazel-only 50-shard
  block must name every TestEmbedded* test exactly once, or
  TestCmdEmbeddedShardManifestGeneratorNotStale fails `go test ./scripts/`.
  `gen_embedded_cmd_shard_manifest.py 50 --weights=duration --write`
  (incremental) placed TestEmbeddedGatedRendering on shard 16 and moved
  no existing assignment; the frozen 20-shard block is untouched.
- .github/scripts/proxied-cmd-test-shards.txt: likewise for the 30-shard
  block and TestProxiedServerGatedRendering (shard 2), via
  `gen_proxied_shard_manifest.py 30 --weights=duration --write`, so
  TestProxiedShardManifestGeneratorNotStale passes.
- internal/httpapi/wireshape/testdata/golden.json: TestWireShapeDigest
  (#7182) pins every response member. `go run
  ./internal/httpapi/wireshape/cmd/gendigest` recorded the PR's new
  IssueDetails.gated_by array and its id/type/reason members as four pure
  additions (+25/-0), so no wire_revision bump is owed.

The PR's own files are unchanged.

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

* docs(gated): state gated_by one way, mark --watch as undecorated, fix stale refs

Review follow-ups for #6606. Comment and doc text only; no behavior change.

- gated_by is now documented in one direction. internal/types/types.go,
  internal/types/gated.go and docs/reference/json-schema.md said the list
  is nonempty EXACTLY when `bd ready` withholds the issue on a gate's
  account. Only one direction holds: the is_blocked recompute also blocks
  a child whose parent is blocked (its parent-child legs), so a child of a
  gated parent leaves `bd ready` with an empty gated_by. All three now say
  "nonempty means withheld", as the OpenAPI text already did, and name the
  parent-child case.
- bd list --watch passes a nil gated map on both routes
  (runListProxiedWatch, displayWatchedIssueList), so a bead the one-shot
  listing marks with the gated glyph keeps its plain status glyph while
  watched. Watch is out of this PR's scope; the three call sites now say
  so instead of reading as a forgotten argument.
- show_format.go named types.ActiveGates, which does not exist; the
  predicate is types.GatesHolding.
- gated.go's best-effort note compared the gate read with `bd list`'s
  blocking annotation, which only the direct route swallows. It now scopes
  that comparison to the direct route and names the proxied route's
  failing read (A-blk-1).
- proxiedGatedIssueIDsOwnUOW now notes that its unit of work is a second
  snapshot, so one render can name a just-resolved gate under "blocked by:"
  but not "gated by:".

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

* fix(list): hydrate proxied gate candidates from both planes (bd-p8k7dm)

The proxied list resolved gate candidates through the use case's
GetIssuesByIDs, which reads the issues table only, while the edges it
resolved came from GetForIssueIDs, which reads both dependency tables.
A wisp gate (`bd mol wisp` clones a formula's gates as wisps, held to a
wisp step by a blocks edge) therefore hydrated to nothing. Its step
listed undecorated in pretty, --flat and agent output while `bd show`,
`--json` and `bd ready` called it gated.

Read the wisps beside the issues, the two-plane idiom
ready_proxied_server.go and uowMolReader already use. A failed wisps
read keeps the durable candidates. Correct the cost-bound comment that
claimed the id-set readers partition the planes on both routes.

Tests: a wisp-step + wisp-gate case in TestProxiedServerGatedRendering
and TestEmbeddedGatedRendering asserts the pretty, --flat and
CLAUDE_CODE=1 rows of `bd list --include-ephemeral`, and
TestProxiedGatedIssueIDsHydratesBothPlanes pins both planes plus the
failed-wisps-read fallback.

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

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-authored-by: Eddie the Engineer <adopt-pr@gascity.com>
2026-10-08 10:37:51 +00:00
Steve Yegge
70f9e2f8a3
Beads 1.2 remediation: migration-consent gate — bd never migrates an existing database without explicit consent (#5764)
* feat(schema): never migrate an existing database without explicit consent (bd-qhn8y)

Beads 1.2 release remediation. 1.2.0/1.2.1 auto-applied migrations 54-65 at
store open on ANY command, including reads; older binaries then refuse the
migrated database. MigrateUp now refuses pending main-sequence migrations on
an existing database before any write (dolt_ignore seeding included) unless
the operator consented: bd migrate / bd migrate schema (preview flags
withhold), bd migrate --force, or BD_ALLOW_MIGRATE=1
(BD_ALLOW_REMOTE_MIGRATE honored as an alias). Fresh init and at-latest
databases are unaffected; the #4259 remote gate keeps all its protections.

Also: freeze shipped migrations (hash-pin test, main 0001-0065 + ignored
0001-0024), retract v1.2.0/v1.2.1 in go.mod, agent-executable un-migrate
runbook (docs/recovery/unmigrate-schema-v65.md), and the upgrade smoke +
historical migration harnesses now model the consent contract and assert
the refusal carries guidance.

No version bump here by design: cutting the release stays with the release
owner.

Rebased onto main 800d43eb8d: the go.mod retract hunk is dropped -
main already retracts v1.2.0/v1.2.1 (and v1.1.1) since #5782. The
uow consent grant moves into the TestMain main added in #6441 (a
second TestMain no longer compiles), and the new files are listed
in the BUILD.bazel targets main now carries (gazelle).

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

* fix(schema): cloned-workspace bootstrap carries creation-consent (bd-qhn8y)

The consent gate treated a workspace `bd init --remote` / `bd bootstrap`
just cloned into existence like a pre-existing database, refusing the
smart gate's provably-safe first-mover migration and stranding init in
the generic open-error path (bypassing the bd-4mpy7 finalize+guidance
ergonomics). Cloning IS creating: those paths now record consent
explicitly, and the #4259 remote-migrate gate still applies to them
unchanged (consent is not its designated-migrator override). Fixes CI
TestEmbeddedInit/remote_behind_schema_gate.

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

* test(migration): consent first in main's wisp lanes too (bd-qhn8y)

The rebase onto 800d43eb8d brought in #6049's wisp-plane lanes, which
postdate this PR's harness changes. Each one makes an ordinary candidate
command the first touch on an old-schema database, and the consent gate
refuses it:

- historical-dolt-upgrade-test.sh run_wisp_plane_upgrade opens with
  `bd list` before any migrate: "candidate could not open the seeded
  wisp workspace" for v1.0.1, v1.1.0, v1.1.2 and v1.2.2 (the
  Migration Test Harness dolt-runtime shard).
- run_dirty_tracked_wisp_scenario (v1.1.2): the consent refusal stops
  the open before MigrateUp reaches the #5816 dirty tables, so the lane
  fails "without naming them".
- upgrade-smoke-test.sh "Wisp plane survives upgrade" upgrades with a
  bare cand_init, so list/ready/blocked/update all hit the refusal
  (4 failures each for v1.3.0 and v1.3.1, both in the PR smoke set).

Use the PR's own pattern: the explicit `bd migrate schema` is the first
candidate touch (cand_upgrade in the smoke script). Base 800d43eb8d
passes these lanes unchanged; with this fixup the full 14-version
historical corpus and all five PR smoke versions pass.

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

* fix(schema): close consent-gate review findings (bd-qhn8y)

Review fixes for the migration-consent gate (adopt-pr review, attempts
1 and 2).

Majors:

- #4566 deadlock rebuilt one check earlier: on a database that is both
  behind and dirty, the consent refusal fired before the dirty-table
  guard, whose remedy (`bd dolt commit`) opens without consent. The
  working-set-reconcile opens now tolerate MigrateConsentError: embedded
  (toleratesConsentRefusal, WSR intent only) and server mode
  (LenientOpen's warnLenientOpenRefusal) print WorkingSetWarning and
  commit at the current schema; strict, read-only and RemoteSync opens
  still refuse. Covered by an embedded test (a refused open writes
  nothing: dolt_status, dolt_ignore and schema_migrations unchanged) and
  a server-mode integration subtest.
- Bare `bd migrate` consented: isMigrateConsentCommand now matches only
  the schema verb, so `bd migrate` (metadata reconcile, including
  --update-repo-id, --inspect and --dry-run) no longer consents to a
  one-way migration; `bd migrate schema` and --force do.
  TestLocalMigrateConsentScope pins the scope through the root pre-run.
  The dirty-table warnings name `bd migrate schema` accordingly.
- Runnable JSON hint: the JSON refusal follows the #4259 AgentDirective
  convention, a non-runnable hint plus a migrate_consent object
  (versions, pending, severity, human_decision_required, options) whose
  commands are retargeted with --global for the shared global database.
  The text refusal prints the same --global hint under `bd --global`.
- Freeze floor: the hash-pinned freeze now covers what v1.3.x shipped,
  main 0001-0066 and ignored 0001-0026; the CHANGELOG puts new
  migrations in 0070+ / 0028+.
- Fresh-bootstrap heal: MigrateUpWithLock with heal authority takes the
  consent-free migrate path, so a retried bd init whose first pass left
  a non-zero cursor converges; other lock callers keep the gate.

Minors: the uow team-server guards are repinned on `bd migrate schema`;
the un-migrate runbook is linked from the recovery index and
cross-linked with the 1.2.1 repair-forward doc; the CHANGELOG BREAKING
entry matches the shipped contract; harness comment grammar.

Docs: the user docs and README named bare `bd migrate` as the step that
applies schema migrations; they now say `bd migrate schema`, which also
exists in the pinned docs release (v1.2.2) and in v1.3.x. The
`bd migrate schema` help no longer claims migrations run automatically
on store open. The Go remedy that sends a remote-gate stop to bare
`bd migrate` for its migrate-or-adopt options is unchanged (pinned by
TestNoticeSharedMigrateRefusalPerDecision).

Upgrade smoke (attempt 2): the consent-gate assertion is graded only when
the old binary left a database. Releases before v1.0 have no
`init --non-interactive`, so prev_init creates nothing there and the
candidate's `bd list` fails with "no beads database found", which has no
consent guidance. Main's Bazel smoke lane (#7331) runs the newest 30
releases, 20 of them pre-1.0, under the required ci-gate; all 20 went red
on the merge. The 10 v1.x releases still take the refusal branch.

Shard manifest (pre-approval CI): the new embedded test
TestEmbeddedMigrateConsent_BehindAndDirtyWorkingSetReconcileRecovers is
listed in the Bazel 15-shard block of embedded-storage-test-shards.txt
(incremental --write; shard 15). Main's ci lane runs
TestStorageEmbeddedShardManifestGeneratorNotStale in //scripts:scripts_test,
which fails on any unlisted top-level embeddeddolt test.

Not addressed (optional): env-only consent docs for embedders, the
unparseable BD_ALLOW_REMOTE_MIGRATE alias hint, and the harness
`|| true` on `cand migrate schema`.

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Co-authored-by: Eddie the Engineer <julianknutsen@users.noreply.github.com>
Co-authored-by: Eddie the Engineer <adopt-pr@gascity.com>
2026-10-08 08:21:31 +00:00
Bee
9b251db072
test(proxied): split TestProxiedServerClose into three parents with legacy rollback pins (#7173)
* test(proxied): split TestProxiedServerClose into Close + Close3 so legacy shard 5 clears the 15m timeout (#7151)

Shard 5 of the legacy 15-shard proxied-server block walled at 927-941s
(go test's 15m timeout) on every measured fork-PR and main run while the
other 14 shards took 337-765s. #7172 pinned the two hash-placed tests
that pushed it over; the parent that dominates the shard remains:
TestProxiedServerClose carries 23 parallel bd-init subtests at 100-130s
apiece under 4-way contention, ~2060 of the shard's ~2712 slot-seconds.

Split it the way TestProxiedServerClose2 was split before: subtests from
close_blocked_refuses_without_force onward (12 of 23) become
TestProxiedServerClose3 with the same header; no subtest body changes.

Manifest: an explicit `15 6 TestProxiedServerClose3` line in the frozen
block (shard 6 is the lightest shard by CI job time that took no #7172
pin; without the line cksum fallback could hash it back onto 5), and
`30 17 TestProxiedServerClose3` beside Close in the Bazel 30-shard block,
which keeps every 30-shard load where it was (heaviest still 372.2s
est.). proxied_test_durations.json apportions the single 174.6s Close
capture by bd-init count (83.5 / 91.1) and says so in its header; the
next sweep replaces both.

Verified: gen_proxied_shard_manifest.py 30 --weights=duration --check
(exit 0); go test ./scripts/ -run 'Shard|Manifest|Coverage'; go vet
./cmd/bd/; BEADS_TEST_PROXIED_SERVER=1 BEADS_TEST_REQUIRE_DOLT_CONTAINER=1
go test ./cmd/bd/ -run '^TestProxiedServerClose3?$' -v: both PASS
(32.24s / 30.53s, 23 subtests).

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

* ci(proxied): pin TestProxiedServerClose3 onto legacy shard 1, not 6 (#7151)

Shard 6 timed out at 15m on this PR's own run (job 111387202139) with
Close3 added: Close3 passed in 5s but TestProxiedServerClose2's
subtests, sharing the 4 parallel slots and the one proxied server with
Close3's 12 bd-init subtests, were still running at 1m18s-2m31s each
when the alarm fired. On main at b1a0690249 shard 6 runs 9m and shard 1
6m, the lightest of the 15 (15: 8m), so shard 1 has the headroom for
the ~6 min of 4-slot wall the 12 subtests cost.

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

* test(proxied): split TestProxiedServerClose3 again into Close3 + Close4 (#7151)

Shard 1 timed out at 15m on this PR's own run (job 111392255572) with
Close3 pinned there: Close3's 12 bd-init subtests finished at 3m33s, but
they held the 4 parallel slots long enough that TestProxiedServerDep2's
subtests only began at 5m35s and were still running when the alarm
fired. Shard 6 did the same before it. Meanwhile shard 5, the shard this
PR exists to relieve, ran 5m with the first 11 subtests.

So 12 inits in one parent is too much for any host shard. Close3 keeps
its first six subtests on shard 1; the last six become
TestProxiedServerClose4, pinned to shard 7 (7m on that run). The
durations file apportions the one 174.6s capture 11/6/6.

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

* ci(proxied): move the Close3 and Close4 pins off legacy shards 1 and 7 onto 13 and 2 (#7151)

The run at 765248af5 put every Proxied Dolt Cmd shard green, with shard 5
down from the 15m alarm to 5m50s. But shard 1, chosen for Close3 as "the
lightest of the 15 on main", ran 14m48s there, the heaviest of the
fifteen: TestProxiedServerDep2's 29 parallel bd-init subtests alone take
about 10.5 minutes of 4-slot wall on this lane, and Close3's six init
subtests landed on top of them. Shard 7, where Close4 went, ran 13m50s
behind TestProxiedServerReady and TestProxiedServerState.

Pin Close3 onto shard 13 (6m51s on that run) and Close4 onto shard 2
(7m57s). Not shard 5: it is light only because Close left it, and
putting Close3 back would recreate most of the set that timed out. The
30-shard Bazel block is unchanged.

Verified: BEADS_TEST_SHARD_LIST_ONLY=1 .github/scripts/proxied-test-shard.sh
13 15 lists Close3 and 2 15 lists Close4, neither on 1 or 7;
gen_proxied_shard_manifest.py 30 --weights=duration --check exit 0;
go test ./scripts/ -run 'Shard|Manifest|Coverage' ok.

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

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-08 06:53:13 +00:00
Bee
8bb99b49d8
fix(close): verify bead gates on the proxied-server route (#5861 item 1) (#6962)
* fix(close): verify bead gates on the proxied-server route (wy-j48b3y)

The close pre-check built its bead-gate lookup on the local store, which
the proxied-server route never opens (the root pre-run short-circuits to
uowProvider). So `bd close <gate>` on a bead gate refused with
"no local store available" there even after the awaited bead had closed,
while `bd gate check` resolved the same gate through its fresh-read
getter. Item 1 of #5861.

The pre-check now picks the getter by route: proxied-server reads through
the same proxiedFreshReadGetter gate check uses (local read, then prefix
routes); direct and embedded keep the store-backed routed getter.

Tests: a proxied integration test covers the open-target refusal (which
now names the target's status), the closed-target close, and --force;
against the old code it fails with the exact upstream refusal. A unit
test pins the route selection. Docs and CHANGELOG drop the limitation.

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

* ci(shards): list TestProxiedServerCloseBeadGate in the proxied 30-shard manifest

#7129 turned the Bazel 30-shard block of
.github/scripts/proxied-cmd-test-shards.txt into an exact-once coverage
gate (TestProxiedShardManifestGeneratorNotStale in scripts/). This PR's
merge-base predates that gate, so after the rebase onto current main the
gate fails with "missing (1): TestProxiedServerCloseBeadGate", the
proxied integration test this PR adds.

Generated with the gate's own fix command,
`python3 scripts/ci/gen_proxied_shard_manifest.py 30 --weights=duration --write`.
The write is incremental: it puts the one name on the lightest shard (2)
and moves no existing assignment. The frozen 15-shard block is untouched.

Agent-Signature: claude-code-unknown-model-max on behalf of Eddie the Engineer
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
Co-authored-by: Eddie the Engineer <adopt-pr@gascity.com>
2026-10-08 06:01:18 +00:00
Julian Knutsen
143c418148
ci(bazel): cut per-lane fixed cost — LLVM .tar.zst slice, release cross-compile lane, no protoc build (#7379)
* ci(bazel): fetch the LLVM toolchain as a 149 MB slice; re-key the runner cache

Port of gascity #7279. @llvm_dist_linux_x86_64 downloaded the 1.94 GB
LLVM-22.1.8-Linux-X64.tar.xz and ran a single-threaded `tar -xJf` over
11 GiB to keep a 688 MB slice. That took 94-147 s in every Bazel lane,
and every cgo, race and stdlib action waits on it.

- llvm_dist.bzl gains `sliced`: download_and_extract of a members-only
  .tar.zst, plus a missing-member check. The xz path stays.
- MODULE.bazel pins the toolchain-llvm-22.1.8-slice-1 asset by sha256
  (de614777...6bec5). The URL is gascity's release asset for now; the
  list form leaves room for a beads mirror of the same bytes.
- tools/cc_toolchain/repack_llvm.sh and llvm_members.txt rebuild the slice
  from the pinned upstream release.
- Runner cache v4, keyed on MODULE.bazel too. MODULE.bazel.lock does not
  record llvm_dist, so the v3 key never changed and kept restoring the
  2.9 GB entry that holds the xz archive.
- bazel_hermetic_cc_test: a sliced llvm_dist may only download from a
  gastownhall/beads or gastownhall/gascity release, and its members must
  equal llvm_members.txt.

Verified locally:
- Every file in the extracted slice (2009 entries: types, modes,
  symlink targets, sha256) is identical to the xz extraction.
- aquery action keys are identical, base vs head, at the same workspace
  path: 7565/7565 over deps(//cmd/bd:bd_for_tests) and 7146/7146 over
  the race deps(//internal/storage/embeddeddolt:embeddeddolt_test).
- Extraction time: 178 s (xz) vs 1.9 s (zstd).

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

* ci(bazel): run the release cross-compile as its own lane

After the LLVM slice, bazel-pure is the longest cached Bazel lane (about
170 s). Its "Cross-compile every release target" step takes 54-58 s of
that (78.9k configured targets, 25k cache-hit lookups) and shares no
analysis with the pure invocations, because release_cross is a split
transition.

The step moves, unchanged, into a new job, bazel-release-cross ("release
cross-compile"). The job uses bazel-pure's runner, `needs: rbe` and skip
rule, so it runs in every mode except skip. It reports job.status like
every lane: the workflow_call output is bazel-release-cross, and pr.yml's
CI Gate requires it as BAZEL_RELEASE_CROSS. bazel-gate.sh skips it only in
mode skip, as it does BAZEL_PURE. Merge groups use the same pr.yml gate.
Push and dispatch runs gate nothing. Existing gate ids are unchanged.

The policy test now pins the step to bazel-release-cross, requires the new
gate id, and rejects any other job that runs the script (no double runs).
The new job is listed as having no CI analytics step. It captured no BEP as
a bazel-pure step either, and the analytics steps are unchanged. Docs:
LINTING.md, TESTING.md, CI_REQUIRED_CHECK_TOPOLOGY.md.

Expected: bazel-pure about 110 s on cached runs; the new lane about 85 s,
in parallel. Cost: one more 2-vCPU Blacksmith runner per run.

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

* build(bazel): stop building protoc for protoc-gen-validate

github.com/envoyproxy/protoc-gen-validate ships validate/validate.pb.go,
but its own validate/BUILD makes the Go library a go_proto_library. So
every lane built protoc from source just to regenerate that file. The
module reaches the graph only through grpc xds and the cloud SDKs.

A gazelle_override now regenerates the module's BUILD files with
`gazelle:proto disable`. It sets build_file_generation = "on" and adds
`gazelle:build_file_name BUILD.bazel`, so gazelle writes BUILD.bazel
(which Bazel prefers) instead of keeping the upstream BUILD. The proto
directive alone changes nothing, because the upstream BUILD files win.
validate is now a plain go_library over validate.pb.go.

Measured locally with aquery:
- //... minus the manual release_cross target: base has 2096 CppCompile,
  612 CppArchive, 314 CppLink and 1 GoProtocGen action; head has 0.
- cquery somepath(//..., @protobuf//:protoc): base goes through
  grpc xds -> envoy core/v3 -> validate_go_proto -> protoc; head is
  empty.
- deps(//cmd/bd:bd_for_tests): 7565 actions become 3077. The race
  deps(//internal/storage/embeddeddolt:embeddeddolt_test): 7146 become
  2658.

MODULE.bazel.lock does not change. The v4 runner cache key includes
MODULE.bazel, so it still moves. Expect one cold compile of the Go
packages above validate on the first run after merge.

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

* build(bazel): bazel mod tidy formatting

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-08 03:13:34 +00:00
Julian Knutsen
4f924fc161
ci(bazel): retire PR Risk's legacy Dolt tiers, pr.yml's legacy Go jobs and the D2 coverage flags (#7353)
Every pull_request and merge group already took the Bazel lanes for the
retired tiers (BAZEL_RETIRES_LEGACY_* and BAZEL_COVERS_FORKS all "true",
and pr.yml/pr-risk.yml run on no other event), so the legacy jobs those
flags stood down could never run again. Remove them with their decision:

- pr-risk.yml: build-embedded, test-embedded-{storage,conformance,cmd},
  test-proxied-cmd, test-server-storage{,-full}, detect-ci-tier (and its
  ci-embedded-tier.sh / ci-capability-selector.sh scripts) and
  bazel-coverage. PR Risk keeps the Nix packaging check (test-nix) and its
  gate, PR Risk Gate / Required.
- pr.yml: build-artifacts, check-cmd-bd-puregeo-tests, pr-core-wrapper and
  bazel-coverage; the BAZEL_RETIRES_LEGACY_* and BAZEL_COVERS_FORKS flags.
  The three BAZEL_*_RETIRED gate ids become one, BAZEL_REMOTE: the Bazel
  call must have run remotely (remote, fork-ro or fork-rw) on every PR and
  merge group, each lane's own id still required. Gate names unchanged.

Policy tests: the D2 decision matrix becomes
TestPRGateRequiresRemoteBazelLanes (bazel.yml's actual rbe step and
pr.yml's actual gate over every event/variable/secret/fork/actor/mint
fact); the parity tests that read the legacy jobs now pin the Bazel lanes
against those jobs' frozen commands.

ga-96smfk.22

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-07 09:31:20 +00:00