Commit graph

115 commits

Author SHA1 Message Date
Julian Knutsen
368b225eef
docs(bazel): make bazel test the primary build and test path (ga-96smfk.23) (#7348)
Bazel is beads' build and test system: bazel.yml's lanes gate every PR,
and nogo (lint + vet), gofmt and the repository guards exist only as
Bazel targets. The docs, the Makefile and the hooks now say so.

Makefile: `make test` runs bazel.yml's test lane (`bazel test //...
--config=ci`), `make check` adds the testing.Short policy and the
`make ci-pr-lint` nogo gate, and `make check-docs` runs the docsync and
doc-freshness Bazel targets before the pinned-release CLI flag check.
BAZEL_FLAGS passes --config=fork-cache or --config=remote-exec through.
The plain-Go recipes stay as explicit twins: test-go, check-go,
check-docs-go. No workflow called the primary names, and
TestWorkflowsNameTheirTestEngine keeps it that way.

Hooks: pre-push runs scripts/pre-push-suite.sh for branch pushes whose
commits change Go or Bazel inputs: the test lane with
--config=remote-exec when some rc names an executor, else
--config=fork-cache. Without bazel, or with BD_PREPUSH_SUITE=go, it runs
make test-go under a banner saying that is not what CI gates on.

Docs: AGENTS.md, CONTRIBUTING.md, engdocs/TESTING.md (a per-lane command
table and the fork-cache/remote-exec setup), README, RELEASING, the PR
template and the .bazelrc header. Bazelisk is a required prerequisite;
go test is an inner-loop convenience CI does not enforce.

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-07 07:46:02 +00:00
Julian Knutsen
a4509deb2d
ci(bazel): nogo replaces go vet and golangci-lint (ga-96smfk.18) (#7341)
* ci(bazel): nogo replaces go vet and golangci-lint (ga-96smfk.18)

Lint and vet now run as nogo inside the Bazel build, so they gate wherever
the Bazel lanes execute (rbe-west), and the golangci-lint and go vet jobs
leave pr.yml and main.yml.

- //tools/nogo (own go.mod, joined to beads' for go_deps only through
  gazelle.go.work): go test's vet checks (cmd/go's defaultVetFlags, the set
  scripts/ci/go-test-vet.sh ran) plus the eight linters .golangci.yml
  enables, each a wrapper over the library version golangci-lint v2.10.1
  uses (depguard, errcheck, forbidigo, gosec, misspell, sloglint, unconvert,
  unparam).
- .golangci.yml stays the single lint policy: Bazel embeds it and
  tools/nogo/internal/golangci applies it as golangci-lint does (enabled
  set, settings, run.tests: false as library-unit-only analysis, lax
  generated-file detection, path/path-except/text exclusion rules), with
  strict decoding so an unimplemented key fails the build.
- gascity's rules_go //nolint-range patch and x/tools ctrlflow patch,
  byte-identical.
- Windows/darwin: cross-configured, not a golangci leg. The pure lane's
  release cross-compile (//tools/bazel:release_cross, every library and
  binary for all eight release platforms, cgo off) runs nogo on every
  compile, a superset of golangci-lint's windows and darwin legs.
  scripts/pr-lint (make ci-pr-lint, bd preflight) runs `bazel build
  --config=nogo //...` plus release_cross for windows_amd64,darwin_arm64.
  release_cross skips tools/nogo, a separate Go module `go build ./...`
  never compiled.
- pr.yml: scripts-go-checks (vet) and pr-lint-wrapper (x3) are gone, with
  their ci-gate entries; main.yml: pr-lint-wrapper (x6) and go-vet-cache.
  scripts/ci/go-test-vet.sh and install-golangci-lint.sh are deleted.
- pre-commit hook and .pre-commit-config.yaml run `make lint-changed
  LINT_CHANGED_SCOPE=staged` (nogo over the staged packages); Makefile adds
  lint, vet and lint-changed. pr-lint.sh no longer runs gofmt
  (//scripts/repochecks:fmt_test owns it; ga-96smfk.41).
- internal/testutil/integration: five gosec findings in integration-tagged
  library files golangci-lint never built, now linted by the integration
  lanes, carry reasoned //nolint directives.

Parity: with the exclusion rules removed, golangci-lint and nogo report the
same 3,916 findings natively and 3,859 each for windows and darwin (file,
line, linter, text); with .golangci.yml as committed both report none.

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

* ci(bazel): equivalence.py leaves nested Go modules' tests out of go test's set

tools/nogo is its own Go module, so `go test ./...` in the root never runs
its tests; Bazel's unit lane does. Its packages are neither expected nor
extra.

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-07 05:17:22 +00:00
Julian Knutsen
ce661175ff
ci(bazel): retire the docker A/B variants and pr.yml's container jobs (#7340)
The dolt-server lane (--config=doltserver) has been the only pre-merge run
of the Dolt-backed domain, uow, tracker, doctor/fix and protocol suites
since BAZEL_COVERS_FORKS went "true": bazel-coverage reports pr_lanes=true
for every pull_request and merge_group, so pr.yml's test-domain-uow and
contract-corpus never run. An A/B run of every requires-docker target
against its dolt-server twin on the same commit shows identical test sets
and statuses (2683 testcases) except TestDoltServerFingerprint/container,
the container half of the fingerprint, which needs docker by design.

Delete the six requires-docker sh_tests, test:docker in .bazelrc, the
requires-docker tag from the taxonomy and lane filters, bazel.yml's
dolt-lane dispatch input and image pull, and pr.yml's test-domain-uow and
contract-corpus jobs with their ci-gate wiring. The testcontainers backend
in internal/testutil stays: it is plain go test's default. pull-dolt-image.sh
stays for pr-risk.yml's legacy tiers. No required check changes: the
rulesets require only CI Gate / Required and PR Risk Gate / Required.

Refs ga-96smfk.21

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-07 04:13:24 +00:00
Julian Knutsen
5e73670866
ci(bazel): cross-compile every release target with Bazel, retire the go build job (#7332)
pr.yml's check-release-target-cross-compilation ran `CGO_ENABLED=0
GOOS/GOARCH go build -tags gms_pure_go ./...` for the eight release targets
on two GitHub/Blacksmith runners. It is now a step of bazel.yml's pure-Go
lane (BAZEL_PURE, already required by ci-gate):
scripts/ci/bazel-release-cross-compile.sh builds //tools/bazel:release_cross
once, remotely, with --//tools/bazel:release_platforms set from
scripts/ci/release-targets.txt (still the single source of truth, pinned to
.goreleaser.yml). release_cross's split transition configures every
go_library/go_binary for each rules_go platform with cgo off, so all eight
platforms build in parallel in one invocation.

- tools/bazel/release_cross.bzl: the split-transition rule and the
  string-list flag.
- tools/bazel/go_srcs.py (make bazel-sync, checked by bazel-sync-check and
  TestBazelGoSrcsBlocksCurrent) keeps the release_cross target list; the
  script checks with bazel query that every Bazel package holding Go
  targets is reached before it builds.
- //tools/bazel:pure_bd_has_no_cgo_only_deps: Bazel compiles gozstd's pure
  stubs where `go build` rejects them, so the pure bd of every platform
  must not link gozstd.
- //internal/storage/embeddeddolt/cmd:cmd (cgo-only main, skipped by
  `go build ./...` under CGO_ENABLED=0) is tagged cgo-only and incompatible
  with pure builds.
- A failed build is re-run per platform (cache hits) to name each failing
  GOOS/GOARCH.

Same cgo-off coverage boundary as the retired job. Refs ga-96smfk.20.

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-07 03:18:37 +00:00
Julian Knutsen
bb9b9e5020
ci(bazel): run the upgrade smoke tests under Bazel; retire cross-version-smoke.yml (#7331)
cross-version-smoke.yml resolved the newest 5 GitHub releases (30 on a tag
push) with `gh release list`, then built the candidate and downloaded each
release on a GitHub runner for scripts/upgrade-smoke-test.sh.

//tests/upgrade_smoke has one target per release in the newest 30 the
release catalog pins a linux/amd64 asset for (@bd_releases//:versions.bzl):
upgrade_smoke_<release>_test runs the script against the non-race
bd_for_tests with that release pinned as PREV_BIN (sha256-verified when
Bazel fetches it; the script checks it reports the release and downloads
nothing). A release added to the catalog joins the window. Tagged
pr-core-only, so bazel-test (not the integration lane) runs them remotely
on every PR, merge group and
push, cached until the candidate, the script or the release changes.

The tested set is now reviewed rather than resolved at run time: stable
releases from the catalog, where the workflow took GitHub releases
including prereleases. cross-version-smoke.yml and the F7c checks of its
chunk fold, path filter, runners and binary cache are removed (the
path-filter and binary-cache checks had no other workflow left).

Refs: ga-96smfk.19

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-07 02:49:39 +00:00
Julian Knutsen
7e0adfd353
ci(bazel): run the historical-upgrade corpus under Bazel; retire migration-test.yml (#7330)
* chore(migration-test): extend the release catalog through v1.3.1

The catalog stopped at v1.1.2 (the v1.2 upgrade census). The migration
corpus already upgrades from v1.2.2, and the Bazel targets that replace
migration-test.yml and cross-version-smoke.yml take their pinned release
binaries from the catalog (@bd_releases), so it has to cover the releases
since. Regenerated with `catalog generate` after raising maximumVersion to
v1.3.1: five new stable versions (v1.2.0, v1.2.1, v1.2.2, v1.3.0, v1.3.1;
three with a linux/amd64 asset) and five new proxy prereleases; no existing
entry, drift record or repository-only exclusion changed. The count
constants and the identity digest are updated to match, and the README now
says how to add a release.

Refs: ga-96smfk.19

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

* ci(bazel): run the historical-upgrade corpus under Bazel; retire migration-test.yml

migration-test.yml ran scripts/migration-test/run.sh --version <release> for
14 reviewed releases in 3 shards on GitHub runners: it downloaded each
release archive, built v0.9.1 from source with Go 1.25 through the module
proxy, installed libicu74 and the dolt 2.1.8 runtime, all over the network.

//tests/migration now has one target per corpus release
(historical_upgrade_<release>_test) plus legacy_bridge_test, all hermetic:
- Published releases come from @bd_releases (the release catalog's
  sha256-verified assets) through a per-target directory
  (HISTORICAL_RELEASE_DIR); lib/binary.sh uses it instead of downloading and
  still checks each binary's self-reported version.
- v0.9.1 is //tests/migration:bd_source_tag, the same `go mod download` +
  `go build -trimpath` with CGO and Go 1.25.0, run offline as a build
  action: the module files come from tests/migration/source_tag_modules.json
  through a file:// GOPROXY tree (tools/bazel/go_module_proxy.bzl), the
  release's own zip is the catalog's source_zip, and go checks every
  dependency against the release's go.sum (SOURCE_TAG_SQLITE_BIN).
- The external Dolt runtime is @dolt_test_runtime_linux_amd64 (dolt.bzl's
  dolt_release gains a version attribute; 2.1.8 is pinned to versions.sh's
  digest), passed as DOLT_BIN to the server-Dolt and wisp-plane releases.
- The workers already provide jq, python3, sqlite3 and libicu74.

The targets are untagged, so bazel-test runs them remotely on every PR,
merge group and push; result caching replaces the path filter. Every
release also passed inside a loopback-only network namespace.
scripts/migration_corpus_bazel_test.go keeps the BUILD lists equal to
versions.sh's corpus, the catalog digests equal to STRICT_RELEASE_SHA256,
the source-tag lock equal to the catalog's source_zip, and the Dolt runtime
pin equal to versions.sh's. migration-test.yml and the policy tests that
pinned its shards, caches, apt step and runner are removed.

Refs: ga-96smfk.19

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

* ci(bazel): run the historical-upgrade targets in the PR-core lane only

The integration lane runs every untagged target too, and its
check_testcases.py requires Go testcases, which a shell test's test.xml does
not list. A new pr-core-only tag keeps //tests/migration out of
--config=integration (bazelIntegrationExcludedTags adds it), so the corpus
runs once, in bazel-test, against the release-shaped bd_for_tests (no
integration tag). build_source_tag.sh carries the build-tags opt-out: it
builds a historical release with that release's own go.mod, which predates
gms_pure_go.

Refs: ga-96smfk.19

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-07 02:16:11 +00:00
Julian Knutsen
9a91f0629e
ci(bazel): run the differential regression suite under Bazel; retire regression.yml (#7324)
regression.yml ran `go test -tags=regression ./tests/regression/...` on a
GitHub runner: it built the candidate with `go build`, downloaded the v0.49.6
baseline release over the network, and pulled the dolt-sql-server image.
None of that works on rbe-west workers (no network for fork lanes, no docker).

- tools/bazel/bd_releases.bzl: a module extension that reads
  scripts/migration-test/release-catalog.json and declares one repository per
  catalog release with a linux_amd64 asset digest (bd_release_<version>,
  verified against the catalog's sha256), behind the @bd_releases hub
  (@bd_releases//:<version>, plus versions.bzl). Adding a release is a
  catalog change only; nothing downloads until a test declares one.
- //tests/regression:regression_test: the suite's files build under
  `regression || integration`, so gazelle generates the target. It runs the
  injected non-race bd_for_tests (BEADS_TEST_BD_BINARY) against
  @bd_releases//:v0.49.6 (BD_REGRESSION_BASELINE_BIN), both over a hermetic
  dolt sql-server (BEADS_TEST_DOLT_SERVER=local, required), in 8 shards.
  TestMain checks the baseline reports BASELINE_VERSION, so the label and the
  file cannot drift. Tagged dolt-server-cmd: bazel.yml's bazel-cmd-dolt lane,
  which pr.yml's gate requires, runs it remotely; test result caching stands
  in for the old path detector.
- A plain `go test -tags=integration ./...` (nightly) compiles the files but
  skips the suite; only -tags=regression (make test-regression) or Bazel
  runs it.
- regression.yml, main.yml's warm-up compile for it and the policy tests that
  pinned its jobs are removed.

Refs: ga-96smfk.19

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-07 01:41:12 +00:00
Julian Knutsen
b1fe68e63a
ci(bazel): run pr.yml's repository guards as Bazel tests (#7329)
fast-checks, PR Policy, and the Linux leg of check-doc-freshness-platforms
ran repository guards on GitHub runners. They now run as Bazel tests in
bazel.yml's `test` lane (remote, cached), each over only the files it reads:

- tools/bazel/repo_subset.bzl picks a narrow, path-selected slice of
  //:repo_files at analysis time. scripts/repochecks/run_check.sh copies that
  slice into a throwaway git checkout and runs the unchanged guard there.
- //scripts/repochecks: build_tags, workflow_tags, go_install_guidance,
  winget_portable_alias, migration_hygiene (checks A and B),
  fmt (registered SDK gofmt), doc_freshness, workapi_frontend_boundary,
  types_gen_drift (`make api-check` drift, oapi-codegen from go.mod).
- //scripts:doc_freshness_required_test (integration lane, -required-suite)
  and //scripts/gitattributespolicy:gitattributespolicy_required_host_test
  cover the Linux doc-freshness leg.
- check-versions stays covered by //internal/versioncheck:versioncheck_test.
  check-testing-short stays covered by //scripts:scripts_test.

pr-policy-wrapper is deleted. fast-checks keeps only the two checks that
need the PR base: migration hygiene's delta half (MIGRATION_HYGIENE_SCOPE=
delta) and the .beads diff. check-doc-flags stays, because it builds bd from
the pinned release tag. The example Go modules leave .bazelignore so gofmt
and the grep guards see them. check_testcases.py now accepts --not-go
//pkg:all.

Refs: ga-96smfk.20

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-07 00:59:18 +00:00
Julian Knutsen
72534f8e57
ci(bazel): check the Dolt server fingerprint on the dolt-server lane; retire pr.yml's fingerprint job (#7328)
pr.yml's every-PR "Test (Dolt server fingerprint)" job installed dolt, pulled
the dolt-sql-server docker image and ran TestDoltServerFingerprint against
both backends. The rbe-west workers have no docker, and the container backend
is now used only by the container-backed legacy jobs, which run only where
bazel-coverage does not cover pr_lanes.

- //internal/testutil:testutil_dolt_test runs testutil_test with the local
  backend selected and required (BEADS_TEST_DOLT_SERVER=local,
  BEADS_TEST_REQUIRE_DOLT_CONTAINER=1) on the dolt-server lane, which
  pr.yml's gate requires: the fingerprint's local half against the pinned
  dolt, plus the TestLocalDoltServer_* tests every other configuration
  skips under BEADS_TEST_SKIP=dolt.
- The container half moves back to test-domain-uow's first test step (where
  it was before D2 step 3), so it runs exactly where containers are used.
  //internal/testutil:testutil_docker_test is its docker-lane A/B control.
  TestPinnedDoltCLIMatchesContainerImage still pins the image tag to the
  dolt release.
- test-dolt-server-fingerprint, its ci-gate need/result and its policy
  tests are removed; TestDoltServerFingerprintRunsWhereEachBackendRuns
  pins the new placement.

Refs: ga-96smfk.19

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-07 00:59:16 +00:00
Julian Knutsen
8761d2c40e
ci(bazel): run the conformance e2e tier under Bazel; retire conformance.yml and the docs-mintlify docsync job (#7321)
conformance.yml ran two tiers on a GitHub runner. Tier 1 (the embedded-Dolt
TestConformance) already runs as the embedded lane's
embeddeddolt_conformance_{core,audit}_test. Tier 2, the real-binary CLI
corpus (`go test -tags 'gms_pure_go e2e' ./test/conformance`), had only a
go_library under Bazel. Its two test files now build under `e2e ||
integration`, so gazelle generates //test/conformance:conformance_test
(integration-only, against the injected non-race bd_for_tests) and
--config=integration runs it remotely in bazel-integration, which pr.yml's
gate requires. PR Core's go test builds neither tag, so the --config=ci
equivalence check is unchanged; scripts/conformance.sh keeps working with
-tags e2e as the local go test entrypoint. With both tiers covered,
conformance.yml and main.yml's warm-up compiles for it are removed.

docs-mintlify.yml drops its docsync job (`go test ./test/docsync`, run by
bazel-test as //test/docsync:docsync_test on every PR) and keeps only
Mintlify's broken-link check, which needs the network (npx mint) and the
base branch's history; its path filter narrows to what that check reads.

Refs: ga-96smfk.17

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-06 22:42:25 +00:00
Julian Knutsen
0500fc6f40
ci(bazel): run the scripts and source-walking tests remotely; retire their go test legs (#7320)
//scripts:scripts_test and //scripts/check-versions:check-versions_test
drop their host-tools/no-remote-exec/no-remote-cache tags and run on the
rbe-west workers like every other target (the worker image ships bash, git,
python3, jq, yq, curl, openssl, unzip and coreutils; a missing tool fails the
test under Bazel rather than skipping it). Go comes in hermetically as the
registered SDK; check-versions.sh's `go build` is stood in for by the
Bazel-built checker.

The tests that walked the source checkout now get it as data:
tools/bazel/go_srcs.py keeps a managed `repo_files` filegroup in every
package and aggregates them into //:repo_files (exactly the tracked files
Bazel can see; make bazel-sync-check fails on a package without one).
scripts_test and docsync_test take it instead of hand-listed filegroups,
and every TEST_SRCDIR/IsBazel skip and go-test-only block in them is gone.
The release formula under .bazelignore'd .beads/ comes in through a
@beads_formulas local repository; npm-package/ and .claude/ are visible to
Bazel again (only their node_modules/worktrees stay ignored), so the npm
manifest release check and the AGENTS.md skill links run under Bazel too.
TestZZStdioNotLeaked falls back to TestMain's pre-run streams instead of
skipping in a shard without its baseline.

tools/bazel/equivalence_allowlist.txt shrinks from 20 skip entries to the
two cmd/bd tests of plain go test's own bd build fallback, which Bazel never
takes; pr-preflight-platforms now runs them on Linux, macOS and Windows. The
scripts-go-checks scripts-test and allowlisted legs, their scripts
(scripts-go-test.sh, allowlisted-go-tests.sh, run_allowlisted_go_tests.py)
and main.yml's --compile-only warm for them are removed. The vet leg stays
(ga-96smfk.18).

Refs: ga-96smfk.16

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-06 22:20:16 +00:00
Julian Knutsen
9f60d71dae
ci(main): push to main runs the Linux test tiers under Bazel only (#7316)
bazel.yml already runs on every push to main and executes the PR Core,
pure-Go, dolt-server, embedded, proxied, server-storage, integration and
cmd/bd Dolt-server tiers on rbe-west in about five minutes. main.yml re-ran
the same tiers as legacy go test jobs (62 jobs, about 380 runner-minutes a
push), and its runs were all failing or cancelled. Remove the duplicated
Linux jobs: the ubuntu -race -short leg with its Codecov upload, PR Core,
the pure-Go compile check, domain+uow, the 6+8 integration shards, the 15
proxied shards, and the embedded build plus its storage, conformance and
cmd shards.

The macOS -race -short suite (rbe-west has no macOS workers) moves to
Blacksmith macOS and restores the macOS saver's caches. The cache savers
that fed the fork path from the removed jobs move to venue matrices: the
macOS saver gains a GitHub-hosted leg, and the Linux saver gains a
GitHub-hosted race leg (the embedded build used to seed it).

Refs ga-96smfk.14

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-06 20:52:01 +00:00
Julian Knutsen
68d8cf99c0
ci(bazel): cover fork and Dependabot PRs with the Bazel lanes (BAZEL_COVERS_FORKS=true) (#7315)
Fork and Dependabot PRs ran both stacks: the legacy embedded, proxied,
server-storage and PR-lane tiers plus the Bazel lanes, which rbe-fork has
executed remotely (fork-ro/fork-rw) since the canary ended. Flip the
committed flag in pr.yml and pr-risk.yml so bazel-coverage retires those
tiers for forks too. A covered run the mint does not serve (mode cache)
already turns CI Gate / Required red with a re-run message; it never falls
back silently.

Refs ga-96smfk.15

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-06 20:51:59 +00:00
Bee
800d43eb8d
docs(engdocs): re-review ERROR_HANDLING.md against cmd/bd and refresh its marker (#7267)
The Last reviewed marker (2026-07-07) passed the 90-day limit in
scripts/check-doc-freshness.sh at 2026-10-06 00:00 UTC, so the required
"Check doc flags freshness" job fails on every PR and merge-group run
(#7266).

Re-reviewed against cmd/bd at e72cd8b31 and corrected what had drifted:

- createConfigYaml takes three arguments.
- cmd/bd/sync.go has no warning or ignored-error sites any more; its
  citations are gone. Line-number citations into init.go and create.go
  no longer matched and are replaced by search strings.
- internal/syncbranch was removed with the sync-branch pipeline; the
  syncbranch.Set example and the sync.branch bullet are gone.
- No code writes last_import_hash; the tracking-metadata examples now
  show the bd_version write (SetLocalMetadata) and verifyMetadata as
  init.go has them.
- CheckReadonly also exits ExitMigrationFrozen under a migration freeze.
- HandleProxyCapabilityError is added to the helper list.

Fixes #7266

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-06 12:46:26 -07:00
Julian Knutsen
e72cd8b315
ci: merge-queue readiness for the required gates; cache test results (fresh nightly) (#7264)
* ci: make the required gates merge-queue ready

The default-branch ruleset requires "CI Gate / Required" and "PR Risk
Gate / Required". Prepare both for a GitHub merge queue (ALLGREEN,
squash), so enabling the ruleset's merge_queue rule is the only step left.

- pr.yml, pr-risk.yml: merge_group pinned to types [checks_requested].
- D2: bazel-coverage covers every merge_group run (same repository, CI
  secrets, actor github-merge-queue[bot], bazel.yml mode remote), so the
  retired legacy tiers stay retired in the queue and ci-gate requires
  their Bazel lanes to have run remotely and passed; a missing secret or
  the farm switch off is red, as on a same-repo PR.
- Diff bases on merge_group: the package gates diff
  merge_group.base_sha..head_sha (not HEAD^, which misses all but the
  last commit of a rebase-method entry), the .beads/issues.jsonl guard
  now runs on merge_group against base_sha (ci-gate no longer excuses
  its skip), and check-doc-flags passes BD_DOCS_DIFF_BASE so CLI-docs
  drift already on main cannot eject every queued PR.
- Test result reuse: on a merge_group run and on attempt 2+ of a PR run,
  the six always-execute Bazel lanes append --config=reuse-test-results
  (--cache_test_results=auto), so tests whose action key is unchanged
  reuse the farm's recorded PASS and only what the merge changed runs.
  Failures are never reused, eviction retries stay 0, and each PR's first
  attempt, push to main and nightly still execute every test.
- scripts/ci_merge_queue_test.go simulates merge_group through the shared
  evalGHExpr evaluator (now with true/false/null literals, hyphenated
  identifiers and case-insensitive ==) and the workflows' own scripts:
  triggers and gate names, concurrency groups, every pull_request field
  read, the coverage and rbe decisions, result reuse, the package-gate,
  .beads and doc-drift diff bases.
- engdocs/CI_REQUIRED_CHECK_TOPOLOGY.md: new "Merge Queue" section (how
  to queue, settings, what runs, result reuse rationale, ejection and
  flakes, rollback).

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

* ci: cache Bazel test results except nightly; queue trust and sizing

Review follow-ups to the merge-queue readiness change.

- Test results (S1): --nocache_test_results also stops Bazel writing
  results, so a PR's first run never fed the cache and the merge-queue
  reuse config could only hit on later reuse runs. Drop it from
  test:embedded, test:doltserver-proxied, test:doltserver-integration and
  test:sole-run (which keeps --experimental_remote_cache_eviction_retries=0),
  and drop test:reuse-test-results and BAZEL_REUSE_RESULTS. Results are now
  cached (read and write) on PRs, merge groups and pushes to main.
  nightly.yml passes the new fresh-test-results input, so every `bazel
  test` appends --config=fresh (--nocache_test_results) and the suite
  re-executes nightly. The docker lane keeps --nocache_test_results.
  Measured locally with a disk cache: a default run writes and the next
  reads ("(cached) PASSED"); a fresh run neither reads nor writes.
- Security headers (S2): bazel.yml now states that a merge_group run
  executes the queued commit's workflows, so a queued fork or Dependabot
  PR's CI edits run with every CI secret, the pre-warm app key included
  (merging-level trust), and records the maintainer rule: review fork
  changes to .github/, .bazelrc, tools/bazel, MODULE.bazel, BUILD files
  and CI scripts before queueing. Same note in the topology doc.
- Queue sizing (S3): recommend max_entries_to_build 3 and
  check_response_timeout_minutes 60 (max_entries_to_merge 5, ALLGREEN,
  SQUASH unchanged).
- Nits: the .beads guard fails closed on a missing diff base, and its
  test runs under GitHub's default `bash -e`; evalGHExpr follows GitHub's
  loose equality (true == 'true' is false, false == '' is true, missing
  context keys are null) with a typed-context variant; the
  detect-package-gates comment notes the SQUASH/HEAD^ equivalence and
  path-filter scope; the doc covers re-run reuse, flake re-sampling via
  dispatch, stale queue runs and how to confirm reuse on the farm.

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-05 13:54:15 -07:00
Julian Knutsen
4493eb8d23
ci(pr): run same-repo macOS preflight/doc-freshness legs on Blacksmith macOS (#7231)
pr-preflight-platforms and check-doc-freshness-platforms now resolve their
same-repo-macos marker like the Linux/Windows legs: blacksmith-6vcpu-macos-26
for same-repo PRs and merge_group, GitHub-hosted macos-latest for forks,
Dependabot and every other event. The label is pinned to macos-26 because
GitHub's macos-latest is macos-26-arm64 today, so both paths run the same
OS/arch; 6 vCPU is already 2x macos-latest's 3 vCPU.

Blacksmith cannot see GitHub-saved caches, so main.yml gains
blacksmith-macos-go-build-cache: a push-to-main-only saver on the same label
(same job guard as the other Blacksmith savers) that builds ./cmd/bd and runs
the shared warm-non-race-cache.sh, saving the module cache and a non-race
GOCACHE keyed by go.sum + UTC day. The PR legs stay restore-only. main.yml's
GitHub-hosted macOS full-suite leg is unchanged and keeps seeding the fork
path.

Policy tests: the macOS marker arm is evaluated for same-repo/merge_group/
fork/deleted-head/dependabot/push/schedule and must match the flat macOS
const; the saver joins the PR-guard and per-day-key sweeps and the cache
ownership inventory; TestBlacksmithMacOSSaverMatchesPRLegs pins the
label/path/key/warm-up contract between saver and PR legs.

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-05 13:19:49 -07:00
Julian Knutsen
6d7fecaa3e
feat(httpclient): OSS HTTP client wire/encode layers (contributed from bd-enterprise under MIT) (#7210)
* feat(httpapi): wire-shape signal — wire_revision, floor header, golden digest, param tokens

S0 of the HTTP role-parity program: give a client a single place to learn
whether this build's wire shape has moved under it, and give CI a gate that
catches an undocumented move.

- GET /v0/beads/context reports wire_revision (bumps only on a non-additive
  response-shape change) and min_client_wire_revision. An optional
  Bd-Wire-Revision request header lets a client declare the revision it was
  built for; checkWireRevision refuses a declared revision below the floor
  with 400 invalid_argument/reason=wire_revision_unsupported and a
  min_wire_revision field, on every route but /healthz (wireRevisionExempt) —
  including the identity handshake, where catching the mismatch is cheapest.
  Absent header is today's behavior; malformed value is invalid_value, never
  wire_revision_unsupported. The floor lives in Server.minClientWireRevision
  (defaulting to the MinClientWireRevision constant) so a test can raise it.
- internal/httpapi/wireshape: a golden digest over every response's every
  content-type schema (including application/problem+json) across the whole
  spec, keyed by schema+member. TestWireShapeDigest fails closed when a
  member's JSON name or type changes without wire_revision bumping to match;
  regenerate with `go run ./internal/httpapi/wireshape/cmd/gendigest`.
- GET /v0/beads/issues' `sort` parameter now carries the issues.listSort
  capability token, the same convention `capabilities` entries use.
  TestNewParameterOnExistingOperationHasABehaviorToken requires every new
  parameter on an existing operation to carry one, checked against a
  write-once grandfather baseline (testdata/pretoken_parameters.json) of
  parameters that predate the rule; TestUntokenedParameterRuleFires proves
  the checker itself against a synthetic fixture.
- Docs: engdocs/design/bd-serve-v0.md gets a "The wire-shape signal" section;
  CHANGELOG.md gets an Added entry.

Live-mutated and reverted three RED demonstrations during development:
retyping api_version in the spec failed TestWireShapeDigest; short-circuiting
checkWireRevision's floor comparison failed
TestWireRevisionBelowFloorRefusesEveryEnforcedRoute; adding an untokened
query parameter to listIssues failed
TestNewParameterOnExistingOperationHasABehaviorToken. All three now pass
against the unmutated tree.

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

* fix(httpapi): rename issues.listSort to issues.list.sort, harden token rule

Opus review of 12c5144ca (HIGH-1, MEDIUM-5):

- Rename the capability token issues.listSort -> issues.list.sort to match
  bd-enterprise's client (httpstore/wire/handshake.go:121, DESIGN.txt S4e),
  and widen capabilityToken to accept an optional third segment.
- untokenedParameters() now requires the extracted token to be one
  Capabilities() actually serves, not just backtick-shaped text. This
  catches real false positives that existed in the spec already
  (workapi.DefaultReadyLimit, status.custom) which only shape-matched the
  old regex; they're added to the pretoken baseline as genuinely
  pre-existing untokened parameters.
- Extend the rule to request body members (new
  testdata/pretoken_request_body_members.json baseline) and exempt
  brand-new operations via a frozen testdata/pretoken_operations.json
  snapshot.
- Add TestPretokenBaselinesNeverGrow pinning all three baseline sizes so
  a future change can't hand-add an exemption instead of a token.
- Update spec prose for the widened rule scope.

go test ./internal/httpapi/... and the reviewer's pmut.py all pass as
expected: plain/bogus modes go RED, reuse (real-but-unrelated token) stays
green, matching the review's literal ask ("a token must be one advertised
by Capabilities()").

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

* fix(wireshape): close four digest-coverage gaps, add gendigest write guard

Opus review of 12c5144ca (HIGH-2, MEDIUM-4). The digest only tracked
Type/Format/Enum/Required on direct properties, missing:

- nullable: true (never read at all)
- array item shape (Issue.labels items string->integer was invisible;
  only object-shaped items got recursed into)
- additionalProperties value shape (IssueCount.groups)
- request bodies entirely (Compute() only walked responses, so
  DeleteIssuesRequest.expected_version string->integer, the other half
  of #6053, was invisible)

Also added defensive oneOf flattening alongside the existing allOf merge
(dormant today -- grep confirms this spec uses oneOf nowhere -- but no
longer silently invisible if that changes).

Extracted the golden-vs-computed comparison into wireshape.Compare(),
shared by TestWireShapeDigest and the new wireshape.SafeToWrite(), which
gendigest now calls before writing: it refuses to overwrite golden.json
with changed/removed entries unless the candidate's wire_revision is
strictly greater than the existing golden's. Pure additions always write.
TestSafeToWrite exercises both guard directions.

golden.json is regenerated. This single regen is a one-time exception to
the new guard, done by writing the digest directly rather than through
gendigest: confirmed via a throwaway diff (not checked in) that every one
of the 57 "changed" entries differs only in the NEW fields the wider walk
now populates (ItemType/ItemFormat/Nullable/AdditionalProps*) -- every
pre-existing Type/Format/Required/Enum value is byte-identical. Nothing on
the wire changed; the measurement got more precise. Bumping
CurrentWireRevision for this would have written a false "the protocol
changed here" entry into the revision history table. Going forward, any
REAL change the guard now reports uses the normal bump-then-regenerate
path, same as before.

Verified against the reviewer's mut.py: nested_type, nullable,
nullable_issue, array_items, addlprops, request_body and format all go RED
on TestWireShapeDigest, each reverted after confirming.

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

* fix(httpapi): make bd_version wire_revision inference advisory

Opus review of 12c5144ca (HIGH-3). The spec told a client inferring
wire_revision from bd_version to use the release cutoff >= 1.3.0, and said
nothing about what happens when that inference is wrong -- which it
demonstrably is for real builds already in the field:

- main builds up to commit b3ef65c85 report bd_version 1.2.2 (below any
  1.3.0 cutoff) while already sending the string-typed revision/
  expected_version shape (#6053).
- 1.3.0-rc.N pre-release builds sort BELOW the release cutoff 1.3.0 under
  plain string comparison despite already carrying the string shape.
- The bd-enterprise compatibility line at d3ab32773462 reports bd_version
  1.1.0 while also sending strings.

Moved the cutoff to >= 1.3.0-rc.1 (compared as semver-with-prerelease,
which at least captures the rc builds), documented both named exceptions
inline, and made the whole inference explicitly ADVISORY: a client must
accept revision/expected_version as either a string or a number whenever
wire_revision is absent (or probe directly) rather than let the inferred
value choose a decoder, and must never refuse solely because the inferred
revision is 0. Mirrored into engdocs/design/bd-serve-v0.md.

This is spec/doc prose only -- there is no server-side inference code to
change, since this server always sends wire_revision directly; the
inference is guidance for clients reading a pre-signal server's response
(this server, past builds, or an unrelated implementation).

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

* fix(httpapi): LOW-7/8/9/10 review follow-ups for wire-revision signal

LOW-7: WireRevisionUnsupported now also sets Problem.wire_revision (this
server's CurrentWireRevision) and Problem.bd_version on the
wire_revision_unsupported refusal, alongside the existing
min_wire_revision, so a client logging the refusal has this server's
full self-description without a second /v0/beads/context call.

LOW-8: gazelle + make bazel-sync add the BUILD.bazel entries the prior
commits were missing: wire_revision.go/wire_revision_test.go in
internal/httpapi's srcs, new BUILD.bazel files for wireshape and
wireshape/cmd/gendigest, and a testdata glob on httpapi's go_test so
the pretoken_*.json baselines are visible under `bazel test`. Verified
with `bazel build //internal/httpapi/...` and
`bazel test //internal/httpapi/... --test_env=BEADS_TEST_SKIP=dolt`
(both green) and `python3 tools/bazel/go_srcs.py --check` (clean).

LOW-9: narrowed CHANGELOG.md and engdocs/design/bd-serve-v0.md to
describe the digest's actual final coverage (format/enum/required/
nullable, array items, additionalProperties, request bodies, $ref/
allOf/oneOf recursion, the SafeToWrite revision-bump guard) and the
token rule's actual final shape (three pinned baselines, request-body
members, Capabilities()-membership validation, new-operation
exemption) instead of the original, narrower claims.

LOW-10: Bd-Wire-Revision now parses via a strict decimal-only
parseStrictNonNegativeInt (no leading '+', no leading zero except a
bare "0") instead of strconv.Atoi alone, so two different header
bytes can no longer name the same revision. New malformed-header test
cases: "+1", "01", "007".

Regenerated apigen/types.gen.go (make api-gen) for the new Problem
fields and wireshape/testdata/golden.json (go run
.../wireshape/cmd/gendigest) for the two new additive Problem members;
the latter wrote cleanly through SafeToWrite itself, since both are
pure additions.

go test ./... and bazel test //internal/httpapi/... both green.

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

* fix(httpapi): re-review LOW follow-ups — retirement test, gendigest -init, docs

1. TestRetiredRevisionsStayBelowTheFloor pins the PRESENCE guarantee the
   wire_revision property doc relies on: CurrentWireRevision >= 2 (so 0
   and 1 stay permanently retired) and MinClientWireRevision <=
   CurrentWireRevision (so this build's own floor never refuses every
   request against itself).

2. gendigest now refuses to create a golden.json that does not exist yet
   unless run with -init. Previously a missing file (moved testdata,
   wrong path, accidental delete) was indistinguishable from a real first
   run and silently wrote a fresh golden with no revision history checked
   against anything. writeGolden() is extracted out of main() so this is
   covered directly: TestWriteGoldenRequiresInitWhenMissing,
   TestWriteGoldenInitCreatesWhenMissing,
   TestWriteGoldenIgnoresInitWhenGoldenExists (the existing-golden path is
   still governed only by SafeToWrite, -init or not).

3. Narrowed the two remaining stale claims that still described the
   digest's original, narrower coverage: the wire_revision property's
   prose in openapi.v0.yaml (regenerated into apigen/types.gen.go via
   make api-gen) and wireshape/doc.go now both list nullable, array item
   shape, additionalProperties value shape, request bodies, and
   $ref/allOf/oneOf recursion, plus the new -init guard.

go test ./internal/httpapi/... and make api-check both green;
bazel test //internal/httpapi/... (httpapi, wireshape, and the new
gendigest test target) green; python3 tools/bazel/go_srcs.py --check
clean.

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

* feat(wireshape): cover operation parameters in the wire-shape digest

The digest previously walked only response and request-body schemas, so a
type, enum, required, or removal change on one of the spec's 138 operation
parameters (123 query, 14 path, 1 header) passed the gate silently — the
open item from PR review on #7182.

Each parameter is now recorded as its own Entry, keyed by
"param:"+operationId / location+":"+name (operation-scoped, not
schema-scoped, since two operations' same-named parameter are independent
wire contracts), capturing type, array item shape, enum, required, style,
explode and default. Adding a parameter stays additive; removing,
retyping, narrowing its enum, or changing required/style/explode/default
now trips SafeToWrite exactly like a response or request-body change.

Verified against the live spec: retyping listIssues' `limit` query
parameter from integer to string now fails TestWireShapeDigest (confirmed
red, then reverted — not part of this commit). golden.json regenerated via
gendigest; the new parameter entries are a pure addition, no wire_revision
bump needed. Added TestParameterMutationsAreCaught (remove/retype/narrow-
enum against real golden entries) and updated wireshape's doc.go, the
`wire_revision` spec prose, and the CHANGELOG to describe the new
coverage.

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

* fix(wireshape): review fixes — stale-golden and lowered-revision arms, effective param serialization, digest boundary

Maintainer fixup from the adopt-pr review loop (iterations 1 and 2), on
top of e17ba924f.

- goldenDrift (A, I): TestWireShapeDigest's comparison moves into a
  goldenDrift helper. An addition alongside a moved wire_revision no
  longer passes with a stale golden: it asks for a regenerate, as a
  changed or removed entry after a bump already did. Every message now
  names response/request-body members AND parameters, and TestGoldenDrift
  pins each arm. This takes only the test half of the stranded fixup
  (adopt-pr/bd-47kdge/stranded-fixup-528cd6095); its doc half, which says
  parameters are outside the digest, is false since e17ba924f and is not
  replayed (J).
- Lowered wire_revision (D): a CurrentWireRevision LOWER than the
  golden's is a wrong constant, not a stale golden, so goldenDrift says to
  restore it instead of regenerating, and SafeToWrite (so gendigest)
  refuses any write at a lower revision, whatever the entries.
- Effective style/explode (B): walkParam records style and explode with
  OpenAPI 3.0's defaults filled in (form for query/cookie, simple for
  path/header; explode defaults to style == form). Adding `explode: false`
  to a query array that relied on form's implicit explode is now a
  changed entry, while spelling out a default changes nothing.
  testdata/golden.json is regenerated with -init: 111 parameter entries
  change only in style/explode (96 to form/true, 15 to simple), 828
  entries before and after, wire_revision stays 2. The golden is new in
  this PR and unreleased, so this needs no bump.
- TestWalkParam (H): a package-internal table test
  (wireshape_internal_test.go) pins every field walkParam extracts,
  through a computeFrom(document, revision) seam that Compute now wraps:
  per-location defaults, $ref'd parameters and items, format, nullable and
  default, content parameters, and the nil returns.
  TestEffectiveSerializationIsCompared pins B end to end through Compare
  and SafeToWrite. BUILD.bazel embeds the library in the go_test, which is
  gazelle's own output.
- Required inputs and the digest boundary (C, E, F; docs only): all five
  prose surfaces (openapi.v0.yaml's wire_revision description and the
  regenerated apigen/types.gen.go, wireshape/doc.go, CHANGELOG.md,
  engdocs/design/bd-serve-v0.md) now say that a new REQUIRED request
  input is recorded as an ordinary addition and needs its own review,
  that value constraints and member-level composition are outside the
  digest, and that object and content parameters are recorded only as
  their container. bd-serve-v0.md also gains the parameter coverage it
  was missing.
- G: a brand-new operation is permanently exempt from the
  capability-token rule; its own review decides its capability story.
- Iteration 2 (nit): walkParam's comment now says that the location
  default it records as a `content` parameter's style and explode is a
  placeholder, since OpenAPI 3.0 applies style and explode only to a
  parameter described by `schema`. All 138 operation parameters in the
  spec use `schema`, so the golden does not change.

Validated: go test ./internal/httpapi/... (gms_pure_go), make api-check,
go vet for linux/windows/darwin, gofmt, git diff --check, gazelle on the
package (no drift), make bazel-sync-check, and bazel test
//internal/httpapi/wireshape/... in the local processwrapper sandbox
(2 of 2 pass). Overlay mutation probes: dropping the added-after-bump
arm, the lowered-revision arm, SafeToWrite's lowered check, or the
effective-default fill each turns the new tests red.
Iteration 2 changes only that comment; go test
./internal/httpapi/wireshape/... (gms_pure_go), go vet, gofmt and git
diff --check pass again.

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>

* feat(httpclient): lift the HTTP client wire/encode layers from bd-enterprise (MIT contribution)

Contributed by gascity from bd-enterprise (github.com/gascity/bd-enterprise,
internal/enterprise/httpstore @ 49d1df2f6) to OSS beads under the MIT
license, with the owner's explicit approval. Every lifted file carries a
provenance header naming its source path.

Lifted into internal/httpclient:
- wire/    the HTTP transport, lazy handshake, project-identity stamping,
           problem-code decoding, retry behaviour and the capability vocabulary
- encode/  request/response encoders for the role operations
- credential*.go, ca*.go, target*.go   the bearer credential ladder,
           host-scoped CA trust and the http_target.json sidecar

Not lifted (stays enterprise-only): the hosted gateway (httpgw/gwauth),
box-login, storage profiles and gasworks.

Deferred to later slices (kept aside, not in this tree): the store transport
seam (WireClient/WireDialer/process-wide dialer, which goes to S3 with
dial.go), the enterprise-only BatchCloseRequest.claim_next encoder
(ClaimNextBody; the OSS server has no claim_next on batch close), and the
tests that need the store/dial layer.

This commit is the mechanical lift: import paths rewritten, package renamed,
two compile gaps removed. The production code builds. Known follow-up in the
next commit: reconcile the client's vocabularies and encoder tables with the
OSS spec (e.g. the OSS problem code notes_overwrite_refused, policy/sort
differences), restore the test helpers the lifted tests need, and wire in the
S0 wire_revision handling and S1 OpenOptions credentials.

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

* fix(httpclient): compile the lifted client and reconcile with the OSS wire

The lift in ab11cb1f8 carried relative test paths and vocabulary tables
from bd-enterprise's internal/enterprise/httpstore (4 directories below
repo root) into internal/httpclient (3 below), and several tables
described enterprise-only server behavior OSS does not serve. Reconcile:

- Add testTarget test helper (written fresh) so internal/httpclient
  compiles and its tests pass.
- Fix four relative paths off by one "../" from the package relocation
  (skew_test.go, ledger_render_test.go, bijection_test.go x2).
- skew_test.go: importsHTTPClient now matches internal/httpclient instead
  of the retired internal/enterprise/httpstore path; the cmd/bd sweep no
  longer hard-fails when it legitimately finds zero matching files (cmd/bd
  does not import this client yet - that's S3's wiring).
- encode/table.go, encode/ledger_fields.go: removed a Reserved "reverse"
  entry and a refused ExcludeIDs field claimed for listIssues/ReadyRequest;
  OSS's listIssues never accepts "reverse" (confirmed against
  internal/httpapi/reads.go and routes.go's CapIssuesListSort, which gates
  `sort` only) and issueops.ReadyRequest carries no ExcludeIDs member in
  OSS. Each removal is documented in place.
- encode/table.go, encode/encode.go, encode/roundtrip_test.go: countIssues
  publishes has_metadata_key and include_ephemeral that CountRequest
  carries and the table/encoder/round-trip corpus all silently dropped;
  mapped and wired through.
- encode/ledger.go: ~70 ledger rows cited enterprise store-conformance and
  cmd/bd subprocess-parity tests (dual-run reader, claim races, flag-mode
  refusals) that don't exist in this package and belong to S3's store/dial
  seam and cmd/bd wiring. Re-pinned to a documented TODO(S3) sentinel
  (pinnedByS3Conformance) rather than deleted, per the ledger's own
  well-formedness discipline.
- wire/handshake.go, wire/vocabulary_test.go: added CapBatchApplyLarge
  (issues.batchApplyLarge) alongside the server's behaviorCapabilities.
- wire/problem.go: mapped the notes_overwrite_refused problem code to
  issueops.ErrNotesOverwrite.

internal/httpclient/... is fully green.

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

* feat(httpclient): wire-revision handshake gate and batch cap from capability

S0 integration (task #2): Client.Handshake now reads ContextResponse's
wire_revision/min_client_wire_revision and refuses with a typed
*WireRevisionSkewError before any post-handshake call when the server's wire
shape falls outside [ClientMinWireRevision, ClientWireRevision] -- mirroring
DESIGN.txt sec 4's "Client rule". A decoded 0 is treated as "the server
omitted the member" per the permanently-retired-values rule, never as a value
needing refusal. The client now also stamps Bd-Wire-Revision on every request
(client.go's stampRequest), and problem.go gained the per-request mirror:
*WireRevisionUnsupportedError, decoded from the reason:"wire_revision_unsupported"
extension members, for the case where the SERVER refuses this client's
declared revision as too old. Both error types are deliberately distinct --
one is this client declining after reading a 200, the other is the server
refusing a request outright -- and neither branches on bd_version (only
assigns it into error text), so TestNoFeatureBranchesOnBdVersionOrSchemaVersion
stays green.

Also added legacyRevisionFields/decodeRevisionToken to problem.go: a
precondition_failed refusal's expected_version/actual_version, typed *string
on the generated Problem, now tolerates a pre-#6053 server sending either as a
bare JSON integer rather than the decimal string every server since has used,
recovering the field the primary decode silently drops rather than losing it.

Batch cap (task #3): ApplyBatch reads the handshake snapshot on every call and
enforces 100 items unless the server advertises issues.batchApplyLarge, in
which case the ceiling is issueops.MaxApplyBatchItems (1000) -- never a bare
compiled constant. A plan over the applicable cap refuses before the dial: via
the existing *CapabilityError machinery when advertising the capability would
help (D7 case 2), or via a new *BatchTooLargeError (unwraps to
issueops.ErrValidation) when it would not. BatchTooLargeError lives in
handshake.go rather than beside ApplyBatch because every exported method in
writes.go is swept by TestEveryOperationMethodRoutesThroughTheSharedDispatch as
an operation-dispatch method.

All three internal/httpclient/... packages build and `go test` passes with
TMPDIR=/data/projects/.scratch/s2t BEADS_TEST_SKIP=dolt.

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

* feat(httpclient): REQUIRE-mode credential resolution bridge to backends.Credential

Task #4: adds the knob internal/storage/backends/backends.go's OpenOptions.Credential
doc explicitly deferred ("S1 does not add a RequireCredential knob to enforce
the multi-tenant rule mechanically -- that is deferred to S2").

ProvidedCredential wraps an embedder-supplied wire.CredentialProvider (via its
httpclient alias) as a backends.Credential, so a multi-tenant embedder (for
example gc, Gas City: one process serving many workspaces) can carry a
per-workspace credential through backends.OpenOptions without the backends
package needing to know this package's CredentialProvider shape.

ResolveCredential(opts, base, require) is the bridge itself:
  - nil Credential, require=false: NewBearerProvider(base), the existing
    single-tenant ambient bearer ladder (unchanged).
  - nil Credential, require=true: ErrCredentialRequired -- the multi-tenant
    fail-closed case backends.go's doc names: a missing per-workspace
    credential must be a loud refusal, not a silent fall-through to
    process-global ambient env that cannot tell one tenant's workspace from
    another's.
  - a ProvidedCredential with a non-nil Provider: returned directly,
    regardless of require.
  - a ProvidedCredential with a nil Provider, or any other
    backends.Credential this package does not recognise: refused -- the
    former as ErrCredentialRequired (a present-but-empty wrapper must not
    look like "a credential was supplied"), the latter wrapping
    backends.ErrUnsupportedCredential per the OpenWith contract
    internal/storage/backends/open_with_test.go already pins
    (TestBackendOpenWithRefusesUnsupportedCredentialType).

No bd-enterprise source was copied for this file; it is new code written
against the OSS backends.go contract and the existing BearerProvider/
CredentialProvider types already lifted into this package. Live-mutated all
three guards (the require branch, the ProvidedCredential type assertion, and
the nil-Provider check) and confirmed each produces a RED test before
reverting.

go build/vet/gofmt clean; `go test ./internal/httpclient/...` passes with
TMPDIR=/data/projects/.scratch/s2t BEADS_TEST_SKIP=dolt.

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

* test(httpclient): S2 task #6 wire-revision/legacy-decode coverage, fix legacyRevisionFields bug

Add httptest coverage for the two wire-revision mechanisms task #2 added
(commit 7ff68b29d8):

- handshake_wire_revision_test.go: the client-initiated skew gate
  (checkWireRevision/WireRevisionSkewError) and the per-request
  Bd-Wire-Revision header stamp. Live-mutated both switch arms in
  checkWireRevision and the stamped header value; confirmed RED, reverted.

- problem_wire_revision_test.go: the server-initiated
  wire_revision_unsupported refusal (reason-before-code dispatch priority)
  and the legacy-integer revision-token fallback.

Writing the legacy-decode tests surfaced a real bug in legacyRevisionFields:
its presence guard treated any non-nil *string field as "already decoded,"
but encoding/json's indirect() pre-allocates a pointer to "" for a *string
field before discovering a type mismatch (e.g. a bare JSON integer). A
type-mismatched expected_version/actual_version therefore arrived as a
non-nil pointer to the empty string, not nil -- exactly the one case the
fallback exists to recover, and exactly the case the old guard skipped.
Fixed by adding revisionNeedsFallback(p) (nil-or-empty), used in place of
the bare nil checks. No legitimate server response uses a literal
empty-string revision token, so this changes no other behavior.
Live-mutated the fixed guard back to the old nil-only checks; confirmed RED
on both recovery tests, reverted.

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

* test(httpclient): S2 task #6 ApplyBatch item-cap coverage

Add writes_batch_cap_test.go: httptest coverage for ApplyBatch's
capability-gated item ceiling (task #3), separate from the generic
two-speed "is issues.batchApply routed at all" gate writes_twospeed_test.go
already covers.

Cases: at-or-under the 100-item floor succeeds without the capability;
over the floor without issues.batchApplyLarge refuses with a
*CapabilityError before any dial past the handshake; the capability raises
the ceiling to issueops.MaxApplyBatchItems (1000), both at the new ceiling
and strictly between the old floor and it; over the absolute ceiling
refuses with *BatchTooLargeError regardless of the capability, also
without dialing the batch-apply endpoint.

Live-mutated all three guards in ApplyBatch (the limit computation, the
n > limit check, and the capability-vs-absolute-ceiling branch); confirmed
each produces a distinct RED, reverted.

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

* test(httpclient): S2 task #6 live TLS coverage for wrong-CA refusal

Add ca_wrong_ca_test.go: an end-to-end httptest TLS dial proving
TransportFor's configured CA pool is actually enforced at the wire, not
just recorded on the transport struct. ca_test.go already proves the
latter (TestTransportForReplacesRootPoolNotExtends, via
x509.CertPool.Equal) and proves the RIGHT CA dials successfully
(TestTransportForFileRotationClosesSupersededIdleConnections's live GETs);
neither exercises a server whose leaf a DIFFERENT CA signed.

TestTransportForWrongCARefusesTheTLSHandshake dials a server through a
transport built from an unrelated CA file and asserts the handshake fails
with x509.UnknownAuthorityError. TestTransportForRightCASucceedsOverTLS is
the positive control, using the same (newly-exercised) ca.startServer
helper that was defined but had no caller before this test -- without it,
a mutation that drops RootCAs entirely (falling back to the system pool)
would still pass the wrong-CA test for the wrong reason; the positive
control catches that case. Live-mutated transportForFile to drop RootCAs;
confirmed the positive control goes RED, reverted.

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

* build(bazel): gazelle BUILD files for the lifted httpclient package tree

Task #7: bazel run //:gazelle, now that internal/httpclient and its
encode/wire subpackages exist in the OSS tree (ab11cb1f8) and have gained
this S2 slice's new files. No existing BUILD.bazel files changed; these
three packages previously had none.

Note for S3: bazel test //internal/httpclient/... fails on tests that read
sibling source trees by relative path at runtime
(TestLedgerRowsAreWellFormed, TestEveryEncoderTableParameterIsPublished,
TestDivergenceLedgerDocMatchesLedger in encode, and
TestNoFeatureBranchesOnBdVersionOrSchemaVersion,
TestEveryOperationMethodRoutesThroughTheSharedDispatch,
TestEveryOperationMethodIsCoveredByTheTwoSpeedTable in wire) -- paths like
../../../cmd/bd and ../../httpapi/spec/openapi.v0.yaml resolve under `go
test`'s working directory but not Bazel's sandbox, which gazelle cannot
infer `data` attributes for. Pre-existing in code from task #1/#2, not
introduced by this commit; `go test ./internal/httpclient/...`,
`go vet ./...`, `gofmt -l .`, `golangci-lint run ./internal/httpclient/...`,
and `make api-check` are all clean.

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

* fix(httpclient/wire): tolerate bare-integer revision on success-path responses

Review HIGH #2: against a fake pre-#6053 server (one whose ContextResponse
omits wire_revision), CloseIssue and its revision-bearing siblings
(ApplyBatch, ReleaseIssue, ReopenIssue, UpdateIssue) failed with an untyped
`json: cannot unmarshal number ... revision of type string`. S0's
string-or-number tolerance (problem.go's legacyRevisionFields) only covered
the problem+json error path, never the success path.

Adds revision_tolerance.go: a pre-unmarshal rewrite that walks a response
body and turns a bare JSON number at a "revision" key into its exact decimal
string, scoped to the five apigen response types that carry the member and
gated on the handshake having seen no wire_revision at all. Left
apigen/types.gen.go and the OpenAPI spec untouched (both are
regenerate-and-diff gated by `make api-check`), rather than introducing a
custom Revision JSON type through codegen, to keep the fix's blast radius to
the wire package's own reader.

Updates ClientMinWireRevision's doc comment (handshake.go) to describe
tolerance on both halves of the wire instead of overclaiming the error-path
fix alone covered it. Adds revision_tolerance_test.go: a read (ListReadyWork)
and a guarded write (CloseIssue with ExpectedVersion) against a fake
pre-#6053 server, plus a modern-server control proving the rewrite never
fires when wire_revision is present. Mutation-tested: disabling the rewrite
reproduces the exact untyped UnmarshalTypeError the review reported.

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

* build(bazel): sandbox internal/httpclient's source-reading tests (Bazel gate green)

Review HIGH #1: the Bazel lane was red because three tests under
internal/httpclient read sibling/cross-package files by relative OS path at
runtime, which bazel test's sandbox does not materialize without an explicit
`data` dependency.

- internal/httpclient/encode/BUILD.bazel: encode_test gets
  data = ["//cmd/bd:go_srcs", "//internal/httpapi/spec:openapi.v0.yaml",
  "//:engdocs/design/http-divergence-ledger.md"] + glob(["*.go"]), covering
  bijection_test.go's cmd/bd scan and ledger_render_test.go's golden-doc read.
- internal/httpclient/wire/BUILD.bazel: wire_test gets
  data = ["//cmd/bd:go_srcs", "//internal/httpclient:go_srcs"] + glob(["*.go"]),
  covering skew_test.go's AST sweep of both trees.
- internal/httpclient/BUILD.bazel gains a go_srcs filegroup via `make
  bazel-sync` (tools/bazel/go_srcs.py): added "internal/httpclient" to the
  script's managed PACKAGES list rather than hand-writing the block.
- internal/httpapi/spec/BUILD.bazel and the root BUILD.bazel gain
  exports_files for openapi.v0.yaml and engdocs/design/http-divergence-ledger.md,
  scoped to //internal/httpclient/encode:__pkg__.
- bijection_test.go's loadPublishedParameters now reads the wire contract
  through spec.OpenAPIV0() (the package's existing go:embed) instead of a
  relative os.ReadFile path, per review suggestion -- the embed makes the
  parameter set reachable without a `data` dependency on the YAML at all; the
  openapi.v0.yaml data entry above stays as defense in depth for any other
  reader the package gains.

Ran via `bazel run //:gazelle` then `python3 tools/bazel/go_srcs.py`
(bazel-sync-check passes). `bazel test //internal/httpclient/...` is fully
green: 3/3 test targets pass.

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

* docs(httpclient): scrub private/enterprise infra references from code and docs

Review MEDIUM #3. Provenance headers ("Contributed by gascity from
bd-enterprise...") stay by design -- this removes references to private
infrastructure and unported internals from comment bodies and generated docs:

- wire/doc.go: dropped the internal/enterprise/hostedbeads and
  internal/enterprise/storageprofile build-tag comparison (neither exists in
  this OSS tree) and the dangling citation of the never-written
  engdocs/design/http-client-backend.md, replacing both with an accurate
  description of this package's own build-tag-free status and a pointer to
  the divergence ledger that does exist.
- credential.go: CredentialProvider's doc no longer names gwauth/DPoP/gateway
  auto-detection by their private spelling; describes the interface generically.
- ca.go: dropped "cherry-to-AWS RTT" (generalized to "a typical cross-region
  RTT") and the cmd/bd/enterprise_connect.go file reference (generalized to
  "a `bd connect --ca-file X`-style command").
- ca_permissions_unix.go / ca_permissions_unix_test.go: ~/.config/gascity and
  /etc/gascity example paths replaced with ~/.config/bd and /etc/bd.
- encode/skew_test.go: beads.corp replaced with bd.example.invalid.
- encode/ledger_render.go + ledger_render_test.go: the generated-doc preamble
  and regenerate-hint strings now name internal/httpclient/encode (this
  package) instead of internal/enterprise/httpstore/encode; regenerated
  engdocs/design/http-divergence-ledger.md via `go test
  ./internal/httpclient/encode -run TestDivergenceLedgerDocMatchesLedger
  -update-ledger-doc` rather than hand-editing it.

Final grep for enterprise/cherry/gascity/corp/gwauth under internal/httpclient
and engdocs turns up only: provenance headers (kept deliberately), this
session's own "no bd-enterprise source copied" disclaimers, and a handful of
generic "enterprise-tagged"/"enterprise server" references describing a
build-tag or commercial-tier server concept in the abstract -- none name a
private host, path, or credential.

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

* test(httpclient): review LOW items -- S3 TODO, env-driven CA test, lockstep doc

Review LOW #4-#6:

- wire/skew_test.go: TODO(S3) on the branch where the cmd/bd AST sweep is
  vacuous (no store/dial wiring yet), naming the slice that closes it.
- ca_wrong_ca_test.go: TestTransportForWrongCAViaEnvRefusesTheTLSHandshake,
  the BEADS_HTTP_CA_FILE env-driven sibling of the existing direct-CAFile
  wrong-CA test -- same live-TLS refusal, resolved through resolveCAFile's
  host-scoped env syntax instead of Target.CAFile.
- vocabulary_test.go: expanded the ClientWireRevision/CurrentWireRevision
  comment to explain why this repo holds them in strict lockstep (client and
  server ship from the same commit) rather than merely <=, distinguishing it
  from the real cross-version compatibility ClientMinWireRevision exists for.

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

* fix(httpclient/wire): re-review HIGH-a/b -- cover IssueDetails, stop recursing into metadata

HIGH-a: the legacy-revision set was missing apigen.IssueDetails (GET
/v0/beads/issues/{id}'s body, an alias for types.IssueDetails that a grep for
"type ... struct" never sees). getIssue is a baseline op that can dispatch
with no cached handshake at all, so serverPredatesRevisionStrings now treats
"no snapshot" the same as "WireRevision == 0" instead of only the latter.
revisionBearingResponse's set is now pinned exhaustively against
internal/httpapi/wireshape/testdata/golden.json -- the same committed digest
TestWireShapeDigest guards -- by a new test
(TestRevisionBearingResponseCoversEveryWireShapeSchemaWithARevisionMember), so
a future schema gaining a `revision` member can't silently miss coverage
again. New coverage: both "with" and "without" a prior handshake for getIssue,
and an explicit items[].revision test for ApplyBatchResponse.

HIGH-b: the previous fix recursed into every nested object looking for a
bare-number "revision" key, which reached caller-owned blobs like
CloseIssueResponse.issue.metadata -- real user data shaped like
{"revision":3} came back silently coerced to a string, on every server the
broadened gate above now also covers. tolerateLegacyRevisionNumbers no longer
recurses at all: it rewrites only the body's own top-level "revision", and,
for *apigen.ApplyBatchResponse specifically, each item's top-level
"revision" in the top-level "items" array. New
TestCloseIssueLegacyRewriteNeverTouchesIssueMetadata proves a metadata
document with "revision" keys at three nesting depths round-trips
byte-for-byte unchanged.

Mutation-tested both guards by hand (not committed): dropping the
IssueDetails case turns TestRevisionBearingResponseCoversEveryWireShapeSchemaWithARevisionMember
and both getIssue tests red with the exact missing-coverage/decode-failure
messages; reinstating a fully recursive rewrite turns
TestCloseIssueLegacyRewriteNeverTouchesIssueMetadata red, showing the
metadata's revision keys silently rewritten at all three depths. Both
reverted clean before this commit.

internal/httpapi/wireshape/BUILD.bazel and internal/httpclient/wire/BUILD.bazel
export/declare testdata/golden.json as data for wire_test's new exhaustiveness
test.

Verified: go test ./internal/httpclient/... (ok, one pre-existing unrelated
flake in ca_wrong_ca_test.go confirmed not reproducible across 8 reruns),
golangci-lint run ./internal/httpclient/... (0 issues), make api-check (no
apigen drift), bazel test //internal/httpclient/... //internal/httpapi/wireshape/...
(5/5 PASSED).

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

* fix(httpclient): stop the wrong-CA TLS tests racing Happy Eyeballs

Root cause: startServer rewrites its httptest TLS server's URL to the
hostname "localhost" so SNI is actually sent, but the server itself only
binds 127.0.0.1. net/http's default dialer does RFC 6555 Happy Eyeballs
for a hostname with more than one address family, racing a tcp6 dial to
::1:<port> against the real tcp4 dial. On this host, many unrelated
processes (JVM tooling) are bound to high ::1 ports, so the tcp6 race
occasionally "won" against a listener that had nothing to do with the
test, and the client spoke TLS to it instead -- surfacing as "tls: first
record does not look like a TLS handshake" rather than the expected
x509.UnknownAuthorityError. Confirmed via ss -tlnp captured at the moment
of failure (a java process holding the exact port raced) and via an
immediate manual redial to 127.0.0.1 on that port succeeding against the
real, still-live test server.

Fix: forceIPv4Loopback (new shared helper in ca_test.go) rewrites the
returned *http.Transport's DialContext to dial tcp4 only. SNI and the
request Host are unaffected, since crypto/tls and net/http derive both
from the URL, never from which address family carried the bytes. Wired
into every TLS fixture test in the package (ca_wrong_ca_test.go's three
tests, and ca_test.go's rotation test) -- grepped the rest of the repo
for the same "rewrite to localhost for SNI" pattern and found no other
occurrences.

Also fixed a latent bug this surfaced: TestTransportForWrongCAViaEnvRefusesTheTLSHandshake
called TransportFor(Target{}) with a nil BaseURL, so caHostMatches always
returned false and the CAFileEnv path was never actually exercised --
the nil RoundTripper was silently masked by http.Client's fallback to
http.DefaultTransport, which also failed to verify (via system roots)
for an unrelated reason. Now passes Target{BaseURL: u} so the test
exercises the host-scoped env-resolution path it documents.

go test -race -count=50 -run WrongCA: 8/8 clean. Whole package
go test -race -count=20: clean, twice. bazel test, golangci-lint,
make api-check: all green.

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

* fix(httpclient): repair CI-red tests and apply review fixes (adopt-pr #7210)

Three defects on the contributor head, none of them present on the base:

- test/docsync's TestEngdocsAndRootMarkdownLinks fails: the generated
  divergence-ledger doc links http-client-backend.md, an architecture
  spec this repository does not carry. Name it in a code span instead,
  in ledgerDocPreamble, and regenerate the doc (-update-ledger-doc).

- TestCAFileHygieneRefusesGroupWritableFile fails under umask 022:
  os.WriteFile's 0o660 passes through the umask, so the file lands 0640,
  is never group-writable, and TransportForFile accepts it. Chmod it
  explicitly. Its acceptance twin had the same gap on its file (only the
  explicitly chmodded directory reached the user-private-group
  exception), so chmod that file too: a mutant that drops the exception
  for files alone passed the old test under umask 022 and fails the new
  one.

- That acceptance twin calls the unix-only isUserPrivateGroup from
  ca_test.go, which carries no build constraint, so the package's tests
  do not compile for GOOS=windows. Move it, otherwise verbatim, into
  ca_permissions_unix_test.go beside the other isUserPrivateGroup tests.

Review fixes (iteration 1):

- Encode dispatched through nine case arms of op/shape conjunctions
  (cyclomatic 24). Switch on an (op, shape) struct key instead, and move
  the getIssue and search-bridge arms into encodeGetIssue and
  encodeSearch. The arms are disjoint, so dispatch and every error string
  are unchanged. Cyclomatic 24 -> 10.

- EventStream.Next kept four accumulators and the per-field switch in
  one loop (cognitive 27). Gather the accumulators into sseEvent and
  fold each field line, per-event cap included, in applyField. Next
  cognitive 27 -> 12; applyField is 11/11.

- The CA hygiene walk joined a relative symlink target onto the textual
  containing directory, so with a/link -> ../b/c and b/c/x -> ../y it
  resolved a/y where the kernel opens b/y: a valid CA was refused, or a
  hygienic file at a/y was checked and read instead. readLinkTarget joins
  onto the directory's EvalSymlinks path, taken after that directory's
  own ancestors passed the hop-by-hop check. The regression test plants
  a decoy at a/y; a lexical-join mutant reads it and fails.

- SaveTarget wrote a relative CAFile that every later LoadTarget
  refuses. Both now go through checkCAFileAbsolute, so SaveTarget refuses
  first, with LoadTarget's own message, and writes nothing.

- Document the cached transport TransportFor and TransportForFile return
  as shared and read-only.

Review fixes (iteration 2):

- The walk still dropped a ".." inside a symlink target textually:
  filepath.Join cleans a relative target, and an absolute target's
  ancestors come from filepath.Dir, while the kernel takes that ".."
  from wherever the component before it really leads. Both reviews
  rated the relative leaf as a wrong-file read, and it is one: with
  x/d -> ../e/s, x/L -> d/../y read a decoy at x/y where the kernel
  opens e/y. The other three shapes are hygiene bypasses: an absolute
  leaf target x/d/../y, and an ancestor link to d/../dir or x/d/../dir
  with the CA at x/L/y, each read a file in a world-writable e that the
  walk never checked. readLinkTarget now refuses a target with a ".."
  after any other component, relative or absolute; a leading run of
  ".." is still taken from the directory's physical path. The test pins
  all four shapes behind a control that refuses e/y named directly, and
  a table pins hasInteriorDotDot's boundary. Mutants that drop the
  refusal, limit it to relative targets, refuse every "..", or count
  "." as a component each fail.

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-05 02:58:34 -07:00
Julian Knutsen
0773e6334e
docs(agents): contributor-only agent instructions and documented-issue intake (#7223)
Makes the repo's agent and contributor surface describe developing beads, not using bd, and requires every PR to link a documented issue.

- Contributor-only root AGENTS.md with a routing table; cmd/bd/AGENTS.md and engdocs/AGENTS.md seam files; CLAUDE.md symlinks so Claude Code loads nested files.
- Bug and feature issue forms, a PR template that requires Closes #, CONTRIBUTING sections for the triage and pipeline labels, and the opt-in fork-cache during dev setup.
- ROADMAP.md for 1.4: versioned beads (#6132), Graph Preview 2 (#7170), contributor onboarding (#7228).
- docsync guards: root AGENTS.md at or under 20 KB; every AGENTS.md symlinked, routed, and with resolving links, paths, and guard-test names.

Agent-Signature: claude-code-claude-opus-5-5-high on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-05 08:43:53 +00:00
Julian Knutsen
ec72c8c563
ci(bazel): drop //cmd/bd:bd_test from the integration lane where the cmd/bd Dolt-server tier is required (#7230)
bazel-integration (--config=integration) and bazel-cmd-dolt
(--config=doltserver-cmd, //cmd/bd:bd_dolt_server_test) both run the
integration-build cmd/bd bd_test; the second without BEADS_TEST_SKIP=dolt,
so it is a superset. Once pr.yml requires bazel-cmd-dolt, the integration
lane's bd_test run is a duplicate.

bazel.yml gains a boolean workflow_call input, cmd-dolt-required (default
false). When true, bazel-integration tests //... -//cmd/bd:bd_test. pr.yml
passes it, and a policy test pins it to pr.yml's BAZEL_CMD_DOLT_REQUIRED
(a `with:` cannot read env), so the drop only happens where ci-gate
requires BAZEL_CMD_DOLT. bazel-farm.yml, nightly.yml, push and dispatch
leave it unset and keep bd_test. While the flag is "false" (current main)
nothing changes; with #7226's flip the input flips with it.

Coverage: both lanes share the same `if:` (modes remote, fork-ro, fork-rw,
cache; Dependabot included) and bazel-gate.sh accepts their skips in the
same modes (skip, local). TestBazelIntegrationExcludesBdTestOnlyWhereCmdDoltCovers
pins that, the exact exclusion, the flag/input equality, the gate's
conditional requirement, and that no other caller passes the input.

Rollback: commit BAZEL_CMD_DOLT_REQUIRED "false" and cmd-dolt-required:
false together in pr.yml.

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-05 01:19:47 -07:00
Julian Knutsen
5439be97ba
feat(httpapi): wire-shape signal — wire_revision, client floor, golden shape digest, param tokens (#7182)
* feat(httpapi): wire-shape signal — wire_revision, floor header, golden digest, param tokens

S0 of the HTTP role-parity program: give a client a single place to learn
whether this build's wire shape has moved under it, and give CI a gate that
catches an undocumented move.

- GET /v0/beads/context reports wire_revision (bumps only on a non-additive
  response-shape change) and min_client_wire_revision. An optional
  Bd-Wire-Revision request header lets a client declare the revision it was
  built for; checkWireRevision refuses a declared revision below the floor
  with 400 invalid_argument/reason=wire_revision_unsupported and a
  min_wire_revision field, on every route but /healthz (wireRevisionExempt) —
  including the identity handshake, where catching the mismatch is cheapest.
  Absent header is today's behavior; malformed value is invalid_value, never
  wire_revision_unsupported. The floor lives in Server.minClientWireRevision
  (defaulting to the MinClientWireRevision constant) so a test can raise it.
- internal/httpapi/wireshape: a golden digest over every response's every
  content-type schema (including application/problem+json) across the whole
  spec, keyed by schema+member. TestWireShapeDigest fails closed when a
  member's JSON name or type changes without wire_revision bumping to match;
  regenerate with `go run ./internal/httpapi/wireshape/cmd/gendigest`.
- GET /v0/beads/issues' `sort` parameter now carries the issues.listSort
  capability token, the same convention `capabilities` entries use.
  TestNewParameterOnExistingOperationHasABehaviorToken requires every new
  parameter on an existing operation to carry one, checked against a
  write-once grandfather baseline (testdata/pretoken_parameters.json) of
  parameters that predate the rule; TestUntokenedParameterRuleFires proves
  the checker itself against a synthetic fixture.
- Docs: engdocs/design/bd-serve-v0.md gets a "The wire-shape signal" section;
  CHANGELOG.md gets an Added entry.

Live-mutated and reverted three RED demonstrations during development:
retyping api_version in the spec failed TestWireShapeDigest; short-circuiting
checkWireRevision's floor comparison failed
TestWireRevisionBelowFloorRefusesEveryEnforcedRoute; adding an untokened
query parameter to listIssues failed
TestNewParameterOnExistingOperationHasABehaviorToken. All three now pass
against the unmutated tree.

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

* fix(httpapi): rename issues.listSort to issues.list.sort, harden token rule

Opus review of 12c5144ca (HIGH-1, MEDIUM-5):

- Rename the capability token issues.listSort -> issues.list.sort to match
  bd-enterprise's client (httpstore/wire/handshake.go:121, DESIGN.txt S4e),
  and widen capabilityToken to accept an optional third segment.
- untokenedParameters() now requires the extracted token to be one
  Capabilities() actually serves, not just backtick-shaped text. This
  catches real false positives that existed in the spec already
  (workapi.DefaultReadyLimit, status.custom) which only shape-matched the
  old regex; they're added to the pretoken baseline as genuinely
  pre-existing untokened parameters.
- Extend the rule to request body members (new
  testdata/pretoken_request_body_members.json baseline) and exempt
  brand-new operations via a frozen testdata/pretoken_operations.json
  snapshot.
- Add TestPretokenBaselinesNeverGrow pinning all three baseline sizes so
  a future change can't hand-add an exemption instead of a token.
- Update spec prose for the widened rule scope.

go test ./internal/httpapi/... and the reviewer's pmut.py all pass as
expected: plain/bogus modes go RED, reuse (real-but-unrelated token) stays
green, matching the review's literal ask ("a token must be one advertised
by Capabilities()").

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

* fix(wireshape): close four digest-coverage gaps, add gendigest write guard

Opus review of 12c5144ca (HIGH-2, MEDIUM-4). The digest only tracked
Type/Format/Enum/Required on direct properties, missing:

- nullable: true (never read at all)
- array item shape (Issue.labels items string->integer was invisible;
  only object-shaped items got recursed into)
- additionalProperties value shape (IssueCount.groups)
- request bodies entirely (Compute() only walked responses, so
  DeleteIssuesRequest.expected_version string->integer, the other half
  of #6053, was invisible)

Also added defensive oneOf flattening alongside the existing allOf merge
(dormant today -- grep confirms this spec uses oneOf nowhere -- but no
longer silently invisible if that changes).

Extracted the golden-vs-computed comparison into wireshape.Compare(),
shared by TestWireShapeDigest and the new wireshape.SafeToWrite(), which
gendigest now calls before writing: it refuses to overwrite golden.json
with changed/removed entries unless the candidate's wire_revision is
strictly greater than the existing golden's. Pure additions always write.
TestSafeToWrite exercises both guard directions.

golden.json is regenerated. This single regen is a one-time exception to
the new guard, done by writing the digest directly rather than through
gendigest: confirmed via a throwaway diff (not checked in) that every one
of the 57 "changed" entries differs only in the NEW fields the wider walk
now populates (ItemType/ItemFormat/Nullable/AdditionalProps*) -- every
pre-existing Type/Format/Required/Enum value is byte-identical. Nothing on
the wire changed; the measurement got more precise. Bumping
CurrentWireRevision for this would have written a false "the protocol
changed here" entry into the revision history table. Going forward, any
REAL change the guard now reports uses the normal bump-then-regenerate
path, same as before.

Verified against the reviewer's mut.py: nested_type, nullable,
nullable_issue, array_items, addlprops, request_body and format all go RED
on TestWireShapeDigest, each reverted after confirming.

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

* fix(httpapi): make bd_version wire_revision inference advisory

Opus review of 12c5144ca (HIGH-3). The spec told a client inferring
wire_revision from bd_version to use the release cutoff >= 1.3.0, and said
nothing about what happens when that inference is wrong -- which it
demonstrably is for real builds already in the field:

- main builds up to commit b3ef65c85 report bd_version 1.2.2 (below any
  1.3.0 cutoff) while already sending the string-typed revision/
  expected_version shape (#6053).
- 1.3.0-rc.N pre-release builds sort BELOW the release cutoff 1.3.0 under
  plain string comparison despite already carrying the string shape.
- The bd-enterprise compatibility line at d3ab32773462 reports bd_version
  1.1.0 while also sending strings.

Moved the cutoff to >= 1.3.0-rc.1 (compared as semver-with-prerelease,
which at least captures the rc builds), documented both named exceptions
inline, and made the whole inference explicitly ADVISORY: a client must
accept revision/expected_version as either a string or a number whenever
wire_revision is absent (or probe directly) rather than let the inferred
value choose a decoder, and must never refuse solely because the inferred
revision is 0. Mirrored into engdocs/design/bd-serve-v0.md.

This is spec/doc prose only -- there is no server-side inference code to
change, since this server always sends wire_revision directly; the
inference is guidance for clients reading a pre-signal server's response
(this server, past builds, or an unrelated implementation).

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

* fix(httpapi): LOW-7/8/9/10 review follow-ups for wire-revision signal

LOW-7: WireRevisionUnsupported now also sets Problem.wire_revision (this
server's CurrentWireRevision) and Problem.bd_version on the
wire_revision_unsupported refusal, alongside the existing
min_wire_revision, so a client logging the refusal has this server's
full self-description without a second /v0/beads/context call.

LOW-8: gazelle + make bazel-sync add the BUILD.bazel entries the prior
commits were missing: wire_revision.go/wire_revision_test.go in
internal/httpapi's srcs, new BUILD.bazel files for wireshape and
wireshape/cmd/gendigest, and a testdata glob on httpapi's go_test so
the pretoken_*.json baselines are visible under `bazel test`. Verified
with `bazel build //internal/httpapi/...` and
`bazel test //internal/httpapi/... --test_env=BEADS_TEST_SKIP=dolt`
(both green) and `python3 tools/bazel/go_srcs.py --check` (clean).

LOW-9: narrowed CHANGELOG.md and engdocs/design/bd-serve-v0.md to
describe the digest's actual final coverage (format/enum/required/
nullable, array items, additionalProperties, request bodies, $ref/
allOf/oneOf recursion, the SafeToWrite revision-bump guard) and the
token rule's actual final shape (three pinned baselines, request-body
members, Capabilities()-membership validation, new-operation
exemption) instead of the original, narrower claims.

LOW-10: Bd-Wire-Revision now parses via a strict decimal-only
parseStrictNonNegativeInt (no leading '+', no leading zero except a
bare "0") instead of strconv.Atoi alone, so two different header
bytes can no longer name the same revision. New malformed-header test
cases: "+1", "01", "007".

Regenerated apigen/types.gen.go (make api-gen) for the new Problem
fields and wireshape/testdata/golden.json (go run
.../wireshape/cmd/gendigest) for the two new additive Problem members;
the latter wrote cleanly through SafeToWrite itself, since both are
pure additions.

go test ./... and bazel test //internal/httpapi/... both green.

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

* fix(httpapi): re-review LOW follow-ups — retirement test, gendigest -init, docs

1. TestRetiredRevisionsStayBelowTheFloor pins the PRESENCE guarantee the
   wire_revision property doc relies on: CurrentWireRevision >= 2 (so 0
   and 1 stay permanently retired) and MinClientWireRevision <=
   CurrentWireRevision (so this build's own floor never refuses every
   request against itself).

2. gendigest now refuses to create a golden.json that does not exist yet
   unless run with -init. Previously a missing file (moved testdata,
   wrong path, accidental delete) was indistinguishable from a real first
   run and silently wrote a fresh golden with no revision history checked
   against anything. writeGolden() is extracted out of main() so this is
   covered directly: TestWriteGoldenRequiresInitWhenMissing,
   TestWriteGoldenInitCreatesWhenMissing,
   TestWriteGoldenIgnoresInitWhenGoldenExists (the existing-golden path is
   still governed only by SafeToWrite, -init or not).

3. Narrowed the two remaining stale claims that still described the
   digest's original, narrower coverage: the wire_revision property's
   prose in openapi.v0.yaml (regenerated into apigen/types.gen.go via
   make api-gen) and wireshape/doc.go now both list nullable, array item
   shape, additionalProperties value shape, request bodies, and
   $ref/allOf/oneOf recursion, plus the new -init guard.

go test ./internal/httpapi/... and make api-check both green;
bazel test //internal/httpapi/... (httpapi, wireshape, and the new
gendigest test target) green; python3 tools/bazel/go_srcs.py --check
clean.

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

* feat(wireshape): cover operation parameters in the wire-shape digest

The digest previously walked only response and request-body schemas, so a
type, enum, required, or removal change on one of the spec's 138 operation
parameters (123 query, 14 path, 1 header) passed the gate silently — the
open item from PR review on #7182.

Each parameter is now recorded as its own Entry, keyed by
"param:"+operationId / location+":"+name (operation-scoped, not
schema-scoped, since two operations' same-named parameter are independent
wire contracts), capturing type, array item shape, enum, required, style,
explode and default. Adding a parameter stays additive; removing,
retyping, narrowing its enum, or changing required/style/explode/default
now trips SafeToWrite exactly like a response or request-body change.

Verified against the live spec: retyping listIssues' `limit` query
parameter from integer to string now fails TestWireShapeDigest (confirmed
red, then reverted — not part of this commit). golden.json regenerated via
gendigest; the new parameter entries are a pure addition, no wire_revision
bump needed. Added TestParameterMutationsAreCaught (remove/retype/narrow-
enum against real golden entries) and updated wireshape's doc.go, the
`wire_revision` spec prose, and the CHANGELOG to describe the new
coverage.

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

* fix(wireshape): review fixes — stale-golden and lowered-revision arms, effective param serialization, digest boundary

Maintainer fixup from the adopt-pr review loop (iterations 1 and 2), on
top of e17ba924f.

- goldenDrift (A, I): TestWireShapeDigest's comparison moves into a
  goldenDrift helper. An addition alongside a moved wire_revision no
  longer passes with a stale golden: it asks for a regenerate, as a
  changed or removed entry after a bump already did. Every message now
  names response/request-body members AND parameters, and TestGoldenDrift
  pins each arm. This takes only the test half of the stranded fixup
  (adopt-pr/bd-47kdge/stranded-fixup-528cd6095); its doc half, which says
  parameters are outside the digest, is false since e17ba924f and is not
  replayed (J).
- Lowered wire_revision (D): a CurrentWireRevision LOWER than the
  golden's is a wrong constant, not a stale golden, so goldenDrift says to
  restore it instead of regenerating, and SafeToWrite (so gendigest)
  refuses any write at a lower revision, whatever the entries.
- Effective style/explode (B): walkParam records style and explode with
  OpenAPI 3.0's defaults filled in (form for query/cookie, simple for
  path/header; explode defaults to style == form). Adding `explode: false`
  to a query array that relied on form's implicit explode is now a
  changed entry, while spelling out a default changes nothing.
  testdata/golden.json is regenerated with -init: 111 parameter entries
  change only in style/explode (96 to form/true, 15 to simple), 828
  entries before and after, wire_revision stays 2. The golden is new in
  this PR and unreleased, so this needs no bump.
- TestWalkParam (H): a package-internal table test
  (wireshape_internal_test.go) pins every field walkParam extracts,
  through a computeFrom(document, revision) seam that Compute now wraps:
  per-location defaults, $ref'd parameters and items, format, nullable and
  default, content parameters, and the nil returns.
  TestEffectiveSerializationIsCompared pins B end to end through Compare
  and SafeToWrite. BUILD.bazel embeds the library in the go_test, which is
  gazelle's own output.
- Required inputs and the digest boundary (C, E, F; docs only): all five
  prose surfaces (openapi.v0.yaml's wire_revision description and the
  regenerated apigen/types.gen.go, wireshape/doc.go, CHANGELOG.md,
  engdocs/design/bd-serve-v0.md) now say that a new REQUIRED request
  input is recorded as an ordinary addition and needs its own review,
  that value constraints and member-level composition are outside the
  digest, and that object and content parameters are recorded only as
  their container. bd-serve-v0.md also gains the parameter coverage it
  was missing.
- G: a brand-new operation is permanently exempt from the
  capability-token rule; its own review decides its capability story.
- Iteration 2 (nit): walkParam's comment now says that the location
  default it records as a `content` parameter's style and explode is a
  placeholder, since OpenAPI 3.0 applies style and explode only to a
  parameter described by `schema`. All 138 operation parameters in the
  spec use `schema`, so the golden does not change.

Validated: go test ./internal/httpapi/... (gms_pure_go), make api-check,
go vet for linux/windows/darwin, gofmt, git diff --check, gazelle on the
package (no drift), make bazel-sync-check, and bazel test
//internal/httpapi/wireshape/... in the local processwrapper sandbox
(2 of 2 pass). Overlay mutation probes: dropping the added-after-bump
arm, the lowered-revision arm, SafeToWrite's lowered check, or the
effective-default fill each turns the new tests red.
Iteration 2 changes only that comment; go test
./internal/httpapi/wireshape/... (gms_pure_go), go vet, gofmt and git
diff --check pass again.

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>
2026-10-04 22:29:12 -07:00
Julian Knutsen
ebe3b6bcb0
test,ci(cmd/bd): run the Dolt-gated cmd/bd suite (advisory Bazel lane), fix in-process runner leaks and rotted tests; init --quiet stays quiet (#7185)
* test(cmd/bd): reset cobra flags between in-process runs; keep them out of parallel tests

runBDInProcess and runBDInProcessAllowError execute the package-level
rootCmd tree again and again in one process, and cobra never resets a
flag between Execute calls: a value one invocation parsed (create's
--title, --labels, list's --status, ...) and its Changed bit stayed on the
FlagSet, so the next invocation saw it, and a slice flag that had been
set appended to the stale value instead of replacing it. With a Dolt test
server (the only setup in which these tests run) that failed about 20
TestCLI_* tests depending on suite order.

TestMain now snapshots every flag of the tree (snapshotCommandFlags,
after all init()s registered them, before any test runs) and both runners
put the tree back before and after each run (resetCommandFlags): the
pointee of each flag.Value is restored (for pflag's scalar types that is
the bound variable; for slice types it also clears the internal "changed"
bit, so the next Set replaces), slice contents via SliceValue.Replace,
and Changed=false. TestResetCommandFlagsRestoresEveryFlag sets every flag
of the real tree and checks the reset. The ad-hoc --title reset in
TestCLI_CreateRejectsEmptyTitle_ProxiedServerMode is no longer needed.

Seven TestCLI_Comment* tests called t.Parallel() around the runners.
inProcessMutex serializes the runners only against each other, so their
chdir, stdio swap, env and config re-initialization raced every other
parallel test (data races on config globals; TestCobraParallelPolicyGuard
failing to read its own source files after a concurrent chdir). They run
serially now, and the guard treats the two runners like rootCmd.Execute.

Also two stale TestCLI_Create* cases: DryRunWithRigPrefix exercised a
create --prefix flag that no longer exists, and the flag-like-title cases
passed "--help" or "--foo-bar" where cobra parses them as flags; they now
pass the title after "--", the only way it reaches create's own guard.

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

* test(cmd/bd): fix the ADO round-trip and bulk-delete tests that rotted unseen

Both need the integration tag and a Dolt test server, which no CI lane
gave cmd/bd (BEADS_TEST_SKIP=dolt everywhere), so they failed unnoticed:

- TestADORoundTrip* stored ado.pat in the database. ado.pat is a secret
  read only from config.yaml or AZURE_DEVOPS_PAT (config.IsYamlOnlyKey),
  so the tracker found no PAT. The fixture sets AZURE_DEVOPS_PAT.
- TestBulkDeleteNoResurrection expected GetIssue to return (nil, nil) for
  a deleted issue; the Dolt store reports storage.ErrNotFound.

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

* test(cmd/bd): fix parity, completion and notion tests that only fail with a Dolt server

These are Dolt-gated (integration tag + test server), so no CI lane ran
them and they rotted:

- TestParityCreate*/TestParityReopenErrorExits1Silently: bd create
  auto-routes via routing.DetectUserRole("."), which warns "beads.role
  not configured (GH#2950)" on stderr when the working directory's git
  config has no beads.role. The suite pins the configured case, so the
  parity env now sets beads.role=maintainer in a test-owned global git
  config ($XDG_CONFIG_HOME/git/config; the role lookup scrubs every
  GIT_CONFIG_* variable, so those cannot be used).
- TestIssueIDCompletion: issueIDCompletion resolves a database path
  before looking at the open store and returns nothing when there is
  none; the test now sets dbPath to its store's path.
- TestIssueIDCompletion_UsesWorktreeFallbackWhenStoreNil and
  TestGetNotionConfigReadsDBPathWhenStoreUnset: the code under test
  reopens the store from metadata.json, which names a database but not
  the per-test branch of the shared database that newTestStore uses, so
  the reopened store saw none of the test's rows. They now use their own
  database (newTestStoreIsolatedDB).

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

* test(cmd/bd): fix stale doctor/e2e/autocommit/readonly Dolt-gated tests

These need the integration tag and a Dolt test server, which no CI lane
gave cmd/bd, so they rotted unseen:

- TestE2E_DoctorFixMetadataRoundtrip, TestE2E_MigrateDoltMetadata,
  TestDoctorCheckHealthReportsVersionMismatchOnRepoLocalPort: bd init now
  defaults to embedded mode, where `bd sql` and `bd dolt start` are
  refused. Init with --server on a repo-local server of their own
  (repoLocalServerEnv: the suite's shared-server port vars cleared, server
  stopped at cleanup) and start it explicitly, since BEADS_TEST_MODE=1 never
  auto-starts one. MigrateDoltMetadata's DELETE also needed `key` quoted.
- TestDoctor{Conventions,Pollution}MaxRows_EnvOnly_Exits2: bdRunRaw drops
  every BEADS_* variable, so the subprocess hit dolt.New's test-database
  firewall (exit 1) before the row cap; pass BEADS_TEST_SERVER=1.
- TestDoltAutoCommit_On_WritesAdvanceHead: the embedded engine keeps its
  data under .beads/embeddeddolt, not .beads/dolt; findDoltRepoDir looks
  in both.
- TestValidateCheck_AllClean: bd doctor validate runs five checks since
  the cross-table duplicates check was added.
- TestConfigValidateReadOnlyIsHermetic: readonly commands take a shared
  workspace gate, whose lock file (.beads/dolt.gate.lock) workspacegate
  creates on first use by design; compare the .beads tree without gate
  lock files.

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

* test(cmd/bd): undo each in-process execution's env and storage-mode leaks

Every in-process run of the bd command tree (runBDInProcess and the many
tests that call rootCmd.Execute directly) leaves process state behind:
PersistentPreRun exports the selected workspace as BEADS_DIR, loads its
.beads/.env, and records the workspace's mode in serverMode /
proxiedServerMode. With a Dolt test server, later tests in the same shard
then resolved a deleted fixture ("no active beads workspace found",
"migration sidecar is missing"), ran subprocess bd against the wrong
workspace ("recorded as proxied-server in .beads/metadata.json"), or took
the proxied path in RunE-level tests ("proxied-server UOW provider not
initialized", a nil-UOW panic in reopenProxiedResolve that killed a shard).

TestMain now registers a cobra initializer/finalizer pair
(installExecuteIsolation) that snapshots the environment and the two mode
globals when an execution starts and restores them when it ends; the
runners' restoreEnvSnapshot shares the helper. TestDoltConfigEnvironmentOverrides
used os.Setenv + defer os.Unsetenv, which deleted the suite's
BEADS_DOLT_SERVER_PORT (the test server's port) for every later test; it
uses t.Setenv now.

Full integration-tagged cmd/bd suite against a hermetic dolt (16 shards):
18 order-dependent failures and the shard panic gone; the 27 remaining
failures all fail alone too.

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

* fix(init): keep --quiet quiet through the Claude/Codex/Cursor auto-setup

`bd init --quiet` ("Suppress output") still printed the project
integration installers' progress to stdout ("Installing Claude hooks for
this project...", "Claude Code integration installed", ...): the
installers write to os.Stdout unconditionally. Point stdout at the null
device around them while quiet; their failures keep going to stderr as
before. Found by TestInitCommand's quiet case, which asserts no output and
had not run in CI (Dolt-gated).

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

* test(init): bring the Dolt-gated init tests up to the current init contract

These tests need a Dolt test server, so no CI lane ran them and they
drifted from the product:

- Embedded is init's default mode, so the server-mode assertions
  (.beads/dolt, opening the database on the test server, dolt_mode
  "server" in metadata.json) now pass --server (TestInitCommand,
  TestInitAlreadyInitialized, TestInitRedirect, TestInitBEADS_DIR,
  TestInitDoltMetadata, TestInitDoltMetadataNoGit, TestInitDatabaseFlag's
  metadata subtests). The in-process ones reset rootCmd's flags around
  themselves so --server cannot leak into later in-process inits.
- Each server init gets its own --database: the suite shares one test
  server, and a "test" database another test created belongs to another
  project (init refuses: PROJECT IDENTITY MISMATCH).
- The marker tests seed a current-era version witness: the legacy-upgrade
  guard refuses a non-empty .beads/dolt without one.
- The redirect test provisions the canonical target with config.yaml: bd
  ignores a redirect to a directory with no project files (#4692).
- Shared-server inits get a free port of their own
  (sharedServerTestEnv): the inherited BEADS_DOLT_SERVER_PORT is the
  suite's test server, which a shared-server start refuses as another
  project's, and the default shared port is 3308, a developer's live
  server.
- --shared-server's config.yaml is now nested YAML (dolt: shared-server:
  true); parse it instead of matching the old flat line.

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

* test(cmd/bd): run the Dolt-gated tests that skipped on a bare dolt.New

setupTestDB (config, kv and Linear round-trip tests), setupGatedTestDB
(mol ready --gated) and the rename-prefix and bd sql tests opened stores
with dolt.New(&dolt.Config{Path: ...}): no server port, no
CreateIfMissing, so against a running test server they got "database ...
not found" and skipped as "Dolt server not available". They now use the
suite's newTestStore helpers (skip only when no test server runs), and
what that exposed is fixed test-side:

- TestCustomStatusConfig: custom_statuses is read back ORDER BY name;
  look statuses up by name / expect name order.
- TestLinearRoundTripCoreFields, TestLinearPullMilestonesCreatesEpicHierarchy:
  linear.api_key is a yaml-only secret (LINEAR_API_KEY), push now needs an
  explicit linear.state_map, and batch push uses TeamLabels and
  issueBatchCreate, which the mock server now answers.
- TestSqlCommand: bd sql refuses in the default embedded mode; set
  serverMode for the server-backed store, and stop discarding RunE errors.
- TestE2E_AutoStartedRepoLocalServerPersistsAcrossCommands skipped on
  this process's embedded mode although every bd it runs is a subprocess
  on a --server workspace; gate on the dolt binary instead and stop the
  auto-started server at cleanup.

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

* test(cmd/bd): no fixed "unused" port, no swallowed JSON, no leaked front-door server

Three more things the Dolt-backed cmd/bd run exposed:

- TestTestServerConnection, TestSharedServerCfgNilHonorsSharedServer and
  the two TestLegacyGuard* e2e tests pointed bd at 127.0.0.1:59999 as a
  port nothing listens on. Any process on the host may hold it; a
  listener that accepts and resets turns the expected "connection
  refused" / "Dolt server unreachable" into another error. They take a
  just-freed port from closedLoopbackPort (testutil.FindFreePort) now.
- TestDoltSetConfigJSONOutput and TestDoltSetConfigWithUpdateConfig
  created .beads 0755, so bd's permissions warning landed in the JSON
  under test and the tests skipped ("output not pure JSON") every run.
  The fixture uses 0700, and non-JSON output fails instead of skipping.
- TestMigrateDoltModeFrontDoor's closing show/list auto-start a
  repo-local server after the reverse migration; nothing stopped it, so
  the suite's leak check failed (when the opt-in
  BEADS_TEST_MIGRATION_FRONTDOOR suite runs). It stops it at cleanup.

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

* ci(bazel): advisory cmd/bd Dolt-server tier (bazel-cmd-dolt)

No CI lane ran cmd/bd's Dolt-gated tests (TestCLI_*, the init and
store-backed suites, the doctor/e2e tests): main.yml's integration shards,
nightly's Full Test Suite, and Bazel's --config=prcore/ci and
--config=integration all pass BEADS_TEST_SKIP=dolt, so cmd/bd's TestMain
never starts a test server and those tests skip; the proxied and embedded
tiers run only their manifests' tests. They rotted unseen.

//cmd/bd:bd_dolt_server_test (tag dolt-server-cmd) runs the whole
integration-tagged cmd/bd suite, the integration build's bd_test, against
a hermetic dolt sql-server: BEADS_TEST_DOLT_SERVER=local starts it from
the pinned dolt in the test wrapper's runfiles, and
BEADS_TEST_REQUIRE_DOLT_CONTAINER=1 fails the target instead of skipping
into a cached pass. No test selection: the Go binary shards itself over
every top-level test (32 shards), so each runs exactly once, and
check_testcases.py fails a shard that ran none. --config=doltserver-cmd
has exactly --config=integration's build flags, so the two lanes share
bd_test's compile; prcore/ci and integration exclude the tag.

bazel.yml's new bazel-cmd-dolt job runs it exactly where bazel-integration
runs (same if: remotely on the farm for same-repo PRs, fork-ro/fork-rw,
and locally with the read-only cache in mode cache for forks). It is
advisory: job-level continue-on-error keeps a failure out of the call's
aggregate (BAZEL), and pr.yml's ci-gate reads its result (BAZEL_CMD_DOLT)
but requires it only while the committed top-level flag
BAZEL_CMD_DOLT_REQUIRED is "true" (now "false"; flipping it is the one
change needed). bazel-gate.sh accepts its skip in modes skip and local.

Policy tests: a third lane category in TestBazelLaneIsGatedAlongsideLegacy
(bazelFlagGatedLanes: gate env wired, never statically required, added by
the run script exactly when the pinned flag is "true"), the gate
simulation over every mode with the flag off (advisory: nothing it
reports reddens the gate) and on (exactly a gated lane), the cache-mode
and execution-mode checks, the tag taxonomy and prcore/integration
exclusions, and TestBazelCmdDoltJob (job steps, timeouts, .bazelrc
config equal to integration's build with no dolt skip or test selection,
the target's dolt-server rules, and bd_test's env repeated).

Measured locally (all fixes in this series, 32 shards, 16 at a time on a
shared host): 3267 top-level tests, all shards pass, max shard 313s (one
5001-issue export test, 214s, sets it), mean 100s.

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

* fix(init): hand the project installers a writer instead of swapping os.Stdout

The --quiet fix earlier in this series pointed the process-global
os.Stdout at the null device around the Claude/Codex/Cursor installers.
That works, but it mutates a global from inside a cobra Run: anything else
writing to stdout meanwhile (a goroutine, a future concurrent installer)
would vanish, and a concurrent read of os.Stdout is a data race.

The installers already write through env structs with stdout/stderr
fields. setup.ProjectInstallOutput carries the two writers, and
InstallClaudeProjectTo / InstallCodexProjectTo / InstallCursorProjectTo
use them (the old entry points keep the process streams). init passes
QuietProjectInstallOutput() under --quiet: progress discarded, error lines
still on stderr. The proxied-server init path (domain adapter
InstallClaudeProject now takes quiet) does the same, so its
"Installing Claude hooks..." is quiet too.

Consistent error policy under --quiet: errors still reach stderr. init's
own "Warning: failed to setup <installer>" lines were suppressed under
--quiet while the installers' "Error:" lines were not, and some installer
failures (Cursor rules) print nothing themselves; the warnings now print
whether or not quiet, like the installers' errors.

Coverage in required lanes: TestProjectInstallersReportToTheGivenOutput
(cmd/bd/setup) and TestEmbeddedInitA/basic, which now asserts that
`bd init --quiet` with agents enabled installs the Claude hooks and prints
none of the installers' progress (verified to fail with the quiet output
disabled).

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

* test(export): exercise the incremental-export fallback with a small threshold

TestTryIncrementalExport_ThresholdExceededFallsBack seeded
incrementalExportThreshold+1 = 5001 issues to cross the threshold. Batch
create is one transaction but still several statements per issue, so under
-race against the shared test server it took ~214 s, the longest test in
cmd/bd's Dolt-backed suite by far. The behaviour under test is only
"more changed issues than the threshold -> full export fallback".

incrementalExportThreshold becomes a var (same value), and the test, which
is not parallel, sets it to 20 and seeds 21 issues: 214 s -> 0.6 s.

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

* test(cmd/bd): tighten the flag-reset self-test, guards and canaries

Review follow-ups:
- TestResetCommandFlagsRestoresEveryFlag no longer skips a flag it cannot
  set: a flag type without a sample value, a Set error, or a non-pointer
  Value (which resetCommandFlags could not restore) is an error, so a new
  flag type cannot go untested. resetCommandFlags documents that it also
  resets flag-bound package globals.
- TestCobraParallelPolicyGuard treats .ExecuteC/.ExecuteContext/
  .ExecuteContextC like .Execute (the per-execution isolation writes the
  mode globals; a parallel execution would race).
- TestConfigValidateReadOnlyIsHermetic ignores only the gate a readonly
  command takes (.beads/dolt.gate.lock and its .info sidecar), not any
  "*.gate.lock*" file, so a new unexpected gate still trips the canary.
- TestCLI_CreateRejectsFlagLikeTitles: a bare `bd create --foo-bar` must
  fail and create no issue (bd-2c0's intent), next to the "--" cases.
- TestCustomStatusConfig cites why statuses come back in name order: the
  normalized custom_statuses table (#2961, 8537d943b) has no ordinal and is
  read ORDER BY name, like custom_types; the test predates it.

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

* ci(bazel): run the cmd/bd Dolt-server tier in 16 shards

Each shard pays ~30-40 s of fixed cost (TestMain plus its own dolt
sql-server), so 32 shards spent roughly 40% of the lane's executor time on
setup and added 32 farm actions to every PR touching cmd/bd. With the
5001-issue export test cut to under a second, 16 shards measure (locally,
--nocache_test_results): max 186 s, mean 137 s, 2,187 executor-seconds
(vs ~2,800-3,200 at 32), all 3,267 top-level tests, every shard passing.
TestBazelCmdDoltJob pins the count; bazel.yml's timing comment is
restated (cache mode ~20-30 minutes).

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

---------

Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-04 03:06:54 -07:00
Julian Knutsen
683993660f
fix(proxy): fail fast with a clear MySQL error when an external upstream is unreachable (#7181)
* fix(proxy): fail fast with a MySQL error when the external upstream is unreachable

A proxied-server command against a stopped external Dolt upstream stalled
~20-30s before failing with a bare "invalid connection". The local db proxy
stays up, so on a refused backend dial (or a front such as stunnel/socat
that accepts and closes because its own upstream is gone) it simply closed
the client connection. The MySQL driver reports that as invalid
connection / unexpected EOF, which the uow bootstrap ping (#6003) classifies
as a transient drop and retries with exponential backoff for its whole 30s
budget. Retrying cannot help: the proxy already proved the upstream at its
own startup, and the outage is the upstream's.

The proxy now answers such a connection itself with a MySQL ERR packet
(2003, HY000) in place of the server greeting, naming the upstream and the
cause, exactly as a real server refuses a connection before the handshake.
The driver surfaces it as a *mysql.MySQLError, which the bootstrap retry
already treats as permanent, so the command fails in ~0.1s with an
actionable message. Only shapes that prove the upstream is not serving
qualify: ECONNREFUSED/ENOENT/EHOSTUNREACH/ENETUNREACH on dial, or a backend
that reaches EOF having sent zero bytes (a MySQL server always speaks
first). A dial timeout or a drop after the greeting keeps the plain close
and the client's transient retry.

External backends only: a managed (local sidecar) backend is owned by the
proxy and its dial can be refused transiently while bd drives it (the
full proxied lane caught TestProxiedServerInitExplicitBeadsDirIsAuthoritative
hitting exactly that mid-init when this applied to every backend), so
managed backends keep the bare close and the client's bootstrap retry.
TestExternalProxyOutageAndRestoreReDialsTCPAndUnix asserted the old
silent close during an outage; it now asserts the ERR packet.

With the latency fixed, TestProxiedOutageReconnectAcceptanceMatrix is
renamed into the proxied discovery pattern as
TestProxiedServerOutageReconnectAcceptanceMatrix and placed in the Bazel
30-shard block by gen_proxied_shard_manifest.py's incremental --write
(shard 8). The frozen legacy 15-shard block is untouched; the test
hash-distributes there like every other test added since it was frozen.

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

* fix(proxy,uow): retry the proxy's upstream-outage report for ~1s; hedge the zero-byte case

Review follow-up to the fail-fast change.

A zero-byte close from the upstream is not proof it is down: Dolt closes
queued connections without a byte when max_connections/back_log are full,
when a queued connection times out, and while it shuts down for a
restart; an L4 front does the same while its target is replaced. Its
report now says "closed the connection before the MySQL greeting (down,
restarting, or at its connection limit)" instead of "unreachable", and
the comment no longer claims proof.

Refusals and endpoint churn also lost #6003's retry entirely, so an
external Dolt restart or a Service with no ready endpoints failed a
command at once. The client now retries the proxy's report
(proxy.IsUpstreamOutageError: 2003 with the "beads db proxy: " prefix)
for upstreamOutageRetryWindow (1s) from the first time it sees it, with
the backoff clamped so the last attempt lands at the window's end; other
transient errors keep the 30s budget. A real outage still fails in about
a second, inside the acceptance test's 3s bound.

Also: the dial report drops Go call-site wrapping ("dial tcp H:P:
connection refused"), truncation keeps UTF-8 intact, the comment states
how the packet differs from a real server's pre-handshake ERR (keeps the
'#'+SQLSTATE marker for vitess; 2003 is a client code chosen on purpose),
a Stats counter for reported outages, and the isTransientPingError
paragraph is reflowed and corrected.

Tests: pingWithRetry retries the report inside the window and gives up
at its end without using the full budget; openDB against a front that
plays the proxy (its real packet) and comes back 300ms after the first
connection succeeds in one call, and fails in about the window when it
never does; NewProxyServer enables the report for external backends
only; the dial message carries no Go type names; rune-safe truncation.

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

* test(proxied): fail, not skip, socat-bridged subtests in the Bazel lane

The external-unix front-door matrix subtest and both outage/reconnect
matrix subtests bridge an external endpoint with socat and skipped when
it was missing, so they could stop running without anyone noticing (the
parent test still passes). requireSocat now fails them when
BEADS_TEST_REQUIRE_SOCAT=1, which //cmd/bd:bd_proxied_test sets (its
remote workers have socat; a recent main run's external-unix subtest
passed there). The legacy GitHub 15-shard jobs have no socat and leave
it unset, so the subtests keep skipping there. The check now runs before
the upstream Dolt server is started, so a skip no longer pays for one.

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

* ci(proxied): measured weight for the outage matrix; pin it to legacy shard 1

Give TestProxiedServerOutageReconnectAcceptanceMatrix a duration entry
(80s: local runs measured 55-79s alone, 60-70s in its shard, and review
68-109s under load) and re-place it with the generator's incremental
--write: it moves from 30/8 to 30/11, one line, nothing else moved. The
heaviest estimated shard is now 435s against a ~357s median; a repack
would even that out but moves most assignments, so it is left to a
separate CI-only change that refreshes all durations together.

Legacy 15-shard block: the test would hash onto shard 14, already ~13.5
of the 15 min timeout on main. It is pinned to shard 1 (~6.5 min in
recent main runs) under the block's reviewed-pin rule; it skips there
today (no socat), and the pin keeps shard 14 safe if that changes.

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

---------

Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-04 02:37:58 -07:00
Julian Knutsen
59dcd83bbd
ci(bazel): use client-id for the rbe-prewarm app token; drop local plan paths (#7164)
actions/create-github-app-token (v3.2.0, pinned) deprecates its app-id
input in favor of client-id. rbe-prewarm's mint step now passes the
bazel-allocator App's public Client ID (Iv23ligrqVEhlamZnoPU, from
GET /apps/bazel-allocator) as a reviewed literal: it is not a credential,
and a literal keeps it policy-tested with the rest of the step instead of
in an unversioned repository variable. The private key stays a secret.

RBE_POOL_APP_ID is now unused, so its workflow_call declaration in
bazel.yml and its pass-through in pr.yml and nightly.yml are removed,
and a policy test rejects any workflow mentioning it again. The
repository secret can be deleted.

engdocs/CI_REQUIRED_CHECK_TOPOLOGY.md's "rbe-west Pre-warm" section now
documents the client-id, the single remaining secret, and
RBE_PREWARM_WORKERS (default 1, clamped to 4, 0 = kill switch, repo
variable currently 2). It also no longer cites a maintainer's local
planning-notes path; a new tracked-file policy test fails if one
reappears.

Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-03 23:03:41 -07:00
Julian Knutsen
88d9b645a6
ci(bazel): pre-warm rbe-west's OSS worker pool when a same-repo PR's Bazel lanes start (#7159)
* ci(bazel): best-effort pre-warm rbe-west's OSS worker pool on PR open

bazel.yml's Bazel lanes each separately wait ~120s at "N actions, 0
running" while gastownhall/gascity's rbe-west NativeLink worker pool
scales up from zero. Add an advisory rbe-prewarm job (never a `needs`
of any lane, never in bazel-gate.sh's vocabulary, job-level
continue-on-error so it can never fail bazel.yml's own run) that
mints a short-lived installation token for a "bazel-allocator" GitHub
App (installed on gastownhall/gascity only, Actions read/write +
Metadata read) and dispatches gastownhall/gascity's
rbe-worker-pool.yml ahead of time, only when this run's lanes will
actually target rbe-west's "oss" instance (modes remote and fork-rw;
fork-ro targets a separate pool this doesn't serve).

Adds RBE_POOL_APP_ID / RBE_POOL_APP_PRIVATE_KEY as new optional
workflow_call secrets, threaded through every caller (pr.yml,
bazel-farm.yml, nightly.yml); either secret missing (the app not yet
provisioned) or repo var RBE_PREWARM_WORKERS=0 disables pre-warming
cleanly. Policy tests (scripts/bazel_rbe_prewarm_test.go, plus updates
to the existing bazel.yml structural tests) pin the mode gate, the
credential scope, the dispatch target, and that the job can never gate
or fail a run; each invariant was hand mutation-tested. Docs added to
engdocs/CI_REQUIRED_CHECK_TOPOLOGY.md ("rbe-west Pre-warm").

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

* fix(ci): close rbe-prewarm token-theft path, fix stale secret-count docs (B1)

Security review of bdef342d5 found a BLOCKER (B1): the rbe-prewarm job
checked out inputs.checkout-sha (the fork head, reachable via
bazel-farm.yml's pull_request_target path) and then ran
.github/scripts/rbe-prewarm.sh with the minted gastownhall/gascity
dispatch token present. Script-file edits don't require workflow-approval
the way workflow-file edits do, so a VIP fork or same-repo branch pusher
could edit that script to steal the shared bazel-allocator key.

Fix: delete the checkout step and the .sh file; inline the dispatch logic
into the step's own `run:` block, whose bytes always come from the
trusted (approval-gated) workflow definition even under
pull_request_target. Mint the token in the immediately preceding step;
nothing after the mint step touches a repo-relative path. Stop forwarding
RBE_POOL_APP_ID/RBE_POOL_APP_PRIVATE_KEY from bazel-farm.yml (that fork
path now gets a cold start instead of pre-warming) and narrow the job's
`if:` to mode == 'remote' only (fork-rw never carried secrets anyway, so
it was dead weight - S1).

Also addresses the review's should-fix items:
- S2: document the widened trust boundary (the bazel-allocator key is
  shared with gascity's own rbe-west scaler; leak blast radius; rotation
  breaks the scaler, so the kill switch is unset-secret /
  RBE_PREWARM_WORKERS=0, not rotation) as an accepted risk in bazel.yml's
  header and engdocs/CI_REQUIRED_CHECK_TOPOLOGY.md.
- S3: fix stale "exactly four secrets" claims (pr.yml/nightly.yml pass 6;
  bazel-farm.yml now correctly passes 4 again) and the false "never a
  long-lived credential" claim.
- S4: flag the continue-on-error-preserves-caller-success assumption as
  reasoned-through but not live-validated in this sandbox.
- N1: drop the unused RBE_PREWARM_IDLE_MINUTES knob entirely.
- N4: strengthen the dispatch-target test to check exact gh command
  strings and ban hardcoded repo/workflow literals outside $POOL_REPO/
  $POOL_WORKFLOW.

Test changes (scripts/bazel_rbe_prewarm_test.go rewritten; ci_workflow_test.go,
bazel_farm_workflow_test.go, bazel_cache_mode_test.go updated for the new
job shape): new TestRBEPrewarmNoCheckoutStep,
TestRBEPrewarmNothingAfterMintTouchesARepoPath,
TestRBEPrewarmTokenOnlyInDispatchStep, and
TestRBEPrewarmAppSecretsOnlyExpectedCallers directly target the B1
mutation class; TestRBEPrewarmDispatchScriptBehavior keeps the fake-gh
behavioral coverage for the now-inlined dispatch script. Verified by hand
that both of the reviewer's mutations (widen the `if:` back to include
fork-rw; add a step after mint running a checked-out script) are now
caught.

Verification: go test ./scripts/..., go vet, gofmt, actionlint on the
four touched workflow files, make ci-pr-policy, make bazel-sync-check,
and `bazel test //scripts:scripts_test` all pass.

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

---------

Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-03 22:31:17 -07:00
Julian Knutsen
1137aeb70d
ci(bazel): embedded-Dolt tier 20/5 → 50/15 duration-balanced Bazel shards (F1) (#7156)
* ci(bazel): embedded-Dolt tier 20/5 -> 40/14 duration-balanced shards (F1)

Give the Bazel-only bazel-embedded job its own duration-balanced manifest
blocks for //cmd/bd:bd_embedded_test (20 -> 40 shards) and
//internal/storage/embeddeddolt:embeddeddolt_embedded_test (5 -> 14
shards), decoupled from PR Risk's/main.yml's legacy frozen 20/5-shard
fork/push jobs, mirroring F2's bd_proxied_test precedent.

- Measured every TestEmbedded* / embeddeddolt test's wall time in
  isolation; split 21 cmd-tier and 1 storage-tier single top-level test
  over 180s into disjoint sub-tests (3 irreducible exceptions left:
  TestEmbeddedUpdateConcurrent 475s, TestEmbeddedCloseConcurrent 308s,
  TestLargeBatchApplyStatementCounts712_Embedded 261s).
- New scripts/ci/gen_embedded_{cmd,storage}_shard_manifest.py +
  _embedded_shard_manifest_lib.py generate/check duration-balanced
  manifest blocks (LPT packing, incremental --write/--repack, exact-once
  --check), chosen at N=40/M=14 where the heaviest shard reaches the
  irreducible-test floor.
- Fixed 18 stale legacy 20-shard cmd manifest entries (and 1 storage
  entry) left over from earlier test splits, which would have hard-failed
  every shard of PR Risk's real test-embedded-cmd jobs on their next run.
- New scripts/embedded_shard_count_test.go policy tests tie the
  Bazel-only block's shard count to bazel.yml's check_shard_coverage.py
  argument and catch generator staleness; generalized
  TestBazelRetiredLanesCheckListedTestsRan's live-shard-count dispatch
  from bd_proxied_test-only to a map covering both embedded targets;
  removed TestBazelEmbeddedJobMirrorsEmbeddedTier's now-invalid
  BUILD.bazel-shard-count-equals-PR-Risk-matrix assertion.
- Verified: go test ./scripts/..., bazel test //scripts:scripts_test,
  actionlint, make ci-pr-policy, make bazel-sync-check all pass; full
  local bazel test of both targets at 40/14 shards passes 2/2; mutation
  testing confirms each new/changed policy test fails exactly when it
  should.

See ~/beads-bazel-plan/f1/impl-report.md for full detail.

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

* fix(embedded-dolt): skip 712-item statement-count assertion under -race (F1)

TestLargeBatchApplyStatementCounts712_Embedded genuinely costs ~260-300s
under -race (confirmed by solo re-measurement: 298.60s) -- 14014 real SQL
statement round-trips through the race-instrumented in-process Dolt engine,
not an artifact and not splittable (one indivisible ApplyBatchInTx
transaction). It was the storage tier's single-test floor for CI shard
packing.

Apply the exact precedent TestLargeBatchApplyWallClock_Embedded already set
for its 1000-item shape: skip this assertion under raceEnabled (the cost is
race-instrumentation overhead on the Dolt engine's own internal
goroutine/lock machinery, not this test's own logic) and extend nightly.yml's
"Embedded Dolt batch-apply suite (non-race)" step's -run regex so the full
pinned 14014-statement baseline still runs, non-race, every night. Verified
directly: under -race the assertion now skips in 0.00s; without -race it
still runs and asserts Total=14015 (within the existing +/-2 tolerance) in
36.76s.

Updates scripts/ci_workflow_test.go's
TestNightlyFullTestRunsEmbeddedDoltBatchApplySuite to match the extended
regex.

Storage tier's new single-test ceiling under the per-PR -race lane drops
from ~260.7s to 152.38s (TestBatchApplyContract).

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

* ci(bazel): correct cmd-tier long-pole durations, re-pack embedded manifolds (F1)

Investigated coordinator item 2 (single-test long poles): TestEmbeddedUpdateConcurrent
(recorded 475.39s) and TestEmbeddedCloseConcurrent (recorded 308.06s), plus
the two other >180s cmd-tier entries from the same capture
(TestEmbeddedInitA 196.94s, TestEmbeddedEpicCloseEligibleReason 192.47s).

Root cause: NOT host contention, NOT backoff/retry sleeps (bdRunWithFlockRetry
contributes negligibly), NOT race-instrumented-subprocess overhead alone.
These numbers were captured via `bazel --nohome_rc test --config=embedded`
with the then-current 20-shard legacy manifest (~10-11 tests/shard) and
`-test.parallel=4`. Go's t.Parallel() starts each parallel test's elapsed
clock when its function is invoked, before the Parallel() call blocks it
waiting for a free one-of-4 slot -- so a test queued behind several other
heavy shard-mates has that queueing wait baked into its own recorded
`--- PASS: TestX (Ys)` time. This is shard-composition-dependent scheduling
delay, not a cost intrinsic to the test.

Confirmed two ways in an isolated clone (not this worktree, per the
no-plain-go-test-from-a-beads-checkout rule):
- Solo (no rivals at all): 151.83s / 106.48s / 63.58s / 66.08s.
- All four together with the real -race -test.parallel=4 flags and exactly
  4 tests requested (so nobody queues -- parallel slots == test count):
  141.34s / 113.80s / 69.79s / 74.63s.
Both agree closely and both are far below the capture-time numbers.

F1's LPT packer already isolates the heaviest tests into shards with few or
no other heavy rivals (TestEmbeddedUpdateConcurrent lands alone in its own
40-shard-block shard), so under the new manifest these tests see little to
no queueing delay in real CI. None of the four needed splitting, parallel
subtests, or raceEnabled-scaled N: once correctly measured, none exceeds the
180s single-test guideline (new corrected weights: 155.0 / 115.0 / 72.0 /
77.0s). Corrected scripts/ci/embedded_cmd_test_durations.json accordingly
(with a doc-comment explaining the methodology and both confirmations) and
re-packed the 40-shard Bazel-only block (--repack --write); --check passes
(exact-once coverage of all 241 discovered tests). The frozen legacy 20-shard
block is untouched and independently re-verified exact-once by simulating
embedded-test-shard.sh across all 20 shards (241/241 tests, no
duplicates/misses/errors).

New cmd-tier single-test ceiling: 179.47s (TestEmbeddedCloseAlreadyClosed,
likely itself somewhat inflated by the same mechanism but already under the
180s line as recorded, so no action needed).

Also updates scripts/ci/embedded_storage_test_durations.json: the prior
commit's raceEnabled-skip for TestLargeBatchApplyStatementCounts712_Embedded
means it now costs ~0s in the per-PR -race lane bazel-embedded actually
packs for (not its real ~260-300s non-race cost, which nightly.yml still
exercises) -- weight set to 1.0 with a doc comment tying it to the skip in
large_batch_apply_measure_test.go. Re-packed the 14-shard Bazel-only block
accordingly; --check passes (exact-once coverage of all 387 discovered
tests, excluding TestMain/TestConformance per that file's existing
convention). The frozen legacy 5-shard block is untouched and independently
re-verified exact-once via embedded-storage-test-shard.sh simulation
(388/388 tests, no duplicates/misses/errors).

Verification: go test ./scripts/... (includes the nightly.yml policy test),
make ci-pr-policy, make bazel-sync-check, actionlint all pass. Real local
`bazel --nohome_rc test --config=embedded //cmd/bd:bd_embedded_test
//internal/storage/embeddeddolt:embeddeddolt_embedded_test`
(--local_test_jobs=8, both targets together, on a shared/noisy sandbox host)
passes both targets; per-shard wall time from each shard's test.xml: cmd/bd
max 218.9s (shard 23/40, min 20.6s), storage max 251.1s (shard 5/14, min
0.98s) -- down from the prior oversubscribed sweep's 783.41s / 351.94s and
well under the single-test-floor-based ~475s projection this slice started
from. Projected tier lane time (max of the two targets, real dedicated CI
runners should do at least this well): ~251s, under the 5-minute target.

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

* test(embedded): un-vacuous TestEmbeddedDepB edges, split epic-close test, trim concurrency stress N (F1 review)

Coordinator review follow-ups on the F1 embedded-Dolt resharding slice:

- TestEmbeddedDepB (one of TestEmbeddedDep's two CI-speed split halves) was
  asserting its tree_* subtests against an edgeless graph, passing
  vacuously; restores the same parent-child/blocks edges TestEmbeddedDepA
  builds so those subtests exercise real multi-node traversal (review S2).
- TestEmbeddedEpicCloseEligibleReason split into
  TestEmbeddedEpicCloseEligibleReasonFlag/...Output for CI shard balance,
  matching the project's established single-concern split pattern.
- TestEmbeddedUpdateConcurrent/TestEmbeddedCloseConcurrent's
  issuesPerWorker reduced 5->2: under real concurrent-shard-load
  measurement these were genuine (not queueing-artifact) serialized-write
  costs; 2 preserves every invariant the test checks (duplicate-ID
  detection across all workers, one non-decreasing-list-count check per
  worker) at a fraction of the serialized work.
- large712ShapeName: the 712-shape's race skip and its zero-match guard now
  share one named constant instead of two independent literal shape-name
  strings, so a future rename of the shape can't silently skip the pinned
  statement-count assertion under race (review N2).
- Comment-only fixes (review N5) in files referencing test names since
  renamed/split by this slice's earlier work: close_proxied_integration_test.go,
  graph_apply_test.go, storage_class_proxied_integration_test.go,
  tests/regression/discovery_test.go, plus doc-comment path cleanups (N1:
  drop unverified ~/beads-bazel-plan paths/bead ids in favor of the
  committed duration JSON files and engdocs/TESTING.md).

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

* ci(bazel): re-derive embedded-Dolt durations under concurrent load; cap cmd shards at Bazel's 50-shard limit (F1 round 2)

Coordinator review required re-deriving every per-test duration weight from
a single, consistent, CI-realistic measurement (all shards running
concurrently, -test.parallel=4, race-enabled) instead of the prior pass's
mix of crowded-shard captures and solo/4-together spot-corrections, and
required measuring per-shard wall time via BEP testAttemptDuration rather
than a shard's outer test.xml <testsuites time> (which can include a
different, already-finished shard-mate's setup/teardown).

- scripts/ci/embedded_cmd_test_durations.json (242 tests) and
  scripts/ci/embedded_storage_test_durations.json (387 tests) rewritten in
  full from one consistent sweep. Every entry is now a fresh measurement;
  none is a carried-over capture-time value or an unverified estimate. Both
  files' _comment blocks retract the earlier "queueing delay baked into a
  test's own reported elapsed time" theory (testing.go's (*T).Parallel does
  not add wait time to a blocked test's own clock) and document the real
  methodology.
- Only one cmd-tier test remains over 200s (TestEmbeddedListFiltering,
  239.70s), already under the ~240s ceiling; no further top-level splits
  were needed this round.
- New finding: Bazel hard-caps shard_count at 50 per sh_test-like rule
  ("Having more than 50 shards is indicative of poor test organization";
  a native analysis-time limit, not configurable). The previous 88-shard
  plan for //cmd/bd:bd_embedded_test (chosen as the LPT-packed floor before
  this limit was discovered) is reverted to 50, Bazel's real ceiling.
  Repacking the fresh weights at 50 shards gives a heaviest shard of
  409.6s -- above the single-test floor of 239.7s, because 50 bins is not
  enough headroom over the suite's ~20145 measured test-seconds to flatten
  every bin to that floor. This makes the <=5 min lane target unreachable
  for the cmd tier via resharding alone within Bazel's native per-rule
  limit; see ~/beads-bazel-plan/f1/impl-report.md section 3c for the full
  writeup and the two remaining levers (suite-wide speedups or a
  multi-Bazel-rule split), neither attempted in this slice.
- internal/storage/embeddeddolt gets 15 Bazel-only shards (unaffected by
  the 50-shard cap): LPT-packed heaviest shard 225.3s, within target.
- cmd/bd/BUILD.bazel, internal/storage/embeddeddolt/BUILD.bazel,
  .github/workflows/bazel.yml, engdocs/CI_REQUIRED_CHECK_TOPOLOGY.md,
  scripts/embedded_shard_count_test.go, scripts/pr_risk_bazel_coverage_test.go,
  scripts/ci/gen_embedded_cmd_shard_manifest.py updated to the corrected
  50/15 shard counts (and, for the generator, N3: --write without an
  explicit total_shards now errors instead of silently regenerating the
  frozen legacy 20-shard block).
- .github/scripts/embedded-{cmd,storage}-test-shards.txt: re-packed
  Bazel-only blocks at 50/15; frozen legacy 20/5 blocks untouched except for
  N5 fixes to stale entries left by this slice's earlier test splits
  (TestShardScriptsListOnlyRealTests catches this class of bug; both
  legacy blocks reconfirmed exact-once).
- .github/workflows/nightly.yml / scripts/ci_workflow_test.go (N4): the
  embedded-dolt batch-apply nightly step now runs with `if: ${{
  !cancelled() }}` and its own explicit `-timeout 20m`, independent of the
  job-level timeout, with both halves now asserted by
  TestNightlyFullTestRunsEmbeddedDoltBatchApplySuite.

Verified: gofmt -l clean, go vet ./scripts/... clean, go test ./scripts/...
green, both generators' --check pass at 50/15 (and legacy 20/5 remain
exact-once via the frozen-block invariant).

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

* test(ci): rename embedded manifest staleness tests out of the ^TestEmbedded skip

The allowlisted go-test leg runs with -skip ^TestEmbedded, so tests named
TestEmbedded*ShardManifestGeneratorNotStale never ran there and the leg
failed with "matched no test that ran".

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

---------

Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-03 21:30:03 -07:00
Julian Knutsen
6be9c861a8
ci: advisory workflows on Blacksmith with restore-only caches, folded matrices, path filters (F7c) (#7147)
* ci(advisory): move Conformance/Regression/Migration/Smoke/Docs/Proxied-Local to Blacksmith, fold matrices, path-filter, drop redundant nix-build PR trigger (F7c)

Reduces per-PR GitHub-hosted job load for advisory (non-required) workflows
per the "PR CI -> 5 min" plan, slice F7c. None of these workflows gate the
required CI Gate / PR Risk Gate checks.

- conformance.yml: same-repo PR/merge_group runs move to Blacksmith
  (4vcpu); PR trigger gets the shared "upgrade-relevant code" path filter
  (any non-test Go change or build input); also now runs on push to main.
- regression.yml: fold detect-regression-need into regression's first step
  (gated via `if:`), eliminating a whole job; move to Blacksmith.
- migration-test.yml: fold the 14-version x cache-identity matrix into 3
  shards (src/pre-dolt/dolt-runtime), looping every version in a shard via
  a new "Verify explicit historical upgrades" step so a bad version does
  not hide the rest; gains the shared path filter; move to Blacksmith.
- cross-version-smoke.yml: fold the 1-job-per-version matrix into chunks of
  5 (delegated to upgrade-smoke-test.sh's native SMOKE_VERSIONS support);
  gains the shared path filter; move to Blacksmith.
- docs-mintlify.yml, proxied-local-smoke.yml: move to Blacksmith
  (2vcpu/4vcpu); add missing timeout-minutes where absent.
- nix-build.yml: drop the pull_request trigger — pr-risk.yml's required
  test-nix job (nix run + nix flake check) is a strict superset of
  `nix build .#default`, pinned by a new regression test.
- main.yml: add blacksmith-setup-go-cache, a push-to-main-only job that
  warms setup-go's implicit cache with cache: true, since Blacksmith
  runners cannot see GitHub-saved actions/cache entries that the six
  workflows above now rely on via setup-go's own caching. Carves a scoped,
  documented exception into assertPinnedGoCacheActions for this one job;
  every other setup-go step in main.yml/pr.yml/pr-risk.yml still must pin
  cache: false.

Forks and Dependabot PRs are unaffected (still ubuntu-latest, no secrets),
via the same conditional runner expression used elsewhere in the repo.

New policy tests in scripts/ci_f7c_advisory_test.go pin: path-filter
identity across the three filtered workflows, full version-set coverage
of the migration-harness fold (no scenario dropped), the per-shard/per-
chunk retry-all-versions-even-on-failure loop, fork/dependabot runner
selection semantics, no Blacksmith job reads secrets, and that the new
cache-seed job exists and that its six consumers don't disable the cache
it warms. All new tests and their underlying behaviors were mutation-
tested (each fails when the behavior it pins is reverted).

Caveat for rollout: the Blacksmith cache-seed job assumes Blacksmith
labels have branch-protected cache isolation from fork/untrusted PRs at
the org level (spec-f7.md Group B precondition) — this needs confirming
with an org admin before merge, since the seed job's cache becomes shared
infrastructure the six advisory workflows implicitly trust.

Replayed the last 60 merged PRs' changed-file lists against the new path
filter: 20/60 would now skip Conformance/Migration/Smoke (matches the
spec's estimate), and none of the 60 touched non-test Go code while being
classified as skip.

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

* fix(ci,advisory): F7c review B1/B2 - pin migration fallback, restore-only Blacksmith caches

B1: migration-test.yml's non-Blacksmith historical-upgrades fallback was
`ubuntu-latest`, which actions/runner-images#14748 schedules to move from
24.04 to 26.04 starting 2026-10-19. 26.04 drops libicu74, which the v0.55.4
fixture's ICU ABI depends on (and which "Install test dependencies" installs
explicitly). Pin the fallback to the literal `ubuntu-24.04` label instead, and
add the matching sameRepoBlacksmith4vcpuNoble constant so the pin itself is
tested. Confirmed via `git show <pre-F7c>` that none of the other five
workflows F7c touched ever had a pinned-OS fallback, so this regression was
scoped to migration-test.yml only.

B2: Blacksmith cannot see GitHub-hosted cache entries, and a same-repo PR
writing a cache entry another PR or main later reads back unverified is a
poisoning vector. Make every advisory consumer (conformance, regression,
migration-test, cross-version-smoke, docs-mintlify, proxied-local-smoke)
disable setup-go's own implicit cache on self-hosted runners and restore-only
from a self-defined `blacksmith-sg-v1-...` key namespace (not setup-go's own
implicit key, so there is no dependency on Blacksmith's $ImageOS matching
GitHub-hosted resolution). Only main.yml's new blacksmith-setup-go-cache job
(push-to-main only, always trusted) saves: it always restores, unconditionally
re-runs every warm-up command (no longer gated on a cache hit, so a stale or
partial restore self-heals), and always saves under the same key. Delete the
now-unneeded goCacheImplicitCacheExceptions carve-out in ci_workflow_test.go.

Also convert cross-version-smoke.yml's smoke-binaries-* and regression.yml's
regression-baseline-* caches from a monolithic actions/cache (auto-saves on
any miss) into an explicit restore (always, modulo the job's own gate) / save
(gated off pull_request) pair, closing the same poisoning vector for
per-release binaries. migration-test.yml's historical-dolt-* cache is left
unchanged: it is already checksum-verified on every read by
scripts/migration-test/lib/binary.sh.

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

* test(ci,advisory): F7c review SF - behavioral tests, path filters, F7a naming coordination

Replace substring-matching tests with behavioral ones that execute the real
embedded bash/jq against synthetic input, closing the reviewer's 12 surviving
mutations:

- TestMigrationHarnessLoopExecutesBehaviorally runs the real "Verify explicit
  historical upgrades" step against a stub run.sh: every version in a shard
  still runs after an earlier one fails (closes `exit 0`/`break` mutations),
  failures are ::error:: annotated and written to $GITHUB_STEP_SUMMARY, a bad
  or empty SHARD_VERSIONS fails closed without ever invoking run.sh, and a
  hung version is bounded by `timeout --kill-after` without hiding the version
  queued after it. The step's env now exports SHARD so its run: body has no
  literal ${{ }} GH-expression syntax left for a test harness to choke on.
- TestMigrationHarnessCacheHashMatchesDerivation pins each shard's cache-hash
  against sha256(join(",", <shard's cache-identity strings>))[:16], recovered
  from the pre-fold 14-entry table (git show 362eecc6bf), closing a stale-
  cache-hash mutation.
- TestMigrationHarnessDoltRuntimeStepGatedByShard pins the exact gate
  expression for "Install Dolt test runtime".
- TestCrossVersionSmokeChunksEveryResolvedVersion now executes the real jq
  chunking and join programs (via the new ghExtractJQProgram helper) against
  synthetic version lists of several sizes, and asserts the smoke step's run:
  command is an exact match - closing jq-slice-off-by-one and
  dropped-SMOKE_VERSIONS mutations a substring check could not catch.
- TestRegressionStepsAfterDetectAreGated pins that every step after
  regression.yml's detect step stays gated on
  steps.detect.outputs.run_regression == 'true', closing an
  ungated-regression-step mutation.
- TestBlacksmithSetupGoSeedExistsForAdvisoryConsumers,
  TestAdvisoryBlacksmithConsumersAreCacheRestoreOnly (replacing
  TestAdvisoryBlacksmithConsumersKeepImplicitSetupGoCache),
  TestBlacksmithSetupGoCacheKeysMatchAcrossSeederAndConsumers, and
  TestAdvisoryBinaryCachesAreRestoreAlwaysSavePRGated cover the B2
  restore-only/seeder-saves cache topology end to end, including a
  seeder/consumer key-match check and scoping the "no save in a consumer job"
  check to the blacksmith-sg-v1- namespace specifically so migration-test.yml's
  legitimate, checksum-verified historical-dolt-* cache is not flagged.

Path filters: add scripts/migrate-legacy-to-current.sh to migration-test.yml
(the harness invokes it directly but it lives outside scripts/migration-test/)
and internal/storage/embeddeddolt/conformance_test.go plus backend/conformance/**
to conformance.yml, with a new TestConformancePushPathsMatchPullRequestPaths
pinning push.paths and pull_request.paths stay identical.

Coordination with F7a (ci/f7a-blacksmith-fold, lands before F7c): F7a
independently defines its own sameRepoBlacksmith4vcpu/2vcpu constants and a
TestSameRepoBlacksmithExpressionSemantics, and is moving a real GH-Actions
expression evaluator into a shared scripts test helper file. Per the
coordinator, rename this branch's same-named test to
TestF7cAdvisorySameRepoBlacksmithExpressionSemantics (deliberately left as the
same simple literal mirror it always was, not a competing evaluator) so it
does not collide with F7a's helper on rebase; at rebase time this test should
be reduced or replaced in favor of F7a's shared evaluator.

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

* docs(ci): update stale nix-build PR-trigger and renamed check-name references (F7c review S6)

F7c (bb81136203) dropped nix-build.yml's pull_request trigger as redundant
with PR Risk's test-nix job, and folded cross-version-smoke.yml's one-job-
per-version matrix into one job per 5-version chunk. Update the docs that
still described the old topology:

- CONTRIBUTING.md: nix build .#default no longer runs on PRs; point at PR
  Risk's required test-nix job instead.
- update-vendor-hash.yml: same correction in its header comment and the
  GITHUB_TOKEN-retrigger caveat.
- engdocs/CI_TEST_SURFACE_AUDIT.md: migration-test.yml now also runs on PRs
  (path-filtered, advisory) across 3 shards instead of 14 per-version legs;
  nix-build.yml's row now reflects push-to-main-only.
- engdocs/CI_REQUIRED_CHECK_TOPOLOGY.md: replace `Upgrade smoke
  (<version> -> candidate)` with the current `Upgrade smoke (chunk N)` job
  name in both the "do not require directly" list and the Cross-Version
  Smoke section; rewrite the Nix Build section to describe nix-build.yml as
  push-to-main-only (no longer a PR check to warn about requiring directly)
  and remove the now-unreachable `nix build .#default` bullet from the
  "do not require" list.

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

* ci(advisory): rebase onto F7a shared Blacksmith helper, drop duplicate const/evaluator

F7a (PR #7139, ci/f7a-blacksmith-fold) landed its own sameRepoBlacksmith4vcpu
const and TestSameRepoBlacksmithExpressionSemantics, plus a real GitHub
Actions expression evaluator (evalGHExpr/mustEvalGHRunsOn) in a new shared
scripts/ci_blacksmith_runner_test.go. This branch rebased onto
origin/ci/f7a-blacksmith-fold and reconciles the two:

- Removed this branch's duplicate sameRepoBlacksmith4vcpu definition in
  ci_workflow_test.go (rebase conflict); it's now served solely by F7a's
  shared const. sameRepoBlacksmith4vcpuNoble (F7c's B1 fix, fallback pinned
  to ubuntu-24.04 instead of ubuntu-latest) is kept as its own const, as
  instructed, since it is F7c-specific and not shared.
- Replaced TestF7cAdvisorySameRepoBlacksmithExpressionSemantics's
  hand-written Go mirror of the same-repo Blacksmith boolean logic with real
  evaluation of each F7c advisory job's actual, as-parsed runs-on expression
  text via F7a's evalGHExpr/mustEvalGHRunsOn, across the same event-shape
  truth table F7a's own test uses (same-repo/fork/dependabot/deleted-fork-
  head/merge_group/push/pull_request_target/schedule/workflow_dispatch).
  This covers all 8 F7c advisory Blacksmith jobs, including
  migration-test.yml's historical-upgrades job falling back to the literal
  ubuntu-24.04 label rather than ubuntu-latest. Confirmed via a cp-backed
  mutation (flipping the Noble fallback back to ubuntu-latest) that this new
  test, unlike the deleted hand-written mirror, actually catches a
  regression in the real expression text.
- Merged two more rebase conflicts in ci_workflow_test.go: the
  assertNoUnmanagedGoCacheSteps main.yml allowlist (F7a's
  windows-test-binaries-cache plus F7c's blacksmith-setup-go-cache) and a
  subsequent non-conflicting-but-incomplete 3-way merge of
  TestSameRepoBlacksmithRunners' main.yml entry (added
  windows-test-binaries-cache alongside blacksmith-setup-go-cache so the "no
  other Blacksmith label leaks" sweep covers both).

Did not merge TestBlacksmithAdvisoryJobsReadNoSecrets into F7a's
TestBlacksmithJobsReadNoSecrets (ci_workflow_test.go) even though the shared
helper file's doc comment suggests it; out of scope for this round per the
coordinator's explicit instructions, left as a follow-up.

Re-ran full verification after rebase + reconciliation: go build/vet/test
./scripts/..., bazel --nohome_rc test //scripts:scripts_test, actionlint
-shellcheck=shellcheck across all touched workflows, make ci-pr-policy, make
bazel-sync-check - all green. gofmt -l clean.

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

* fix(ci,advisory): close F7c re-review blocker X1 and S1-S5/N1 gaps

Re-review (~/beads-bazel-plan/f7c/rereview.md) found one blocker and five
should-fix gaps against ci/f7c-advisory-workflows:

X1 (blocker): migration-test.yml's historical-dolt-* cache was still a bare
actions/cache that auto-saves on any key miss on Blacksmith for same-repo
PRs. tar -P extraction plus lib/binary.sh's cp -f following a planted
symlink can redirect a write before sha256 verification ever runs, so the
"checksum-verified" exemption was unsound. Converted to the same
restore-always/save-off-PR split as smoke-binaries-*/regression-baseline-*,
dropped the exemption comments, and added it to advisoryBinaryCaches.

S1: TestRegressionDetectStepBehavioral executes regression.yml's detect
step's actual bash against a scratch git repo, closing mutation M13 (detect
step hard-wired to emit run_regression=false).

S2: TestBlacksmithReachableAdvisoryJobsNeverSaveACache sweeps every job in
every F7c advisory workflow (plus main.yml) whose runs-on resolves to a
Blacksmith label under a same-repo pull_request/merge_group context, and
fails on any bare actions/cache, any un-gated actions/cache/save, or any
setup-go/setup-node/setup-python step that would still cache there. Also
added a job-level `if: github.event_name == 'push' && github.ref ==
'refs/heads/main' && github.repository == 'gastownhall/beads'` guard to
main.yml's seeder job (TestBlacksmithSeederGuardedAgainstPullRequest) so a
future pull_request/merge_group trigger on main.yml can't turn the seeder
into a same-repo-PR-reachable cache writer.

S3: advisoryBinaryCaches' save-gate check is now exact-equality, not
strings.Contains, so a `... || true` gate can no longer slip past it.

S4: conformance.yml's path filters now include
internal/storage/embeddeddolt/test_fixture_test.go, which holds TestMain
for the whole package (moved out of conformance_test.go) and was previously
excluded by the blanket !**_test.go negation.

S5: main.yml's blacksmith-setup-go-cache seeder keyed its save on
github.sha, so every push to main - regardless of whether go.sum changed -
wrote a new multi-GB ~/go/pkg/mod + ~/.cache/go-build entry, risking LRU
eviction of F7a's own Blacksmith-seeded caches. Added a "Compute cache
date" step and keyed on the UTC calendar day instead, capping writes to at
most once per day; the same step/key was added to all 6 consumers so their
restore key stays byte-identical to the seeder's save key
(TestBlacksmithSetupGoCacheKeysMatchAcrossSeederAndConsumers).

N1: flipped `cache: ${{ runner.environment != 'self-hosted' }}` to
`cache: ${{ runner.environment == 'github-hosted' }}` on setup-go's own
implicit cache across all 7 call sites, so an empty/unknown
runner.environment value fails closed (caching off) instead of open.

Verification: go build/vet/test ./scripts/..., bazel --nohome_rc test
//scripts:scripts_test, actionlint -shellcheck=shellcheck
.github/workflows/*.yml, make ci-pr-policy, make bazel-sync-check all pass.

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

* fix(ci,advisory): close merge_group gap in binary-cache save gates

Running TestBlacksmithReachableAdvisoryJobsNeverSaveACache against every
Blacksmith trust context it is reachable under (instead of stopping at the
first match found, which made the check's coverage depend on Go's
randomized map iteration order) surfaced a real gap the S2 sweep was meant
to close: smoke-binaries-*, regression-baseline-* and historical-dolt-*'s
save gates were all `if: github.event_name != 'pull_request'`, a deny-list
that also admits a hypothetical future merge_group event. All three jobs'
runs-on expressions already resolve to a Blacksmith label under
merge_group, so a merge_group run would have been able to write those
caches too - the same same-repo-writer risk X1 closed for pull_request,
just not currently reachable since none of these three workflows has an
`on: merge_group:` trigger today.

Changed all three save gates to an exact allow-list of the triggers they
actually intend to write from (push, workflow_dispatch) rather than a
deny-list of the one trigger they don't. Updated
TestAdvisoryBinaryCachesAreRestoreAlwaysSavePRGated's wantSaveIf strings to
match, and made TestBlacksmithReachableAdvisoryJobsNeverSaveACache check
every blacksmithTrustContexts entry per job (sorted for determinism)
instead of breaking on the first Blacksmith-reachable context, so this
class of context-dependent gate gap can't hide behind map iteration order
again.

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

* test(ci,advisory): directly assert main.yml has no PR-reachable trigger

TestBlacksmithSeederGuardedAgainstPullRequest's job-level guard defuses the
vulnerability structurally, but a mutation that only edits main.yml's on:
block (adding pull_request:) without touching the job-level if: was not
caught by any existing test (confirmed: mutate.py's N6 probe survived).

Add TestMainWorkflowHasNoSameRepoPRReachableTrigger, the direct half of
F7c review fix S2's "pin the seeder's trust boundary" ask: assert main.yml's
on: has none of pull_request/pull_request_target/merge_group/workflow_run,
and still has push. Confirmed this kills N6 (manually applied and reverted
via a cp backup).

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/37159233834
(`make bazel-sync`: gazelle, tools/bazel/go_srcs.py, bazel mod tidy).
Only BUILD.bazel, MODULE.bazel and MODULE.bazel.lock are ever pushed; see
scripts/bazel-autofix-push.sh.

---------

Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
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-03 16:03:39 -07:00
Julian Knutsen
fac9a1e32c
ci: same-repo Linux PR jobs on Blacksmith; fold tiny checks and cross-compile legs (F7a) (#7139)
* ci: F7a same-repo Blacksmith moves and job folds (pr.yml, pr-risk.yml)

Move cache-free same-repo pr.yml/pr-risk.yml jobs onto the org's Blacksmith
runner pool (forks/Dependabot stay ubuntu-latest), and fold several
independent single-purpose jobs into fewer multi-step jobs, to cut same-repo
PR queue time without changing either required gate's name or its token
contract:

- fast-checks: folds check-build-tags, check-version-consistency,
  check-migration-hygiene, check-no-beads-changes and fmt-check into one
  Blacksmith job with five independent steps; ci-gate reads each step's
  outcome via job outputs into the same CI_GATE_REQUIRED token the standalone
  job used, plus a FAST_CHECKS backstop token for a lost job.
- check-release-target-cross-compilation: 8 per-target matrix legs collapse
  to 2 (unix/desktop), driven by the new scripts/ci/release-targets.txt
  manifest (kept in sync with .goreleaser.yml) and
  scripts/ci/check-release-cross-compile.sh.
- advisory-reports: folds build-examples and complexity-report (both
  already advisory) into one job, keeping their pre-fold
  step-level continue-on-error/timeout design.
- windows-make-shell: 3-way host matrix folds into one job with an
  aggregator step reproducing the old native/MSYS2/Cygwin pass/fail rules;
  test-windows-doltversion and test-windows-dbproxy-server fold into
  test-windows-small (neither was gated).
- Runner moves: fast-checks, advisory-reports,
  check-release-target-cross-compilation, check-doc-flags,
  pr-policy-wrapper, test-dolt-server-fingerprint (pr.yml) and test-nix
  (pr-risk.yml) move to the same-repo Blacksmith expression at their
  measured vCPU size.

Policy tests: extend TestSameRepoBlacksmithRunners for the moved/added jobs,
add TestSameRepoBlacksmithExpressionSemantics, TestBlacksmithJobsReadNoSecrets
and TestPRCIGateFastChecksTokens, retarget the complexity/build-examples and
dolt-server-fingerprint tests, rewrite
TestReleaseTargetCrossCompilationMatrixMatchesGoreleaser against the new
manifest, and teach the ci-gate simulation helper to resolve
needs.fast-checks.outputs.*. Document the moves/folds and the Blacksmith-off
revert set in engdocs/CI_REQUIRED_CHECK_TOPOLOGY.md.

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

* fix(ci): windows-make-shell/test-windows-small fail natively, raise advisory-reports headroom (review SF-1, SF-2, N-2, N-3)

- windows-make-shell: drop continue-on-error from install/exercise steps
  (kept only on the Cygwin setup step), delete the hand-written "Fail if a
  required Windows Make shell leg failed" aggregator, and delete the unused
  native/msys2/cygwin job outputs. A failing leg now reds the job via native
  GitHub Actions propagation instead of relying on an aggregator step that a
  mutation showed could silently undershoot (SF-1, N-3).
- test-windows-small: same fix - drop continue-on-error from doltversion/
  dbproxy-server steps and delete their aggregator step.
- Add timeout-minutes: 10 to the MSYS2 and Cygwin "Set up ... GNU Make"
  steps, so a hung installer download can no longer take out the whole job
  (SF-2).
- advisory-reports: raise timeout-minutes from 45 to 60 for more headroom
  above the sum of its step timeouts (N-2).

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

* test(ci): real GH-expression evaluator shared with F7c, behavioral xcompile test, secret/run-command coverage (review SF-3, SF-5, SF-6, N-1, N-4, N-6)

- New scripts/ci_blacksmith_runner_test.go: a real GitHub Actions expression
  evaluator (tokenizer + recursive-descent parser for ==, !=, &&, ||, !,
  parens, string literals, dotted lookups, with GitHub's short-circuit-
  returns-operand && / || semantics) that evaluates the REAL pinned
  sameRepoBlacksmith{2,4,8}vcpu expression strings from pr.yml/pr-risk.yml,
  replacing the old TestSameRepoBlacksmithExpressionSemantics' tautological
  hand-written Go mirror (SF-3). This file is the shared helper F7c's own
  TestSameRepoBlacksmithExpressionSemantics should rebase onto - see its
  doc comment for the "Public surface" (the three consts, evalGHExpr, and
  mustEvalGHRunsOn) (SF-5).
- ci_workflow_test.go: drop the old consts/test now living in the shared
  file; extend TestBlacksmithJobsReadNoSecrets to also scan job.If and
  step.If for secret references, not just env/with/run (N-4; container/
  services credentials and matrix-marker resolution stay deferred to F7b);
  pin fast-checks' build-tags step invoking all 3 scripts and the
  migration-hygiene BASE_SHA env, and add
  TestPRWindowsSmallDbproxyServerIsCGODisabled (N-6); add
  TestPRWindowsMakeShellLegsFailTheJob and
  TestPRWindowsMakeShellSetupStepsHaveTimeouts pinning the SF-1/SF-2 fixes.
- New scripts/check_release_cross_compile_test.go: behavioral test for
  check-release-cross-compile.sh using a fake `go` on PATH - asserts a
  failing target propagates as non-zero, every target in the group is still
  attempted, every invocation passes CGO_ENABLED=0 and the gms_pure_go tag,
  and an unknown group fails loudly with zero invocations (SF-6).
- check-release-cross-compile.sh: document the deliberate sequential-build
  (vs. the spec's 2-wide suggestion) choice and its revisit trigger (N-1).
- scripts/BUILD.bazel: add the two new test files to scripts_test's explicit
  srcs list (not a glob); verified against `make bazel-sync-check`.

All new/changed tests mutation-tested: each production-code mutation was
caught by the relevant test, then reverted via `cp` from a /tmp backup and
diff-verified byte-identical (never git stash / git checkout --).

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

* docs(ci): fix stale check names and aggregator description in CI_REQUIRED_CHECK_TOPOLOGY.md (review N-7)

- Replace the stale "Check build-tag policy", "Check version consistency",
  "Check for .beads changes" and "Check formatting" entries under "Do not
  require these existing check names" with the actual post-fold name,
  "Fast checks (build tags, versions, migrations, beads diff, fmt)", and add
  the cross-compilation and windows-make-shell fold's actual check names.
- Rewrite the windows-make-shell fold description: it no longer has a
  hand-written aggregator step (deleted per SF-1 in the prior commit), and
  "the separate cygwin job" is now described correctly as a pre-fold matrix
  leg, not a job.
- Update the advisory-reports timeout mention from 45 to 60 minutes (N-2).

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

* docs(ci): drop local design-doc path from topology doc

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

---------

Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-03 13:13:33 -07:00
Julian Knutsen
f0f8879ac4
ci(bazel): fork PRs execute on rbe-west's fork pool (fork-ro/fork-rw), cache fallback (#7136)
* ci(bazel): fork and Dependabot PRs execute remotely on rbe-fork when rbe-west's mint is open (F9)

Fork and Dependabot pull_request runs get no secrets, no OIDC token and no
repository variables, so rbe-west decides for them. bazel.yml's rbe job asks
rbe-fork-mint's /v1/status (rbe-mint.ops.gascity.com:8444) once per run:

- open, tier ro: mode fork-ro (instance oss-fork, the fork pool, nothing
  cached for anyone);
- open, tier rw (allowlisted author's own fork, allowlisted trigger): mode
  fork-rw (instance oss, the OSS pool);
- closed, refusing, unreachable or anything else: mode cache, exactly as
  today (local execution plus the anonymous read-only cache).

In the fork modes every lane runs, remotely, from a GitHub-hosted runner:
setup-bazel makes an EC P-256 key and a CSR, uploads the CSR as an artifact
of this run (the mint's proof), gets a ~2 h certificate
(fork-credential.sh, a byte copy of gascity's tools/rbe/fork-credential.sh
from F6) and writes an rc for grpcs://rbe-fork.ops.gascity.com:8444 with
the mint's instance. A lane whose certificate names another tier than the
rbe job fails ("re-run all jobs"). Fork lanes add --config=sole-run like
mode remote.

BAZEL_COVERS_FORKS ships "false" in pr.yml and pr-risk.yml: forks and
Dependabot keep their legacy tiers, and the Bazel lanes run beside them
(remotely while rbe-fork is open). F13 commits "true"; then a covered fork
run in mode cache is red, like a covered same-repo PR without the secret.

Safe while rbe-fork is dark: with the gate closed the mint's port resets
connections and the status probe falls back to mode cache in seconds; with
the mint up but disabled, canaried or rw off it answers open false or 403,
also mode cache.

Not in this change (later slices): bazel-farm.yml and its inputs stay (F12),
bazel.yml keeps its push trigger and pr.yml/pr-risk.yml gain none (F14).
keep their go build fallback on GitHub-hosted runners.

Tests: the rbe decision against a stubbed mint (ro, rw, closed, rw closed,
canary, busy, garbage, unknown tier, unreachable); the coverage and gate
matrices learn the fork modes, BAZEL_COVERS_FORKS and mint answers that
change between runs; TestBazelCacheModeReachesTheRC drives setup-bazel's
fork steps against a stand-in mint and checks each lane's rc;
fork-credential.sh's client contract and write-bazelrc.sh's fork mode and
exclusivity; the endpoint pin is allowed as exactly its one line.

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

* ci(bazel): fork-credential.sh retries the mint's 429 and never sleeps after the last try

A 429 (per-minute rate, live-certificate quota) may pass on its own like a
502, so it is retried with the same 10/20/30 s backoff (one minute, the
rate window); the loop no longer sleeps after the fourth failed attempt.
The cert request and the rbe job's /v1/status probe give up connecting
after 5 s, so a closed gate (dropped SYNs) costs seconds, not minutes.
Byte-identical to gascity's tools/rbe/fork-credential.sh.

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

---------

Co-authored-by: gascity-agent <agent@gascity.ai>
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-03 12:10:14 -07:00
Julian Knutsen
bc19f6e478
ci: parallel PR Lint matrix with pinned golangci-lint, fold duplicate Lint, split scripts-go-checks (F5) (#7127)
* ci(lint,scripts): fold duplicate Lint job; matrix PR Lint and scripts-go-checks (F5)

Lint (golangci-lint-action, only-new-issues) was functionally identical to
pr-lint-wrapper's native leg (H7): same pinned binary, config, flags, and
diff scope. Fold it into the wrapper in both pr.yml and main.yml, and drop
LINT from pr.yml's ci-gate.

pr-lint-wrapper becomes a 3-leg matrix (native/windows/darwin, fail-fast:
false) under the same PR_LINT_WRAPPER gate id, installing golangci-lint
v2.10.1 from a pinned, sha256-verified release binary
(scripts/ci/install-golangci-lint.sh) instead of go install/the Action, with
a per-leg golangci-lint cache (pr.yml restores only; main.yml's matrix is
the sole saver). scripts-go-checks becomes a 3-leg matrix
(scripts-test/vet/allowlisted, fail-fast: false) under the same
SCRIPTS_GO_CHECKS gate id, giving go vet its own build cache instead of
sharing the race build cache. main.yml gains a go-vet-cache job to warm that
cache on push; build-artifacts remains the Go module cache's sole saver.

Splitting each job's previously-sequential passes into parallel matrix legs,
combined with removing the duplicate Lint job outright, takes wall-clock
time off the PR gate's critical path.

Updates scripts/ci_workflow_test.go and scripts/pr_lanes_bazel_coverage_test.go
for the new matrices, cache topology, and the removed LINT id; adds
TestGolangciLintInstallScriptPinned. Updates engdocs/LINTING.md and the live
prose in engdocs/CI_REQUIRED_CHECK_TOPOLOGY.md (its disclaimed "historical
snapshot" gate-wiring block is left as-is).

Verified: go test ./scripts/..., bazel --nohome_rc test //scripts:scripts_test
(after adding engdocs/LINTING.md and .githooks/pre-commit as scripts_test
data), actionlint, shellcheck, make ci-pr-policy, make bazel-sync-check.
Confirmed lint-leg parity against current main with the pinned binary (0
issues PR-scoped; the same two pre-existing unparam findings full-tree,
unchanged) and scripts-go-checks leg parity standalone. Mutation-tested the
new/updated policy assertions with six deliberate breaks (dropped matrix
leg, reintroduced LINT, corrupted the pinned sha256, removed a cache-save
step, dropped the vet leg, reintroduced the lint job); each was caught with
an on-target failure.

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

* fix(ci): review-fix pass on F5's lint/scripts-go-checks matrix (SF-1..SF-5, N-1..N-8)

Addresses all SHOULD-FIX and NIT findings from the review of 7e858e2714
(no BLOCKERs):

- SF-1: lint/vet cache saves now run on !cancelled() instead of bare
  cache-miss, so a red lint/vet run (main is currently lint-red on two
  pre-existing, unrelated unparam findings) still warms the cache for
  PR legs.
- SF-2: ci-measurements.yml now exports golangci-lint's install dir onto
  PATH in the same step, since $GITHUB_PATH only takes effect in later
  steps.
- SF-3: adds a behavioral test (fake curl/tar) proving the install
  script's sha256 verification fails closed.
- SF-4: drops the commit sha from the golangci-lint cache key (saves
  only on config/dependency change, not every push) and trims the
  windows/darwin legs to cache only the small golangci-lint result
  cache, not their large GOCACHE.
- SF-5: removes the vet cache's dead non-race-build-cache fallback
  restore key (different path list, can never hit) in both pr.yml and
  main.yml.
- N-1..N-8: doc/comment accuracy fixes, restores the "moved code reads
  as new" caveat, adds a module-cache restore step and timeout-minutes
  to pr-lint-wrapper/go-vet-cache, pins fetch-depth/GOCACHE via new
  policy-test assertions, and flags a superseded doc snapshot.

New commit on top of 7e858e2714; existing commit trailers are left
untouched per explicit instruction. Not pushed, no PR opened.

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/37105481015
(`make bazel-sync`: gazelle, tools/bazel/go_srcs.py, bazel mod tidy).
Only BUILD.bazel, MODULE.bazel and MODULE.bazel.lock are ever pushed; see
scripts/bazel-autofix-push.sh.

---------

Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-10-03 09:36:20 -07:00
Julian Knutsen
6e9a15507e
ci(bazel): proxied-server tier 15 → 30 duration-balanced shards; un-hide 12 proxied tests (F2) (#7129)
* ci(bazel): raise proxied-server tier from 15 to 30 shards (F2)

bazel.yml's bazel-proxied lane (//cmd/bd:bd_proxied_test, run only with
remote execution) was sharing PR Risk's legacy 15-shard, frozen
bd-init-cost-proxy manifest block, so its longest shard was the long
pole of the Bazel-only lanes. Give it its own 30-shard block in
.github/scripts/proxied-cmd-test-shards.txt, bin-packed
longest-processing-time-first by measured wall-time
(scripts/ci/proxied_test_durations.json, captured from two bazel-proxied
job failures' testlogs) instead of the bd-init count proxy, via
scripts/ci/gen_proxied_shard_manifest.py's new --weights=duration mode.
Coverage is proven equal to the full discovered test set by two
independent methods (sorted-name diff and an actual 30-shard invocation
of proxied-test-shard.sh in list-only mode), both exact matches with no
duplicates.

cmd/bd:bd_proxied_test's shard_count moves to 30; PR Risk's and
main.yml's own test-proxied-cmd jobs keep their 15-shard matrix and
frozen manifest block untouched, per D2's retirement design (the Bazel
lane only needs to run the same tests, not the same split). Updated the
two coupled policy tests (scripts/ci_workflow_test.go's
TestBazelDoltServerTiersMirrorPRRisk, scripts/pr_risk_bazel_coverage_test.go's
TestBazelRetiredLanesCheckListedTestsRan) to allow the Bazel target's
shard_count to differ from its legacy job's own matrix size, and
engdocs/CI_REQUIRED_CHECK_TOPOLOGY.md / engdocs/TESTING.md to document
the split.

Verified: go test ./scripts/...; bazel --nohome_rc test
//scripts:scripts_test; actionlint on bazel.yml; make bazel-sync-check;
make ci-pr-policy; 3 representative shards (1, 15, 30 of 30) run
directly against Bazel-built race bd_test/bd_for_tests binaries and the
pinned dolt 2.2.0 release, all green, 55-81s wall time each (the
duration data's absolute seconds are from a contention-era sample and
run far faster here; the LPT balance itself, not the absolute SLA, is
the property that matters).

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

* fix(ci,bazel): close fork-PR gap in proxied 30-shard manifest validation (review B1/S1)

TestShardScriptsListOnlyRealTests only ran proxied-test-shard.sh at PR
Risk's legacy 15-shard matrix, never at the Bazel-only bazel-proxied
lane's 30-shard manifest block. bazel-proxied only runs in mode=remote
(skipped on fork PRs), so a fork PR could rename, duplicate, or corrupt
a TestProxiedServer*/TestServerMode* manifest entry in the 30-block and
merge green via go test ./scripts/... (which runs on every PR), only
breaking the required lane afterward on main and every same-repo PR.

Fix: the test now computes every shard total it must validate per
script (this job's own PR Risk matrix size, every distinct total found
in that script's own committed manifest, and - for proxied-test-shard.sh
- cmd/bd:bd_proxied_test's live shard_count from BUILD.bazel) and runs
the full per-shard validation loop at each one, relying on the script's
own duplicate/stale-name guards. It also sums each total's "manifest: N"
counts across all shards and fails if they sum to zero, catching a
silently-deleted block that would otherwise fall back to 100% hashing
undetected.

Also fold in S1: replace the independently hard-coded `30` overrides in
ci_workflow_test.go and pr_risk_bazel_coverage_test.go with
bazelProxiedShardCount(t), a new shared helper that reads
cmd/bd:bd_proxied_test's shard_count live from cmd/bd/BUILD.bazel. This
turns the check_shard_coverage.py argument comparison in
pr_risk_bazel_coverage_test.go into a genuine cross-file pin (BUILD.bazel
vs bazel.yml) instead of two literals that could drift together
unnoticed. ci_workflow_test.go's tiers loop no longer asserts
BUILD.bazel's shard_count against a value read from the same file
(tautological); it instead asserts pr-risk.yml's and main.yml's legacy
test-proxied-cmd matrices equal each other, restoring the pin S1 found
removed on this branch relative to base.

Verified against the reviewer's mutations (duplicate entry, bogus
entry, whole-block deletion, stale rename, matrix divergence, BUILD
shard_count drift, bazel.yml arg drift): each now fails go test
./scripts/..., where it previously passed.

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

* fix(ci,bazel): add generator --write/--check and freeze legacy manifest block (review S3/N1/N4/N5)

gen_proxied_shard_manifest.py:
- Add --write (rewrite only the target total_shards block in place,
  leaving every other block's header/body text untouched) and --check
  (regenerate in memory and diff against the committed block, exiting
  1 with the exact --write command needed if stale). Both operate via
  new split_blocks()/write_block()/check_block() helpers that round-trip
  the real manifest file losslessly.
- N1: fix the duration-weights header's false claim about the
  fallback ratio.
- N5: warn on stderr when proxied_test_durations.json has duration
  captures for tests that no longer exist in cmd/bd/*_test.go (renamed,
  split, or deleted since the last capture).

proxied-cmd-test-shards.txt:
- N4: mark the legacy 15-shard block's header as frozen for
  pr-risk.yml's/main.yml's legacy fork/push jobs: it is deliberately
  not kept in sync with newly-added tests (those hash-fallback
  instead), so regenerating it is not routine maintenance. Only the
  header text changed; all 149 explicit assignment lines and the
  "known blind spots" callouts are untouched (verified: a fresh
  --write would pack all 164 currently-discovered tests explicitly,
  silently changing which shard runs which test for this block, which
  is exactly what "frozen" means to avoid).
- Regenerate the Bazel-only 30-shard block's header via
  `gen_proxied_shard_manifest.py 30 --weights=duration --write` to
  describe --write/--check instead of the old manual-copy-paste
  instructions. proxied_test_durations.json has not changed yet (S2
  is still in progress), so this run only touched header text; the 164
  assignment lines are unchanged.

pr_risk_bazel_coverage_test.go:
- Add TestProxiedShardManifestGeneratorNotStale: runs
  gen_proxied_shard_manifest.py 30 --weights=duration --check under
  plain `go test` (skipped under `bazel test`, whose runfiles hold
  neither the generator's sources nor cmd/bd) so a stale 30-block
  (e.g. committed by hand, or left behind after adding tests without
  regenerating) fails scripts-go-checks on every PR, including forks.

tools/bazel/equivalence_allowlist.txt: allowlist the new test's guarded
Bazel skip.

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

* fix(ci,bazel): rename 14 undiscovered proxied-gated tests; N2/N3/N6 doc fixes

cmd/bd/*_test.go: 14 tests call requireProxiedServerEnv/
requireSharedProxiedServer but their names did not match the shard
scripts' discovery regex ^Test(ProxiedServer|ServerMode), so no CI lane
ever set BEADS_TEST_PROXIED_SERVER=1 for them and they silently skipped
everywhere (pre-existing gap, not caused by F2; list was in
~/beads-bazel-plan/f2/review/undiscovered_gated.txt).

Fixed by renaming rather than widening discovery: 162 of the 164
already-discovered tests call one of the two gate functions in the first
few lines of their body, so name and gate already correlate almost
perfectly, but the 14 tests' names are each styled differently with no
single regex term that would cover all of them without a hand-maintained
list. Renaming lets the existing discovery mechanism, hash-fallback
behavior, and both shard-coverage policy tests pick them up with zero
other changes. Checked each of the 14 names for cross-references first;
each appeared only in its own file plus at most one doc-comment in a
sibling file, both updated alongside the rename. No collisions with
existing test names.

Discovery went from 164 to 178 tests. Regenerated the Bazel-only 30-shard
block (gen_proxied_shard_manifest.py 30 --weights=duration --write) to
pack the 14 new tests; this is the first --write this round to actually
change assignments, not just header text. The frozen legacy 15-shard
block (N4) was deliberately left alone: the 14 renamed tests now
hash-fallback into it, exactly like every other test added since it was
last generated.

cmd/bd/BUILD.bazel (N6): restore the bd_proxied_test comment sentence
bazel.yml's mirror comment kept but BUILD.bazel's had dropped: PR Risk
builds its bd-cmd-test with -race, as here; main.yml's test-proxied-cmd
twin uses build-artifacts' non-race bd-cmd-test, so this lane is the
stricter of the two.

.github/workflows/bazel.yml, .bazelrc (N2/N3): remove stale timing
language ("30 shards of ~5-10 minutes" / ".bazelrc's leftover "15 shards
of ~10 minutes") never reconciled with this task's own local
representative-shard measurements (55-81s/shard); replaced with the
concurrency argument (30 simultaneous dolt sql-servers don't fit a
GitHub-hosted runner regardless of any single shard's wall time). Also
removes the "within 5s of each other" balance claim (S2): the underlying
duration weights are contaminated by -test.parallel overlap in the
top-level <testsuite time> figures they were derived from; a corrected
re-measurement is in progress (separate commit once it lands).

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

* fix(ci,bazel): re-derive proxied duration weights without overlap double-counting (review S2)

scripts/ci/proxied_test_durations.json's 178 entries are now each a
clean, single-job (no concurrent heavy bazel/dolt job on the box),
-test.parallel=1 measurement: a fresh manifest-aligned 30-shard sweep's
own <testsuite time> per top-level test where errors="0" (including
failing-but-complete suites, whose elapsed time is still trustworthy),
plus, for the handful too slow to finish inside Bazel's default
per-target timeout, a `bazel run` leaf-subtest-only sum that never adds
a parallel group's own PASS/FAIL line on top of its already-overlapping
children's lines. An earlier pass at this data summed every PASS/FAIL
line indiscriminately, double-counting parallel subtest groups.

A first attempt at re-measuring the slow stragglers overlapped in
wall-clock time with a second, unrelated heavy sweep and came out 2-3x
inflated versus the same tests measured cleanly; that contaminated data
was discarded in favor of isolated re-runs. TestProxiedServerDep2
initially looked hung during its isolated re-run (15+ minutes with no
PASS/FAIL output and no CPU growth in the top-level test binary) but
was not: each of its subtests does real `bd init --proxied-server`
work in a short-lived child process, and Go buffers a parallel
subtest group's output until the group's last member finishes. Letting
it run to completion (2357.72s) rather than guessing avoided reporting
bad data.

seconds_per_init_fallback is recomputed as the weighted average
seconds-per-init across all 178 measured tests (sum of durations / sum
of inits), for use only when a brand-new test has no entry yet.

Re-packing the 30-shard manifest with this corrected data changes the
shard-balance picture: TestProxiedServerDep2 and TestProxiedServerClose
are each large enough, alone, to dominate their own shard (~2358s and
~1105s locally) while every other shard clusters around 741-876s. The
"within 5s" claim this replaces was never earned by the underlying
data; .github/workflows/bazel.yml now documents the real, uneven
spread and flags that the two outlier shards' local numbers already
exceed the job's 25m step timeout on their own merits (unverified
against RBE's actual per-shard throughput, since this job has only
ever run remote).

Verified: go vet ./scripts/..., go test ./scripts/... (includes the
manifest/coverage policy tests), actionlint, make bazel-sync-check,
make ci-pr-policy all pass. Exact-once coverage re-confirmed: 178
manifest assignments for 178 discovered tests, zero duplicates, zero
gaps.

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

* fix(cmd/bd): apply re-review candidate fixes; revert 2 unready renames (R-B1)

Re-review found the prior round's 14 renames would turn the required
Bazel + legacy 15-shard lanes red once discovered:

- TestProxiedServerHistoryRemoteRefusalFrontDoorMatrix/external-unix and
  TestProxiedServerOutageReconnectAcceptanceMatrix/external-unix-socket
  built a dolt.sock path under t.TempDir(), which nests Bazel's hermetic
  tmp-root plus the (64-byte-truncated) test name deep enough to exceed
  sockaddr_un's 108-byte sun_path limit. Both now use a new shortSocketPath
  helper (a short os.MkdirTemp("", "bds") directory) instead.

- runProxiedDeadline raced a deadline-watcher goroutine against
  exec.Cmd.Start()/Run()'s write to cmd.Process, caught by -race. Replaced
  with cmd.Cancel, which exec.CommandContext only invokes after Start, so
  the read is ordered after Start's write.

With those two fixes applied, TestProxiedServerHistoryRemoteRefusalFrontDoorMatrix
passes outright. TestProxiedServerOutageReconnectAcceptanceMatrix's race is
fixed, but both its subtests still fail a real "exceeded 3s bound" assertion
against a stopped external upstream -- a genuine latency issue, not a test
bug -- so it is reverted back to its original name
(TestProxiedOutageReconnectAcceptanceMatrix) with a comment explaining why,
pending a bead against the underlying latency.

TestServerModeSharedServeGlobalReportsTheServedDatabase also reverted back
to TestSharedServerModeServeGlobalReportsTheServedDatabase: `bd serve
--global` refuses to auto-apply 4 pending schema migrations (v65->v69) to a
shared/proxied server database and exits 1 with a consent-required usage
message instead of starting, per the #5920 migration-consent guard. Also a
genuine product/test-fixture question, not fixed here; reverted with a
comment, pending a bead.

The other 12 of the original 14 renames are kept; all 12 verified passing
in both lanes (see commits that follow for the manifest update and full
verification).

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

* fix(ci,bazel): re-derive proxied weights from parallel=4 CI-identical sweep (R-S1)

The prior round's duration data (committed in 6be9605d9f) was captured at
-test.parallel=1 (serial). That fixed a real double-counting bug, but
serial timings don't model this lane, which always runs -test.parallel=4
(--config=doltserver-proxied's own setting). Re-review measured near-zero
correlation (r=0.08) between the serial-derived predicted shard load and
actual parallel=4 wall time -- e.g. TestProxiedServerRecomputeBlocked was
weighted 812s serially but measured 33s actual at parallel=4.

Replaced with a full fresh capture: `bazel --nohome_rc test
--config=doltserver-proxied //cmd/bd:bd_proxied_test` (local execution
only, the exact config bazel.yml's proxied-server tier uses), 30/30 shards
passing, 0 failures, 0 races. Every one of the 176 discovered tests'
top-level <testsuite time> was captured directly from this run's
bazel-testlogs test.xml files -- no leaf-summation workaround was needed
this time, since none of the 176 hit Bazel's per-target default timeout
running alongside the rest of its shard.

Re-ran `gen_proxied_shard_manifest.py 30 --weights=duration --repack
--write` with these corrected weights: a deliberate full reweight, not an
incremental add, since every weight changed. The new packing clusters all
30 shards within a few seconds of ~355-360s each (176 tests summing to
10712s / 30), a dramatic improvement over the serial data's wrongly
implied two-outlier-shard spread (TestProxiedServerDep2 alone at ~2358s,
TestProxiedServerClose alone at ~1105s -- both artifacts of serial
timing, not real per-shard cost). Updated bazel.yml's paragraph to report
this honestly instead of the prior, false "exceeds 25-minute timeout"
claim, which was itself downstream of the serial/parallel mismatch.

Verified: the 12 tests kept renamed in the previous commit, plus
TestProxiedServerHistoryRemoteRefusalFrontDoorMatrix's socket-path fix,
all pass under the new 30-shard Bazel manifest (this capture run) and
under the legacy 15-shard hash-fallback script (ran the 7 shards their
hash lands in: 2, 3, 4, 5, 8, 10, 11 -- all pass).

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

* fix(ci,bazel): incremental --write, --repack, name-coverage --check (R-S2)

The prior --check compared the committed 30-shard block byte-for-byte
against a fresh from-scratch LPT pack, and --write always did a full
repack. That meant any weight drift (even from proxied_test_durations.json
alone, with no test added/renamed/removed) failed --check, and two
unrelated PRs each adding one proxied test would both force a full
repack and conflict on unrelated shard lines -- re-review demonstrated
one new test moving 73 assignment lines under the old full-repack
behavior.

Redesigned:

- --check now verifies exact-once NAME coverage of the currently
  discovered TestProxiedServer*/TestServerMode* set against the
  committed block -- missing, stale, or duplicated names fail with an
  actionable message -- but does NOT compare shard assignments, so a
  weights-only change no longer forces --check to fail.
- --write is now incremental by default: every already-assigned test
  keeps its current shard, stale (no longer discovered) names are
  dropped, and only newly-discovered names are LPT-placed onto whichever
  shard is currently lightest. A full from-scratch LPT pack now requires
  the explicit --repack flag (used in the preceding commit for the
  deliberate full reweight; ordinary new-test additions should use the
  incremental default).

Mutation-tested directly (not just reviewed): verified --check correctly
flags a stale name as "stale/unknown" and a newly added test as "missing"
with the exact --write command to fix it; verified incremental --write
touches only the lines for the added/removed names; verified --repack
--write produces a materially different (full rebalance) diff from the
incremental default.

Updated TestProxiedShardManifestGeneratorNotStale's comment in
pr_risk_bazel_coverage_test.go to describe the new name-coverage-only
--check semantics (it previously described the old byte-identical-packing
behavior; the test's own assertion -- exit code only -- was already
correct and unaffected).

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

---------

Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-03 09:36:05 -07:00
Julian Knutsen
aaae7e6aff
ci: package gates start after rbe, MCP pytest -n 8, gate jobs on Blacksmith (F3) (#7126)
* ci(bazel): move package-mcp/package-npm gates into bazel.yml (F3)

Package gates now build bd via Bazel (no --config=ci) when the rbe job
enables it and fall back to go build otherwise, so forks/Dependabot/rbe-off
runs are unaffected. pr.yml's CI Gate keeps PACKAGE_MCP/PACKAGE_NPM required
and never-skippable, now sourced from needs.bazel.outputs.*; the retired
detect-package-gates/package-mcp/package-npm pr.yml jobs and
DETECT_PACKAGE_GATES are deleted. MCP pytest pins -n 8 explicitly with
pytest-xdist locked via uv lock. rbe, bazel-coverage, and both required gate
jobs move to Blacksmith for same-repo PRs (gate names unchanged).

Also closes a gap in detect-package-gates.sh (missing bazel.yml in the
force-both-gates path list, since the job definitions moved there) and wires
integrations/beads-mcp's manifest/lock into scripts_test's Bazel data so the
new pytest-xdist pin check runs under `bazel test` too.

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

* fix(bazel): review fix-up for F3 package gates (SF-1, SF-2, nits)

Review of 65f378d241 (~/beads-bazel-plan/f3/review.md, no blockers) found:

- SF-1: the package gates' `bazel build //cmd/bd:bd_for_tests` resolved to
  a different output configuration (k8-fastbuild) than `bazel test
  --config=ci`'s bd_for_tests (k8-fastbuild-ST-..., via test:ci ->
  test:prcore's --@rules_go//go/config:race), so it got no action-cache
  reuse from the test job. Add the matching race flag to both jobs' build
  step; verified with cquery that both invocations now cquery to the
  identical bazel-out/k8-fastbuild-ST-.../bin/cmd/bd/bd_for_tests/bd path,
  and with a real build that it's an action-cache hit once bazel test
  --config=ci has run. Update the pinned Run string in
  pr_lanes_bazel_coverage_test.go and the impl report's cache-reuse claim.
- SF-2: drop stale comments/doc text saying the package gates download
  bazel-ci-build-artifacts; they build their own bd now (bazel.yml,
  pr.yml, engdocs/CI_REQUIRED_CHECK_TOPOLOGY.md).

Nits: pin both required gates' display names in TestSameRepoBlacksmithRunners
(nothing else reads job.Name, so a rename would otherwise go uncaught); pin
the package jobs' Python/uv/Node setup against main.yml's copies; add
timeout-minutes to both gate jobs and detect-ci-tier (same-repo PRs now run
on paid Blacksmith minutes, not a free runner's 360-minute default); shut
down Bazel and remove the RBE client key right after each package job
packages its Bazel-built bd (nothing downstream needs either); add
scripts/ci/package-bazel-bd.sh to detect-package-gates.sh's both-gates
trigger arm and pin it in TestDetectPackageGatesCoversBazelWorkflow.

Every fix mutation-tested (mutate -> test fails with a specific message ->
restore from a /tmp backup, diff-confirmed identical -> test passes again).

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

---------

Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-03 00:03:43 -07:00
Julian Knutsen
e2b78f7d7a
ci(bazel): run integration on fork PRs via the read-only cache; retry Go module fetches (#7120)
* ci(bazel): retry Go module fetches and scale download timeouts in every mode

A fork run failed Bazel / test on one proxy.golang.org TLS handshake
timeout. gazelle's go_repository fetches modules with the go command
(fetch_repo), which never retries, and Bazel's downloader retry flags do
not reach it. setup-bazel's generated rc now sets
--repo_env=GOPROXY=https://proxy.golang.org|https://proxy.golang.org|direct:
with "|" the go command moves to the next entry on any error, so the proxy
is tried twice and then the module's origin. fetch_repo checks every
module against its go.sum hash whatever the source. Verified with Bazel
9.2.0: an unreachable first entry still fetches all 438 go_deps repos,
and without a fallback the fetch fails.

--http_timeout_scaling=2.0 doubles the timeouts of Bazel's own
downloader (the Go SDK, http_archive), which already retries.

Both flags are key neutral (repository fetching only) and apply in every
mode, because repository fetching always runs on the runner.

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

* ci(bazel): run the integration lane for fork and Dependabot PRs in cache mode

bazel-integration was remote-only, so fork and Dependabot PRs (mode
cache) had no PR-time integration run at all: main.yml's integration jobs
run only after merge. With rbe-west's anonymous read-only cache, every
action trusted CI already ran is a hit, so the GitHub-hosted runner builds
and tests only what the PR changed.

Simulated in an ubuntu:24.04 container with 4 CPUs and only the generated
rc (no user rc). This setup's action keys match CI's: the ci lane
reproduced the fork run's 6550 processes with 4847 cache hits.
- Main HEAD: 143 s (4656 hits, 12 local, 113 of 115 tests cached).
- A cmd/bd change: 170-290 s.
- Cache closed (cold, all local): about 30 minutes.

- bazel.yml: the lane's if is now mode remote or cache, never local
  (rbe=off). The step timeout goes from 45 to 75 minutes (job 85), so a
  closed cache (the farm's kill switch) still leaves fork PRs green.
- bazel-gate.sh: mode cache no longer allows BAZEL_INTEGRATION to skip.
  Mode local still does.
- New TestBazelCacheModeReachesTheRC runs, end to end, the real decision
  step for 22 starts:
  - fork, Dependabot and same-repo PRs, push, rbe=cache/off dispatches
    and bazel-farm, each with the variable on and unset;
  - same-repo runs with and without the secret;
  - a fork PR that "has" the secrets, and one passing fork-farm.
  For each start it evaluates every lane's if and setup-bazel env, runs
  write-bazelrc.sh, and checks bazel-gate.sh's skips. A cache-mode rc
  carries --config=fork-cache and the fetch hardening, and no executor,
  TLS file, instance, upload, header, BES or masked secret.
- ci_workflow_test.go: the integration if, the run modes, and a
  closed-cache floor for the step timeout.
- Comments in bazel.yml, pr.yml and bazel-farm.yml, and the topology
  engdoc. The engdoc also covers:
  - fork-cache's slow-blob behaviour: 15 s read deadlines trip the
    breaker, then "Lost inputs" and one build restart, still green;
  - why the endpoint's FindMissingBlobs denial never affects cache-only
    clients.

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

---------

Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-02 17:15:56 -07:00
Julian Knutsen
0588af25d1
ci: retire pr.yml's legacy PR Core, build, pure-Go, domain+uow and contract jobs where the gated Bazel lanes run them (D2 step 3) (#7097)
* ci: retire pr.yml's legacy PR Core, build, pure-Go, domain+uow and contract jobs where the gated Bazel lanes run them (D2 step 3)

On same-repo, non-Dependabot pull_requests while the committed
BAZEL_RETIRES_LEGACY_PR_LANES flag is "true" (bazel-coverage's new
pr_lanes output; the job stays identical in pr.yml and pr-risk.yml),
pr.yml's build-artifacts, pr-core-wrapper, check-cmd-bd-puregeo-tests,
test-domain-uow and contract-corpus stand down. ci-gate accepts those
skips only then, and BAZEL_PR_LANES_RETIRED requires the same run's
Bazel test, pure-Go/js-wasm and dolt-server lanes to have run remotely
and passed. Revert: commit the flag "false" in both workflows.

What the retired jobs did besides their tests keeps running on every PR:
- the package gates take bazel-ci-build-artifacts (bazel-test's bd, same
  layout) where build-artifacts stands down;
- the Dolt server fingerprint moves to its own required job;
- the Go tests Bazel does not run or skips (equivalence allowlist) run
  under go test in pr-preflight-platforms' Linux leg, each required to
  pass (tools/bazel/run_allowlisted_go_tests.py).

In mode remote the three lanes' bazel test invocations add
--config=sole-run (no cached test results, no whole-invocation retry on
remote cache eviction), as steps 1 and 2 do for their lanes.

Policy tests: decision matrix and named cases extended to the third
flag, gate simulation for the pr.yml tier, artifact consumers, pinned
lane steps and rc lines, a repo-wide narrowing scan of BUILD rules and
.bzl files, and the allowlisted-test runner.

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

* docs(ci): record the retired pr.yml PR Core, build, pure-Go, domain+uow and contract jobs in the check topology

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

* test(ci): only pr.yml's workflow env sets a BAZEL_RETIRES_* flag, and only the decision step reads one

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

* ci(pr): keep go test ./scripts/..., go test's vet and the Bazel-skipped tests on every PR (D2 step 3 review F1, F1b, F3, L2)

Review of D2 step 3: retiring PR Core removed the only required pre-merge
`go test` of the scripts packages, whose policy tests (the D2 guards
among them) check part or all of their rules under go test only, and
go test's implicit vet for every package (rules_go's go_test runs none).

New required job scripts-go-checks (SCRIPTS_GO_CHECKS), on every PR, in
PR Core's environment (dolt, git and dolt identity, test-env):
- scripts/ci/scripts-go-test.sh: `go test ./scripts/...` with PR Core's
  flags;
- scripts/ci/go-test-vet.sh: `go vet` with cmd/go's defaultVetFlags over
  ./..., policy-tested equal to the running toolchain's list;
- scripts/ci/allowlisted-go-tests.sh, moved here from
  pr-preflight-platforms.

TestBazelOnlySkipsAreAllowlisted also requires every test that runs part
of its checks under go test only (a Bazel-guarded return/continue, or a
go-test-only block that reports failures) to live under ./scripts, the
only packages go test still runs on every PR; and step 3's
TestRunAllowlistedGoTestsScript gets its allowlist entry.

Package gates on a covered PR whose Bazel call did not run remotely (the
farm switch off) now fail in their own step naming
BAZEL_PR_LANES_RETIRED instead of on a missing artifact (L2).

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

* docs(ci): record scripts-go-checks, the skip-allowlist check and the re-run-safe uploads for D2 step 3

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

---------

Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-02 06:08:52 -07:00
Julian Knutsen
3789dde785
ci: retire PR Risk's legacy proxied and server-Dolt tiers where the gated Bazel lanes run them (D2 step 2) (#7094)
* ci: retire PR Risk's legacy proxied and server-Dolt tiers where the gated Bazel lanes run them (D2 step 2)

On same-repo, non-Dependabot pull_requests, PR Risk's test-proxied-cmd (15),
test-server-storage and test-server-storage-full (16) jobs stand down while
the committed BAZEL_RETIRES_LEGACY_DOLT_SERVER_TIERS flag is "true" (in both
pr.yml and pr-risk.yml, policy-tested equal); pr.yml's gated Bazel
proxied-server and server-Dolt storage lanes are then the tiers' only
pre-merge run. build-embedded, whose embedded-test-binaries artifact feeds
exactly the six retired legacy test jobs, stands down where both D2 steps
apply.

Generalizes step 1 instead of copying it:
- bazel-embedded-coverage becomes bazel-coverage (identical in both
  workflows): one decision step, outputs embedded and dolt_server, each
  flag && pull_request && !fork && actor != dependabot[bot]; gate id
  BAZEL_COVERAGE.
- PR Risk's gate accepts the retired jobs' skips only when their output is
  true, and BUILD_EMBEDDED's only when both are.
- pr.yml's gate adds BAZEL_DOLT_SERVER_RETIRED: red when dolt_server is true
  and the mode is not remote or BAZEL_PROXIED / BAZEL_SERVER_STORAGE is not
  success (shared helper with BAZEL_EMBEDDED_RETIRED).
- Lane hardening as for embedded: --nocache_test_results for
  doltserver-proxied and doltserver-integration, the flaky-target query,
  check_shard_coverage.py (proxied 15 shards; server full suite 16 shards
  plus --whole conformance), pinned test steps, rc lines and target
  args/env; the shard listings now run concurrently (the server script
  forks per test).
- Policy tests generalized over the retired tiers: decision equivalence
  with bazel.yml's mode across two runs, both gates simulated, flag
  equality, artifact consumers, real shard scripts in list-only mode.

Revert: commit BAZEL_RETIRES_LEGACY_DOLT_SERVER_TIERS: "false" in both
workflows.

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

* docs(ci): record the retired legacy proxied and server-Dolt tiers in the check topology

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

* ci(bazel): no whole-invocation retry on remote cache eviction in the retired tiers' lanes

Review F1 (D2 step 2): Bazel 9 re-runs a whole `bazel test` invocation
(--experimental_remote_cache_eviction_retries, default 5) when an input was
evicted from the remote cache, and that exit code outranks a test
failure. With --nocache_test_results every test runs again and only the
retry is reported, so a flaky failure in the embedded, proxied or
server-storage lane (each now its tier's only pre-merge run) could turn
green. Set the retries to 0 in test:embedded, test:doltserver-proxied and
test:doltserver-integration (not remote-exec, which must stay key-neutral),
pin the lines, forbid any other line or the setup-bazel action from
setting the count, and correct the topology doc, which claimed the retry
never re-runs a failed test.

Reproduced against a local HTTP cache emptied mid-build: with the default
the build hit "Lost inputs", retried and exited 0; with 0 it failed.

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

* test(ci): pin how the retired lanes' shard scripts run their tests

Review F2 (D2 step 2): the narrowing scan covered tools/bazel and the
setup-bazel action but not the four .github/scripts/*-test-shard.sh
scripts the sharded targets execute, so appending -test.short to an exec
line or exporting BEADS_TEST_SKIP there passed the policy tests (and
check_shard_coverage.py only rejects a shard that is entirely skipped).
Pin each script's prebuilt-binary and go test fallback commands exactly
and its RUN_REGEX construction, and forbid anything else in the scripts
from running tests or selecting, skipping or switching them. The scripts
themselves are unchanged (the legacy jobs run them too); a self-test
checks that six narrowing edits are rejected.

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

* test(ci): simulate a non-true coverage decision per retired tier

Review F3 (D2 step 2): the "decision succeeded but its output is not
exactly 'true'" gate scenarios set both bazel-coverage outputs bad at
once, so the embedded ids reddened the gate whatever the dolt_server rule
said, and weakening PR Risk's gate to `!= "false"` for one tier passed.
Run them per tier, with the other output a valid "false" and only that
tier's job skipped, and isolate build-embedded's both-true rule the same
way. Failed or cancelled decisions keep the all-skipped scenarios.

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

* docs(ci): list Bazel tier coverage and the proxied/server-Dolt checks as not directly required

Review F4 (D2 step 2): the topology doc still named the renamed
`Bazel embedded coverage` job, and its list of check names not to require
directly lacked the proxied and server-Dolt test jobs.

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

* test(ci): skip the real shard-script listing test on bash < 4

The CI shard scripts use associative arrays and only run on Linux runners;
macOS's /bin/bash 3.2 can't execute them.

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

---------

Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-02 02:20:30 -07:00
Julian Knutsen
6cd1184687
feat(httpapi): opt-in large issues:batchApply envelope (≤1000 items, one transaction) (#7051)
* test(storage): measure ApplyBatchInTx SQL statement counts (B0)

Adds a driver.Connector-level counting/latency-injecting wrapper
(internal/storage/sqlcount) plus shared plan-request fixtures
(internal/storage/batchfixtures: mol-normalized 356/712-item shapes and a
40-item classic shape) and backend-specific pinning tests + benchmarks
(internal/storage/embeddeddolt, internal/storage/dolt) that measure the
ACTUAL number of SQL statements issueops.ApplyBatchInTx issues for each
shape, on both the embedded and Dolt (TCP) backends.

Measured totals (Prepare+Exec+Query+StmtExec+StmtQuery inside one
transaction): 356 items ~7008-7009, 712 items 14014-14015, 40 items 846,
identical on both backends (expected: statement issuance is driven by Go
application logic, not backend-specific SQL planning). Pinned with a small
(+/-2) tolerance to absorb an observed, host-contention-driven +/-1 Query
drift (Exec is deterministic on every run). This is the regression baseline
slice B2 (a later, lighter fast path) must demonstrably lower.

batchfixtures.UncappedPlan bypasses issueops.MaxApplyBatchItems so this
measurement does not depend on slice B1's cap raise.

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

* feat(httpapi,issueops): raise batchApply envelope to 1000 items with bounded large-apply handling

POST /v0/beads/issues:batchApply now accepts up to 1000 items (up from 100);
issueops.MaxApplyBatchItems moves accordingly and the request body cap rises
to 16 MiB. The whole plan still applies in exactly ONE transaction. A request
over 100 items runs under a separate, flat, operator-configured whole-run
budget (`bd serve --large-apply-ceiling`, 5 minutes by default) instead of
the ordinary 60s request deadline; a request at or under 100 items is
unaffected and keeps exactly the 60s deadline and 15s commit-retry ceiling it
always had.

Concurrency and shutdown are bounded, not just documented:
- Oversized requests serialize through a dedicated one-wide semaphore, and at
  most one caller may wait for that semaphore at a time (a CAS-guarded single
  waiter) — a burst of oversized requests is shed with 503 rather than
  queuing and starving ordinary traffic behind the general semaphore.
- The run deadline is stamped only once the slot is actually acquired, not
  at the time the request arrived.
- Graceful shutdown closes new admissions before computing its drain budget,
  then waits out an in-flight large apply up to its own remaining deadline
  (plus a few seconds' grace for the response to write); any large apply
  still queued for the semaphore when shutdown begins is refused rather than
  extending the drain further. A queued caller that disconnects gets a clean
  503, never a misclassified context error. `bd serve`'s orchestrator stop
  grace must be at least `--large-apply-ceiling` — see
  engdocs/SERVE_RUNBOOK.md.
- ApplyBatch's commit-retry budget only extends past the ordinary 15s ceiling
  on this explicit large-apply path (via a context marker), with headroom
  reserved so the final retry attempt can't be killed mid-commit by the
  context's own expiry.

A new `issues.batchApplyLarge` capability token on `GET /v0/beads/context`
lets a client learn whether a given server accepts the raised envelope.

Wall-clock measurement (embedded Dolt, whole-transaction build+commit) backs
the 5-minute ceiling default: 356 items ~12.6s (23.8x headroom), 1000 items
~57.5s (5.2x headroom).

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

* fix(httpapi,serve): wire the large-apply retry budget; repair stale pins

Review fixes for the large batchApply envelope, on top of the test
repairs the PR needed against main.

The extended commit-retry budget was never switched on.
internal/storage/uow's retryTxBudget lets a large apply keep retrying a
commit-time conflict past the ordinary 15s ceiling only when its context
carries issueops.WithExtendedRetryBudget's marker, and the docs on both
sides say admitLargeApply sets it, but nothing did: the marker's only
callers were the uow tests, which mark their contexts by hand. A
1000-item apply that hit a conflict still gave up after 15s with most of
its 5-minute ceiling unused. admitLargeApply now marks the run context
it builds, and TestApplyBatchMarksOnlyALargeApplyForTheExtendedRetryBudget
pins the seam over HTTP: marked at 101 and 1000 items, unmarked at 100.
Removing the mark fails the 101 and 1000 cases; marking every request in
handleApplyBatch fails the 100 case.

Smaller fixes from the same review:

- `bd serve --large-apply-ceiling` repeated the 5m default as a literal
  of its own, and since bd serve always passes a positive ceiling, that
  literal, not httpapi's, was the default every deployment ran. Export
  httpapi.DefaultLargeApplyCeiling, default the flag to it, and pin the
  flag's 5m0s default in TestServeFlags.
- admitLargeApply's release cancels the run context before clearing
  s.largeApplyDeadline, the order acquireLargeApply's doc states; it
  cleared the deadline first.
- Drop the batchfixtures test's dead t.Skipf, which waited for the cap
  to reach 1000, and correct a graph-counter comment that still cited
  the 100-item cap and the TestServeFlags doc line that called the
  no-argument server unchanged.

The PR raises issueops.MaxApplyBatchItems from 100 to 1000 and adds
`bd serve --large-apply-ceiling`, but two base-owned tests still pinned
the old surface and went red on every lane that runs them (Bazel / test,
Test (macos-latest)):

- TestServeFlags pins the exact `bd serve` flag list; add
  large-apply-ceiling.
- TestPlanApplyBatchRefusesAnUnusableRequest/too_many_items built 101
  items and expected "at most 100 items", a request the 1000 cap now
  plans successfully. Size the over-cap request and its message from
  issueops.MaxApplyBatchItems, as TestPlanApplyBatchAcceptsTheBoundary
  already does for the other side of the cap; the cap's value stays
  pinned by TestCapBatchApplyLargeTiesAllThreeLimits.

The PR's own TestLargeApplyBurstNeverStarvesSmallRequestsForSemTimeout
also went red in PR Core (-race, -p 4 on a 4-vCPU runner): all eight
small requests took 160-165ms against a 100ms bound. The stall it
guards against lasts semTimeout (5s), while a small request can still
queue briefly behind the refused large requests, each holding a general
sem slot while its body decodes. Bound it at a second, the "want well
under a second" its sibling TestLargeApplyQueueDoesNotStarveOrdinaryRequests
already uses. Pinned to four cores beside 24 busy loops, small requests
measured 183ms mean and 338ms max, and the 1s bound passed 80/80 runs;
with the one-waiter gate in acquireLargeApply disabled the test still
fails 3/3, on its 2s never-completed check.

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

* fix(uow): stop a doomed large-apply retry before ctx cuts it off

retryTxBudget sizes maxElapsed once at ApplyBatch entry, but says nothing
about how long an individual attempt takes. A slow first attempt (e.g.
157s of a large apply's commit) left little of the budget for a retry,
which then got killed mid-transaction by ctx's own deadline instead of
finishing and reporting its own outcome -- surfacing as
context.DeadlineExceeded (isUnavailable excludes it -> a generic 500)
instead of the exhausted-write-conflict result this loop already reports
correctly (-> 503 + Retry-After).

RunTxResultWithin now tracks the previous attempt's duration and, before
starting a new one, stops early with the last real serialization error
when time left on ctx is less than that duration plus a fixed headroom --
but only when publicops.HasExtendedRetryBudget(ctx) is set (the same
marker retryTxBudget itself checks). Applying the look-ahead
unconditionally regressed TestApplyBatchHonorsAnExtendedRetryBudgetFromContext's
unmarked case: ordinary requests have cheap attempts and are meant to run
until their own ctx deadline ends the loop, and the large-apply-sized 5s
headroom was tripping that for any short-ctx caller with a near-instant
failing attempt.

Adds TestRunTxResultWithin_SlowAttemptStopsBeforeADoomedRetry (a 1.2s
commit against a 2s marked ctx must stop after one attempt with its own
serialization error, never DeadlineExceeded, and never touch a second
unit of work) and its control, TestRunTxResultWithin_ShortAttemptStillRetries
(a 50ms attempt against the same shape must still retry and succeed).
Both mutation-checked against the look-ahead condition and its gate.

Also updates the stale "items accepts at most 100 entries" prose on the
applyBatch endpoint description (openapi.v0.yaml) to the large-envelope
wording already used elsewhere in the spec: 1000-item cap behind the
issues.batchApplyLarge capability, large-apply-ceiling deadline extension,
<=100 unaffected. dependencies:count's own "at most 100" lines are
unrelated and untouched.

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

* fix(ci,serve): fit the 1000-item cap's tests in the storage shard budget

Review fixes for the relaunched #7051, iteration 1.

Raising issueops.MaxApplyBatchItems from 100 to 1000 made the base-owned
TestBatchApplyContract take 604s under -race, against 97s at the old cap
(main run 35862663577). It hashed onto the legacy test-embedded-storage
shard 2/5, beside ~5m of other tests, and that shard hit its 15m budget
twice (PR Risk run 36807191489). PR Risk no longer runs the legacy tier
on same-repo PRs (#7071), but Main's push run and fork PRs still do, so
the merge would have carried the timeout to Main.

Raising the jobs' timeout-minutes alone would not fix it: the shard
script passes the binary its own -test.timeout=15m. So:

- embedded-storage-test-shard.sh passes -test.timeout=20m (and its go
  test fallback -timeout 20m), as embedded-test-shard.sh does for
  cmd/bd.
- test-embedded-storage in main.yml and pr-risk.yml: timeout-minutes 15
  -> 25, the script's 20m plus setup.
- embeddeddolt_embedded_test appends -test.timeout=19m, as
  bd_embedded_test does, so Go's timeout, which dumps every goroutine,
  fires before rbe-west's 1200s action kill, which does not.
  TestBazelEmbeddedJobMirrorsEmbeddedTier now checks the override on
  both sharded targets instead of only cmd/bd's, and the PR Risk
  coverage test pins the storage target's new args.
- embedded-storage-test-shards.txt places TestBatchApplyContract on
  shard 4, which has ~3m of other tests, and the PR's two large-batch
  tests, TestLargeBatchApplyStatementCounts_Embedded (247s) and
  TestLargeBatchApplyWallClock_Embedded (261s), on shards 2 and 5. From
  the PR run's per-test times, the heaviest shard projects to ~13m, down
  from shard 2's 15m-plus.

Also correct the stop-grace guidance. For an in-flight large apply,
Serve's drain waits out the apply's remaining deadline plus drainGrace
(5s), so the orchestrator's stop grace must be at least
--large-apply-ceiling plus 5s, as Serve's own doc says. The runbook, the
flag help, the LargeApplyCeiling field doc and the CHANGELOG entry asked
for the ceiling alone.

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

---------

Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-01 08:32:56 -07:00
Julian Knutsen
b81fdc0b20
fix(init): #5791 follow-up — name --recreate-missing without a paste-ready command; align help, playbook and ADR 0004 (#7070)
* fix(init): name --recreate-missing in the refusal without a paste-ready command

The missing-server-database refusal added in #5791 ended with a complete
`bd init --recreate-missing --prefix <prefix>` line. ADR 0002 Invariant 4
keeps complete destructive invocations out of bd error output, and this
refusal also fires when the server merely could not be reached: a stopped
server, a wrong port and a wrong data dir all look the same from here, and
recreating in any of them strands the real data behind an empty database of
the same name. The line also echoed the raw --prefix flag value, so a run
without --prefix printed `--prefix ` with nothing after it.

The refusal now names the flag and points to `bd help init-safety`, which
keeps the full invocation behind the diagnosis it requires. The unused
prefix parameter stays as `_` so the guard call sites are unchanged.

Also:
- --force / --reinit-local flag help, `bd help init-safety` and the init
  guard comment now say neither flag authorizes recreating a missing
  server-mode database; the --recreate-missing stanza says to rule out a
  stopped server or wrong port/data dir and restore first.
- bootstrap.go comments no longer describe #5791 as open and unmerged.
- TestInitGuardMissingServerDBMessage_RefusalTextNoEcho pins the wording
  for both evidence arms, with and without a prefix.
- TestInitGuard_RecreateMissingE2ECreatesMissingServerDB runs the real
  binary against a live server lacking the database: refused without the
  flag, created with it. The unit tests flip initAllowRecreateMissing
  directly, so nothing exercised the documented command end to end.

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

* docs(recovery): init-missing-server-db covers both evidence arms and the flag limits

The init-missing-server-db section described only the project_id arm of the
guard. Under --reinit-local or --force a workspace that predates project_id
is also refused when its local Dolt data directory survives, and the refusal
then cites that directory instead of metadata.json. "What happened" now
covers both arms.

"Limits worth knowing" replaces the stale "fails open" bullet with a table
of which local state meets the refusal under bd init and under
--reinit-local / --force, and what --recreate-missing changes. The
init-force-refused section now says --force / --reinit-local bypass only the
local data-safety guard, not this refusal or the remote one, and step 3 says
why the refusal names --recreate-missing without printing the command
(ADR 0002 Invariant 4).

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

* docs(adr): mark ADR 0004 Accepted now that #5791 has landed

ADR 0004 (the missing-database guard signal) still read "Proposed" after the
guards implementing it merged in #5791, and its Consequences said
checkExistingBeadsDataAt "does not change" although the same PR gave it the
Tier 1 probe ahead of project_id. Record the acceptance and say what the PR
already changed; DOC_INVENTORY.md follows the status.

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

---------

Co-authored-by: Eddie the Engineer <adopt-pr@gascity.local>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 07:22:49 -07:00
Harry Miller
1cc19040af
fix(context): resolve from .beads when outside a git repository (#4772) (#4792)
* fix(context): resolve from .beads when outside a git repository

`bd context` is documented to read directly from config files and work "in
degraded states", but it hard-failed with "cannot determine repository root:
not a git repository" whenever the working directory wasn't inside a git
repo — even with a valid, discoverable .beads/ present. Consumers that use
`bd context --json` as a health/identity probe got a false "unreachable" in
healthy non-git scopes (GH#4772).

When GetRepoContext returns the repo-root error, a boundary-checked .beads
directory has already been found and the only missing piece is the git repo
root. Fall back to the .beads parent as the repo root and continue, so
backend identity still resolves from config. Only this specific error
triggers the fallback; "no .beads directory found" and unsafe-location
errors still surface as before.

Adds an embedded regression subtest that removes .git from a workspace and
asserts `bd context --json` still resolves (backend/beads_dir populated, no
error). Verified end-to-end: reproduced the exact "cannot determine
repository root" error pre-fix; post-fix reports backend=dolt.

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

* fix(context): select the no-git fallback by type, and cover both routes

Review follow-up on the GH#4772 fix.

The fallback was selected with strings.Contains(err.Error(), "cannot
determine repository root"). buildRepoContext's other failure — the
SEC-003 unsafe-location rejection — embeds the offending path verbatim
in its message, so the discriminator was controlled by the path being
rejected: a workspace whose path contained the probe phrase would take
the fallback and have its unsafe-location error cleared.

Replace it with a typed error. buildRepoContext now returns
*beads.NoRepoRootError, carrying the .beads directory that has already
cleared the found + safe-boundary checks — which is exactly what makes
recovering from this one failure safe, and removes the need to
re-derive it with a second FindBeadsDir call. The message text is
unchanged.

The recovery itself moves into beads.GetRepoContextAllowingNoGit, so
both `bd context` routes share it: the direct one in context_cmd.go and
the proxied one, whose provider (domain/fs contextRepositoryImpl
RepoContext + Role) propagated GetRepoContext's error unchanged and so
still failed outside git. Callers that actually run git commands keep
using GetRepoContext, so a missing repository stays an error where it
matters.

Tests:
- Discriminator regression: an unsafe-location error built with a
  hostile path still matches the old substring test but does NOT
  satisfy errors.As for *NoRepoRootError.
- GetRepoContextAllowingNoGit resolves a non-git workspace (BeadsDir,
  RepoRoot = .beads parent, empty CWDRepoRoot) while GetRepoContext
  still refuses.
- The embedded regression now decodes ContextInfo and asserts exact
  beads_dir, repo_root, backend, bd_version and is_worktree instead of
  probing for a key name (fields are not omitempty, so an empty or
  wrong value passed before).
- Same assertions added for the proxied route.
- ngDir -> nonGitDir.

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

* fix(context): report the redirect on the no-git path, and test the discriminator

Two blocking items.

B1. The synthesized context left IsRedirected at its zero value, so a
    workspace reached via BEADS_DIR from a non-git working directory denied
    being redirected, and Role() withheld the Contributor that
    "BEADS_DIR implies contributor (external repo mode)" promises. That
    contradicts the field's own contract two screens up in the same file,
    and a probe sold as a health/identity check giving the wrong identity is
    a worse failure than the error it replaced.

    The normal path's answer is genuinely unavailable here:
    isExternalBeadsDir compares git COMMON DIRS, and the CWD side of that
    comparison cannot be computed without a repository — which is exactly
    the state this branch serves. An explicitly-set BEADS_DIR is the only
    evidence left, and it is the same signal FindBeadsDir's step 1 used to
    choose the directory, so the fallback now mirrors that condition. A
    .beads found by the working-directory walk still reports false.
    IsWorktree stays false, with a comment saying why rather than by
    omission.

B2. TestNoRepoRootError_DoesNotMatchUnsafeLocation never called the
    selection. Asking errors.As about two hand-built values tests the
    standard library, and passes whatever discriminator this package
    actually uses — which the reviewer demonstrated by swapping the typed
    check for the substring test the test is named after and watching it
    stay green.

    The selection is now recoverNoGit(rc, err), split out of
    GetRepoContextAllowingNoGit, and the test drives it: the unsafe-location
    error must come back out unchanged, and so must the no-.beads error and
    a successful context. Under the reviewer's probe B it now fails, naming
    the context the substring version wrongly recovered.

Nits, taken:

N1. NoRepoRootError's doc claimed the workspace "is not inside a git repo".
    It means git could not tell us a root: GetMainRepoRoot bottoms out in
    one `git rev-parse`, so a dangling gitfile, a dubious-ownership refusal
    or git missing from PATH all arrive the same way. Recovery is equally
    safe in all of them, but the command whose pitch is diagnostics in
    degraded states should not swallow the fact — printContextText now
    prints `cwd repo: git: unavailable` instead of nothing, which is the
    text-output counterpart of the omitted JSON field.

N2. The comment on fs/context.go claimed there is no `git config beads.role`
    to read outside a repo. `git config --get` reads global and system
    config with no repository; I hit it by accident running the probe above,
    where Role() returned "maintainer" from my own ~/.gitconfig. Comment
    corrected — the behavior was fine.

N3. CHANGELOG [Unreleased] entry citing #4772, and a "Resolving Without Git"
    section in engdocs/REPO_CONTEXT.md — the reference for this module,
    which documented the boundary validation and the IsRedirected semantics
    B1 bends but neither the new entry point nor the no-git case. It carries
    the typed-selection rationale and a table of what the synthesized
    context can and cannot know.

N4 (allocation) noted and left: correctness first, and two allocations on a
config-reading path is not worth a cache whose invalidation would be a new
thing to get wrong.

Reported-by: bee-ghosttrack
Agent-Signature: claude-code-opus-5-unknown-reasoning on behalf of Harry Miller

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

* fix(context): ask the caller's BEADS_DIR, not the one bd exported for itself

Round-2 blocker, and an embarrassing one: this is the same provenance bug I
fixed in #4795 an hour earlier, reintroduced one layer up.

beadsDirNamedByEnv read os.Getenv("BEADS_DIR") live. By the time
recoverNoGit runs, bd has already exported one: cmd/bd/context_cmd.go:75
calls prepareSelectedNoDBContext(selected) immediately before
GetRepoContextAllowingNoGit, and that ends in os.Setenv("BEADS_DIR", ...)
with whatever discovery just found. The proxied route arrives the same way
through the root pre-run. So on the no-git path EVERY walk-found workspace
reported itself as a redirect and claimed Contributor — the opposite of the
Round-1 bug, and worse, because it is the common case rather than the
unusual one. Reproduced against the built binary:

    $ cd $T/proj/sub && env -u BEADS_DIR bd context --json
    "is_redirected": true,   "role": "contributor"     ← no BEADS_DIR anywhere

internal/beads now takes the same package-init snapshot package main does,
for the same reason: provenance has to be captured before the process starts
overwriting the evidence. beadsDirNamedByCaller compares against that.

Two things worth recording while I was in there. First, a redirect FILE
cannot be missed by this branch: buildRepoContext checks GetRedirectInfo()
at step 3, and a redirect sends it down the isExternal branch that never
asks git for a root — so by construction the only redirect this code can be
looking at is a caller-named BEADS_DIR. That is now a comment rather than an
assumption. Second, the unit tests passed through the bug because they drive
recoverNoGit directly with an env they set themselves, which is exactly the
distinction that cannot be tested in process.

So the regression is end-to-end, on both routes, as asked:

- assertNonGitContext (shared by the embedded and proxied route tests) now
  asserts is_redirected == false for the walk-found case. Reverting the fix:
  "is_redirected should be false for a .beads found by the
  working-directory walk".
- a new embedded subtest runs the binary from an unrelated directory with
  BEADS_DIR supplied in the subprocess environment — the only place a
  caller-supplied value is distinguishable from a bd-exported one — and
  asserts is_redirected == true AND role == contributor.

N1: the `cwd repo: git: unavailable` line was unpinned (their probe P3
deleted the branch and every -run Context test stayed green).
TestPrintContextText_* now pins all three cases: empty CWD repo root reports
git unavailable, a matching one prints nothing, a differing one prints the
path and must NOT say unavailable. Deleting the branch now fails. Kept as an
in-process capture rather than another subprocess, since cmd/bd has no
runtime budget to spare (GH#6253).

N2: filed as GH#6560 — and my attribution on the PR thread was wrong. It is
not a legacy ~/.beads/config.yaml (I have none); it is BEADS_ACTOR in the
environment, which resolveConfiguredActor deliberately checks ahead of
config.yaml as the fix for GH#4645. `env -u BEADS_ACTOR` makes both tests
pass.

Reported-by: bee-ghosttrack
Agent-Signature: claude-code-opus-5-unknown-reasoning on behalf of Harry Miller

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

* chore(bazel): enumerate the PR's two new test files in go_test srcs

Pre-review CI repair for PR #4792. The helper reads CI Readiness: pass, but
those nine green runs were created 2026-09-23 against the contributor head
961aa6239 -- before this branch was rebased onto 8269a88cb, an advance that
brings in the entire Bazel scaffold (.bazelrc, .bazelignore,
.github/actions/setup-bazel). So the green cohort predates the Bazel lanes
entirely and cannot certify them; the adopted head has never been seen by CI.

Both affected packages declare go_test srcs as an EXPLICIT list, not a glob, so
the PR's two added test files were invisible to bazel:

  cmd/bd/BUILD.bazel          + "context_text_test.go"
  internal/beads/BUILD.bazel  + "no_repo_root_test.go"

Base parity puts the obligation on this PR rather than on base: neither file
exists at the rebase base, so neither row could have been owed there.

The failure mode is a FAKE GREEN, not a red, which is why no check caught it.
Measured on //internal/beads:beads_test: with the row, bazel runs
TestGetRepoContextAllowingNoGit_RecoversOutsideGitRepo (rc=0). With the row
removed, the target still exits 0 -- and that test never runs. A silently
unexecuted regression test is exactly what this enumeration prevents.

Generated by the repository's own `make bazel-sync` (gazelle); the rows are
placed alphabetically, the diff is +1/-0 per file, and a second sync is a no-op.

* fix(context): root the no-git context at the .beads repo and decide redirects positionally

Maintainer review fixups for the two gating findings on the no-git recovery
path, plus the nearby non-gating cleanups.

Finding 1 (major) -- recoverNoGit rooted repo_root at filepath.Dir(BeadsDir),
but the failure that reaches it is the CWD's missing repository, not the
.beads's. A .beads that did live inside a repo therefore reported a
SUBDIRECTORY of that repo, so one workspace answered differently depending
only on where the caller stood. Root via repoRootForBeadsDir, which asks git
from the .beads side (needing no CWD repo) and already falls back to
filepath.Dir(beadsDir), so the documented no-git-anywhere answer is unchanged.
The conflated premise is corrected in the field comment and in
engdocs/REPO_CONTEXT.md.

Finding 2 (major) -- the provenance snapshot was captured at package init and
covered only BEADS_DIR, but bd has four caller-directed workspace channels:
--db, BEADS_DB/BD_DB and -C all resolve through selectedNoDBBeadsDir and end
in an os.Setenv("BEADS_DIR", ...) that runs after init, so the snapshot could
not see them and they reported is_redirected:false / role:maintainer outside
git. Decide externality POSITIONALLY instead: the resolved .beads is a
redirect iff discovery standing in the CWD would not have found it. This is
the reviewer's preferred arm -- it needs no environment inventory, so it
covers all four channels uniformly and stays correct as channels are added (a
further BEADS_DIR writer already exists in cmd/bd/doctor.go). It reuses
FindBeadsDirFrom, the same primitive -C itself resolves through, which reads
none of the routing variables and scrubs routing env from its git probe. The
package-init snapshot and its helper are removed. The boundary the review left
unspecified is settled deliberately: a store reachable only by being named is
a redirect, including one in a sibling directory of the CWD, because with no
repository for the CWD there is no enclosing scope that could make a sibling
local.

Finding 3 (minor) -- TestGetRepoContextAllowingNoGit_RecoversOutsideGitRepo
now scrubs BEADS_DIR, which takes priority at FindBeadsDir step 1. Measured:
three assertions fail under an ambient BEADS_DIR without the scrub and the
package is ok with it. The remedy's second part (stubbing the init snapshot)
is obsolete rather than skipped -- positional provenance reads no snapshot, so
there is nothing left to stub.

Findings 4 and 5 (nits) -- the beadsDirFromCaller / GH#4635 cross-reference
resolved to nothing at head or at base; it is gone along with the snapshot it
described. The CWDRepoRoot comment now states the value is known-empty because
the one cached git context its three readers share has already failed, which
is also a firmer justification for IsWorktree: false than "there is none".

Verification: both majors are pinned by new tests proven to red when the fix
is reverted, and measured end to end with a built binary from a non-git cwd --
BEADS_DIR, BEADS_DB, BD_DB, --db and -C all now report is_redirected:true /
role:contributor, while a walk-discoverable workspace correctly reports
false / maintainer. Contributor commits are preserved.

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
2026-10-01 07:08:12 -07:00
Julian Knutsen
291987ea22
ci(bazel): fork PRs use rbe-west's anonymous read-only cache (#7065)
* ci(bazel): fork PRs use rbe-west's anonymous read-only cache (mode cache)

Fork PRs (unless bazel-farm.yml authorized them), rbe=cache dispatches and
secret-less same-repo runs (Dependabot) now run in mode "cache": local
execution on ubuntu-latest as before, plus .bazelrc's new fork-cache config,
rbe-west's credential-free rbe-cache endpoint (instance oss, reads only).
rbe=off keeps the old local mode without the cache.

- .bazelrc: build:fork-cache. Only key-neutral flags (--jobs, --remote_*), so
  fork actions hash like trusted ones. --noremote_upload_local_results, and
  --remote_local_fallback plus
  --incompatible_remote_local_fallback_for_remote_cache: without both, a
  closed endpoint (farm kill switch) fails every action in GetCapabilities.
- setup-bazel: BAZEL_FORK_CACHE=true appends --config=fork-cache; it is
  mutually exclusive with the RBE secrets; new output cache.
- bazel.yml: RBE_INPUT_CACHE, mode cache, dispatch option cache; every
  setup-bazel step gets BAZEL_FORK_CACHE. Remote and fork-farm paths
  unchanged.
- bazel-gate.sh: cache/false is valid and skips what local skips.
- Policy tests: the two public endpoint lines are allowlisted in .bazelrc
  only; TestBazelForkCacheConfig pins the fork-cache contents and checks both
  fork-cache and remote-exec stay key neutral; decision, gate and rc-writer
  tests cover cache mode.

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

* ci(bazel): fork cache gives up on a slow endpoint and uploads no BEP files

Review fixes for the fork read-only cache (mode cache).

- .bazelrc fork-cache: --remote_timeout 60 -> 15 and
  --experimental_circuit_breaker_strategy=failure, so a slow (not closed)
  endpoint stops being called once too many lookups fail instead of
  costing every lookup 60s x retries; --experimental_build_event_upload_strategy=local,
  because bazel.yml's --build_event_json_file and --profile otherwise make
  Bazel upload test logs and the profile over ByteStream. equivalence.py
  and check_testcases.py read test.xml from the local testlogs dir, not
  from BEP URIs, so they are unaffected.
- Policy test: parseBazelrcOptions now scans plain command lines too
  (lane checks still ignore them), so `build|common --config=fork-cache`
  is caught. Outside fork-cache and remote-exec, no line (test: lines
  included) may turn uploads on, turn either fallback off, or set a
  non-local BEP upload strategy. fork-cache must end with the breaker,
  the local BEP strategy and a --remote_timeout of 1-15s; keyNeutralFlag
  accepts the breaker and BEP-strategy flags.
- engdoc: the closed-endpoint fallback sentence now also describes the
  slow-endpoint path (timeout, breaker). bazel-farm.yml and pr.yml
  comments say fork PRs run in mode cache, not plain local.

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

* ci(bazel): reconcile fork cache (mode cache) with the legacy embedded retirement

After the rebase onto D2 step 1 (#7071), two policy tests failed against
mode cache.

- evalRBEExpr learns `inputs.rbe == 'cache'` (bazel.yml's RBE_INPUT_CACHE).
  The decision itself is unchanged and right for mode cache: covered never
  depends on the mode, forks and Dependabot (now mode cache) keep the legacy
  tier, and a covered same-repo PR without the secret (now mode cache, not
  local) still turns pr.yml's gate red. The named cases now pin the mode
  too, and the "mode alone makes it red" check includes cache.
- TestBazelEmbeddedLaneCannotBeNarrowed treats fork-cache like remote-exec:
  a config setup-bazel's rc enables for every command. Its lines (and any
  config they reference) are now in use for the lane, so the rc narrowing
  regex applies to them, including a forbidden nested --config=. The
  setup-bazel scan accepts exactly --config=remote-exec and
  --config=fork-cache.
- Comments in bazel.yml, pr.yml, pr-risk.yml and the engdoc that said
  missing-secret, fork or Dependabot runs take mode local now say cache.

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

---------

Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-01 05:24:06 -07:00
Jim Wordelman
a4bf13f042
Fix: test suites fail closed instead of open on the ambient Dolt port when no test container is started (be-napos) (#5885)
* test(dolt): red — testdb_* leak onto production Dolt port when Docker absent (refs be-h2h25)

* feat: green — Test suites create testdb_* on the PRODUCTION dolt server: harness fails open on the ambient port when Docker is absent (refs be-h2h25)

* docs(release-gate): add be-napos gate — ambient Dolt port fail-open to fail-closed

Deploy bead be-napos (build be-h2h25, review be-7fym1, verdict pass round 2).
7/7 gate criteria PASS; full independent evidence in the gate doc.

refs be-napos, be-h2h25, be-7fym1

* docs(release-gate): record PR link for be-napos gate

refs be-napos

* test(testutil): make the fail-closed gate deterministic, not Docker-conditional

The regression test skipped itself on every host that has Docker, by calling
the real EnsureDoltContainerForTestMain and skipping when it succeeded. That
asserted nothing on CI -- the only lane where it matters -- and on a
Docker-having host it also started the shared singleton container purely to
decide to skip, with no TestMain in internal/testutil to terminate it.

Add checkDoltFn, a package-level seam over checkDolt, so the test can force a
not-ready state without a Docker daemon and without starting a container. Only
EnsureDoltContainerForTestMain routes through it; the neighbouring t.Skip call
sites gate a skip rather than the fail-closed behaviour, so they keep calling
checkDolt directly.

The gate now covers all four not-ready states rather than the one the old test
happened to hit, which also pins the intent that an explicit
BEADS_TEST_SKIP=dolt opt-out must fail closed exactly as a Docker-less host
does. Split into a platform-independent half (the helper's own contract, both
variables cleared, idempotent) and a !windows half (the wiring, via the seam).

Red/green: with the neutralizeAmbientDoltPort call removed from the not-ready
branch, 4 of 4 subtests fail and 0 pass; restored, 4 of 4 pass in 0.06s with
no Docker and no container. (refs be-napos)

* fix(testutil): clear the ambient Dolt port on the Windows stub too

The Windows EnsureDoltContainerForTestMain returned its error without touching
BEADS_DOLT_SERVER_PORT / BEADS_DOLT_PORT, so the fail-open this branch fixes
still shipped there -- unconditionally, since that stub never succeeds. Windows
is a real lane: .github/workflows/pr.yml runs windows-latest on four jobs plus
the cross-platform matrix.

Gating it needed one pre-existing repair. testdoltserver_env_test.go has no
build tag but calls checkDolt, which is !windows-only, so the internal/testutil
test binary has never compiled for Windows -- reproduced identically on
origin/main. Tagging that file !windows fixes the whole package's Windows test
lane; without it a new Windows gate would compile nowhere and assert nothing,
which is the same defect this branch is already correcting.

Verified GOOS=windows go vet ./internal/testutil/ clean (it fails on
origin/main), and GOOS=windows go build clean before and after. The Windows
gate itself is compile-verified only -- no Windows host here to execute it.
(refs be-napos)

* docs(testing): state that ambient BEADS_DOLT_*_PORT is never honored

The guard fires on every not-ready state, not only "Docker unavailable" -- a
missing or wrong-version image and an explicit BEADS_TEST_SKIP=dolt opt-out
clear the ambient port too. That is deliberate: the invariant is the absence of
a test container, not the reason for it. Say so where the next person will look
before investigating, and name the supported way to target a specific server.
(refs be-napos)

* chore: remove leaked internal release-gate doc from PR branch

  release-gates/be-napos-ambient-dolt-port-failclosed-gate.md

Tracked our internal gc-management/beads-rig release-gate checklist and
should never have been committed to this upstream branch -- it's process
residue from our deploy tooling, not part of the change itself.

Per maintainer bee-ghosttrack's request during review of PR #6571. The
root cause (our deploy tooling auto-committing this file) is already fixed
as of gm-qatxl1; this branch predates that fix, so this commit is cleanup
only -- no other content on this branch is touched.

Ref: be-lk7o3

* chore(bazel): enumerate the PR's new test files in BUILD.bazel

Base added BUILD.bazel to internal/testutil and internal/storage/dolt after
this PR was opened (#6881 made the Bazel lane real, and fork PRs always run
it). The four new test files this PR adds were therefore absent from the
go_test srcs lists, which the bazel lane's equivalence check reports as a
missing target.

Generated by 'make bazel-sync' (gazelle), not hand-edited, because the CI
drift step diffs against exactly what gazelle emits.

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

* fix(testutil): reconcile the shared-server harness with the fail-closed clear

Review iterations 1-2 (adopt-pr, PR #5885): every gating finding from both
review syntheses, plus their minors and nits.

Iteration 1, Major 1 (Change Impact / Blast Radius). scripts/test.sh's
BEADS_TEST_SHARED_SERVER=1 flow starts a dockerless `dolt sql-server` and
exports BEADS_DOLT_PORT for every package to reuse. checkDolt() has no notion
of an already-provisioned shared server, so on that flow's primary audience --
a host without Docker -- all 12 EnsureDoltContainerForTestMain callers erased
the harness's own sanctioned port before m.Run(), turning green dockerless runs
red, while engdocs/CI_TEST_SURFACE_AUDIT.md and the new TESTING.md paragraph
advertised the two mechanisms unreconciled.

Taken: a dedicated marker, BEADS_TEST_SHARED_DOLT_SERVER, exported by
scripts/test.sh beside the port it allocated, which the helper's failure paths
honor. Both docs state the reconciliation, including the precedence: a
container, where one can be started, still overwrites both variables. Not
taken: "skip the clear when BEADS_TEST_SHARED_SERVER=1 and a port var is
already set". That flag is overloaded (cmd/bd/shared_server_integration_test.go
reads it too), and the script starts no server when a port is already set, so
the flag beside a port is exactly the case where the port is ambient.

Iteration 2, blocker (Behavioral Correctness). Iteration 1 shipped that marker
as a boolean ("1") which spared BOTH port variables, while the script vouched
only for the BEADS_DOLT_PORT it exported and its entry guard never looked at
BEADS_DOLT_SERVER_PORT -- the variable applyConfigDefaults resolves first. The
runner's test environment (beads_test_env_enter) unsets both variables before
the flow runs, so the hole needed that isolation skipped, e.g. with the
documented BEADS_TEST_ENV_DISABLE=1; then an inherited BEADS_DOLT_SERVER_PORT
reached `go test` beside the marker and outranked the shared server --
gm-2g3g5r, re-opened by its own fix. Measured with a fake `go` that prints its
environment: SERVER_PORT=59999 PORT=<shared> MARKER=1 under the iteration-1
script. Now:

  - the marker's value is the port it vouches for, and the helper decides per
    variable (neutralizeUnvouchedDoltPorts): only a variable holding exactly
    that port survives, and says so on stderr; every other one is cleared,
    marker or not;
  - the flow starts only when neither port variable is set, and says on stderr
    when BEADS_TEST_SHARED_SERVER=1 is ignored for that reason.

Not taken: also exporting BEADS_DOLT_SERVER_PORT from the flow. The widened
guard means it is always unset there, so the export adds no safety, and five
sites read that variable alone (internal/doltserver/doltserver.go:796,
cmd/bd/init.go:773 and :1351, cmd/bd/bootstrap.go:857,
internal/testutil/testdoltbranch.go:164) -- consumers the flow has never fed.

Iteration 2, minor (Test Evidence Quality). The exception's second arm, a
container that would not start, was reached by no test with its guard live.
Both failure paths now share one clear, and the container start is a seam
(startSharedContainerFn, pinned to startSharedContainer by identity) so tests
reach that path without consuming doltServerOnce.
TestEnsureDoltContainerForTestMain_KeepsHarnessProvisionedPort runs its whole
table, marked_but_divergent_var included, through both paths.

Iteration 2, minor (Contract & Interface Fidelity). The marker prose in
TESTING.md, CI_TEST_SURFACE_AUDIT.md, test.sh and testdoltserver.go describes
the per-port behavior the code now implements.

Iteration 1, Major 2 (Contract & Interface Fidelity). neutralizeAmbientDoltPort's
doc comment claimed "With no port resolvable, applyConfigDefaults'
BEADS_TEST_MODE guard forces port 1". Clearing the env vars is not "no port
resolvable": resolution falls through to the file chain and derives a
directory from filepath.Dir(cfg.Path) when BeadsDir is empty
(store.go:1661-1664), so a reachable .beads/dolt-server.port still yields a
non-zero port and the ServerPort == 0 arm (store.go:1683-1687) never fires;
production-port detection is strictly narrower than resolution. Narrowed to
what the change actually guarantees -- no environment-named port is honored --
at all three sites carrying the claim: the helper doc, the TESTING.md
paragraph, and TestApplyConfigDefaults_NoResolvablePortFailsClosed's own
comment, whose fixture (an empty beadsDir) is what excludes the surviving
path. The residual stays tracked in be-rl6tm. That test's stale
cross-reference to a renamed test is corrected in the same pass.

Iteration 1, minor (Test Evidence Quality). The Windows gate's comment claimed
a CI lane it does not have; it now states the coverage exactly --
compile-checked, not CI-executed -- and lists the four windows-latest jobs'
named selectors.

Iteration 1, nits. doltServerErr is read under doltServerMu via
sharedContainerErr(); TestCheckDoltFn_DefaultsToRealProbe pins function
identity with reflect instead of asserting non-nil, which any leaked stub
satisfied.

Mutation ledger (scoped `go test ./internal/testutil/`, scrubbed env; every
mutant restored from a copy and verified byte-identical):

  a set marker spares every    marked_but_divergent_var, divergent_legacy_var,
  variable (the i2 blocker)    marker_names_neither_var and boolean_marker red
                               on BOTH failure paths
  the marker covers            marked_but_divergent_var, marker_names_neither_var
  BEADS_DOLT_PORT only         and boolean_marker red on both paths
  presence instead of value    the same red set as the first row
  no clear after a failed      the 5 container_start_failed cases that expect
  container start              a clear red; every not_ready case stays green
  start attempted before the   all four incumbent fail-closed subtests and
  probe                        every not_ready case red
  leak a wrapper into          StartSharedContainerFn_DefaultsToRealStart red
  startSharedContainerFn
  delete the hermetic          ClearsAmbientPortWhenNotReady red
  t.Setenv, marker ambient
  at the fixture's port

Full package green with Docker, including the real-container
EnsureDoltContainerForTestMain path (43 test and subtest passes, no skips);
`go test ./scripts/`, which drives test.sh, green; `GOOS=windows go vet
./internal/testutil/` clean; `tools/bazel/go_srcs.py --check` clean, and no
BUILD change is due (no new files, no new non-stdlib imports).

Deferred deliberately: the iteration-1 synthesis's optional windows-latest step
for ./internal/testutil/. It is newly feasible -- this branch is what made the
package's Windows test binary compile -- but it would also newly execute four
pre-existing test functions in this package that have never run on Windows, so
it belongs in its own change. RequireDoltContainer's unsynchronized
doltServerErr read is base-owned and left alone for the same reason.

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

---------

Co-authored-by: Julian Knutsen <julian@gastownhall.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
2026-10-01 05:21:49 -07:00
Julian Knutsen
46e670abbf
ci: retire PR Risk's legacy embedded tier where the gated Bazel lane runs it (D2 step 1) (#7071)
* ci(pr-risk): stand down legacy embedded tier where the gated Bazel lane runs it

D2 step 1. A new bazel-embedded-coverage job decides, from the same
expressions as bazel.yml's rbe job, whether pr.yml's Bazel call takes
execution mode remote on a same-repo pull_request (RBE_WEST_WORKERS on,
executor secret present, not a fork). Only then do test-embedded-storage,
test-embedded-conformance and test-embedded-cmd (27 jobs) skip, and PR
Risk's gate accepts those skips only then; a failed or missing decision is
red. Forks, Dependabot, secret-less runs, the farm switch unset and
merge_group keep the legacy tier. build-embedded keeps running: its
artifact feeds the proxied and server Dolt jobs.

The decision job reads no repository code and the secret only as an
emptiness test. scripts/pr_risk_bazel_coverage_test.go runs both actual
decision scripts over every event/var/secret/fork combination and requires
covered <=> (pull_request && Bazel mode remote), pins the shared env
expressions, checks pr.yml still requires BAZEL_EMBEDDED and shares PR
Risk's triggers, and simulates PR Risk's gate over every tier/decision.

Revert: unset RBE_WEST_WORKERS.

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

* docs(ci): record the retired legacy embedded tier in the check topology

Who keeps the legacy tier, how the decision and gate work, the drift
guard, the residual cross-run race, the conformance.yml duplicate, and
how to revert (unset RBE_WEST_WORKERS).

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

* ci(pr-risk): retire the embedded tier by committed flag; pr.yml gate fails closed

Review F1. PR Risk's coverage decision read the mutable RBE_WEST_WORKERS
variable in a different run from pr.yml's rbe job, so unsetting it and
re-running one workflow could leave both required checks green with
neither the legacy tier nor the Bazel lane having run the tier.

- Both workflows now commit BAZEL_RETIRES_LEGACY_EMBEDDED (policy-tested
  equal) and run the identical bazel-embedded-coverage job:
  covered = flag && pull_request && !fork && executor secret present.
  RBE_WEST_WORKERS is no longer read by PR Risk at all.
- pr.yml's ci-gate requires the job's result (BAZEL_EMBEDDED_COVERAGE)
  and BAZEL_EMBEDDED_RETIRED, which is red when covered but the Bazel
  embedded lane did not run remotely and pass (mode skip included).
- Revert is a commit of the flag to "false" in both workflows; in-flight
  PRs pick it up on their next push. The kill-switch runbook now flips
  the flag first.

Tests run both decision steps, bazel.yml's rbe step and pr.yml's real
gate step over every event/var/secret/fork/flag combination, with the
variable differing between the two runs, and require no double-green
without the tier.

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

* ci(bazel): never cache embedded-tier test results

Review F2. Since D2 step 1 the Bazel embedded lane is the tier's only
pre-merge run on same-repo PRs, so a cached PASS (stale, or a poisoned
entry in the shared farm action cache) or a cached run that never
re-exercises an intermittent -race finding would stand in for the legacy
jobs' -test.count=1 run. test:embedded now sets --nocache_test_results,
and the policy test requires it and forbids any other rc line that turns
test result caching back on.

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

* test(ci): forbid flaky-test retries in the gated Bazel lanes

Review F3. Adding --flaky_test_attempts to a lane's config or
flaky = True to a lane target passed every policy test, and would hide
a flaky failure the legacy jobs (which ran each test once) would have
reported; since D2 step 1 nothing else runs the embedded tier on
same-repo PRs. TestBazelGatedLanesNeverRetryFlakyTests rejects
flaky_test_attempts and runs_per_test_detects_flakes in .bazelrc,
.github (workflows, setup-bazel's generated rc) and tools/bazel, and
flaky = True in every BUILD file and .bzl macro.

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

* test(ci): pin the Bazel embedded lane's command line and config

Review F4. An extra --test_arg=-test.short/-test.skip on bazel.yml's
`bazel test //... --config=embedded` line, or a test:embedded
--test_filter in .bazelrc, narrowed the tier while every policy test
passed (check_testcases only rejects a shard with zero tests). Since D2
step 1 this lane is the tier's only pre-merge run on same-repo PRs, so:

- bazel-embedded's test step must be exactly the pinned script;
- the --config=embedded lines must be exactly the pinned list, in order;
- no unconfigured common/build/test line, and nothing setup-bazel's
  generated rc writes, may select or narrow tests (test_filter,
  test_arg, -test.short/run/skip, tag/size/lang/timeout filters).

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

* build(bazel): add the D2 policy tests to scripts_test

scripts/pr_risk_bazel_coverage_test.go was missing from
//scripts:scripts_test's srcs, so `bazel test //scripts:scripts_test`
(and the BUILD-sync check) did not see it. The repository-walking
flaky-retry test skips under Bazel, whose runfiles hold no other
package's BUILD files.

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

* ci(bazel): check every listed embedded test ran in its Bazel shard

Review F5. The shard scripts discover tests from source with grep, but
each Bazel test binary holds only its target's srcs, so a discovered test
the binary lacks matches nothing in the shard's -test.run selector and
passes silently (check_testcases.py only rejects a shard with no tests).

tools/bazel/check_shard_coverage.py runs each shard script in list-only
mode (BEADS_TEST_SHARD_LIST_ONLY=1) and requires every Bazel shard's
test.xml to hold exactly the listed top-level tests: missing, extra,
wrong-shard, shard-count mismatch, missing test.xml and a failing script
are errors. bazel-embedded runs it after the tier for
//cmd/bd:bd_embedded_test (20) and embeddeddolt_embedded_test (5); the
policy test pins the suites to pr-risk.yml's jobs and shard counts, and
a fixture test exercises the script.

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

* docs(ci): correct the D2 enforcement, re-run and merge-queue claims

Review F6.
- The beads-only ruleset enforces both gates on main only; release/**
  PRs run them but merging does not wait for them, before and after D2.
- There is no merge queue and strict is off: merge_group runs are not a
  pre-merge safety net for the retired tier.
- Spell out "Re-run all/failed jobs" semantics under the committed flag,
  the remaining secret-deletion window, and that the revert needs a new
  push to in-flight PRs.
- Record the lane hardening the retirement relies on (no result caching,
  no retries, pinned selection, per-shard coverage check).

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

* fix(ci): drop TestMain from the embedded shard-coverage check

Re-review G1 (blocking). embedded-storage-test-shard.sh discovers tests
with `grep '^func Test'`, which also lists TestMain(m *testing.M)
(internal/storage/embeddeddolt/test_fixture_test.go). It is never a
<testcase>, so check_shard_coverage.py reported it missing on every real
remote run, turning bazel-embedded and CI Gate red on every same-repo PR.

The checker now drops NOT_TESTS = {TestMain}. The shard scripts are left
unchanged so the legacy jobs' -test.run selection stays byte-for-byte the
same (dropping TestMain there would be harmless to shard assignment,
which hashes per name, but would touch the legacy CI scripts this step
does not otherwise change).

TestEmbeddedShardScriptsListOnlyRealTests runs both real shard scripts
in list-only mode for every shard and requires each listed name to be a
`func Name(t *testing.T)` in the package, or in NOT_TESTS (which may hold
only TestMain, and only if it is not a test). The fixture shard script
now lists TestMain too, so the filter itself is exercised.

Verified on a real remote run (`bazel test //... --config=embedded
--config=remote-exec`, 4/4 targets, 27 test.xml, 582 top-level tests,
348 s uncached): check_testcases.py and check_shard_coverage.py both
pass (199 cmd + 381 storage tests); the previous checker failed on
TestMain.

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

* ci(pr-risk): decide embedded coverage by actor, not by the executor secret

Re-review G2. covered still read secrets.RBE_WEST_EXECUTOR, which an admin
can delete between PR Risk's run and a re-run of pr.yml: PR Risk stayed
green with the legacy tier skipped, while the re-run computed covered =
false, took mode local and passed with no embedded lane.

Both workflows' bazel-embedded-coverage now decide
covered = flag && pull_request && !fork && github.actor != dependabot[bot]
and read no secret or variable at all (PR Risk now reads no secret).
Dependabot (no Actions secrets) keeps the legacy tier; github.actor,
unlike triggering_actor, survives a re-run by someone else. A same-repo
PR without the secret is covered, so pr.yml's gate goes red (mode local)
instead of passing.

The two-run test matrix now varies the secret as well as RBE_WEST_WORKERS
between PR Risk's and pr.yml's runs, adds the actor to the facts, and
names the missing-secret case (red). Docs updated: the residual is gone,
the cost of failing closed is recorded.

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

* test(ci): close the remaining ways to narrow the Bazel embedded lane

Re-review G3. Skip-inducing edits outside the pinned --config=embedded
lines and command line still passed every policy test (reviewer
survivors m1, m2, m5, m6, m9, m10, m11), and the runtime checks counted
skipped testcases as run.

TestBazelEmbeddedLaneCannotBeNarrowed now rejects:
- any .bazelrc line of a config the lane uses (unconfigured, embedded,
  remote-exec from setup-bazel's rc, and any config they reference) that
  filters, narrows, re-runs or re-routes tests (test_filter, test_arg,
  -test.*, *_filters, test_env=BEADS_TEST*/GO_TEST*/TESTBRIDGE*,
  --config=, cache_test_results, run_under other than test_env, flaky,
  runs_per_test, sharding strategy);
- any import other than the two gitignored try-imports, and any
  committed rc file besides .bazelrc (try-import would load it in CI);
- -test.short/run/skip/list, BEADS_TEST_SKIP, BEADS_TEST_EMBEDDED_DOLT,
  TESTBRIDGE_TEST_ONLY and similar in tools/bazel/*.sh (test_env.sh,
  go_test_manifest_shard.sh, ...) and anywhere in the setup-bazel action,
  and any --config= there but remote-exec;
- any change to the set of embedded-tagged targets or their args/env.

At run time check_shard_coverage.py fails a shard whose top-level tests
were all skipped, and its new --whole option applies the same check to
the unsharded conformance core/audit targets (added to bazel-embedded's
step). The real remote run still passes (no shard is all-skipped today;
one cmd shard has 1 of 9 tests skipped).

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

* ci(bazel): ask Bazel for flaky test targets before the embedded tier

Re-review G4. The F3 grep wanted a literal `flaky = True`, so
`flaky = _RETRY` (or a macro default) slipped through (reviewer m3).

- bazel-embedded runs `bazel query 'attr(flaky, 1, tests(//...))'` after
  setup-bazel and before the tier, and fails on any result (loading only;
  about 0.2 s warm). Verified locally: with `_RETRY = True` /
  `flaky = _RETRY` on embeddeddolt_embedded_test the query lists it.
- The policy grep now rejects any `flaky =` whose value is not a literal
  False or 0, and TestBazelEmbeddedQueriesFlakyTargets pins the step.

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

* test(ci): cover the zero-testcase shard in check_shard_coverage

Re-review G5. Skipping the "listed but did not run" report when a shard's
test.xml has no top-level tests survived the fixture test (reviewer m7);
check_testcases.py catches that shard at run time, but the coverage
check should not depend on it. Two fixture cases: a shard with no
testcases, and one with only a subtest.

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

* docs(ci): record the G1-G5 embedded-lane hardening in the topology doc

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

---------

Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-01 02:03:46 -07:00
Denis Redozubov
02f05340f6
fix(externaldeps): guard explicit claims and batch closes (#6738)
* fix(externaldeps): guard explicit claims and batch closes

Preserve external capability policy across lifecycle updates and batch close/claim-next operations, including direct, embedded, and proxied paths. Follow up on upstream PR #4753 and issue #4769.

Agent-Signature: codex-unknown-model-unknown-reasoning on behalf of Denis Redozubov

* test(externaldeps): include embedded regression in CI discovery

* test(serve): preserve external close policy when peeling hooks

Replace the raw batch-closer identity assertion with a behavioral policy check, retaining the no-hooks assertion. Document full-workspace claim filtering and batch lookup cost.

Agent-Signature: codex-unknown-model-unknown-reasoning on behalf of Denis Redozubov

* test(externaldeps): align the mixed-batch pin with #6648's partial-failure exit

Maintainer fixup applied while adopting PR #6738.

`exerciseExternalMutationPolicy`'s `mixed_batch_and_claim_next` subtest asserted
that a partially-refused `bd close` batch keeps the CLI's zero exit status. That
was true at this PR's original base, but #6740 (Beads #6648) landed on main in
the meantime and made a partial batch close exit 1 with an
`N of M issues failed to close` summary. The two changes are independently
correct and merge without a textual conflict, so the stale expectation only
surfaces as a red `cmd/bd` shard after the rebase.

The PR's substance is unchanged: the externally blocked issue is still refused
with its blocker named, the eligible item still closes, and `--claim-next` still
claims. Only the exit-status expectation moves onto the current contract, and
the summary line is now pinned so the interaction between the two features stays
covered.

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

* test(dolt): check version scope on the transaction owner

withWriteTx and withRetryTx delegate transaction creation to commitWriteTx after #6719. Point the existing completeness guard at that owner so it still checks BeginTx and the versioned-history scope together.

Agent-Signature: codex-unknown-model-unknown-reasoning on behalf of Denis Redozubov

* fix(ci): register external policy files and isolate server cleanup

Include all six new Go files in Bazel targets. Run the direct-server fixture before parallel proxied tests because its cleanup purges dropped databases across their shared server; observed initialization failures coincide with that cleanup.

Agent-Signature: codex-unknown-model-unknown-reasoning on behalf of Denis Redozubov

* fix(externaldeps): scope close-only batch policy and drop the claim --force hint

Review-loop fixup for PR #6738 (iteration 1). The review approved with no
blocker or major findings; this takes its three minors and its nit, all in
code this PR introduces. Each minor lands with a test that a mutation of the
covered code turns red.

[minor] A refused proxied claim suggested an override that cannot work. The
external claim guard ignores --force but shares ErrCloseBlocked with the close
policy, so on the proxied route `bd update <id> --claim` against an externally
blocked issue printed "(use --force to override)". proxiedUpdateFailure now
reports a refused claim as the generic update failure, as the direct route
always has. claim_is_atomic asserts the refusal never mentions --force;
restoring the unconditional hint fails it on the proxied lane.

[minor] A close-only batch demanded policy support for unrelated blockers.
Without ClaimNext the batch closer still passed the workspace's whole
externally blocked set to BatchCloserWithPolicy, so one external blocker
anywhere made a backend lacking PolicyBatchCloserSource (such as one
registered through internal/storage/backends) refuse to close unblocked
issues. The policy is now scoped to the batch items unless the batch claims
next work, which still needs every blocker for FilterClaim. CheckClose looks
up exact ids, so no refusal changes. The NewBatchClosePolicy doc now says when
the whole set is required. TestBatchCloserScopesPolicyWithoutClaim covers an
unrelated blocker, a blocked item, and a next claim against such a backend.

[minor] The policy's fallback target read had no pin.
TestExecuteCloseBatchWithPolicyDefersToTheTargetRead drives it through
sqlmock: a missing target keeps the backend's not-found, and a failing status
read reports that failure, never ErrCloseBlocked. Refusing the missing target
or swallowing the read error each fails it.

[nit] DoltStore and EmbeddedDoltStore BatchCloserWithPolicy return
ErrUnsupported on a nil receiver, as NewBatchCloser does.

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 <noreply@anthropic.com>
Co-authored-by: Eddie the Engineer <adopt-pr@gascity.com>
Co-authored-by: Eddie the Engineer <adopt-pr@gascity.local>
2026-10-01 01:35:54 -07:00
ecuthiell
46f182aa26
fix(ci): require direct workflow build tags (#5679)
* fix(ci): require direct workflow build tags

Parse workflow run scalars structurally and require recognizable direct Go commands to declare the literal gms_pure_go tag. Keep shell and Make checks lightweight and preserve their existing conventions.

Fixes #5527

Agent-Signature: codex-gpt-5-unknown-reasoning on behalf of Ewen Cuthiell
Signed-off-by: Ewen Cuthiell <ewencuthiell@gmail.com>

* fix(ci): recognize double-dash Go build tag flags

Address PR #5679 review 5191180453. Preserve last-tag precedence and test argument boundaries, including --args.

Agent-Signature: codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell

* fix(ci): bazel-sync the new checker, restore its opt-out and the Bazel census

Maintainer review fixes for PR #5679, adoption iterations 1 and 2. Iteration
1's synthesis is `request_changes` on one major plus three minors; all four
are addressed. Iteration 2 approves with one minor, also addressed.

Major (Release Safety): the PR adds two production Go packages with no
BUILD.bazel, so `bazel build //...` could not see them and the repo's own
"BUILD files in sync" step fails on the resulting gazelle drift. Added the two
generated files via `make bazel-sync`; yaml.v3 is already a direct go.mod
requirement, so no module change is owed.

Minor (Release Safety): the new checker runs in the required pr-policy lane with
no way out, while the shell checker it partly replaces honors
`# build-tags: allow-bare` in a file's first five lines (check-build-tags.sh, and
engdocs/ICU-POLICY.md documents that window). CheckDir now honors the same
marker in the same window -- one convention, not two -- pinned by a table that
includes the fifth line and the sixth, so the two checkers cannot drift apart on
where the window ends.

Minor (Change Impact): dropping the workflow glob from `candidates` moved
workflows to the Go checker but also, silently, out of the `bazel_users` census --
and the Go checker does no Bazel handling at all, so .bazelrc could have lost its
tag with this gate still green. Workflows now feed the census through their own
`git ls-files` list and a separate loop, deliberately not rejoining the `go`-verb
scan. This is not hypothetical: `.github/workflows/bazel.yml` matches the Bazel
invocation regex, so it is exactly the file the census was losing.

Minor (Test Evidence): `Line` is the operator-facing half of a violation -- it is
what the error message points at -- and nothing asserted it, so reporting every
violation at line 1 would have been invisible. Added a `wantLine` column, asserted
on the multi-line "source is not workflow authority" case (line 2), and asserted
`Path`/`Job` where CheckDir fills them in.

One deviation, recorded: the finding also asked for `Line` on the existing
"continuation" case. That case is tagged, so it reports no violation and has no
Line to assert. Added a continuing-but-violating case instead, which makes the
same attribution observable -- a logical line spanning three physical ones is
reported at the first.

Not included: `make bazel-sync` also wants `//internal/debug` in
internal/utils/BUILD.bazel. That is base drift, not PR content -- absent at this
branch's rebase base but already present on origin/main, 24 commits ahead -- so it
heals on the next base refresh, and carrying it would duplicate main's own fix on
a file this PR never touches.

Minor (Test Evidence, iteration 2): the census half of the Change Impact fix
was right in code but pinned by nothing -- turning the workflow `bazel_users`
append into a no-op, or feeding the census-only list into the `go`-verb loop,
left every check_build_tags_test.go case green. Two cases on the existing
fixture harness now pin both directions: a workflow that runs `bazel build`
with an untagged .bazelrc fails and is named as the Bazel user, and a workflow
`run: go test ./...` passes here because scripts/checkworkflowtags owns it.
Each fails under its mutant, as does one more apiece (re-adding the workflow
glob to `candidates`; dropping `*.yml` from the census list), while the three
existing cases stay green under all four.

Validation: ./scripts/workflowtags passes (all four CheckDir tests and the full
CheckRun table), `go vet ./scripts/...` clean, `bash -n` clean, and both checkers
run green against the repository itself -- check-build-tags.sh reports 90 files
scanned all clear, and checkworkflowtags reports all direct commands clear.
For iteration 2, `go test ./scripts/` passes, and on a merge with current main
`bazel test //scripts:scripts_test` passes too; on this branch's own base that
target cannot build, because of the internal/utils drift noted above.

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>

* test(ci): pin main.yml's bd-cmd-test build to the literal gms_pure_go tag

#6940 pinned main.yml build-artifacts' non-race bd-cmd-test build as
`go test -tags "$BEADS_BUILD_TAGS" -c -o artifacts/bd-cmd-test ./cmd/bd`.
This PR requires a literal gms_pure_go tag on direct workflow Go commands
and rewrites that line to `go test -tags gms_pure_go -c ...`, so on
current main TestBazelDoltServerTiersMirrorPRRisk fails in both
`go test ./scripts` and //scripts:scripts_test. Restoring the pinned
spelling is not an option: checkworkflowtags rejects it ("direct `go test`
must declare literal gms_pure_go in -tags").

Update the pin to the literal spelling. It still pins what #6940 cares
about, a non-race bd-cmd-test built from ./cmd/bd: adding -race to that
line still fails the test.

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

---------

Signed-off-by: Ewen Cuthiell <ewencuthiell@gmail.com>
Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 01:24:03 -07:00
Jim Wordelman
2db739e8b0
perf(storage): SearchIssueSummaries narrow-projection foundation (be-nu4.3) (#3458)
* feat(search): re-cut SearchIssueSummaries atop Lite as searchProjection[T]

Re-cuts release/be-nu4.3-stack onto current main, resolved against the
merged Lite foundation (#3906) instead of the stale pre-Lite conflict set.

SearchIssueSummaries moves from a standalone search_summary.go into a
summaryProjection literal alongside issueProjection/issueLiteProjection/
idProjection in issueops/search.go, sharing the generic searchInTx core
instead of a parallel top-level function — retiring the anti-pattern
coffeegoddd's CHANGES_REQUESTED flagged. LessSummary shares lessFields
with Less via a summarySortFields adapter so the two comparators can't
drift on NULL-handling or tie-break rules.

Adds parity coverage (SearchIssues vs SearchIssueSummaries agree on ID
set/order and on every IssueSummary field) and the three-way wide/lite/
summary A/B benchmark, extending dolt_benchmark_test.go — which still
only compiles together with the projection method, the fact that
retired the earlier "land the bench file first" plan.

* test(feat): red — fix parity test to compare order directly + add comparator/wisp-limit coverage (refs be-be3pj)

- TestSearchIssuesAndSearchIssueSummaries_Parity now compares
  SearchIssues/SearchIssueSummaries IDs order-sensitively (slices.Equal)
  instead of via the sort-then-compare equalStringSlices helper, which
  would silently pass an ordering/top-N regression.
- Add TestLessSummaryMatchesLessAcrossSortKeys: Less vs LessSummary
  produce identical order across every SortDefs key + "id", both
  directions.
- Add TestSearchIssueSummariesInTx_MergesAcrossIssuesAndWisps: be-yrtwi
  regression pattern for summaryProjection specifically, covering
  wisp-merge top-N truncation under a limit.

* fix(types): give IssueSummary the same JSON tags as Issue

IssueSummary carried no struct tags, so encoding/json emitted Go's default
field names ({"ID":…,"Title":…}). The type exists to back list-shaped
rendering and `bd list --json` is one of that command's primary modes, so
the wiring follow-up would have silently changed the wire shape for every
consumer parsing bd output. Zero production callers today makes this a
zero-risk moment to fix it.

Tags mirror the same-named fields on types.Issue exactly, including
priority carrying no omitempty (0 is a valid P0). Three tests pin it: a
reflection test comparing every tag against Issue's so the two cannot
drift, an exact-key-set marshal test, and an omitempty test.

Reviewer item 1 (maphew, 2026-08-03).

* docs(storage): pin the --sort id contract on SearchIssueSummaries

The interface said SortBy/SortDesc are honored identically to SearchIssues,
which is true but left the id case looking like a gap in the summary path.
It is not a gap, and the doc now says why: sqlbuild.OrderBy emits no ORDER BY
for id (sqlbuild.IsGoSideSort), so *neither* path gets a SQL id order, and
both carry a comparator used only where the issues+wisps merge re-sorts
(sqlbuild.Less / sqlbuild.LessSummary).

The user-facing id order is cmd/bd's own, applied after the call via
utils.NaturalCompareIDs (cmd/bd/list.go sortIssues -> compareIssuesBy) —
numeric-aware, so bd-2 sorts before bd-10. Adding a lexicographic
storage-side summary sorter would therefore diverge from SearchIssues and
still not match what bd list renders.

Reviewer question (maphew, 2026-08-03): the contract no longer depends on
an unfiled follow-up to be readable.

* fix(backend): alias IssueSummary into the public backend contract

#5321 landed the public backend surface and its reflection drift guard on
2026-08-03, about two hours after this branch's last push, so the 08-11
maintenance rebase brought the branch under a gate that did not exist when
the engine interface was widened. TestPublicSurfaceComplete fails on both
platforms at the rebased head:

    internal type github.com/steveyegge/beads/internal/types.IssueSummary
    is reachable from the public backend contract but has no alias in
    package backend

The gate is right and the rebase broke nothing. SearchIssueSummaries
returns []*types.IssueSummary on storage.Storage, which backend.DoltStorage
aliases whole, so the row type is now part of the contract an out-of-tree
backend writes against — and without the alias that backend cannot name it.

Verified this is ours rather than base breakage: the same test passes on
origin/main and fails only on this branch.

* ci: retrigger after infra-flake red on dc92c3c3

Run 34381971686 went red on two failures, neither of them in this PR's
15-file diff:

- Test (storage domain + uow): internal/tracker lost its Dolt
  testcontainer mid-suite after a Ryuk reaper handshake reset
  (54 failed, 1994 passed). Known parallel-binary reaper flake; the
  fix is PR #5770, open and unmerged upstream since 2026-08-15. Third
  recorded recurrence, same package and same mapped port as the prior
  two.

- PR Core (wrapper timing): TestDoltServer_LogFile_CapturesOutput in
  internal/storage/dbproxy/server, a package this PR does not touch.
  Not reproducible locally in 55 attempts against clean main, 30 of
  them under 2x CPU load with the CI-pinned dolt 2.2.0.

We are pull-only on the upstream repo and cannot rerun jobs, so an
empty commit is the only retrigger lever available.

* test(issueops): tie the summary column list to its scanner, delete a third copy

Review point (minor 2): IssueSummaryColumns, ScanIssueSummaryFrom's dest list
and search_summary_merge_test.go's summaryColumnNames were three hand-synced
copies of the same list, with only the real-database field-parity test to
catch a drift between them.

Two changes rather than one guard over three lists:

  - summaryColumnNames now derives from IssueSummaryColumns instead of
    restating it, so the fixture cannot drift at all. summaryMergeRow places
    its values by column NAME against that list rather than by literal
    position, so adding a column widens the row automatically instead of
    silently shifting every value one slot left.

  - TestIssueSummaryColumnsMatchScanner pins the remaining pair by count,
    using a counting scanner that needs no database. This is the summary
    counterpart of TestIssueSelectColumns_LitePlusHeavyEqualsFull.

TestIssueSummaryColumnsAreRealIssueColumns covers what a count cannot: a
misspelled column keeps the widths equal and fails only at query time against
a real database, as an opaque unknown-column error from whichever caller runs
first. Requiring membership in IssueSelectColumns catches it in a unit test.

Membership, not order: unlike IssueSelectColumnsLite, IssueSummaryColumns is
deliberately not a subsequence of the full list, so there is no analogue of
TestIssueSelectColumnsLite_IsFullMinusHeavyInOrder.

Both guards verified red-before-green by mutation: adding a column without a
dest fails the first, and misspelling one fails the second.

* fix(types): carry the wisp-plane markers through the summary projection

Review point (MAJOR): IssueSummary's doc comment promises a summary-backed
list serializes to the same wire shape a full-Issue-backed one does, and
issueops.searchInTx merges wisp rows into every result whose filter does not
set SkipWisps. But IssueSummary had no Ephemeral, NoHistory, WispType or
StorageClass, so a wisp rendered through it dropped ephemeral, no_history,
wisp_type and storage_class from `bd list --json` while every other key stayed
identical -- a wisp and a durable bead became indistinguishable on the wire.
maphew raised this on 2026-08-03 and it was still open.

Adding the fields, not excluding wisps. Excluding them would break the
same-wisp-merge-semantics claim that is this PR's central design argument, and
would make the wiring follow-up silently drop wisps from `bd list` entirely --
a strictly worse outcome than the missing keys.

Correcting our own 2026-08-03 reasoning, which argued the other way. That
comment observed that no list *renderer* reads Ephemeral or WispType back off
the row, which is true and beside the point: `--json` does not read fields,
it marshals the struct. It also treated the cost as the one D3 exists to
remove. These four are narrow scalars -- two TINYINT(1), two short VARCHARs,
already present on both the issues and wisps tables and already scanned by
ScanIssueFrom -- not the multi-KB TEXT bodies and JSON parse the projection is
narrow to avoid. Zero callers today makes this free; after the wiring lands it
is a wire-format change.

Verified red-before-green at both levels:

  - TestIssueSummaryCarriesWispMarkers failed on all four fields before the
    change (reflection against Issue, asserting tag AND type -- WispType and
    StorageClass are named string types that a plain string would impersonate
    under a tag-only check).

  - TestIssueSummaryWispKeysMatchIssue marshals the same marker values through
    both types and compares the four keys byte for byte, including a durable
    row that must emit none of them.

  - TestSearchIssueSummaries_FieldsMatchSearchIssues now seeds an ephemeral
    wisp and a no-history wisp (mutually exclusive, so one row each) and
    compares all four markers against SearchIssues on a real Dolt database. It
    refuses to pass vacuously: fewer than two wisp rows in the result is a
    fatal, since zero-vs-zero marker comparisons would otherwise succeed if
    the merge stopped returning wisps. Mutating ScanIssueSummaryFrom to stop
    mapping wisp_type fails it on both seeded rows.

ScanIssueSummaryFrom maps the four exactly as ScanIssueFrom does, including a
NULL storage_class staying empty for EffectiveStorageClass to resolve per
plane rather than being pinned to a literal.

* perf(sqlbuild): compare sortFields through pointers, not two copies per call

Review point (minor 3): the shared-comparator refactor made Less build two
sortFields values per comparison and pass them by value, a small regression on
the pre-existing issues+wisps merge sort inside a perf PR.

lessFields and sortKeyCompareFields now take *sortFields. sortFields is a
~150-byte struct, so passing by value copied it twice into lessFields and
twice more into sortKeyCompareFields on every comparison; that is now zero
copies after the adapters run. The adapters still build one value per row --
that normalization is exactly what buys Less and LessSummary a single shared
body, and giving it up would reintroduce the drift this PR exists to remove.

No allocation either way, before or after: escape analysis reports nothing in
Less/LessSummary/lessFields escaping to heap (the only escapes in sort.go are
the pre-existing SortDefs map and OrderBy's string formatting), and both arms
measure 0 B/op, 0 allocs/op. A throwaway A/B in one binary, -benchtime=3s
-count=3 on the priority key, put the by-value median at 26.33 ns/op and the
pointer median at 25.35 ns/op, with non-overlapping ranges -- a consistent but
small ~4% win.

Stating that plainly rather than claiming more: the value here is removing four
struct copies per comparison from the hot path, not the wall-clock number,
which is within a couple of nanoseconds. Behavior is unchanged; the sqlbuild
suite, including the parity and LessID-honors-sortDesc tests, passes.

* test(dolt): vary SortBy across the summary parity table

Review point (minor 4): none of the nine parity cases set SortBy, so
LessSummary-versus-SQL ORDER BY agreement was proven by unit test alone
(TestLessSummaryMatchesLessAcrossSortKeys) and never against a real database.
Every case ran at the default order, priority ASC.

Nine rows added, covering created, title, status, updated and assignee -- the
first two in both directions -- plus id in both directions. Each carries a
Limit, so the merge's sort-before-trim actually decides which rows survive
rather than the ordering being cosmetic: an ordering bug that only shows up in
which rows a top-N keeps is the failure mode this table exists to catch.

id is included deliberately even though sqlbuild.OrderBy emits no ORDER BY for
it. It is the one Go-side key, so these two rows pin that both paths still
agree on the order the merge comparator produces where SQL contributes none.

All nine pass against a real Dolt database.

* docs(storage): document the summary projection's caller contract

Two review points, both about the contract being legible to a caller who has
only the interface and the extension guide.

Minor 1 -- IncludeDependencies is a silent no-op on the summary path, because
types.IssueSummary has no Dependencies field to populate. hydrateSummaryLabels
says why in its own comment; the interface a caller actually reads did not.
SearchIssueSummaries' doc now states it, alongside the neighbouring facts that
SkipLabels IS honored identically and that wisps are not excluded.

Minor 5 -- engdocs/EXTENDING.md documented the Lite projection's contract and
never mentioned the third one. It now carries a parallel section: what a caller
may read, why there is no IsLitePartial equivalent (a narrower type makes a
missing field a compile error rather than a silent zero value, which is the
substantive difference from Lite), the dependency and wisp rules above, the
ordering guarantee, and where each is enforced -- including the note that
IssueSummaryColumns is deliberately not an ordered subsequence of the full
list, so it has no analogue of the lite path's in-order guard.

The Lite section is left intact, its own Backend coverage subsection included;
the new section follows it rather than interleaving.

* chore(bazel): enumerate the two new test files in their go_test srcs

The PR adds internal/types/issue_summary_test.go and
internal/storage/issueops/search_summary_merge_test.go. Both are untagged,
and both packages carry a base-added BUILD.bazel whose go_test enumerates
srcs explicitly, so bazel silently would not have compiled or run them:
measured on //internal/types:types_test, the unrepaired binary lists 0 of
the 5 new tests (68 total) and the repaired one lists 5 of 5 (73), with
both builds exiting 0 -- a fake green, since bazel reports "1 test passes"
either way.

Base parity at 43a526b828 is clean (102 packages / 1192 untagged test files
enumerated, 0 srcs gaps), so the omission is PR-introduced rather than an
unenforced list. make bazel-sync-check and tools/bazel/go_srcs.py --check
both exit 0 on the broken head; generated with make bazel-sync (gazelle),
which is idempotent here.

Maintainer fixup applied during adopt-pr rebase (PR #3458).

* docs: announce the required SearchIssueSummaries method and inventory its span

Review follow-through for #3458 (maintainer fixup, iteration 1).

CHANGELOG.md: backend/backend.go promises that a required method added to
the engine interface is called out in CHANGELOG.md. SearchIssueSummaries is
one and had no entry. Adds an [Unreleased] "Changed" bullet in the #4911
form, next to the #6731 GetReadyWorkWithCountsAndTotal announcement: the
method and its signature, that callers are unaffected while implementers
must add it to compile, and its contract (SortBy/SortDesc and SkipLabels as
in SearchIssues, IncludeDependencies a silent no-op, wisps merged with their
markers set).

engdocs/design/otel/otel-data-model.md: the direct-operations block calls
itself a complete inventory and was exact at the PR base. The PR's new
storage.SearchIssueSummaries span was the one missing name. Inserted in
alphabetical order and bumped the count to 74. A set-diff against the
s.op(ctx, "...") names in internal/telemetry/storage.go now finds 74 == 74
with no drift in either direction.

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

---------

Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 01:19:24 -07:00
Julian Knutsen
7a21446e6c
ci(bazel): require the integration lane on same-repo PRs (#7069)
pr.yml's bazel.yml call now passes integration: "on", and its ci-gate
requires BAZEL_INTEGRATION (bazel-integration's job.status output, a
missing result reading as skipped). The lane stays remote-only:
bazel-gate.sh allows it to skip in modes local (fork and Dependabot PRs,
until the farm has a read-only cache for them) and skip, never in remote.
bazel-farm.yml's advisory call runs it too.

The integration test step gets 45 minutes (job 55) for cold PR compiles;
the policy test keeps it at or above a 20-minute cold compile plus
.bazelrc's test:integration --test_timeout (the 1200s per-action cap).
The integration input (default "on") stays for callers that want the lane
off; pr.yml's call inputs are pinned, and the gate simulation now covers
the lane skipped, failed and cancelled in each mode.

Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-30 23:56:33 -07:00
ecuthiell
6899813df6
fix(preflight): share checkout lint authority (#5780)
* fix(preflight): share checkout lint authority

Move the Beads repository's native and Windows non-CGO lint policy into a checkout-owned Go driver. The supported Make/Bash wrapper and bd preflight now execute that same authority, while generic Go repositories retain their direct lint contract and formatting is rooted at the detected project.

Fixes #5300.

Agent-Signature: codex-gpt-5-unknown-reasoning on behalf of Ewen Cuthiell

* docs(lint): clarify shared driver scope and timeout limits

Address PR #5780 review 5191123668. Document existing inherited-tag semantics and distinguish the wrapper/preflight driver from standalone workflow and pre-commit callers.

Agent-Signature: codex-unknown-model-unknown-reasoning on behalf of Ewen Cuthiell

* fix(lint): prefer the selected Windows Go toolchain (#6865)

Keep per-pass toolchain requests and deadlines while avoiding the extra auto-selection launcher under the linter. Nonstandard SDKs retain their original PATH.

Agent-Signature: codex-tui-gpt-6-astra-max on behalf of Ewen Cuthiell

* fix(lint): retain PATH for SDK directories containing separators (#6865)

Agent-Signature: codex-tui-gpt-6-astra-max on behalf of Ewen Cuthiell

* test(preflight): declare lint fixture executable for Bazel (#5300)

Agent-Signature: codex-tui-gpt-6-astra-max on behalf of Ewen Cuthiell

* fix(bazel): keep cmd/bd/testdata out of gazelle's package scan

PR #5780 adds the compilable fixture cmd/bd/testdata/preflight-go.go. Left to
itself gazelle generates a BUILD.bazel for cmd/bd/testdata, which makes it its
own package and then (a) empties cmd/bd's data = glob(["testdata/**"]) under the
default allow_empty = False and (b) puts testdata/preflight-go.go across a
package boundary from the preflight_go_fixture target that lists it.

bazel.yml's "BUILD files in sync" step runs `make bazel-sync` and fails on any
resulting drift, and fork PRs always run that job, so this was a live red whose
prescribed remedy ("commit the result") would have broken the build further.
Exclude the directory instead, and take gazelle's ordering for the data list.

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

* fix(preflight): bound the lint deadline and report each check's scope

Review iteration 1 for PR #5780. Synthesis and scorecard both approve (975/1000,
no blocker or major), so this addresses non-gating findings only.

Finding 4 (Resource Lifecycle) - the 13-minute deadline could not bound the call
it guards. CombinedOutput collects through a pipe every descendant inherits, so
Wait kept blocking on a surviving golangci-lint after the context killed the
direct `go run` child. Measured on the same process shape (direct child killed at
1s, descendant holding the pipe for 8s): without WaitDelay the call returned in
8.00s, with WaitDelay in 1.50s. Sets cmd.WaitDelay so the deadline is a real
bound and the "lint check exceeded" line can actually print.

Also gates that line on err != nil, which retires the claude lane's nit (a): a
child that exits cleanly as the deadline fires is a pass, not a timeout. Measured
at the crossover, 68 of 300 passing runs would have carried a false "exceeded"
line; 0 after the gate.

Finding 1 (Change Impact) and nit 7 (Debuggability), one remedy - the PR re-roots
lint and fmt at preflightProjectRoot() but leaves runTestCheck in the caller's
cwd, so a --check run from a subdirectory mixes a repo-wide verdict with a
subtree-only one "with nothing in the output distinguishing them", and the
reported command is only reproducible from the root. CheckResult now carries the
directory each check resolved to, and the report prints it.

Took the synthesis's second arm (state the scope split) rather than re-rooting
runTestCheck, because re-rooting is a behaviour change neither lane priced: it
widens a subdirectory user's test run from 5 packages to 128, including every
Dolt-dependent package, on a repo whose full test gate the PR body already
discloses as red. The stated hazard is that the scopes are indistinguishable,
which reporting the directory discharges directly.

Finding 2 (Architectural Consistency), second clause - adds
TestBuildFlagsContractMatchesShellSource, which parses .buildflags and pins the
driver constants to it. The existing mirror test asserts today's values from the
Go side only, so the files could drift silently; buildEnvironment overrides
rather than merges -tags, so a tag added to .buildflags alone would be dropped
with every test still green. Each of the three legs was mutation-proved to red.

Declined, with the measurements that decided it:

- Finding 2's first clause (route the key comparisons through
  internal/execenv.KeyEqualForOS). The two are provably equivalent today -
  execenv's keyIdentityForWindows is strings.ToLower for the same documented
  reason - so this is de-duplication, not a defect, and the hazard it closes
  (os/exec key-identity semantics changing) is far less live than the
  .buildflags drift the second clause pins. The faithful swap means threading
  goos through five driver functions and ~27 test call sites in this PR's
  centerpiece file, and it would put a non-stdlib dependency into pr-lint_lib,
  which the binary currently does not have. Worth doing on its own footing, not
  inside a non-gating cleanup.

- Nit 6 (parse GOFLAGS into fields instead of a substring test). .buildflags:22
  guards its own append with `!= *gms_pure_go*`, a substring test, and the Go
  code is a deliberate mirror of it. Making only the Go side stricter would
  manufacture exactly the drift finding 2 warns about: on
  GOFLAGS=-tags=gms_pure_go_x the shell would skip its append while the driver
  performed one. The fix belongs to .buildflags and the driver together, and
  .buildflags is outside this PR. The new mirror test now pins that agreement.

- Nit 5 (probe golangci-lint as well as `go`). The claude lane examined the
  LookPath target change and recorded it as deliberate, with the driver's own
  missing-linter error as the mitigation. The suggested alternative - have the
  driver emit preflight's `--skip-lint` hint - puts a bd-specific flag into a
  driver that CI also invokes, where that advice is wrong.

- Finding 3 (two false PR-body claims). Correcting the body is outward-facing
  and belongs to finalize; stamped for it. Swept the in-tree copies: the PR's own
  LINTING.md sentence "Toolchain requests, formatting, and lint deadlines are
  unchanged" is scoped to the Windows SDK-preference paragraph it sits in and is
  true there, so it is graded rather than repaired. CHANGELOG.md contains no
  pr-lint entry, so the remedy's CHANGELOG half has no target in this PR.

Validation: go build, go vet and gofmt clean on the changed packages;
./scripts/pr-lint/ 12 pass / 2 Windows-only skip; ./scripts/prlintmake/ pass;
cmd/bd preflight selector pass; scripts/check-doc-freshness.sh PASSED;
make bazel-sync idempotent and bazel test //scripts/pr-lint:pr-lint_test PASSED.

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

* test(prlintmake): inject the pr-lint wrapper's gofmt shim through GOFMT

The merge with #6294 (be-gx8) left runPRLintWrapper relying on a
code path #6294 made deliberately loud. The helper put its gofmt shim
on PATH. Since #6294, fmt-check.sh resolves gofmt through
scripts/ci/gofmt-bin.sh, which ignores a PATH gofmt by design.

Both TestPRLintWrapper* tests still passed, but only via the
resolver's fallback. The go shim answers `go env GOVERSION` and
`go env GOROOT` with nothing, so gofmt-bin.sh warns "could not resolve
a gofmt from go.mod's go1.26.7 toolchain" and falls back to whatever
gofmt is first on PATH, which happened to be the shim. With GOFMT set
in the environment, which is #6294's documented override, the
resolver uses that value instead. Both tests then fail: exit status
127 from fmt-check.sh, and a missing aggregate failure diagnostic
because pr-lint.sh stops before `go run`. At the pre-merge head
(7f37ba5165) the same ambient GOFMT=/nonexistent run passed all 5
tests.

Pass the shim through GOFMT, as main's runFmtCheck does, and keep it
off PATH so only the go shim is found there. gofmt-bin.sh now returns
the override immediately, and the go shim sees only `version <shim>`
and `run ... ./scripts/pr-lint`. Both wrapper assertions, on the
driver arguments and on the failure diagnostic, are unchanged.

go test ./scripts/prlintmake/: 9/9 pass by default and 9/9 pass with
GOFMT=/nonexistent in the environment. Before this change the second
run was 7/9.

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

---------

Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-30 22:41:55 -07:00
Jim Wordelman
da89d21813
docs(testutil): document migration-0032 hang and Ryuk-disabled container-leak caveats (#6001)
* docs(testutil): document migration-0032 hang and container-leak caveats (refs be-r7j5x)

Adds a comment near DoltDockerImage documenting two known limitations
of the podman-rootless + testcontainers-go real-server test harness:

- Schema migration 0032 hangs indefinitely over the sql-server wire
  protocol in this harness only; not reachable on real GitHub Actions
  CI or a bare-host-process dolt sql-server (be-j3szz).
- Containers can leak because Ryuk is disabled for this harness, so
  there is no reap safety net if a test process skips its cleanup
  (be-5kkk6).

No production code changes.

* docs(testutil): fix Ryuk-disabled citation and causal claim (refs be-ohrc0)

Round-1 review (be-ohrc0) flagged that the container-leak bullet cited
be-hsa9t for the TESTCONTAINERS_RYUK_DISABLED=true rationale and claimed
it was a workaround for this host's broken dockerd/containerd. Neither
is accurate: be-hsa9t is an unrelated git-remote E2BIG fix that never
mentions Ryuk or dockerd/containerd.

Corrects the citation to be-w3n2m (open, undecided) and the causal claim
to match its actual finding: under rootless podman, Ryuk frequently
cannot start because it wants the runtime socket.

No production code changes.

* docs(testing): move the Dolt container caveats out of DoltDockerImage

Review #6001 asked for this to leave the source file, on three grounds
that all check out.

CONTRIBUTING_PR_GUIDELINES.md line 33 is explicit — "Minimize inline code
comments … let the commit message and PR description carry the why" — and
a 23-line comment-only diff is the shape it names. DoltDockerImage is also
the wrong hook: it is the image pin guarded by test/docsync/doltpin_test.go
and read by container_provider.go and testdoltserver.go, so harness
lifecycle lore attached to it reaches every caller including CI.

The Ryuk sentence was also wrong as written. It claimed Ryuk "is disabled
for this harness (TESTCONTAINERS_RYUK_DISABLED=true)". This repository sets
that variable nowhere — not in Go, scripts/, the Makefile, or
.github/workflows/; the only tracked occurrences are release-gates/*.md,
which are records of operators' local podman runs. CI therefore runs with
Ryuk enabled, and the original text described a local shell as if it were
the repo's harness. Reworded to say what is true: the podman-rootless flow
generally requires disabling Ryuk by hand, and doing so is what removes the
safety net.

Both caveats now live in engdocs/TESTING.md as a sibling of "Test
Environment and Readiness", the section that already covers
BEADS_TEST_SKIP=dolt and BEADS_TEST_ENV_RUN_DOLT. Content is otherwise
preserved, including the be-j3szz / be-w3n2m / be-5kkk6 evidence chain, plus
a stray-container check and a pointer to testMainInner in beads_test.go.
engdocs/TESTING.md is not in check-doc-freshness.sh's DOCS list, so this
needs no inventory or freshness marker.

internal/testutil/testdoltcommon.go is now byte-identical to main.

Addresses the doc half of #6171. Refs be-8n9ns.

* docs(testing): scope the Dolt caveats to podman-rootless and fix the repro

Maintainer review fixes for PR #6001 (adopt-pr review iterations 1 and 2).
All edits are phrase-level and confined to engdocs/TESTING.md.

- Scope the causal claim to the podman-rootless path. CI runs the same
  containerized wire path green on every risk-tier PR -- pr-risk.yml's
  test-server-storage* jobs pull the pinned image precisely to defeat the
  self-skip and run with no BEADS_TEST_SKIP=dolt -- so "the container
  port-forwarding path" as a general cause is refuted by the repo's own CI,
  and as written invited a Docker developer to dismiss a real 0032/initSchema
  hang as a known harness limitation. Softened "Neither is reachable ... on
  GitHub Actions" to "Neither failure mode manifests ...", which is what is
  actually true.

- State every way a suite reaches a real dolt sql-server. The entry condition
  named one mechanism (testcontainers-go) and one fallback (self-skip), but
  the uow package the section uses as its repro also has suites that call
  testutil.RequireDoltBinary and start a server from the local dolt CLI
  (proxy.BackendLocalServer) with no container involved, and lanes that set
  BEADS_TEST_REQUIRE_DOLT_CONTAINER=1 fail rather than skip. The sentence now
  covers all three and scopes the two limitations to the containerized path.
  The testcontainers leg says "by default" so it stays true once main's
  BEADS_TEST_DOLT_SERVER=local backend section merges above it, without
  forward-referencing a section this branch does not have.

- Attribute the two failure shapes separately. The fenced banner could not be
  produced by the repro printed beside it: the uow entry points pass
  context.Background(), so context deadline exceeded has no producer there;
  the only 60s in the uow package is bo.MaxElapsedTime, a backoff budget that
  backoff.Retry consults only between attempts and which therefore cannot
  bound a hang inside one. The banner's only producer is store.go's
  "failed to initialize schema: %w" inside newServerMode, the server-mode
  store open, which runs initSchema with the caller's context -- so the doc
  names that path. (Iteration 1 labelled it the embedded-store open, which
  contradicted the section's own statement that the embedded/CLI engine does
  not hang.) Kept the uow "sits until the package timeout" sentence (the
  accurate half), dropped the unverifiable ~60s figure, and dropped the
  "failed to create embedded DoltStore: " prefix, which has zero occurrences
  in the tree, so the quoted line is greppable.

- Make the stray-container check runnable under the flow the section is about.
  A bare docker ps talks to the CLI's default endpoint and returns a false
  all-clear on exactly the leaked-container incident the paragraph cites; it
  now carries DOCKER_HOST=unix:///run/user/$(id -u)/podman/podman.sock, the
  form all six in-repo records of this flow use.

- Close the image-pin duplication without touching the guard, and make the
  read fail loudly. The command read the tag from a hand-copy outside
  test/docsync/doltpin_test.go's reach; it now reads it from
  internal/testutil/testdoltcommon.go, resolved from the repository root with
  git rev-parse --show-toplevel so it works from any directory in the tree.
  An empty read would reproduce the false all-clear (docker ps --filter
  ancestor= exits 0 listing nothing), so the tag is expanded as
  ${dolt_image:?...}, which refuses to run docker without it. A trailing
  "[ -n ... ] || { ...; return 1; }" guard does not do that when pasted at an
  interactive prompt: a top-level return stops neither bash nor zsh, and the
  next line still runs docker with an empty filter. Deliberately NOT added to
  doltpin_test.go's scanned set: doltPinImageRE requires the assignment form
  DoltDockerImage = "..." which cannot appear in prose, and find() t.Fatalf's
  on a miss, so that would red a currently green test.

Validation: git diff --check clean; go test ./test/docsync/ 8 PASS / 0 FAIL /
0 SKIP with TestDoltVersionPinsAgree green; scripts/check-doc-freshness.sh
exit 0; the snippet extracted from the doc passes bash -n and zsh -n, resolves
dolthub/dolt-sql-server:2.2.0 from the repository root and from a
subdirectory in interactive bash and zsh, and outside a repository prints the
error without running docker (checked against a stub docker).

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

---------

Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 20:17:56 -07:00
Jim Wordelman
7d545486e5
fix(init): refuse to silently recreate a missing server-side database as empty (#5791)
* test(init): red — existing project with missing server DB must refuse init

be-5up5: server mode never has a local dolt/ directory, whether this is a
genuine fresh clone or an existing project whose database was lost from the
server — doltDirExists==false alone (GH#2433's signal) can't distinguish
them. Adds TestInitGuard_ExistingProjectMissingServerDB_Refuses, which spins
up a real dolt sql-server with no database and a metadata.json carrying a
non-empty project_id (proof of a prior real init). Currently fails: the
guard returns nil and lets init silently recreate the database as empty,
which is the 2026-08-11 fleet-wide data loss.

RED only — checkExistingBeadsDataAt is not yet fixed.

* fix(init): refuse to recreate a missing server-mode database (be-5up5)

bd init's server-mode "already initialized" check treated a missing or
unreachable database the same as a genuine fresh clone, silently
returning nil and letting init proceed to create an empty database —
even when metadata.json's project_id proved this was an existing
project whose database had gone missing (the 2026-08-11 fleet-wide
data loss).

Guard on cfg.ProjectID != "" to distinguish the two cases. An existing
project now gets a refusal (initGuardMissingServerDBMessage) that
names bd doctor / bd dolt status / bd backup restore as the recovery
path and explicitly does not recommend bd bootstrap, since bootstrap
has its own related mode-blind create bug (tracked separately). A new
--recreate-missing flag is required to opt into creating fresh in this
case — never implied by --force, config, or env. Genuine fresh clones
(empty project_id) are unaffected.

Also:
- doctor/gitignore.go: drop the "bd init (safe to re-run)" fix hint,
  since re-running bd init is exactly the unsafe action this fix
  prevents in the case that matters.
- storage/dolt/errors.go: the general "database not found" hint no
  longer claims bd bootstrap is a safe first step for "an existing
  project" — only for genuine fresh-clone / shared-server-recovery,
  which is what the existing tests actually cover.

* test(init): pin exit_contract's bootstrap-not-recommended requirement (be-5up5)

TestInitGuard_ExistingProjectMissingServerDB_Refuses checked the refusal
and the absence of --force, but not the exit_contract's explicit "does
not recommend bd bootstrap for a server-mode workspace" requirement —
that was only verified by hand during self-review. Pin it directly, and
assert the message names an actual recovery path.

* test(init): cover --recreate-missing positive path (be-ab3b)

be-5up5's guard already correctly permits init to proceed when
--recreate-missing is set; only the negative path (flag absent -> refuse)
had test coverage. Adds TestInitGuard_ExistingProjectMissingServerDB_
RecreateMissingAllows, covering both guard sites the flag gates:
init.go:2566 (server reachable, database confirmed missing) and
init.go:2578 (server unreachable / errored during the check).

refs be-3mvz (review round 1 request-changes), closes be-ab3b

* chore: release gate PASS for bd init missing-server-DB guard fix (be-udx2)

* chore: record full pre-PR contributor check results for be-udx2 gate

* test(init): red — bd init --force recreates a missing server DB as empty

--force is a deprecated alias for --reinit-local (init.go ~395), and the
existing-data guard is gated on !reinitLocal (~763), so --force skips
checkExistingBeadsData — and with it the be-5up5 missing-database refusal
this PR added. The reinit path's own typed confirmation does not cover the
gap either: it keys on countExistingIssues, which returns 0 or an error in
exactly the case where the server-side database is missing, so no prompt
and no destroy token are ever required.

Net effect at this commit, measured against a real dolt sql-server
(2.2.3) holding no "myproject" database, with metadata.json carrying a
project_id:

    $ bd init --force --prefix myproject --skip-hooks
    ...
      Database: myproject
      Issue prefix: myproject
    Run bd quickstart to get started.
    $ echo $?
    0
    $ ls <server data-dir>
    config.yaml  .dolt  .doltcfg  myproject      <-- created, empty

An empty database at the name the real one used to occupy, exit 0, no
prompt. That is the 2026-08-11 fleet-wide data-loss reflex, reached
through the flag an operator in a panic is most likely to reach for.

This test drives the real binary because that is the only way to exercise
the --force -> reinitLocal -> "skip the guard" path end to end; a unit
test on the guard function cannot see that the caller never runs it.
Both subtests fail at this commit.

Reported in review of PR #5791 by bee-ghosttrack, item 1.

* fix(init): green — --reinit-local/--force cannot bypass the missing-DB guard

Add guardMissingServerDatabaseAt, a narrowed form of the be-5up5 refusal
that answers only one question — is this an already-initialized
server-mode project whose configured database is missing or
unconfirmable? — and run it on the reinitLocal path, which
checkExistingBeadsData never reaches.

The distinction the guard encodes: --reinit-local/--force authorize
destroying a database that EXISTS. They do not authorize inventing an
empty one where the configured database has gone missing. Only the
explicit, per-invocation --recreate-missing does that, which is what makes
that flag's "never implied by --force" help text an honest guarantee
rather than an aspiration. The review suggested softening that help text
instead; making the claim true seemed better than documenting that it
isn't.

Deliberately narrow. It returns nil for every state except the missing
database — no metadata, non-Dolt backend, non-server mode, empty
project_id, or a local dolt/ directory all fall through — so it never
resurrects the "already initialized" refusal that --reinit-local is
legitimately meant to bypass. The "stays silent on a fresh clone with no
project_id" subtest pins that boundary.

Same scenario as the previous commit, now:

    $ bd init --force --prefix myproject --skip-hooks
    Error:
    (warn) Database "myproject" not found on server at 127.0.0.1:34813 ...
    bd init will NOT create an empty database here — that would strand any
    existing issue data behind a new, empty database of the same name.
    $ echo $?
    1
    $ ls <server data-dir>
    config.yaml  .dolt  .doltcfg            <-- nothing created

Addresses review of PR #5791 by bee-ghosttrack, item 1.

* test(init): cover the unreachable-server refuse branch

Review of PR #5791, item 2. The PR claimed
TestInitGuard_ExistingProjectMissingServerDB_Refuses covered both guard
sites — server reachable with the database missing, and server unreachable
or errored while checking. It does not: that test starts a live dolt
sql-server, so it only ever exercises the first. The unreachable site had
coverage on the PERMIT side only (the BEADS_DOLT_SERVER_PORT=1 subtest of
_RecreateMissingAllows), which would not notice if its refusal were
dropped.

TestInitGuard_UnreachableServerRefuses closes that: port 1 is unreachable
by construction, so it needs no dolt binary and runs in the fast lane.

Also drops a comment reference to scripts/repro-bd-init-recreates-empty-db.sh,
which is not in the repo or in this diff (item 3, third bullet), and
describes the state the test sets up instead.

Addresses review of PR #5791 by bee-ghosttrack, item 2.

* docs(init-safety): document --recreate-missing and its known limits

Review of PR #5791, item 3 (doc drift), plus the non-blocking note.

The flag's own help pointed users at `bd help init-safety`, whose FLAG
SURFACE section did not list it — so the one place the help sends you was
the one place it was missing. Added there, stating plainly that it is
per-invocation only and never implied by --force/--reinit-local, config,
or env.

docs/recovery/init-safety.md gains an init-missing-server-db section (and
a TOC entry) covering the refusal users will actually hit: why the
fresh-clone and lost-database cases are indistinguishable from the local
filesystem in server mode, why the old "assume fresh clone" answer caused
the 2026-08-11 loss, and the three ways out in the order they should be
tried — diagnose the server first (a stopped server or wrong --data-dir
presents identically and needs no re-init), then restore from an export,
then --recreate-missing as the deliberate last resort.

Both limits the review flagged as non-blocking are recorded there and in
the guard comment rather than left as folklore:

- The guard keys on project_id, minted by GH#2372. A pre-GH#2372 workspace
  carries none and is indistinguishable from a fresh clone, so it FAILS
  OPEN. Accepted deliberately — failing closed would block legitimate
  first inits on every such clone, and this guard's job is to stop a
  silent recreate where prior initialization can be PROVEN, not to guess
  where it cannot.
- Server mode only. Proxied-server mode returns early on a missing root
  and never reaches the guard, and bd bootstrap has its own separate
  mode-blind create path.

Addresses review of PR #5791 by bee-ghosttrack, item 3 and the
non-blocking notes.

* docs(changelog): record the --force missing-database bypass fix

Under Unreleased/Fixed. This is a behavior change to bd init --force on
every server-mode workspace whose database has gone missing, and it was
not recorded anywhere users read.

* fix(init): make the missing-server-database guard fire in shared-server mode

Review round 2, item 1 (blocking): the guard was a no-op in shared-server mode
— the topology of the 2026-08-11 data loss, and so the primary case.

guardMissingServerDatabaseAt statted doltserver.ResolveDoltDir(beadsDir) and
returned early when it was a directory, reading that as "there is local data to
protect". In shared mode ResolveDoltDir returns the machine-global
~/.beads/shared-server/dolt, and SharedDoltDir() MkdirAlls it
(internal/doltserver/doltserver.go:281). The stat therefore always succeeded and
checkDatabaseOnServer was never reached, while every per-project test kept
passing.

Fix per the reviewer's first option: test for THIS project's database directory
rather than the data directory that holds it. A Dolt data dir contains one
subdirectory per database, each with its own .dolt — verified on disk — so
<doltDir>/<dbName>/.dolt is the correct probe in BOTH modes, and it is strictly
more precise in per-project mode too: a data dir that exists but holds no
database for this project no longer counts as local data to protect.

Two new tests, both against a real dolt sql-server rather than an unreachable
port, covering the two cases the reviewer noted were uncovered:

  TestInitGuard_SharedServerMode_MissingServerDB_Refuses
      reachable server, database absent -> must refuse.  This is the actual
      loss shape. Reverting the one-line guard change turns it red with
      "got nil error"; the pre-existing per-project tests stay green, so it
      pins the shared-mode gap specifically.
  TestInitGuard_SharedServerMode_PresentServerDB_Allows
      reachable server, database present -> must NOT refuse, so --reinit-local
      and ordinary reinit keep working. The reviewer verified this by hand and
      flagged it as untested.

Also from the same review:
- docs/recovery/init-safety.md overstated the proxied limit. The proxied path
  does not reach THIS guard (dispatch at init.go:619 precedes the
  initAllowRecreateMissing assignment at :767), but it does reach the older
  checkExistingBeadsData (init_proxied_server.go:89) — and because the flag is
  never assigned there, --recreate-missing is inert under --proxied-server.
  Documented as pre-existing rather than silently fixed.
- Shared-server mode now named explicitly in the same Limits section.
- checkExistingBeedsData typo corrected.
- The "### 3." heading wrapped onto a second line and rendered broken.

Verified: full TestInitGuard suite 15/15 PASS, 0 SKIP (12.1s), including all
pre-existing guard tests. go build ./... clean, gofmt clean, go vet clean.

Refs be-ok1tt, be-udx2.

* test(init): redirect the shared-mode fixtures with BEADS_SHARED_SERVER_DIR

Round-3 MINOR-2, unaddressed through round 4. The two shared-server tests
redirected HOME so SharedDoltDir() would resolve inside the test tree, but
SharedServerPath() reads BEADS_SHARED_SERVER_DIR first and only then falls
back to os.UserHomeDir(). An ambient BEADS_SHARED_SERVER_DIR — the override
that function's own comment advertises for testing — silently won, and the
pair then wrote into and asserted against the developer's real
~/.beads/shared-server/dolt, failing spuriously if a real "myproject" lived
there. HOME is also a no-op on Windows, where os.UserHomeDir() reads
%USERPROFILE%.

Set the variable the resolver actually consults first. No behavior change.

* test(init): make the present-database control pin the early return

Round-3 NIT-4, unaddressed through round 4, and demonstrated there: with the
local-database probe reverted, _SharedServerMode_PresentServerDB_Allows stayed
green, so it pinned nothing of the early return that commit rewrote. It
returned nil via the server check alone, because the fixture never gave this
project a database directory under the shared data dir.

Create that directory, the way a real shared-mode install has one, and then
assert the early return specifically: with the server made unreachable, the
local database directory alone must still satisfy the guard. Removing the
early return now turns this test red.

* test(init): red — the documented --recreate-missing recovery cannot reach its opt-in

Round-3 MAJOR-1 / round-4 finding 1. checkExistingBeadsDataAt derives "is this
project's database here?" from os.Stat(ResolveDoltDir(beadsDir)) — the DATA
directory, which exists on every initialized workspace (shared-server mode
MkdirAlls the machine-global one in SharedDoltDir; per-project mode MkdirAlls
it in ensureDoltInit). So the FR-010 missing-vs-present branch never runs and
both --recreate-missing opt-ins inside it are unreachable.

Four surfaces tell the operator to run `bd init --recreate-missing --prefix
<p>`: the flag help, `bd help init-safety`, docs/recovery/init-safety.md, and
the guard's own refusal text. That command exits 1 with a false "already
initialized" message pointing back at --reinit-local, which is the destructive
path. The documented recovery is a dead end and the only thing that works,
--reinit-local --recreate-missing, is named nowhere.

The existing _Refuses/_RecreateMissingAllows fixtures cannot see this: they
omit the data directory entirely, so their branch condition is true for the
wrong reason. These two add it, which is the state of every real workspace
whose server-side database was dropped.

Both fail at this commit.

* fix(init): green — probe this project's database directory, not the data dir holding it

Round-3 MAJOR-1 / round-4 finding 1. Test for <dolt-data-dir>/<database>/.dolt
instead of the data directory itself, so the FR-010 missing-vs-present branch
is reachable on an initialized workspace and `bd init --recreate-missing`
reaches its own opt-in. This is the same probe, for the same reason, that
guardMissingServerDatabaseAt already uses on the reinit path.

Making that branch reachable also exposes states the data-dir stat used to
shadow, and permitting them would be a new fail-open policy rather than a fix.
The clearest is a workspace that predates GH#2372: it carries no project_id,
so `existingProject` is false, and the branch would permit a silent empty
recreate on exactly the installed base this guard exists to protect. The
data-dir stat therefore stays — it stops being the gate and becomes the permit
condition, admitting only what the old probe already admitted, plus the
explicit per-invocation opt-in. Net behavior change is the opt-in becoming
reachable, and the false "already initialized" message being replaced by the
accurate missing-database refusal where the database is genuinely gone.

Choosing a better proof of prior local init is deliberately NOT done here.
project_id comes from git-tracked .beads/metadata.json, so a fresh clone
inherits one (round-4 finding 2); the replacement signal needs a different
answer in per-project and shared-server mode, and is tracked as its own
architecture decision on be-5pjhd. The known limit is now recorded in the
guard comment and in docs/recovery/init-safety.md rather than left implicit.

Tests: the two red tests from the previous commit now pass, and two more pin
the narrowing — a pre-project_id workspace with a local data dir stays blocked,
and --recreate-missing still opens it.

* docs: record the --recreate-missing fix and the fresh-clone project_id limit

Round-3 NIT-3 / round-4 finding 4: the round-3 probe change (data dir to
<dolt-data-dir>/<database>/.dolt) was never written down, and it is
user-visible wherever the data dir exists but the database is gone. Both that
and this round's --recreate-missing fix are now under [Unreleased] / ### Fixed.
The stray double blank line is gone with the section's move.

Also records, in docs/recovery/init-safety.md's "Limits worth knowing", that
project_id is inherited by a fresh clone because .beads/metadata.json is
git-tracked by default — the round-4 finding-2 gap this series deliberately
does not close. It fails in the safe direction and --recreate-missing is the
supported way through it; the replacement signal is tracked separately.

* docs(adr): ADR-0004 — proof-of-prior-init signal for the missing-database guards

Round-4 finding 2 asked what should replace project_id as the proof that a
workspace was initialized locally, and what the fail-open/fail-closed policy
should be per server mode. It needed a design decision rather than a
mechanical fix, so it was escalated; this records the answer.

The decision is to formalize what the code already does for local hosts and
keep project_id where nothing local can ever help. Presence of this project's
own <dolt-data-dir>/<database>/.dolt is unconditional proof, because the path
is gitignored and only a real local process creates it. Its ABSENCE, however,
cannot be promoted to proof in either direction: it looks identical whether
the workspace was never initialized here or was initialized here and lost its
storage — and the second is the shape of the 2026-08-11 incident. For a
genuinely remote host the probe is not merely silent today, it is structurally
silent forever, since the only code that creates that directory runs on local
server-management paths.

So project_id stays as the tier-2 fallback with its git-inheritance weakness
accepted, and --recreate-missing is the permanent resolution UX rather than a
stopgap. A local-only init marker and repurposing .local_version are recorded
as rejected, with reasons, so neither is re-proposed each review round.

Extends ADR 0002, which set the init safety invariants but left the evidence
question open.

* test(init): red — the reinit guard waves through a pre-project_id workspace

ADR-0004 follow-up 1. guardMissingServerDatabaseAt is the safety net for
--reinit-local and --force, which bypass checkExistingBeadsDataAt entirely. It
returns nil the moment cfg.ProjectID is empty, BEFORE it ever reaches the
per-database .dolt probe eighteen lines below.

checkExistingBeadsDataAt does the opposite: it probes first, and only falls
back to project_id — narrowed by the coarse-directory permit condition — when
that probe comes up empty. So a workspace initialized before GH#2372 minted
project_id, whose local Dolt storage has since been lost, is protected under
plain `bd init` and waved straight through under the two flags an operator
reaches for in a panic. The weaker path is the one behind --force.

Three tests through guardMissingServerDatabaseAt, mirroring the plain-init
trio: no project_id with a local data dir present must refuse; no project_id
with nothing local at all is a genuine fresh clone and must be allowed; and
--recreate-missing must still open the refused case.

The first fails at this commit. The other two pass, and pin the directions the
fix must not break.

* fix(init): green — probe the local database before consulting project_id

ADR-0004 follow-up 1. Move the per-database <dolt-data-dir>/<database>/.dolt
probe above the project_id check in guardMissingServerDatabaseAt, and run it
unconditionally, so this guard reasons in the same order as the plain-init
guard it backstops.

When the probe comes up empty and project_id is also absent, apply the same
coarse-directory permit condition checkExistingBeadsDataAt uses: allow only
when there is no local Dolt data directory either. A data directory with no
database in it still says this workspace has touched local Dolt storage, and
that is exactly the pre-GH#2372 lost-storage case the old early return waved
through under --reinit-local and --force.

One cell of the behavior matrix changes: no project_id, no local database, but
a local data directory present now refuses instead of returning nil.
Everything else is untouched, --recreate-missing still returns nil at the top
of the function, and a workspace with nothing local at all is still treated as
a fresh clone.

The comment records the shared-server asymmetry ADR-0004 accepts — there the
coarse directory is machine-global, so that cell is more conservative — as
settled rather than as an open defect, since it fails toward refuse and its
population only shrinks.

* docs: cite ADR-0004 from the plain-init guard, the recovery doc and CHANGELOG

The comment at checkExistingBeadsDataAt's project_id check said the limit was
"OPEN and tracked by be-5pjhd" and that the replacement signal was
"deliberately not made here". It is made now, so the comment says settled
instead of open, and points at the ADR rather than at a bead — with a note to
read it before reopening, since the two obvious alternatives are recorded
there as rejected rather than unconsidered.

docs/recovery/init-safety.md said the same thing in operator language and is
updated the same way, plus a new bullet stating that the guard now applies
equally to bd init, --reinit-local and --force. That equality is the
user-visible half of the fix and was not previously stated anywhere.

Its "Last reviewed" marker moves to today. The doc is freshness-tracked
against cmd/bd/init.go, which this series changes, and leaving the marker at
2026-09-08 would claim text written today had been reviewed eight days before
it existed.

* chore: remove leaked internal release-gate doc from PR branch

  release-gates/be-udx2-init-missing-db-guard-gate.md

Tracked our internal gc-management/beads-rig release-gate checklist and
should never have been committed to this upstream branch -- it's process
residue from our deploy tooling, not part of the change itself.

Per maintainer bee-ghosttrack's request during review of PR #6571. The
root cause (our deploy tooling auto-committing this file) is already fixed
as of gm-qatxl1; this branch predates that fix, so this commit is cleanup
only -- no other content on this branch is touched.

Ref: be-lk7o3

* chore(bazel): enumerate init_guard_force_e2e_test.go in cmd/bd srcs

The PR adds cmd/bd/init_guard_force_e2e_test.go under a plain '//go:build cgo'
tag, which is the tag class cmd/bd/BUILD.bazel enumerates (the 23 unenumerated
test files in this package are all 'cgo && integration', 'scripttests' or
'chaos'). cmd/bd/BUILD.bazel is base-added, so the contributor's branch could
not have carried this row. Generated by 'make bazel-sync'; no hand edits.

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

* fix(init): honor --recreate-missing on the proxied route; scope the refusal's evidence claim

Maintainer review fixes for PR #5791 (iteration 1). Five review minors; the
three substantive ones:

1. --recreate-missing was inert under --proxied-server. runInit dispatches to
   runInitProxiedServer and returns before the assignment site, while
   runInitProxiedServer calls checkExistingBeadsData, which reads the global —
   so converting a server-mode workspace with a missing database to proxied
   mode was refused despite the explicit opt-in, and the refusal named the
   exact flag the operator had just passed. It failed closed, so there was no
   data hazard, only a recovery dead-end. The assignment now sits beside its
   flag read, upstream of every dispatch in runInit.

   The PR's recovery runbook documented this inertness as "pre-existing
   behaviour, not introduced here". The early dispatch is pre-existing, but
   --recreate-missing is introduced by this PR, so the flag could not have had
   pre-existing inertness. That paragraph is rewritten to the new behaviour.

2. initGuardMissingServerDBMessage asserted "metadata.json has a project_id"
   unconditionally, but the --reinit-local/--force guard also emits it for a
   workspace predating GH#2372 where only local Dolt storage proves prior use —
   the population the CHANGELOG bullet names. The evidence sentence is now
   selected by the caller, so the message never cites an artifact its caller
   does not have. Pinned from both sides: the project_id cell must cite that
   evidence, the no-project_id cell must not.

3. The new doc comment claimed initGuardServerMessage is "used when there is no
   evidence either way". It has no production caller, so the contrast was
   asserted as two live code paths. Reworded to intent. The dead message's
   surviving "existing project -> bd bootstrap" sentence is pre-existing, is
   pinned by four tests, and is left for a follow-up.

Also re-cited two stale path:line references by symbol and branch (the recovery
runbook's three, and a test comment's two), and expanded the else-branch comment
in checkExistingBeadsDataAt to cover the reachable-but-missing fall-through that
lands there — the branch's guards are correct for both cases only because their
conditions do not mention reachability.

Declined, with reasons, as out of scope for opportunistic cleanup: restructuring
the fall-through itself (a control-flow change in the diff's most complex
function, which both review lanes agree is behaviourally correct today);
rewording the caller-less message's bootstrap sentence (four pinned tests,
pre-existing); and adding --recreate-missing to the generated CLI reference
(the required check-doc-flags job passes at this head and seven other registered
initCmd flags are equally absent, so that page is not a flag enumeration).

Validation: go build ./... and go vet ./cmd/bd/ clean; gofmt clean;
go test ./cmd/bd/ -run 'TestInitGuard|TestCheckExistingBeadsData' ok (26 tests,
real Dolt servers); scripts/check-doc-freshness.sh PASSED; git diff --check
clean. The evidence pin was proved non-vacuous by mutation: forcing the reinit
call site back to an unconditional project_id claim reddens exactly the
no-project_id test and nothing else.

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

* fix(doctor): drop the bd init hint from #5634's permissions warning

1d7629213b on this branch removed "bd init (safe to re-run)" from the
.beads/.gitignore fix hints, because re-running bd init is the unsafe
action be-5up5 guards against. #5634 (c33738d209) reached main while
this PR was open. It added a CheckGitignore warning for unexpected file
permissions that still carries the old hint, so after the merge it was
the only gitignore check that suggested bd init.

Give it the same "Run: bd doctor --fix" hint as the four other
gitignore warnings. That is a complete repair here: FixGitignore
restores mode 0600, and #5634's test already checks that the warning
clears after it runs.

TestCheckGitignore_WarnsOnLoosePermsWhenPatternComplete only checked
that Fix was non-empty. It now pins the exact hint. With the old
gitignore.go line put back, the test fails.

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(init): name the real gitignore template in ADR-0004 and init.go

ADR-0004 and the matching comment in init.go both cite
`defaultGitignoreContent` in cmd/bd/doctor/gitignore.go as the place
that says .beads/metadata.json is git-tracked by default. No symbol by
that name exists, in this branch or in main's history. The constant
that says it is GitignoreTemplate. Its closing lines read "Config files
(metadata.json, config.yaml) are tracked by git by default since no
pattern above ignores them".

Rename the reference in both places. The claim itself is unchanged.
Neither file changes outside that one identifier.

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: Gas City Adopt-PR <adopt-pr@gascity.local>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-30 20:07:49 -07:00
Julian Knutsen
a3b6dc9ac5
ci(bazel): remote-execution Bazel lanes for allowlisted fork authors (advisory) (#6994)
* ci(bazel): remote Bazel lanes for allowlisted fork authors (advisory)

Add bazel-farm.yml, a pull_request_target caller of bazel.yml. It gives the
RBE farm to fork PRs to main whose author and triggering user (sender: the
pusher on synchronize) are both on .github/bazel-farm-allowlist.txt, which
is read from the base commit. The list has julianknutsen, quad341, sjarmak
and csells, the same as gascity's blacksmith allowlist.

- authorize job: sparse checkout of github.sha that holds only the
  allowlist and .github/scripts/bazel-farm-authorize.sh; no token on disk,
  no secrets, event facts through env only. The script also checks fork vs
  base repo, the default branch, the action, and a 40-hex head SHA.
- farm job: calls bazel.yml with contents: read, exactly the four RBE
  secrets, checkout-sha pinned to the event's head SHA, and
  fork-farm: authorized.
- bazel.yml: new checkout-sha and fork-farm inputs (no-ops for pr.yml and
  nightly.yml). Every lane checks out inputs.checkout-sha with
  persist-credentials: false. The rbe job runs a fork remotely only for an
  authorized pull_request_target call, and then remote or skip, never
  local. PR concurrency also cancels on pull_request_target. The
  bazel-sync-patch upload is skipped on pull_request_target.

Advisory only: pr.yml is unchanged, so every fork PR still runs the local
Bazel lanes inside the enforced CI Gate / Required.

Policy tests pin the trigger and types, both jobs' conditions, the
allowlist source and contents, the pinned checkout, read-only permissions,
where secrets appear, no expressions in run scripts, per-PR concurrency,
the timeout, and that no workflow_run consumer can pick up a farm run.
TestBazelLaneIsGatedAlongsideLegacy now allows pull_request_target on a
bazel.yml caller for bazel-farm.yml only. 26 mutations were each caught
by these tests (sender check dropped, allowlist read from the PR head,
write permission added, event data interpolated into run, SHA pin dropped,
and others).

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

* docs(ci): trusted-author fork PR farm design and threat model

Document bazel-farm.yml in the required-check topology:
- the design, and why it is advisory rather than part of the enforced
  gate;
- the gate options considered;
- the threat model: allowlist spoofing, sender vs. author, TOCTOU with the
  pinned SHA, workflow-file edits, script, label and comment injection,
  token scope, artifact poisoning, and farm and Actions cache poisoning;
- what can only be verified on GitHub.

The one capability a listed author gets beyond a same-repo PR is called
out as an accepted risk, with mitigations: pull_request_target runs use
the default branch's Actions cache scope.

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

* fix(ci): opt the farm's lane checkouts into fork-head checkout (F1)

actions/checkout@3d3c42e5 is v7.0.1, not v6, and v7 refuses to check out
a fork PR's head SHA on pull_request_target unless
allow-unsafe-pr-checkout is true. Every lane of an authorized farm run
therefore failed at checkout.

- Each bazel.yml lane checkout now sets allow-unsafe-pr-checkout to
  inputs.fork-farm == 'authorized' && github.event_name ==
  'pull_request_target'. That is false for every other caller and event.
- TestBazelWorkflowForkFarmInputs pins that exact expression. It also
  fails if the key appears anywhere else in the workflows (so never a
  literal true, and never on the authorize checkout).
- Relabel the checkout pin as # v7.0.1 in bazel.yml and bazel-farm.yml.
- Add the opt-in to the engdoc's design section and to the
  verify-on-GitHub list.

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

* fix(ci): verify everything restored from caches in Bazel lanes (F3)

A farm run executes PR code in the default branch's cache scope. GitHub's
own cache is read-only for pull_request_target: GitHub issues a read-only
token, and cache-mode defaults to read. Whether Blacksmith's colocated
cache enforces the same is unverified. So trusted runs no longer execute
anything they restore without verifying it first:

- setup-bazel: Bazelisk's home moves out of the runner cache to a fresh
  $RUNNER_TEMP/bazelisk-home, so the Bazel binary is never restored from
  a cache. BAZELISK_VERIFY_SHA256 is set to the release sha256 pinned for
  the .bazelversion version on each arch (9.2.0 amd64 and arm64). The
  wrapper step then re-checks every Bazel binary in that home.
- write-bazelrc.sh: add common --repo_contents_cache=. The repo contents
  cache holds extracted repos that Bazel never re-verifies. The
  content-addressable repository cache stays, since Bazel re-hashes it on
  every hit.
- Runner cache key bumped to bazel-repo-v3 (the content changed).
- bazel-test runs `go mod verify` right after the Go module cache restore.
- Policy tests:
  - cache-mode may only be read or none in bazel-farm.yml, bazel.yml and
    setup-bazel;
  - bazel.yml permissions are exactly contents: read;
  - the Bazel sha pin matches .bazelversion, and Bazelisk's home is
    outside the cache;
  - the binary is verified after download;
  - go mod verify follows every module cache restore;
  - the rc disables the repo contents cache.
- Engdoc and bazel-farm.yml header: corrected about GitHub's read-only
  cache, noted Blacksmith as unknown, and listed the full blast radius
  (release.yml hardening tracked separately). The canary design is in the
  rollout notes.

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

* fix(ci): farm runs only the author's own fork, on opened/synchronize (F4)

"The sender is listed" did not prove that a listed user chose the head
commit:
- A listed author could open a PR whose head is a third party's fork, and
  that fork's owner could push between the author's review and "Create".
- A collaborator on a listed author's fork could push while the PR was
  closed or a draft (that push is skipped), and the author's later
  "Reopen" or "Ready for review" click would run it with secrets.

Changes:
- The authorize script requires the head repository owner's numeric id to
  equal the PR author's (HEAD_OWNER_ID, PR_AUTHOR_ID, passed via env).
- Drop the reopened and ready_for_review triggers, and the script now
  refuses those actions too. Drafts already run on opened and
  synchronize.
- Tests pin the trigger types and the new env, and add script cases:
  - cross-fork head, missing or non-numeric owner id;
  - reopened and ready_for_review refused;
  - unanchored action (xopenedx);
  - base-repo prefix (gastownhall/beads-evil). This covers two mutations
    the reviewer found surviving.
- Engdoc: the new checks, and the residual that stays the listed author's
  responsibility (commits pushed by fork collaborators).

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

* fix(ci): match the farm allowlist on numeric user ids (F5)

Logins are mutable: after a rename, anyone can register the old login,
and before this change they would then be listed as both author and
sender.

- The allowlist now holds one numeric user id per line, with the login as
  a comment. The ids were looked up with gh api users/<login> --jq .id.
- The authorize script matches PR_AUTHOR_ID and SENDER_ID
  (github.event.pull_request.user.id, github.event.sender.id). Logins are
  now used only in the log. An allowlist entry that is not a numeric id
  fails the job.
- Tests pin the id-to-login table and the SENDER_ID env. Script cases:
  - a renamed login re-registered with a new id (author and sender);
  - id prefix, suffix and leading zero;
  - an id that appears only in a comment;
  - listed ids with unlisted logins;
  - a PR from another listed user's fork;
  - broken allowlists (a login entry, a signed id).

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

* docs(ci): farm re-run semantics and the add/remove-user procedure (F6)

A re-run replays the original event. It checks out the same pinned head
SHA, which is fine. It also reads the allowlist at the original base
commit, so a user removed from the list still gets the RBE secrets when
one of their old runs is re-run. Only users with write access can
re-run.

- Engdoc: how to add a user.
- Engdoc: how to remove a user. Merge the removal, then cancel and delete
  their farm runs (a gh api query by head-repository owner id). For
  cause, rotate RBE_TLS_CERT/KEY and have the farm revoke the old
  certificate; rotating also closes the re-run window.
- bazel-farm.yml header: points to the procedure.

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

* fix(ci): name the farm call "Bazel Farm", not "Bazel" (F7)

The farm's check runs were named "Bazel / <lane>", the same as pr.yml's.
Farm results are PR-controlled: PR code runs setup-bazel and can make a
lane exit 0. If a ruleset ever required a "Bazel / ..." check, a farm run
could satisfy it. The farm's checks are now "Bazel Farm / <lane>", and a
test pins the name and requires it to differ from pr.yml's bazel job.

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

* fix(ci): run the farm authorize script in the C locale (F8)

Bash bracket ranges and ${v,,} depend on the locale. In en_US.UTF-8,
[0-9], [0-9a-f] and [A-Za-z] match some non-ASCII characters, and the
Kelvin sign lowercases to "k". This is not exploitable (GitHub ids,
logins and SHAs are ASCII, and the allowlist is maintainer-controlled),
but the script now exports LC_ALL=C.

The script tests now run under en_US.UTF-8 and add cases with non-ASCII
digits in ids and a non-ASCII character in the SHA. Without the export,
the SHA case fails, so the tests catch its removal.

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

* fix(ci): farm authorize script runs on bash 3.2 (macOS)

${v,,} is bash >= 4; macOS runners' /bin/bash is 3.2, so the script's
tests failed there. Lowercase with tr under LC_ALL=C (ASCII only, as before).

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

---------

Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-30 14:54:06 -07:00
Julian Knutsen
e1b2e79484
ci: gate PRs on the Bazel lanes, alongside the legacy jobs (D1) (#6941)
* ci(bazel): gate the Bazel lane alongside the legacy jobs (D1)

pr.yml now calls bazel.yml (workflow_call) as its `bazel` job, and its
CI Gate / Required requires the call's aggregate (BAZEL) plus each gated
lane's result (BAZEL_TEST, BAZEL_PURE, BAZEL_EMBEDDED, BAZEL_DOLTSERVER).
No legacy job is removed: PR Core, build-artifacts, the pure-Go/js-wasm
check, domain+uow, contract corpus and pr-risk.yml's embedded tier stay
required (D2 is separate).

- bazel.yml drops its own pull_request/merge_group triggers, so a PR runs
  the lane once; push to main, workflow_dispatch and workflow_call stay.
- Every lane records job.status in an always() last step and exports it
  as a workflow_call output named after the job, next to the rbe job's
  rbe-mode / rbe-enabled.
- .github/scripts/bazel-gate.sh reads the call's rbe-mode/rbe-enabled and
  never re-derives the variable/fork/secret condition: mode skip allows
  every Bazel id to skip, local only the remote-only BAZEL_EMBEDDED,
  remote none; a missing or inconsistent mode fails the gate.
- bazel-integration runs in the PR call but stays advisory (its legacy
  counterparts in main.yml run only on push to main): no gate id, and the
  gate script excuses the aggregate failure only when that lane reported
  failure or cancelled in remote mode; the gated lanes are still checked
  on their own ids.
- Callers (pr.yml, nightly.yml) pass exactly the four RBE secrets that
  bazel.yml now declares, never `secrets: inherit`.
- Inside pr.yml's run the Bazel bd artifact is bazel-ci-build-artifacts,
  so it cannot collide with build-artifacts' ci-build-artifacts upload.
- bazel-autofix.yml now triggers on workflow "PR": the bazel-sync-patch
  artifact is uploaded inside the PR run, and "Bazel" runs are no longer
  PR events. Its security model is unchanged (base-branch checkout only,
  artifact read from the triggering run id, data-only patch).
- Policy tests (review D1 F3/F4/F7):
  - TestBazelLaneIsGatedAlongsideLegacy: every bazel.yml job is the rbe
    job, a gated lane (bazelLaneGateIDs) or an advisory lane with a
    reason; gate ids, env expressions and outputs are derived from that
    map; no re-derivation in the gate step or script.
  - TestBazelGateSimulation runs pr.yml's actual gate step over mode in
    {remote, local, skip} (pull_request and merge_group): the script's
    skips equal the ids whose job `if:` is false, and for each lane that
    should run, it alone skipped, failed or cancelled turns the gate red
    whatever the aggregate says; advisory, aggregate and invalid-mode
    cases too.
  - TestBazelArtifactNamesUniqueInCallerRuns: no artifact name collides
    within a pr.yml or nightly.yml run, following local workflow calls.
  - Autofix: workflow_run on "PR", which must upload bazel-sync-patch
    itself or through an unconditional local call.

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

* ci(bazel): keep integration out of the PR call; pin the call's inputs (D1 review v2)

- N1: bazel.yml gains a string workflow_call input `integration`
  (default "on"); bazel-integration runs only when remote and
  `inputs.integration != 'off'`. A string, not a boolean: on push and
  dispatch the input is null, and null == false would silently stop the
  lane on main. pr.yml passes integration: "off" (main.yml's integration
  jobs, its legacy counterpart, run only on push to main). The gate no
  longer reads bazel-integration and bazel-gate.sh no longer excuses an
  aggregate failure: BAZEL is the call's result, red on a missing or
  inconsistent rbe mode.
- N3: pr.yml's call passes exactly build-artifact-name and
  integration: "off" (no rbe or other override).
- N4: bazel.yml's concurrency group never uses github.workflow (the
  caller's name in a call) and differs from each caller's group for every
  event, so the call cannot deadlock against pr.yml.
- N5: no caller of bazel.yml (pr.yml, nightly.yml) may have a
  pull_request_target or workflow_run trigger.
- Simulation: lanes' run modes are evaluated with pr.yml's call inputs;
  advisory lanes must not run in the PR call, gated lanes must run when
  remote.
- engdocs: runbook for main BUILD drift, a farm outage or the RBE cert
  expiry (~2027-09-27): fix main / renew, or unset RBE_WEST_WORKERS.

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

* docs(ci): record the enforced required-gates ruleset and PR Risk's renamed gate

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

* ci(bazel): gate the proxied-server and server-Dolt storage lanes

bazel-proxied and bazel-server-storage (remote-only, #6940) join the
gated lanes like bazel-embedded: pr.yml's ci-gate requires
BAZEL_PROXIED and BAZEL_SERVER_STORAGE, each read from the lane's
job.status output (always() recorder step, workflow_call output named
after the job). Both run in pr.yml's call (no integration switch).

bazel-gate.sh allows them to skip in mode local (forks, Dependabot:
pr-risk.yml's legacy tiers cover those PRs) and in mode skip, never in
mode remote. The gate simulation derives this from the jobs' ifs, so
each lane skipped, failed or cancelled in remote mode turns the gate
red. Jobs are renamed "proxied-server tier" / "server-Dolt storage tier"
(shown as "Bazel / ..." under pr.yml's call).

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

---------

Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-29 03:33:20 -07:00
Julian Knutsen
e7138e93af
ci(bazel): server-Dolt storage and proxied tiers on remote execution (#6940)
* test(integration): let SubprocessRunner reuse a prebuilt test binary

BEADS_TEST_SUBPROCESS_BINARY hands SubprocessRunner an already-built test
binary of the package instead of running `go test -c`, which no Bazel
action can do offline (it needs the module source tree and module cache).
A Bazel target passes the running go_test itself: the helper tests
(TestHelperSchemaInit, TestHelperMultiStore) live in the same package.
Unset, behavior is unchanged.

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

* test(dolt): keep a lane's REQUIRE switch out of the leak-probe child

TestSuiteFixtureLeakFailsOwningSuite re-runs the suite with
BEADS_TEST_SKIP=dolt on purpose. When the parent runs under
BEADS_TEST_REQUIRE_DOLT_CONTAINER=1 (a fail-closed server lane), the child
inherited it and TestMain exited FATAL before the leak sweep the test
checks. Clear it in the child like the other suite-scoped variables.

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

* feat(bazel): proxied-server and server-Dolt storage tiers (D6d, D6e)

PR Risk's "Test (Proxied Dolt Cmd N/15)" (also main.yml's) and "Test
(Server Dolt Conformance)" / "Test (Server Dolt Full Suite N/16)" as
Bazel variants against local dolt sql-servers (internal/testutil local
backend, pinned dolt from the test wrapper), fail-closed like the
dolt-server lane:

- //cmd/bd:bd_proxied_test: 15 shards; shard k runs the job's
  proxied-test-shard.sh k+1 15 through go_test_manifest_shard.sh over the
  race bd_test, non-race bd_for_tests as the subprocess bd,
  BEADS_TEST_PROXIED_SERVER=1, GOMAXPROCS=4. Tag dolt-server-proxied,
  --config=doltserver-proxied (the doltserver lane's build).
- //internal/storage/dolt:dolt_server_{conformance,full}_test over
  dolt_race_off (go_test_race_off of dolt_test: the jobs' binary is not
  race); the full suite runs server-storage-test-shard.sh k+1 16 with
  BEADS_TEST_ENV_RUN_DOLT=1 and hands SubprocessRunner its own binary.
  Tag dolt-server-integration, --config=doltserver-integration, whose
  build flags are exactly --config=integration's, so the tier shares that
  lane's compile (race-off deps land where bd_for_tests already is)
  instead of compiling the tagged graph a third time.
- dolt_test gains //internal/storage/schema:migrations as data (the
  PR4107/migration replay tests read ../schema/migrations).
- test_env.sh: BEADS_TEST_GIT_IDENTITY=1 writes the jobs' global git
  identity ("Configure Git"); the git-remote tests commit in fresh repos.
- Both tags join the taxonomy and bazelPRCoreExcludedTags, so prcore/ci
  and integration exclude them.

Per-shard names and statuses equal a replay of the jobs' commands
(container backend) for all 32 jobs.

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

* ci(bazel): run the proxied and server storage tiers remotely (advisory)

bazel-doltserver gains a second, remote-only step, `bazel test //...
--config=doltserver-proxied` (15 shards of ~5-10 min with a busy dolt
sql-server each do not fit a GitHub-hosted runner; forks and rbe=off keep
the local lane unchanged). bazel-integration gains `bazel test //...
--config=doltserver-integration`, which shares its build flags, so the
server storage tier compiles nothing the integration step has not. Both
steps write their own BEP, run check_testcases.py on it, run even when the
job's first test step failed, and upload logs on failure.

Policy (TestBazelDoltServerTiersMirrorPRRisk): each variant runs its jobs'
shard script with their shard total and has script + manifest in data;
the conformance variant passes the job's flags; the jobs' race/non-race
binaries and switches (BEADS_TEST_PROXIED_SERVER, BEADS_TEST_ENV_RUN_DOLT)
match; doltserver-integration's tags and race equal --config=integration's;
the steps are pinned to their jobs. checkDoltServerRules now holds all
three dolt-server lane tags to the local-backend, fail-closed,
remote-capable rules.

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

* ci(bazel): run the proxied and server storage tiers in jobs of their own

Review of D6d/e: as steps of bazel-doltserver and bazel-integration the
tiers inherited those jobs' gating (a caller switching the integration
lane off would drop PR Risk's PR-time server tier; a gate requiring the
dolt-server lane would silently require the proxied tier too) and
lengthened their critical paths.

bazel-proxied (--config=doltserver-proxied, 15 shards) and
bazel-server-storage (--config=doltserver-integration: conformance + 16
shards) are remote-only jobs that need only rbe, each with its own BEP,
check_testcases.py step and log upload, 25-minute test step inside a
30-minute job. bazel-doltserver and bazel-integration are back to their
previous content, including the dolt-server step's 80-minute timeout for
local runs. The server tier shares bazel-integration's compiles through
the remote cache (same build flags).

The proxied tier mirrors PR Risk's race bd-cmd-test; main.yml's twin
job runs build-artifacts' non-race one, so Bazel is the stricter of the
two. Comments now say so, and the policy test pins main.yml's build so a
change there is noticed. Policy: the new jobs are pinned (command,
config, remote-only if, BEP + testcase steps, timeouts, log upload), and
no tier step may run in bazel-integration or bazel-doltserver.

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

---------

Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-28 23:01:40 -07:00