Commit graph

27 commits

Author SHA1 Message Date
Julian Knutsen
90b84ea150
ci: auto-push Bazel BUILD sync fixes to PRs; harden docs autofix (#6907)
* ci(bazel): auto-push `make bazel-sync` fixes to PR branches

bazel.yml's BUILD sync step now writes the BUILD.bazel / MODULE.bazel /
MODULE.bazel.lock part of its drift as the bazel-sync-patch artifact
(scripts/ci/bazel-sync-patch.sh) and still fails. The new bazel-autofix.yml
workflow_run job (on "Bazel" and "PR") applies it with
scripts/bazel-autofix-push.sh: a sync commit on same-repo PR branches, an
idempotent apply-recipe comment on fork PRs.

Same security model as docs-autofix: the write-permission side never checks
out or runs PR code, extracts only the two expected regular files, and
refuses any patch naming a path outside an anchored allowlist (no hidden or
`..` segments, nothing under third_party/) or carrying a mode change,
symlink, rename or binary hunk; `git apply --index` and a post-apply check
back that up. Reuses the DOCS_AUTOFIX_TOKEN secret for the push.

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

* build(bazel): add bazel_autofix_push_test.go to scripts_test

`make bazel-sync` output, produced by scripts/ci/bazel-sync-patch.sh and
applied with scripts/bazel-autofix-push.sh as an end-to-end exercise of the
new autofix path.

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

* fix(ci): harden the bazel and docs autofix push scripts

Addresses the security review of the autofix pipeline, identically in
scripts/bazel-autofix-push.sh and scripts/docs-autofix-push.sh (the
security-critical functions are now shared verbatim):

- validate_patch refuses ANY "rename "/"copy " header (the legacy
  "rename old/new" form slipped past and, on docs-autofix, pushed a
  scripts.sh -> docs/cli-reference/x.md rename), checks every "index "
  line whatever its ids, takes creations/deletions/renames from
  `git apply --summary`, and reads names from `--numstat -z` (which
  names only the NEW path of a rename; the old comment was wrong).
- docs-autofix gains the post-apply staged re-check and a --check mode.
- The patch is applied to an index in a bare clone (read-tree +
  apply --cached + commit-tree): the PR tree never touches the disk.
  All git calls run with core.hooksPath=/dev/null, GIT_LFS_SKIP_SMUDGE=1.
- Push is leased: --force-with-lease=refs/heads/$HEAD_BRANCH:$HEAD_SHA.
- The PR must target this repo, and the head branch must be neither
  protected nor under a ruleset per the GitHub API (fail closed), on top
  of the name list.
- Only a marker comment written by github-actions[bot] is ever edited.
- bazel-autofix only pushes files in packages the PR changed
  (merge-base..head, computed from fetched refs), MODULE files only when
  go.mod/go.sum/MODULE changed; base-branch drift is left alone and
  listed, and a patch with nothing attributable gets a comment only.

Tests cover each reviewer attack for both scripts (--check and the full
flow against a local bare remote and fake gh), the staged check alone
with the validator disabled, spoofed comments, protection/ruleset/API
errors, the lease, main drift, and symlinked PR trees.

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

* fix(ci): trigger bazel-autofix on Bazel only; share job-level concurrency

- bazel-autofix.yml triggers only on "Bazel": pr.yml never calls
  bazel.yml, so "PR" runs never carry the artifact, and their completions
  cancelled real fixes through the workflow-level group. The policy test
  now requires the triggering workflow to run on pull_request and upload
  the consumed artifact instead of asserting the false claim.
- Both autofix workflows use one job-level concurrency group per head
  branch (autofix-<head repo>-<head branch>) without cancel-in-progress:
  skipped runs take no part, and the two bots queue instead of racing.
- Base checkouts use persist-credentials: false; docs-autofix extracts
  only cli-docs-freshness.patch, as a regular file, outside the workspace.
- Policy tests for the trigger, concurrency scope, checkout, and the
  scripts' shared guards (rename/index checks, comment author, lease,
  protection lookup, index-only apply, hook-free git).

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

* fix(ci): tighten autofix attribution, circuit breaker and PR selection

Re-review follow-ups for the bazel and docs autofix push scripts:

- Root package: paths outside any Bazel package (docs/, .github/,
  README.md, ...) no longer count as changing //:. Only root-level Go and
  build inputs (*.go, *.s, *.c, *.h, *.bzl, go.mod, go.sum, BUILD.bazel,
  MODULE.bazel*) make root BUILD.bazel drift the PR's, so main's root
  drift is not pushed onto a docs-only PR.
- Circuit breaker: the head subject is read from the fetched commit (no
  API), a failed read counts as non-convergent, and the check runs only
  once the PR's own staged fix is non-empty. A bot head whose remaining
  drift is main's now gets the "files this PR did not change" comment
  instead of a wrong "did not converge" one. Same in docs-autofix.
- PR selection: several open PRs can share one head branch. bazel picks
  the one whose number matches the artifact metadata (among PRs already
  matching head repo/branch/base repo; head sha still verified); without
  a unique match both scripts skip instead of taking .[0].
- The privileged clone fetches only the head (and, for bazel, base)
  branch into an init'ed bare partial repo instead of cloning every
  branch.
- docs-autofix job gets timeout-minutes: 10 (it shares a non-cancelling
  concurrency group with bazel-autofix).

Tests: docs-only/README/workflow/Makefile PRs with root drift get no push,
a root Go change gets root BUILD.bazel; breaker cases (bot head with own
vs main drift, unreadable subject) for both scripts; PR selection by
metadata and ambiguity; HEAD_SHA 40-hex guard; staged-check mode arm; a
--summary-only validator copy; both workflows' download steps run as
written against a fake gh (run-scoped artifact listing, only the named
files extracted, symlinked entries refused); timeout asserted for both
jobs.

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

* fix(ci): bazel-autofix requires bash 4; skip its tests on macOS bash 3.2

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

* test(ci): skip every autofix script test on bash < 4

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

* build(bazel): sync internal/utils BUILD with main

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 17:23:27 -07:00
Bùi Phan Viết Cường
5cc896c8f0
fix(lint): suppress two darwin-only gosec findings and cross-lint the darwin build in CI (#6243)
* fix(lint): suppress two darwin-only gosec findings and cross-lint the darwin build in CI

scripts/ci/pr-lint.sh lints natively on the ubuntu runner plus one
GOOS=windows CGO_ENABLED=0 cross-lint, so files behind //go:build darwin
(and the !windows && !linux fallbacks) were never linted in CI. Linting the
darwin build reports two gosec findings that are clean on linux:

- internal/config/permissions_open_nonlinux.go: G304 on os.Open(path). The
  file comment already explains why it is safe (fixBeadsDirPermissions
  re-checks descriptor identity before chmod); it just had no directive.
- internal/utils/path_case_darwin.go: G103 on unsafe.Pointer. A directive
  existed but sat on the first line of a multi-line unix.Syscall call,
  while gosec reports the argument line four lines down, so it never
  covered the finding. It now sits on its own line above the statement,
  the placement cmd/bd/nocow_linux.go already uses.

Add a GOOS=darwin GOARCH=arm64 CGO_ENABLED=0 cross-lint block to
pr-lint.sh mirroring the windows block (same flags, same lane scoping,
skipped when the native target already matches), and update the three
places that described the wrapper as two passes: engdocs/LINTING.md,
engdocs/CI_CLEANUP_PLAN.md and the comment in main.yml.

The darwin pass is compile-only on the Linux runner: no macOS runner, no
change to the pr-lint platform column. Like the windows pass it is
CGO_ENABLED=0, so darwin+cgo code stays outside its reach.

* docs(linting): bump the Last reviewed marker alongside the pr-lint change
2026-09-28 15:44:52 -07:00
ecuthiell
4dc96f6f21
fix(config): identify native config environment in path errors (#6325)
* fix(config): name the native config environment source in errors

Identify APPDATA on Windows, HOME on Darwin/iOS, home on Plan9, and the
selected XDG_CONFIG_HOME or HOME source on other Unix hosts. Only error
labels change; the standard-library resolver and path precedence remain
the same, and the original wrapped error is retained.

Fixes #6314
Reported-by: bee-ghosttrack
Bead: saa-cgh.95
Agent-Signature: unknown-model/unknown-reasoning

* test(config): exercise native source diagnostics on the required platforms

Select the diagnostic parent and its two XDG states through one Bash3.2
driver in the existing three-host preflight matrix. Bind the declared OS
to Bash and the setup-selected Go host/target, retain child process status,
and reject missing, duplicate, unexpected, failed or skipped execution.

Preserve existing platform steps, job identity and required gate mapping.
Use the existing YAML workflow helpers to pin the new placement.

Follow-up: https://github.com/gastownhall/beads/issues/6314
Bead: saa-cgh.95
Agent-Signature: unknown-model/unknown-reasoning

* fix(config): keep native diagnostics with candidate builder (saa-cgh.95)

Agent-Signature: unknown-model/unknown-reasoning on behalf of Ewen Cuthiell
2026-09-28 12:17:20 -07:00
Julian Knutsen
fc4d7d3958
ci(bazel): PR-gate parity lanes (docker, pure-Go, js/wasm) + bd artifact (#6887)
* test(bazel): require exclude read-permission coverage in test:prcore

pr.yml's PR Core step sets BEADS_TEST_REQUIRE_EXCLUDE_PERMISSION=1 so
TestAddExcludePatternsRefusesReadErrors fails, rather than skips, on a root
or non-POSIX executor. test:prcore now sets it too, and a policy test keeps
the two in step.

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

* feat(bazel): compare Bazel runs with one CI job's go test results

equivalence.py --job takes a job's `go test -json` as the complete expected
set, so a Bazel selection can be shown to replace that job: every top-level
test the job ran must run under Bazel, no other test in those packages may,
and nothing the job passed may be skipped. --bep is repeatable (a job can map
to --config=ci plus --config=docker), and go_test_variant.sh sh_tests count,
since their go_test binary writes the same test.xml. In job mode a test seen
in several targets keeps its best status: the prcore run skips what the
docker variant exists to run.

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

* test(bazel): docker-lane variant for internal/tracker

pr.yml's "Test (storage domain + uow)" job runs ./internal/tracker/... with
-race and without -short or BEADS_TEST_SKIP=dolt, so tracker's TestMain
starts the shared dolt container and all 112 top-level tests run. Under
--config=prcore they skip. tracker_docker_test reruns tracker_test that way
in the docker lane, and tracker's TestMain now fails instead of skipping when
BEADS_TEST_REQUIRE_DOLT_CONTAINER=1 and the container does not start.

The job's other packages (storage/domain, domain/fs, domain/git,
tracker/conformance) consult neither testing.Short nor the dolt skip, and
pass identically under --config=ci.

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

* ci(bazel): publish the Bazel-built bd as a ci-build-artifacts artifact

pr.yml's build-artifacts job uploads ci-build-artifacts (bd-linux-gms-pure,
SHA256SUMS, build-manifest.txt), which PR Core, the domain+uow job and both
package gates download and check with `sha256sum -c`. The Bazel lane now
uploads the same name and layout from //cmd/bd:bd_for_tests, the non-race
gms_pure_go cgo bd its own tests exec (//cmd/bd:bd is race-built under
--config=ci); test:ci downloads it under --remote_download_minimal. No
consumer is repointed yet.

A rules_go binary has no vcs.* or CGO_ENABLED build settings: `bd version`
shows no commit, and scripts/verify-cgo.sh would pass it vacuously. No
consumer of this artifact reads either; the manifest records the commit.

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

* ci(bazel): pure-Go and js/wasm lane for pr.yml's boundary job

pr.yml's "Check pure-Go and js/wasm boundaries (CGO_ENABLED=0)" job builds
bd and three test binaries with CGO off, runs a 16-name -short cmd/bd subset,
and runs the js/wasm hook refusal test under node with an exact count guard.
bazel.yml's new bazel-pure job does the same with Bazel binaries:

- --config=pure (--@rules_go//go/config:pure, -test.short) builds //cmd/bd:bd,
  bd_test, embeddeddolt_test and tracker_test, and runs bd_test unsharded
  with the job's -run selector (policy-tested to stay equal to pr.yml's).
- --config=js-wasm builds //internal/hooks:hooks_test for js/wasm
  (--use_target_platform_for_tests satisfies the test toolchain; nothing is
  tested by Bazel under it); the Go SDK's go_js_wasm_exec runs it under node
  with pr.yml's selector and count guard, verbatim.

rules_go compiles every declared dep, and gazelle's deps ignore the cgo
constraint of beads' embedded-Dolt files, so a pure build compiled dolt's
store/nbs and failed in github.com/dolthub/gozstd (cgo only; go build never
imports it with CGO_ENABLED=0). third_party/patches/gozstd_nocgo.patch adds
panicking !cgo stubs for the API dolt uses.

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

* test(bazel): run prcore tests with -test.parallel=4 like pr-core.sh

pr-core.sh runs go test -parallel 4. test:prcore passed no -test.parallel,
so Go defaulted to GOMAXPROCS: the executor's core count (192 on a farm
worker) instead of a runner's 4, which let dozens of t.Parallel bd
subprocesses run at once. A policy test keeps the value equal to
pr-core.sh's GO_TEST_PARALLEL default.

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

* test(bazel): -test.parallel=4 in the pure lane

pr.yml's pure-Go job passes no -parallel, so go test uses GOMAXPROCS, 4 on
ubuntu-latest; under Bazel the default would be the executor's core count.

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

* test(bazel): run the contract corpus non-race in the docker lane

pr.yml's Contract corpus job runs go test ./cmd/bd/protocol without -race,
but --config=docker races every target. protocol_docker_test now runs
:protocol_race_off, protocol_test built through a race=false transition
(tools/bazel/race.bzl), so no second go_test rule has to track gazelle's
srcs. Tagged manual so other lanes do not build it; the extra non-race work
is protocol_test's link plus ~100 test-only libraries.

The docker lane also mirrors the jobs' concurrency now: they pass no -p or
-parallel, so go test uses GOMAXPROCS, 4 on ubuntu-latest, for both; the
lane runs at most 4 test processes (so at most 4 dolt containers start at
once) with -test.parallel=4. It writes -test.v test.xml like test:ci, for
equivalence.py.

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

* ci(bazel): run the docker lane in bazel.yml

New advisory job bazel-docker runs `bazel test //... --config=docker` on
ubuntu-latest after pre-pulling the dolt image like pr.yml's container jobs.
The requires-docker variants (domain/db, uow, tracker, doctor/fix,
protocol) run on the runner against its docker daemon (no-remote-exec);
their builds use remote execution when setup-bazel configured it. With
bazel-test's --config=ci this covers "Test (storage domain + uow)" and
"Contract corpus". The lane name is one env var, so a hermetic dolt-server
lane can replace it.

Policy tests now cover every bazel.yml job: an exact job list, timeouts, no
continue-on-error, pinned actions (setup-node added), one setup-bazel step
per job as the only secret reader, cache saves only in bazel-test, plus
job-specific mirrors of pr.yml (the docker job's runner, image pull and
lane; a requires-docker target in each container-backed package).

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

* perf(bazel): build the non-race contract corpus in bd_for_tests' configuration

go_test_race_off only set race=false, while rules_go's go_transition (as
used by //cmd/bd:bd_for_tests, race = "off") also records the overridden
value in original_race. The two non-race configurations differed, so the
docker lane (and --config=ci, which builds protocol_docker_test through
//...) compiled the whole dolt graph twice without race. Record
original_race the same way: aquery GoCompilePkg for
deps(protocol_docker_test) under race drops from ~2630 actions in two
configurations to 1359 in one.

Fix the BUILD comment: manual does not keep protocol_race_off out of other
lanes' builds; protocol_docker_test pulls it in.

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

* fix(bazel): job-mode equivalence fails on any target's failure or missing test.xml

In --job mode a test seen in several targets keeps its best status, so a
failure in one variant was hidden when another target passed the test, and
a go_test_variant.sh sh_test without a test.xml was skipped silently. List
every failed test per target and every target in the job's packages whose
test.xml is missing, and fail on either.

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

* fix(bazel): gate pure-lane contamination, never cache docker-lane results

- gozstd_nocgo.patch: the stubs' package init panics, so a pure binary
  that links gozstd (which CGO_ENABLED=0 go build rejects at compile time)
  fails at startup. bazel-pure starts every pure artifact (bd version, and
  embeddeddolt_test/tracker_test with -test.run=^$; bd_test runs its
  subset) so contamination fails the lane.
- test:docker --nocache_test_results: the requires-docker variants depend on
  host state no action key covers, like the container jobs' -count=1.
  build:remote-exec --noremote_upload_local_results in the committed rc, so
  local runs cannot seed the shared cache with host-dependent results.
- The artifact packaging moves to scripts/ci/package-bazel-bd.sh, which
  sources .buildflags itself; sourcing it in bazel.yml exempted the whole
  workflow from the build-tag scan.
- bazel-pure and bazel-docker use bazel-test's runs-on (Blacksmith when
  remote execution is possible); the policy test pins it for every job.

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

* ci(bazel): put the pure and docker lanes behind the rbe-west gate

Apply bazel-test's rbe-west setup-bazel env (RBE_WEST_EXECUTOR, instance
oss, RBE_WEST_WORKERS) and its job if to bazel-pure and bazel-docker, so
same-repo runs of all three lanes skip together until the variable is set
and forks and rbe=off dispatches still run locally. The policy test pins
runs-on, if and the setup-bazel env for every bazel.yml job.

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

* fix(ci): run the js/wasm hook test with a minimal environment

wasm_exec.js caps argv+env size, and the Blacksmith runner's environment
exceeds it ("total length of command line and environment variables
exceeds limit").

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-09-28 02:03:51 -07:00
Julian Knutsen
6da2a43477
ci(bazel): advisory Bazel workflow + go test/Bazel equivalence check (#6881)
* ci(bazel): add advisory Bazel workflow and setup-bazel action

Add .github/workflows/bazel.yml, a side-by-side lane that runs
`bazel test //... --config=ci` (PR Core parity) on pull_request,
merge_group, push to main and workflow_dispatch. It is advisory: not in
ci-gate's CI_GATE_REQUIRED.

.github/actions/setup-bazel installs a sha256-pinned Bazelisk (Bazel from
.bazelversion), restores the runner cache (--disk_cache and
--repository_cache only), and writes a CI bazelrc outside the workspace
and outside the cached directory. Remote execution is enabled only when
BAZEL_REMOTE_EXECUTOR, RBE_TLS_CERT and RBE_TLS_KEY are all set (base64
PEM cert/key; optional RBE_TLS_CA, RBE_INSTANCE); none set (fork PRs, or
workflow_dispatch rbe=off) runs locally; a partial set fails. The endpoint
and its bare host are masked. The rc logic lives in write-bazelrc.sh so it
is testable offline.

The runner cache is saved only by push-to-main runs under a run-unique key
and restored by prefix, so it never freezes at its first save and PRs do
not churn the quota. The job also reports the tier (T1/T2/local) and
wall time in the step summary, runs tools/bazel/critpath.py against the
profile, and checks BUILD drift with make bazel-sync-check plus
make bazel-sync and a clean git status.

tools/bazel/critpath.py reports the critical path as the sum of the
chained "critical path component" events rather than the longest one (a
cold race build: 395s over 75 components, where the single-component
version printed 69s and a false scheduling gap), lists the longest
members and Bazel's processes: cache line, and checks a report-only
budget (warning annotation, exit 0) unless --enforce is given.

scripts/ci_workflow_test.go covers the new lane: not wired into any gate,
every action SHA-pinned to the repo's released SHAs, no monolithic
actions/cache, no unbounded apt-get, the cache topology, secrets only
reaching setup-bazel, --profile after `test`, and the rc writer's
none/partial/full/invalid-PEM/secret-dir-in-workspace behaviour.

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

* ci(bazel): check go test / Bazel test equivalence in the Bazel lane

tools/bazel/equivalence.py compares the Go tests `bazel test //...
--config=ci` ran with the ones pr.yml's go test lanes run, so a tag
filter, a stray manual tag, a package without a go_test target, or a
shard that runs zero tests cannot shrink the Bazel lane while it stays
green:

- package set: every package `go list -race -tags gms_pure_go` reports
  with test files has a go_test target (bazel query);
- test-name set: every top-level TestXxx in the files go list selects
  (minus ^TestEmbedded, as PR Core skips) appears as a testcase in the
  test.xml of a go_test target this invocation tested (from the BEP);
  runtime skips count as run. Tests Bazel ran that go test would not
  are divergences too.

Expected differences go in tools/bazel/equivalence_allowlist.txt, one
justified line each (empty today); unused entries are reported.
Results go to the step summary; the full listing with --details.

.bazelrc test:ci now sets GO_TEST_WRAP_TESTV=1 (rules_go lists passing
tests in test.xml only under -test.v) and downloads test.xml despite
--remote_download_minimal.

The Bazel workflow runs the check after the critical-path report, and
nightly.yml calls the workflow (suite "bazel", and on schedule) with the
full listing.

Verified locally against a remote --config=ci run: 103 packages and
8843 tests on both sides. Tagging //internal/gitignore:gitignore_test
manual keeps `bazel test` green but fails the check, listing its two
tests.

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

* test(fs): run RepoContextAndRole from its own git repo

The test relied on its working directory being inside a git checkout to
make BEADS_DIR external to the CWD repo. Under Bazel the working
directory is the runfiles tree, not a git repository, so RepoContext
failed with "not a git repository" and the test skipped itself.
Create a second temporary repo and chdir into it instead; go test keeps
passing and Bazel now runs the assertions.

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

* fix(bazel): fail equivalence on tests Bazel skips but go test passes

The equivalence docstring claimed runtime skips count as run because go
test skips them the same way. It does not: against PR Core's go test
-json on the same commit, 11 tests passed under go test and skipped
under Bazel while the check printed ok with an empty allowlist.

- equivalence.py --go-test-json compares per-test status with the
  Bazel test.xml: passed under go test and skipped under Bazel is a
  divergence; other status differences are listed, not failed. The
  in-job (PR) run cannot see skip divergences and says so.
- The allowlist gains a `skip` kind (`<pkg> <test> skip  # why`, the
  justification still mandatory) and lists the 10 intentional skips:
  cmd/bd TestGOMODCACHENotUnderTestHome and TestZZStdioNotLeaked, and
  the scripts policy tests that walk the source checkout. The eleventh,
  fs TestContextRepository_RepoContextAndRole, is fixed in the test.
- scripts/ci/pr-core.sh writes `go test -json` to
  BEADS_PR_CORE_GO_TEST_JSON when set (same flags otherwise).
- nightly.yml runs that in a new job, uploads the JSON, and calls
  bazel.yml with go-test-json-artifact, which downloads it and passes
  --go-test-json to the equivalence step.

Verified on a remote `bazel test //... --config=ci` run: ok with the
allowlist; a TEST_SRCDIR-only t.Skip injected into
internal/gitignore TestAppendLines fails the check (and passes the
name-only in-job check, as documented).

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

* ci(bazel): freeze the runner cache per lock, mask key material, tighten policy

Runner cache: every push to main saved ~2.3 GB (repository cache, disk
cache, Bazelisk) under a run-unique key, on a repo already over its
Actions cache quota. The cache now holds only the repository cache and
Bazelisk, whose content is fixed by .bazelversion and MODULE.bazel.lock:
exact key bazel-repo-v2-<os>-<hash>, restore falls back to the previous
lock's entry, and only a push to main that missed the key saves. No
--disk_cache in either mode (remote runs have the remote cache; local
runs never used it). About 2 GB per lock change.

Credentials:
- write-bazelrc.sh masks every non-armor line of each decoded PEM
  (cert, key, CA). GitHub only masks the base64 value as stored. The CA
  used to be decoded inside the rc redirect, so its mask commands would
  have gone into the rc; it is decoded first now.
- The CI rc sets build:remote-exec --noremote_upload_local_results, so
  CI never writes locally executed (PR-code) results into the shared
  action cache. Developer rcs keep Bazel's default.
- RBE_INSTANCE stays optional; an empty one is a ::warning.
- bazel.yml's header states the accepted risk: same-repo PR code runs
  with the RBE client certificate (as in gascity); forks never get it;
  what is in place and what is pending a human decision.

Policy tests (each proved with a scratch mutation that now fails):
triggers must be exactly pull_request, merge_group, push,
workflow_dispatch and workflow_call (no pull_request_target); secrets
may appear only in the setup-bazel step's env, not in workflow or job
env, run, with or if; no continue-on-error anywhere in bazel.yml or
setup-bazel; the cache-save if is matched exactly; the critical-path
and equivalence steps must end with the bare script call and the test
step with exit "$rc", with no exit 0, || true, || :, ; true, set +e or
trap.

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

* docs(ci): record the same-repo RBE decision in bazel.yml

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

* fix(ci): bazel wrapper version check; keep go-test prose out of the build-tag scan

The wrapper prepends --bazelrc, so 'bazel --version' reached the server
as an unknown startup option; ask bazelisk directly. check-build-tags
matched 'go test' in workflow prose and step names.

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

* fix(ci): run the RBE lane on Blacksmith runners; mask the executor's IPs

GitHub-hosted runners are refused by the remote-execution edge; the
Blacksmith pool (as in gascity) is admitted and does not count against
GitHub's concurrent-job cap. Forks and rbe=off keep ubuntu-latest.
Bazel prints the resolved executor address in connection errors, so mask
every address the endpoint host resolves to.

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

* ci(bazel): target rbe-west (instance oss) behind RBE_WEST_WORKERS

The original edge does not admit CI runners. Mirror gascity: remote
execution uses secrets.RBE_WEST_EXECUTOR and instance oss when the repo
variable RBE_WEST_WORKERS is true; same-repo runs are skipped until then
instead of failing, while forks and rbe=off still run locally.

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-09-27 23:05:21 -07:00
ecuthiell
cefcabb1e3
fix(gitenv): retain explicit null config suppression (#6461)
* fix(exec): match Windows environment key identity (#5618)

Centralize os/exec-compatible environment-key comparison and use it for credential, metrics, Git-hook, trace, and repro subprocess filters. Preserve exact Unix semantics and Unicode near-collisions.

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

* fix(worktree): scrub inherited Git routing state

Establish CWD as the worktree repository boundary before discovery can consume inherited Git routing. Fence the startup config probe, clear routing in-process before root pre-run discovery, and retain command-owned subprocess scrubbing as defense in depth without changing PID or signal semantics.

Fixes #5531

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

* refactor(worktree): explain owned filtering and remove an unused shim

Document why filtering the fresh routing slice in place is safe and call
the shared routing-key classifier directly from tests. Retain the two
forwarders used by production worktree subprocess/removal paths.

Review: https://github.com/gastownhall/beads/pull/5623#pullrequestreview-5098421671
Bead: saa-cgh.23
Agent-Signature: unknown-model/unknown-reasoning

* fix(config): isolate identity and tracked-file Git probes from routing

Reuse the worktree routing owner for GetIdentity and isGitTracked so
explicit cwd/path selection is not displaced by inherited repository,
index or injected config state. Preserve identity precedence and the
tracked-secret refusal contract, with real target/decoy regressions.

Follow-up: https://github.com/gastownhall/beads/issues/6222
Dependency: https://github.com/gastownhall/beads/pull/5623
Reported-by: bee-ghosttrack
Bead: saa-cgh.93
Agent-Signature: unknown-model/unknown-reasoning

* test(execenv): exercise every environment operation under both host rules

Thread the host choice through narrow private helpers behind the existing
exported functions. Keep one normalization owner and retain native wrapper
tests; the additional table covers both host branches for equality, prefix
matching, last-wins lookup, filtering and input preservation.

Review: https://github.com/gastownhall/beads/pull/5672#pullrequestreview-5096948965
Bead: saa-cgh.78
Agent-Signature: unknown-model/unknown-reasoning

* docs(worktree): explain startup Git environment scope (saa-cgh.23)

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

* test(execenv): exercise exported host policy wiring (saa-cgh.78)

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

* fix(config): share subprocess key identity for Git routing (saa-cgh.93)

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

* fix(config): isolate role commands from Git routing (saa-cgh.99)

Follow-up to bee-ghosttrack's review of gastownhall/beads#6322; refs #6357.

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

* test(env): exercise shared key helpers on native Windows (saa-cgh.78)

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

* refactor(gitenv): share key parsing and normalize routing membership once (saa-cgh.93)

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

* docs(config): explain role command routing policy (saa-cgh.99)

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

* fix(config): isolate role readers from inherited Git routing (saa-cgh.109.1)

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

* fix(doctor): isolate role lookups from inherited Git routing (saa-cgh.109.2)

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

* fix(git): isolate domain role configuration from inherited routing (saa-cgh.109.5)

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

* fix(doctor): isolate explicit-path worktree fallback from Git routing (saa-cgh.109.6)

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

* fix(init): probe the selected repository before configuring roles (saa-cgh.109.8)

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

* test(beads): cover common-directory role routing (saa-cgh.109.1)

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

* test(git): explain system config routing flags (saa-cgh.109.6)

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

* docs(init): explain role probe discovery ceiling behavior (saa-cgh.109.8)

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

* fix(beads): scope stable worktree probes to selected path (saa-cgh.109.13)

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

* fix(init): bind proxied tail Git operations to selected directory (saa-cgh.109.14)

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

* Clarify selected discovery probes and cover separate routing vectors (saa-cgh.120)

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

* Keep init role operations on the captured selected Git context (saa-cgh.120)

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

* Observe inline Git configuration directly in linked-worktree fixture (saa-cgh.120)

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

* Align selected-tail fixtures with captured role authority (saa-cgh.120)

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

* fix(beads): select explicit directory discovery context (GH#6384) (saa-cgh.120.6)

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

* fix(gitenv): retain explicit Git config suppression (saa-cgh.120.7)

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

* test(config): pin identity under null config suppression (saa-cgh.120.7)

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

* fix(gitenv): keep role authority off inherited config suppression

Maintainer review fixes for PR #6461 (adopt-pr iterations 1-2). Addresses the
three major findings raised against the contributor branch, plus the major,
three minors and nit that iteration 2 raised against the first fixup; each fix
is pinned by a test that was mutation-proved against the pre-fix source.

F1 (major, security) — the leaf exempts GIT_CONFIG_GLOBAL=/dev/null,
GIT_CONFIG_SYSTEM=/dev/null and GIT_CONFIG_NOSYSTEM from ScrubRouting. Null
suppression cannot redirect a read, but it can blind one, and DetectUserRole
answers a missed read with detectFromURL, whose no-remote and SSH arms both
return Maintainer. Reproduced on this branch: a global beads.role=contributor
with GIT_CONFIG_GLOBAL=/dev/null resolved to maintainer, where the leaf's
parent fb7a93ad4 scrubbed the entry and read contributor.

Taken the synthesis's alternative arm (a): keep the exemption where the value
has no authority, drop it where it does. New ScrubRoutingAndSuppression
applies at every beads.role reader — internal/routing, doctor/role.go,
config_show.go, RepoContext.Role, bd config get/set/unset/set-many, and the
domain adapter's key-specific arms (see A1: iteration 1 claimed that last site
and did not actually reach it). Arm (b), making roleFromGitConfig's miss
non-permissive, was declined: "no beads.role and no remote implies maintainer"
is documented base behavior for local projects, so closing it there would
reclassify every such user rather than the blinded slice this PR introduced.

F2 (major, blast radius) — the stack hardened every role reader and left four
writer/reader sites fully inherited, a divergence that did not exist at base:
an inherited GIT_DIR sends setBeadsRole's write to another repository while
the scrubbed readers look at the one the user is standing in. All four now
share the same boundary (init.go's getBeadsRole/setBeadsRole,
init_contributor.go, hooks.go's uninstall --get/--unset pair).

The required fix also asked for cmd.Dir = repoRoot on the init.go pair. Still
not taken, but not on the grounds iteration 1 recorded (see A2). What holds is
the measurement against the vector the fix targets: with GIT_DIR, GIT_WORK_TREE
and GIT_COMMON_DIR gone, no production path chdirs away from the invocation
directory — `grep -rn 'os\.Chdir' --include='*.go'` over production cmd/bd
returns nothing and `bd init` takes no path argument — so threading a repoRoot
through both signatures and their eight call sites buys no behavior change
against a redirect.

F3 (major, security) — this PR converted internal/config's isGitTracked probe
from inherited to scrub-only. The guard is fail-open by construction, so in a
legitimately routed checkout (bare repo.git, GIT_DIR/GIT_WORK_TREE exported,
no in-tree .git) the probe stopped answering and `bd config set
linear.api_key` would have written the credential into a tracked file.
Restored the two-probe shape sibling #6464 applied to the structural twin:
scrubbed probe first, inherited second, either "tracked" refuses.

F5 (minor) — disclose that scrubbing GIT_CEILING_DIRECTORIES widens upward
discovery rather than bounding it, in the worktree comment and the docs
paragraph that asserted only the narrowing effect. F2's fix extends that
trade-off to two more sites, so the disclosure is now load-bearing.

F7 (minor) — renamed isConfigSuppression to isConfigSuppressionControl and
documented why the NOSYSTEM arm is deliberately value-blind. Took the
rename/document arm rather than restricting the arm to git-true values, which
would have contradicted the PR's own pinned table.

F10 (nit) — pinned both suppression tables in the windows-latest required
list; verified each name matches the gate's grep exactly once.

--- Iteration 2 ---

The first fixup's F1 census named a site it did not reach, and its cmd.Dir
rationale named a mechanism that does not hold. Both are corrected here.

A1 (major, security) — the domain adapter's key-specific arm was guarded by
`key == "beads.role" && r.env == nil`, which is dead on the only production
role path: runInitProxiedServerTail rebinds the use case to
NewInitGitRepository whenever t.workDir != "" (its sole construction site
passes cwd), and that constructor captures ScrubRouting(os.Environ()) —
non-nil, suppression retained. The nil-env constructor has no
BeadsRole/SetBeadsRole caller, so the arm could only fire from tests, while
`bd init` under an inherited GIT_CONFIG_GLOBAL=/dev/null still missed a global
role, took hasRole=false, and persisted beads.role=maintainer into
repository-local config, where it outranks the global value for every later
read in a clean environment. Iteration 1 therefore left F1's escalation not
just alive but durable, on the one path the fix was supposed to close.

Fixed by keying the strict scrub on the config key alone and applying it to
whichever environment the repository already carries (roleAuthorityEnv). That
preserves capture semantics — NewInitGitRepository keeps its captured HOME,
the property git_test.go's captured_home case pins — and removes only the
suppression entries. Codex's alternative of rebuilding the constructor's whole
env was declined: it moves every key for no gain on this finding.

A2 (minor, contract fidelity) — iteration 1 justified declining cmd.Dir with
"repository selection is left to the working directory — the one input the
scrub keeps". That is false, and false in the file a future reader consults
before deciding whether to bound the pair: GIT_CEILING_DIRECTORIES is a routing
key too, so the scrub removes a bound rather than installing one. Measured from
a non-repository directory nested under a repository: `git config beads.role
<value>` fails "not in a git directory" while a ceiling below that repository is
inherited, and writes that repository's local config once the ceiling is
scrubbed. The decline itself stands, since the measurement behind it was made
against the GIT_DIR vector; getBeadsRole now records selection as the working
directory *or a containing ancestor*, which is also what makes
clearWorktreeGitRoutingEnv's existing cross-reference to "init's role probe"
true.

A3 (minor, consistency) — `bd config unset beads.role` and `bd config set-many
beads.role=` were the two spellings of that mutation still on ScrubRouting, in
the same file as the two that moved. Both measured inert: `git config <key>
<value>` and `--unset <key>` target the repository-local file, which the
suppression variables cannot select. Moved for parity rather than annotated,
because a divergence inside one file is how the next one starts.

Test evidence (minor) — the writer pair's two subtests both pass on the
redirect alone, so downgrading getBeadsRole back to ScrubRouting left them
green even though suppression is the load-bearing half at those sites
(init.go treats a getBeadsRole miss as permission to write a default role).
Added a global_null blinding subtest with the same unblinded fixture guard.

A4 (nit) — doctor/role.go's isGitRepo was the last probe in that file on the
suppression-retaining scrub, and it gates the "beads.role not configured"
warning. rev-parse is config-sensitive through safe.directory, which lives in
global config, so a retained GIT_CONFIG_GLOBAL=/dev/null can downgrade that
warning to "N/A (not a git repository)". Moved onto the same boundary as its
two siblings. As the finding records, the safe.directory precondition was not
reproduced end to end; the change is uniformity within the file.

Tests. Every pin reds only on its own defect:
- routing: reverting to ScrubRouting reds only the blinded-read subtest; the
  unblinded fixture guard and the PR's inject-vector table stay green.
- gitenv: keeping suppression reds 10 of 16 new subtests, none of the PR's.
- cmd/bd: restoring the inherited env reds both redirect subtests and names
  both halves ("the write did not land where bd is standing" / "an inherited
  GIT_DIR captured the write"), while the PR's own role roundtrip stays green
  — it followed the same redirect on both sides, so it never saw this.
- config: the two arms are proved separately. Scrub-only reds only the
  legitimate-routing subtest; inherited-only reds only the poisoned-routing
  subtest, so the new fallback cannot be read as a way around the scrub.
- domain/git (A1): restoring the r.env == nil provenance guard reds
  global_null only; unblinded stays green, and no other test in the package
  moves — which is the same measurement that confirms the arm had no coverage
  before this iteration.

Deferred to follow-up, recorded for the approval summary: F4 (delete
isRoleGitRepo and resolve the dead else-if), F6 (user.name degrading to
hostname, which needs the PR's own subtest re-pointed), F8 (execenv fold
divergence), F9 and F11 (GetIdentity hostname degradation under inherited
suppression). F9's mechanism is confirmed — identity supplied only via
GIT_CONFIG_COUNT is lost when GIT_CONFIG_* is stripped, git reports "Please
tell me who you are", while GIT_AUTHOR_*/GIT_COMMITTER_* survive — but its
"leave artifact commits on the inherited environment" arm would re-open the
GIT_DIR redirect this PR's tail swap closed, and the non-regressing arm
(re-injecting inline identity pre-scrub) is a design change with no observed
victim in this repo.

Validation (iteration 2): internal/{gitenv,routing,storage/domain/git} full
packages green; cmd/bd/doctor full package run; targeted cmd/bd run over the
role, config and init blast radius green at 54 tests; go build ./... clean; go
vet plus CGO_ENABLED=0 and GOOS=windows CGO_ENABLED=0 vet clean on every
changed package. Remaining local reds are base-parity, each matching the
recorded cause: cmd/bd/doctor's seven (the launcher's global
beads.role=maintainer short-circuits CheckBeadsRole before isGitRepo is
reached, plus Dolt server availability) and
TestInitContributorSetsBeadsRoleContributor ("--contributor requires
interactive prompts", this session's stdin is not a TTY).

--- Iteration 3 ---

Iteration 3 reviewed 0220eed32 and approved it: claude filed no findings,
codex's six fix validations all came back correct, synthesis recorded
Decision: approve, and the scorecard scored 881/1000 with Required Changes:
None. The residual was two minors and a nit, none of them merge gates. All
three are taken here because they are comment-and-constant scope, so nothing
in the approved behavior moves.

B1 (minor, blast radius; codex filed it as major, demoted at synthesis) — the
isGitRepo() gate that decides whether the role pair runs is still fully
inherited while the pair it guards is now strict, so from a non-repository
directory with an inherited GIT_DIR the gate opens, the scrubbed read misses,
and the safety-net write fails "not in a git directory". Recorded at the
GH#2950 safety net rather than restructured, for the three reasons the
demotion rests on. The achievable outcome is base parity: sync_git.go is
byte-identical at base and the pair was inherited there too, so a GIT_DIR
holder already reached Maintainer before this PR — more directly, by pointing
at a repository whose beads.role is maintainer. The failure is not silent:
init prints "Warning: failed to set beads.role" unless --quiet, and every
later detection prints "beads.role not configured (GH#2950)" with two Fix
lines. And the prescribed roleRepoAvailable() gate provably does not close it:
all five gate sites are bare `if isGitRepo()` with no else, so a strict gate
answers false in exactly the described band, nothing is written, the role
stays unset, and detection still falls to detectFromURL. The optional
hardening is therefore declined rather than deferred — it would delete a
warning and change no role — and the comment says so, so the next reader does
not mistake a gate change for closing the fail-open path.

B2 (minor, contract fidelity) — the getBeadsRole rationale iteration 2 wrote
to close A2 introduced a new overstatement in its closing sentence: "bd init
takes no path argument — the residual is upward discovery from an unintended
cwd, not a redirect". `bd -C <dir>` is a redirect and takes no path argument.
Verified in tree rather than from the finding: applyChangeDirSelection
(main.go) resolves the target's .beads dir and sets BEADS_DIR with no chdir,
it runs from the root PersistentPreRunE ahead of every init-related early
return in that hook, and init honors BEADS_DIR for workspace selection — so
`bd -C other init` acts on other/.beads while the pair reads and writes
beads.role in the invocation repository. init.go's own "PersistentPreRun
doesn't run for init command" note is about the later skipsStoreInit return,
not about -C, which is what made this vector easy to miss twice. Reachability
is bounded: -C requires an existing beads project at the target, so the
pairing arises on re-init rather than first init. Comment narrowed to name the
residual; threading init's resolved project root through the pair is the
stronger arm and stays out of scope as a behavior change.

B3 (nit, architectural consistency) — the adapter selected the role-authority
boundary on a bare "beads.role" literal while the use case passed the
unexported beadsRoleConfigKey, two spellings of one contract the compiler
could not couple. Exported it as domain.BeadsRoleConfigKey and compared
against it at both adapter arms; no new import edge, since package git already
imports domain. Mutation-proved rather than asserted: replacing the
comparison with the case-variant "Beads.Role" the finding names reds
TestInitGitRepositoryRoleIgnoresInheritedConfigSuppression/global_null alone
while unblinded stays green, so the drift the nit describes is caught by an
existing pin. The comparison is still exact, not case-folded: git config names
are case-insensitive, so a caller hand-writing a variant spelling would bypass
roleAuthorityEnv, but folding widens which keys take the strict environment
and no production caller passes anything but the const — a behavior change the
nit did not ask for.

Validation (iteration 3): go build ./... clean; go vet plus CGO_ENABLED=0 and
GOOS=windows CGO_ENABLED=0 vet clean on cmd/bd, cmd/bd/doctor,
internal/storage/domain, internal/storage/domain/git and internal/gitenv;
internal/storage/domain/... full packages green (domain, db, fs, git); targeted
cmd/bd role run green at 19 subtests with no skips
(TestBeadsRoleCommandsIgnoreInheritedGitRouting and
TestBeadsRoleWriterIgnoresInheritedGitRouting, including the suppression
subtest added in iteration 2); gofmt and git diff --check clean. Full cmd/bd is
still not run locally: it times out at base as well. The iteration-1 deferrals
are unchanged and still owed follow-up bead ids at finalize (F4, F6/F11, F8,
F9).

---------

Signed-off-by: Ewen Cuthiell <ewencuthiell@gmail.com>
Co-authored-by: Bee <bee@ghosttrack.com>
Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
Co-authored-by: Julian Knutsen <julianknutsen@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-27 15:59:08 -07:00
Julian Knutsen
469462d56a
test(bazel): run every Bazel test against a hermetic, pinned dolt CLI (#6853)
* test(bazel): run every test against a hermetic, pinned dolt CLI (slice B4)

Tests that shell out to dolt ran whatever /usr/local/bin/dolt the executor
had, a version outside the action key, and skipped (a vacuous, cacheable
PASS) on an executor without one.

- tools/bazel/dolt.bzl: dolt_release repository rule fetching the upstream
  release pinned to scripts/ci/install-dolt.sh (2.2.0), sha256 for
  linux/darwin amd64/arm64; MODULE.bazel declares one repo per platform and
  //tools/bazel:dolt selects the one for the execution platform.
- //tools/bazel:test_env (the --run_under wrapper) carries the pinned dolt
  as data. Bazel merges the run_under runfiles into every test's runfiles, so
  every test action declares dolt as an input; test_env.sh puts it first on
  PATH, exports BEADS_TEST_DOLT_BINARY, and fails the test if it is missing.
  DOLT_ROOT_PATH identity seeding stays in test_env.sh.
- testutil.requireDoltBinaryPresent fails instead of skipping under Bazel.
- TestPinnedDoltCLIMatchesContainerImage also checks tools/bazel/dolt.bzl.
  scripts_test declares the pin files and resolves the repo root through
  bazeltest, so the three dolt pin tests now pass under bazel test.

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

* test(bazel): declare the Go source dolt_test's scope guards scan

TestEveryRawTxJournalScopeIsScopedOrExempt, TestEveryRawTxVersionScopeIsScopedOrExempt,
TestTxMintingWrappersScopeVersionedHistory and TestHelperSubprocessSentinelsAreComplete
parse internal/storage/dolt and internal/storage/issueops at test time; under
bazel test that source was not in the runfiles, so all four failed.

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

* fix(bazel): tie hermetic dolt download to its version; skip on unpinned platforms

- Key DOLT_SHA256 by version and pass canonical_id=url, so bumping
  DOLT_VERSION without new digests fails instead of silently reusing the
  previous release from the sha256-keyed repository cache.
- //tools/bazel:dolt_version_test runs the hermetic dolt and checks it
  reports DOLT_VERSION.
- Unpinned platforms (e.g. windows) resolve to an incompatible target, so
  bazel build //... skips the wrapper there instead of failing analysis.
- test_env.sh also unsets BEADS_DOLT_BIN so it cannot bypass the pin.

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-09-27 14:29:49 -07:00
Julian Knutsen
f66375459f
test(bazel): runfiles helpers + declared inputs for scan-guard tests (#6828)
* test(bazel): add internal/testutil/bazeltest runfiles helpers

Repository-path resolution for tests that works identically under plain
go test (package cwd, full checkout), bazel test locally, and remote
execution (declared runfiles only):

- IsBazel, RepoRoot (BEADS_TEST_REPO_ROOT, then the runfiles workspace
  root, then a go.mod walk), OverrideRoot (drop-in condition for existing
  helpers; empty under plain go test), CallerDir
- Runfile for $(rlocationpath) values, GOROOT for type-checking tests
- ShardFreeEnv for helpers that re-exec a test binary

Every helper reduces to the pre-Bazel behavior under go test.

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

* test(bazel): declare source/data reads for 14 scan-guard targets

Source-scanning and repo-file tests read files their Bazel targets never
declared, so they failed under `bazel test` (and could not run on remote
workers at all). Declare narrow inputs as `data` and resolve paths through
bazeltest where the test located the tree via runtime.Caller:

- tools/bazel/go_srcs.py (run by `make bazel-sync` after gazelle) keeps a
  managed `go_srcs` filegroup in the packages whose Go source tests scan,
  plus `//internal/storage:tree_go_srcs` for the storage-tree walk. Bazel
  globs stop at package boundaries, so the aggregate needs one filegroup
  per package; the script keeps it in sync and gazelle-stable.
- Hand-written narrow inputs: //internal/storage/schema:migrations,
  //:docsync_files, //plugins/beads:plugin_files, and exports of
  .gitattributes, .claude-plugin/marketplace.json, cmd/bd list.go and
  ready.go, testutil/testdoltcommon.go, scripts README.md and the release
  catalog, each visible only to its consumer.
- runtime.Caller-based roots in backend, backend/conformance,
  internal/storage, internal/formula and test/docsync now go through
  bazeltest.CallerDir / OverrideRoot; relative-path tests need data only.
- integrations/ leaves .bazelignore (it is still gazelle-excluded) so the
  docsync link check can declare integrations/beads-mcp/PYPI.md.

Under --config=prcore every target reports the same PASS/SKIP/FAIL test
set as `go test -race -short` for its package, locally and remotely.
Plain `go test` behavior is unchanged.

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

* test(bazel): guard generated go_srcs and harden bazeltest root override

- tools/bazel/go_srcs.py: add --check (print diff, exit 1 on stale blocks);
  new `make bazel-sync-check` target runs it.
- scripts/bazel_policy_test.go: under go test, assert every tree_go_srcs
  (//internal/storage) lists exactly the BUILD.bazel packages below its
  root, run go_srcs.py --check, and forbid BUILD files under docs/ and
  engdocs/ (they would cut subtrees out of //:docsync_files).
- bazeltest: honor BEADS_TEST_REPO_ROOT only when it holds go.mod
  (RepoRoot fails loudly otherwise); drop the unused GOROOT() helper,
  whose compiled-in branch could never fire under rules_go.
- scripts/ci/lib/test-env.sh: unset BEADS_TEST_REPO_ROOT.
- Document the hand-listed out-of-tree link targets in //:docsync_files.

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

* build(bazel): re-sync BUILD files with main

Regenerated with make bazel-sync after commits that landed while the
scaffold PR was in CI (new internal/execenv, gitenv, gitignore packages
and new sources/deps).

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

* test(bazel): declare init_safety_help.go for docsync

TestInitSafetyCLIHelpCoversReCloneGotchas (#6431) reads
cmd/bd/init_safety_help.go; export it to //test/docsync only.

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-09-27 08:24:08 -07:00
ecuthiell
79631656c0
fix(config): pin role writes to a fresh common-config context (#6454)
* fix(exec): match Windows environment key identity (#5618)

Centralize os/exec-compatible environment-key comparison and use it for credential, metrics, Git-hook, trace, and repro subprocess filters. Preserve exact Unix semantics and Unicode near-collisions.

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

* fix(worktree): scrub inherited Git routing state

Establish CWD as the worktree repository boundary before discovery can consume inherited Git routing. Fence the startup config probe, clear routing in-process before root pre-run discovery, and retain command-owned subprocess scrubbing as defense in depth without changing PID or signal semantics.

Fixes #5531

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

* refactor(worktree): explain owned filtering and remove an unused shim

Document why filtering the fresh routing slice in place is safe and call
the shared routing-key classifier directly from tests. Retain the two
forwarders used by production worktree subprocess/removal paths.

Review: https://github.com/gastownhall/beads/pull/5623#pullrequestreview-5098421671
Bead: saa-cgh.23
Agent-Signature: unknown-model/unknown-reasoning

* fix(config): isolate identity and tracked-file Git probes from routing

Reuse the worktree routing owner for GetIdentity and isGitTracked so
explicit cwd/path selection is not displaced by inherited repository,
index or injected config state. Preserve identity precedence and the
tracked-secret refusal contract, with real target/decoy regressions.

Follow-up: https://github.com/gastownhall/beads/issues/6222
Dependency: https://github.com/gastownhall/beads/pull/5623
Reported-by: bee-ghosttrack
Bead: saa-cgh.93
Agent-Signature: unknown-model/unknown-reasoning

* test(execenv): exercise every environment operation under both host rules

Thread the host choice through narrow private helpers behind the existing
exported functions. Keep one normalization owner and retain native wrapper
tests; the additional table covers both host branches for equality, prefix
matching, last-wins lookup, filtering and input preservation.

Review: https://github.com/gastownhall/beads/pull/5672#pullrequestreview-5096948965
Bead: saa-cgh.78
Agent-Signature: unknown-model/unknown-reasoning

* docs(worktree): explain startup Git environment scope (saa-cgh.23)

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

* test(execenv): exercise exported host policy wiring (saa-cgh.78)

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

* fix(config): share subprocess key identity for Git routing (saa-cgh.93)

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

* fix(hooks): isolate tracked-file guard from Git routing (saa-cgh.98)

Follow-up to bee-ghosttrack's review of gastownhall/beads#6322; refs #6356.

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

* fix(config): isolate role commands from Git routing (saa-cgh.99)

Follow-up to bee-ghosttrack's review of gastownhall/beads#6322; refs #6357.

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

* test(env): exercise shared key helpers on native Windows (saa-cgh.78)

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

* refactor(gitenv): share key parsing and normalize routing membership once (saa-cgh.93)

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

* docs(config): explain role command routing policy (saa-cgh.99)

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

* fix(hooks): retain legitimate inherited tracking context (saa-cgh.98)

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

* test(hooks): isolate trusted global configuration fixture (saa-cgh.98)

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

* fix(hooks): isolate role cleanup in the selected repository (saa-cgh.109.4)

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

* fix(hooks): reset only common local role configuration (saa-cgh.109.10)

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

* fix(hooks): scope hooks-path cleanup to selected common config (saa-cgh.109.11)

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

* test(hooks): make worktree role preservation independent (saa-cgh.120)

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

* Report selected config read failures during hook reset (saa-cgh.120)

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

* fix(hooks): keep successful config stdout separate from diagnostics (saa-cgh.120)

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

* fix(config): pin role writes to fresh common context (GH#6384) (saa-cgh.120.3)

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

* fix(config): retain Git diagnostics from role writes (saa-cgh.120.3)

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

* test(config): assert the actual Git lock diagnostic (saa-cgh.120.3)

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

* fix(config,hooks): restore the inherited-tracking fallback in the secret guard

Maintainer review fixes for PR #6454 (adopt-pr iteration 1). The scorecard
approved at 913/1000 with no blocker or major surviving synthesis; these are
the non-gating findings that were cheap to close while the fixup was open.

Finding 1 (minor, security) is the only in-range regression in the report. The
range switched internal/config.isGitTracked from the inherited environment to
gitenv.ScrubRouting only, so a config.yaml tracked solely through legitimate
routing -- a bare repository whose work tree is named by GIT_DIR/GIT_WORK_TREE
-- reported untracked, and a secret-key write that upstream-base refused was
silently allowed. Restores the scrubbed-then-inherited union the same stack
already gave cmd/bd.isGitTrackedFile.

Finding 4 (nit) composes with it rather than conflicting, so both land as one
change: the inherited probe now runs only when the scrubbed probe failed for a
configuration reason. git's exit codes discriminate exactly -- 0 tracked, 1
repository reached but path untracked (final), 128 no reachable repository --
so the ordinary untracked-hook miss no longer spawns a second `git ls-files`
while the bare-work-tree fallback is preserved.

Finding 2 (minor). scrubWorktreeRemovalGitEnvForOS keyed its stricter
no-optional-locks policy on strings.ToUpper while the rest of the PR uses
execenv key identity. The two disagree in both directions on Windows:
GIT_OPTIONAL_LOCKS with a dotted capital I (U+0130) survived the scrub although
Git honors it, and GIT_OPTIONAL_LOCK with a long s (U+017F) was dropped
although os/exec keeps it distinct. normalizeWorktreeGitEnvKey is deleted in
favour of execenv.KeyEqualForOS. Base applied ToUpper on all platforms, so this
is a consistency fix in newly rewritten code, not a regression.

Finding 5 (nit). The comment above resetHooksPathIfBeadsManaged's probe
asserted that repoRoot and commonDir share the cached Git context. Probed
false: with cwd A and GIT_DIR=B/.git, `git rev-parse --git-common-dir
--show-toplevel` prints B/.git and A. Restated as intent.

Finding 3 (scrubGitHookEnv is a fifth, strictly weaker routing scrubber) is
deliberately not taken here: cmd/bd/export_auto.go is untouched by this range,
so the hazard is byte-identical at base, and the synthesis scoped it to a
follow-up bead rather than growing this stack.

Each fix is mutation-proved. Reverting isGitTracked reds only the new
TestSecretGitTrackingHonorsInheritedBareWorkTree -- including "refusal = <nil>",
the actual security consequence -- while the incumbent decoy test stays green,
so the pin adds coverage rather than duplicating it. Restoring ToUpper reds
only the new Windows row, showing both directions at once.
TestGuardHookWritePathHonorsInheritedRepository gains a fixture guard asserting
its scrubbed probe fails for a configuration reason rather than exit 1, so a
future fixture change cannot silently make the fallback unreachable.
scrubWorktreeRemovalGitEnvForOS had no test at all before this.

Green locally: ./internal/config, ./internal/execenv, ./internal/gitenv,
./internal/githooksenv, ./internal/gittraceenv, ./internal/metrics, ./scripts,
./internal/beads (the GIT_CONFIG_GLOBAL blast radius neither reviewer ran), and
a blast-radius cmd/bd run over the hooks, worktree, role and uninstall suites.

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

---------

Signed-off-by: Ewen Cuthiell <ewencuthiell@gmail.com>
Co-authored-by: Bee <bee@ghosttrack.com>
Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
Co-authored-by: Julian Knutsen <julianknutsen@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-27 02:00:16 -07:00
Jim Wordelman
6e36c3f19c
ci: raise proxied Dolt cmd test job timeout, add step timeout, refresh shard manifest (#6689)
* ci(proxied-cmd): green — give the proxied-shard job its own step timeout, refresh manifest (refs be-bruke)

The job-level timeout-minutes was the only backstop for the "Test
proxied-server cmd shard" step, and it counts the "Download binaries"
step too — so a slow download alone could exhaust the job budget and
kill an otherwise-healthy shard's test run with no way to tell the two
failure modes apart. Give the test step its own 16m timeout inside the
existing 30m job budget, and regenerate the bin-packed shard manifest
via scripts/ci/gen_proxied_shard_manifest.py so it stays in sync with
the current TestProxiedServer* set (0 drift, all 15 shards fallback:0).

* ci(proxied-cmd): mirror the shard timeouts onto the main lane, regen the manifest at the adoption base

Adoption review of #6689, iteration 1 — three minor findings, applied here
rather than deferred.

main.yml's `test-proxied-cmd` is the same job as pr-risk.yml's twin — same
proxied-test-shard.sh, same manifest, same total 15 — behind a
download/verify step inside a 20m budget with no step timeout, so the exact
ambiguous-timeout failure mode this PR removes from the PR lane survived on
the post-merge lane, which is where triage happens with nobody watching.
Mirror both edits (job 20m -> 30m, step 16m) and record the ordering at the
step, since it is not obvious from the site that 16m is deliberately below
the script's own -test.timeout=15m plus setup.

The manifest's only record of the cost proxy's two known blind spots lived
in a hand-written comment block the regeneration deleted:
TestProxiedServerListSortRetiresTheWalk seeds 1400 rows and walks the
listing three ways off a single init, and TestProxiedServerServeReadParity
is the CLI/HTTP read-parity oracle whose presence in this gate-required lane
is what makes the anti-drift claim enforced. Re-adding prose to a generated
file would just be deleted again, so it moves into the generator's emitted
header.

Base drift since authoring left the refreshed manifest one test stale —
#6584 added TestProxiedServerBackupRefusedOnExternalTopology, which
hash-distributed to shard 14 — so "0 drift, all 15 shards fallback:0" was
already false on the merge base. Benign (unlisted tests hash-distribute and
still run, and drift removed no name, so the strict parser's stale-entry
hard-fail was unreachable), but the stated deliverable did not hold.
Regenerated at the adoption base: 149 of 149 discovered tests listed,
fallback:0 on every shard, peak load unchanged at 39 estimated inits. That
figure is a point-in-time measurement, not an invariant: nothing in CI diffs
the committed manifest against a regeneration, so it re-drifts the moment
the next TestProxiedServer* lands. A freshness step
(`gen_proxied_shard_manifest.py 15 | diff - <manifest>`) on a lane already
triggered by .github/scripts/* would make it one; that is follow-up scope.

Verified: the generator reproduces the committed manifest byte-identically;
BEADS_TEST_SHARD_LIST_ONLY=1 across all 15 shards assigns all 149 discovered
TestProxiedServer* functions exactly once with no duplicates or orphans;
actionlint clean on both workflows.

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

---------

Co-authored-by: Julian Knutsen <julianknutsen@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-26 07:17:03 -07:00
Julian Knutsen
b3d17caa6d Merge release/1.3.0 into main (post-tag forward-port)
Forward-ports the 38 commits that shipped on release/1.3.0 (tagged v1.3.0 at
f45b249ce) into main, as RELEASING.md mandates after a tag. None of them had
ever been forward-ported. Recorded as a merge so main becomes a superset of
the release branch and the lineage is in the history.

Migration ordinal collision (the reason this needed a human-shaped merge):
both branches independently claimed clone-local ignored slot 0026 under
different filenames, so git merged both in with no conflict and left the
series with two migrations at ordinal 26 — a single-integer cursor cannot
address that, and migrationSource.list() panics on it.

Main's ignored/0026_add_wisps_current_revision is renumbered to 0027.
Release's 0026_dep_rekey_dedup_marker is in the shipped v1.3.0 tag, so field
stores have already recorded it at 26 and it can never move; main's twin has
never shipped in any release, so it is the one that is free to move. 0027 was
unused in the ignored series (both sides topped out at 26).

This trips check-migration-hygiene.sh Check C (frozen migrations), which has
no exemption mechanism. That is expected and accepted: breaking the collision
requires a rename, and the ignored series' cursor table is itself dolt-ignored,
so its content hashes are clone-local and never participate in the cross-clone
ContentHashSkew comparison that Check C exists to protect. Main's 0067 body is
deliberately NOT edited for the same reason in reverse — it is main-plane and
its hash IS compared across clones.

Conflicts resolved:

  CHANGELOG.md                       release's finalized [1.3.0] section kept
                                     byte-identical; main's two unreleased
                                     entries (#6023, #5859) moved up under
                                     [Unreleased] where they belong
  cmd/bd/init_safety.go              union — release's added paragraph is
  cmd/bd/init_safety_help.go         accurate against the merged code (three
                                     exit-12 sources, incl. init.go:3147)
  internal/storage/uow/dolt_sql_provider.go
                                     kept main's newProvider refactor AND
                                     release's readOnly field/assertion;
                                     newProvider gained readOnly: opts.readOnly
                                     so release's read-through-refused-migration
                                     behavior survives main's refactor
  .github/workflows/main.yml         single -timeout=30m per release's #6091
  scripts/ci_workflow_test.go        design (flag on the invocation, not in
                                     matrix.test-flags); the shadowed 25m in
                                     matrix.test-flags removed
  scripts/migration-test/lib/versions.sh
                                     union — main's darwin/arm64 corpus plus
                                     release's v1.2.2 linux/amd64 entry
  integrations/beads-mcp/uv.lock     ruff 0.16.5 (release, newer); block is
                                     internally consistent, uv lock --check ok
  default.nix                        vendorHash left at main's value and is
                                     KNOWN STALE — see below

Version stamp lands at 1.3.0 (main had been sitting at the previously-released
1.2.2, this project's between-releases pattern). check-versions.sh: 24/24.

Known follow-up: default.nix vendorHash. The merged go.mod/go.sum is a genuine
union (release's kin-openapi/oapi-codegen bumps + main's newer Dolt stack) and
matches neither side, so neither recorded hash is correct. It must be
regenerated with scripts/update-nix-vendorhash.sh. The repo's automatic fixer
(update-vendor-hash.yml) is dependabot-only and will not run on this PR.
2026-09-15 22:09:13 +00:00
Julian Knutsen
2acf75edc7
ci(pr-core): give the -race lane an explicit 30m go-test timeout (#6091)
cmd/bd has outgrown Go's implicit 10m per-package default. Measured
through this wrapper it takes 572s, leaving under 5% margin, so runner
variance pushes it over: it failed at 600.343s and 600.728s on two
consecutive runs of #6090 while #6038 landed just under.

No single test is responsible, so the timeout panic names whichever test
was in flight and reads like a hang rather than the package running out
of clock.

30m matches every other -race lane in the repo for this same code:
main.yml's integration package and cmd/bd shards, ci-measurements.yml,
and nightly.yml. Splitting or de-slowing cmd/bd is the real fix and
belongs on main; this only stops the clock from being the failure.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-31 00:34:10 -07:00
Julian Knutsen
d530cddfa6
ci: add advisory cyclomatic complexity reporting (#6081)
* ci: add advisory cyclomatic complexity reporting (bd-7g21)

Add a pinned gocyclo report, checked-in baseline, stable-key PR diff, and opt-in guard for shipped Go code. Run the report on every PR as a non-required artifact while maintainers measure signal quality; preserve existing complexity as grandfathered debt.

Agent-Signature: unknown-model/unknown-reasoning

* test(protocol): refresh dependency removal corpus
2026-08-30 19:05:17 -07:00
Julian Knutsen
e7894732e0
fix(ci): make a failed pinned-dolt download actually fail the job (#5935)
* fix(ci): make a failed pinned-dolt download actually fail the job

scripts/ci/install-dolt.sh retried the download with

    if curl -fsSL -o "$workdir/$asset" "$url"; then
      break
    fi
    status=$?

`status=$?` there reads the status of the *if compound*, not of curl. A
compound whose condition fails and which has no else branch is itself
successful, so `status` was 0 on every failed attempt, and the
retries-exhausted branch ran `exit 0`. A download that never succeeded
reported success.

That defeats the entire point of the script. The step goes green, the
version-drift guard at the bottom never runs, and the job proceeds on
whatever `dolt` the runner image already had on PATH -- the unpinned
binary the pin exists to keep out, and the one that made
TestFreshBootstrapHealIncarnation flake when releases/latest moved to
2.3.x.

Capture curl's status directly instead, and include it in the
retries-exhausted message so the log says which failure it was.

Guarded by TestInstallDoltPropagatesDownloadFailure, which runs the real
script against stub curl/sleep/tar/sudo/dolt/uname on PATH. Against the
unfixed script exactly one subtest reddens ("exhausted retries": exit 0,
want 42); "immediate success", "eventual success" and "installed version
drifts" stay green, so the harness demonstrably observes success and the
new signal is specific to this bug rather than to everything failing.

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

* test(ci): pin what install-dolt.sh actually downloads and installs

The review council mutated the script and found two changes the new test
waved through: swapping the pinned release URL for releases/latest, and
installing mode 0644 into /opt/dolt instead of 0755 into /usr/local/bin.
Both are exactly the drift this script exists to prevent, and both left
all four subtests green because the test only counted calls. The sibling
pull_dolt_image_test.go already asserts its docker argv; this one now
does the same for curl and sudo.

The council also flagged the drift guard itself: `[[ $installed !=
*"$version"* ]]` accepts any version containing the pin as a substring,
so 12.2.0 and 2.2.0-rc1 both pass. Compare the version token exactly.

Red before green, by real on-disk swaps (a -overlay cannot reach a file
the test execs):

  releases/latest URL          all 5 subtests red (was: all green)
  install -m 0644 /opt/dolt    4 of 5 red -- exhausted_retries stays
                               green because it never reaches sudo
  substring drift guard        only installed_version_merely_contains
                               _the_pin reddens

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

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-21 16:58:46 -07:00
Julian Knutsen
825cd4c937
fix(ci): pin the Dolt CLI — 2.3.0 broke DOLT_RESET on fresh databases (ga-m0dlk) (#5894)
* fix(dolt): git-remote tests need a sql-server that shares their filesystem

The four git-remote tests that push through the store API fail on every run
of the new test-server-storage-full lane (#5836), which is what has the
merge pipeline stalled: shards 1, 9, 10 and 15 all die with

  the remote: origin 'git+file:///tmp/embedded-git-remote-test-*/remote.git'
  could not be accessed; fatal: ... does not appear to be a git repository

setupEmbeddedGitRemote dates from when this package had an in-process
embedded engine. store.go now hardcodes serverMode:true, so New() connects
to the suite's shared Dolt server — which TestMain runs in a Docker
container whose only mount is the image's own /var/lib/dolt. CALL DOLT_PUSH
executes inside that container, so the host bare repo the test just created
does not exist for it, and neither does the store's own Path (which is why
TestGitRemotePushSkipsUserPrePushHook cannot find its cache mirror and
TestGitRemoteSyncRoundTrip's clone comes up empty). The dolt credential
hints in the log are generic advice, not a credential problem — nothing
here needs a credential.

Give these tests their own local dolt sql-server rooted at the store's data
directory, the arrangement TestGitRemoteExternalServerRouting,
TestSQLRemotePersistsAcrossExternalServerRestart and
TestCredentialCLIRoutingE2E already use. The server is spawned with
doltserver.ServerSpawnEnv(), the same environment bd gives the server it
starts: a `dolt` CLI command run against a directory a sql-server already
serves is proxied to that server, so the git subprocess is spawned by the
server and the CLI-side guards (git tracing, core.hooksPath) only take
effect if the server carries them too.

Two consequences fall out and are fixed here:

  - The setup now takes a genesis CommitAll. Commit() deliberately skips
    config (GH#2455), so issue_prefix stayed dirty forever: Pull() refuses
    to auto-commit a dirty internal config key, and a peer cloning the
    database got no prefix at all. The CLI sibling setupGitRemote has
    always done this with DOLT_COMMIT('-Am', 'Genesis: schema and config').

  - The gate is testutil.RequireDoltBinary rather than skipIfNoDolt: these
    tests no longer need the shared container, only dolt and git, so
    requiring the container would be a skip for no reason.

Setup asserts <Path>/<db>/.dolt exists on this filesystem, so if the store
ever drifts back onto a containerized server these tests fail loudly
instead of quietly testing nothing.

Verified against the real shard script on a live Dolt server: shard 1 goes
from 1 failure to 0, shard 9 from 1 to 0.

* test(dolt): pin what TestCreateIssueAfterPull's Pull actually delivered

Shard 1 still fails in CI after the topology fix, now at the last assertion:
'GetIssue(ai-clone-001) failed: not found'. Deterministic across two CI runs,
not reproducible locally on dolt 2.1.8 or 2.3.1 (the whole shard is green
here). The end-of-test assertion cannot distinguish 'Pull() reported success
but merged nothing' from 'Pull() delivered the row and the post-pull
CreateIssue dropped it', which are different bugs in different places.

Assert immediately after Pull, before the post-pull write, so the CI failure
names which one it is.

* fix(ci): pin the Dolt CLI — 2.3.0 broke DOLT_RESET on fresh databases

Test (Server Dolt Full Suite 12/16) has been failing on a coin flip with

  TestFreshBootstrapHealIncarnation/exact_creator_heals_its_interrupted_bootstrap
  creator-authorized migration: schema migration: pending schema migrations
  alter pre-existing dirty tables: issues; run 'bd dolt commit' ... (#4566)
      schema: fresh-bootstrap reset: Error 1105 (HY000): context canceled

That second line is the whole story, and it is not a beads bug. The heal was
authorized and its capability consumed; what failed is the
CALL DOLT_RESET('--hard') in schema.MigrateUpWithLock. Dolt 2.3.0 regressed
that procedure: roughly one freshly created database in twenty comes up with
it permanently unusable, answering "Error 1105 (HY000): context canceled" to
every session, from any connection, for the life of the server process. It is
not transient and not load-related — a beads-free probe that only does
CREATE DATABASE followed immediately by the procedure reproduces it:

  dolt 2.1.8   0/40 databases broken
  dolt 2.2.0   0/60
  dolt 2.3.0   3/60
  dolt 2.3.1   3/100

Every workflow installed the CLI by piping dolthub/dolt's releases/latest
install.sh, so the binary under test changed the moment 2.3.x shipped —
while internal/testutil/testdoltcommon.go had the sql-server container pinned
at 2.2.0 the whole time. Server-mode tests run both halves at once against the
same databases, so the suite was exercising a Dolt pair no release ever
shipped. Pin the CLI to the container's release and keep the two locked
together:

- scripts/ci/install-dolt.sh installs a pinned Dolt, verifies `dolt version`
  on PATH actually resolves to it, and records the per-version measurements
  and the criterion for raising the pin.
- All 25 install sites across six workflows route through it.
- TestWorkflowsInstallPinnedDolt rejects any reintroduction of
  releases/latest; TestPinnedDoltCLIMatchesContainerImage fails when the CLI
  pin, DoltDockerImage and pull-dolt-image.sh disagree.

The test itself is unchanged in what it asserts. It gains one preflight probe:
before exercising the heal it checks that this server can hard-reset the
database it just created, so a broken Dolt is named as such instead of
surfacing as the generic #4566 refusal — which reads like a beads defect and
sends the reader to "run 'bd dolt commit'", advice that cannot work when the
reset the heal needs is the thing that is broken. On a pristine database the
probe is a no-op, and over 60 fresh databases a successful first reset never
broke a later one.

Verification: 48 runs of the test (6 workers x 8) and two full shard-12 runs
on the pinned 2.2.0, zero failures. Same binary on 2.3.1: 3 of 24 runs still
fail, now in 0.04s with the explicit diagnosis instead of 1s in with the
misleading one.

Beyond this test: bd dolt compact, bd dolt flatten and mergesettle's rollback
all issue DOLT_RESET('--hard'), so they are unreliable for real users on any
Dolt 2.3.x server. That needs an upstream report; pinning CI does not fix it.

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

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-20 20:59:27 -07:00
ecuthiell
1b67d0b1fb
fix(ci): remove recursive Make from lint formatting (#5302) (#5320)
Agent-Signature: codex-gpt-5-unknown-reasoning on behalf of Ewen Cuthiell
2026-08-10 21:43:59 -07:00
Julian Knutsen
cff62bd631
Make the pre-commit lint gate trustworthy, and stop one main-side lint word from reddening every PR (#5538)
* fix(githooks): build golangci-lint with the repo's Go, not golangci-lint's

The pre-commit hook ran `go run golangci-lint@v2.10.1`. For a pkg@version
build the go command honours the TARGET module's toolchain directive, so
GOTOOLCHAIN=auto downgraded to go1.25.12 — and golangci-lint built by
go1.25 refuses this repo's `go 1.26.5` at config load:

    go: github.com/golangci/golangci-lint/v2@v2.10.1 requires go >= 1.25.0; switching to go1.25.12
    Error: can't load config: the Go language version (go1.25) used to build golangci-lint is lower than the targeted Go version (1.26.5)

Every Go commit failed there, so the hook taught six-plus contributors to
reach for --no-verify — the one habit a lint gate must never train.

CI never hit it because actions/setup-go installs the go.mod version and
exports GOTOOLCHAIN=local, so its `go install ...@v2.10.1` compiles the
linter with go1.26.5. Pinning GOTOOLCHAIN to the go directive reproduces
that resolution on any host, including one whose base toolchain is older
than the repo's target (where a bare GOTOOLCHAIN=local would pin the
linter to that older toolchain instead).

Verified on a real staged Go change: red before with the message above,
`0 issues.` after, and still exit 1 on a planted errcheck violation.

Bead: ga-2ltro.13

* ci: lint PRs for what they introduce, sweep the whole tree on main

Both PR lint gates linted the whole tree: the `lint` job left
only-new-issues at its false default, and pr-lint-wrapper ran
`make ci-pr-lint` over ./... . So a single lint word landing on main —
twice this wave, once a prose misspell — turned EVERY open PR red for a
change it did not make, and each author had to either fix someone else's
line or wait.

The tradeoff, recorded beside the job: a pre-existing issue in untouched
code no longer blocks a PR, and because "new" is measured off the diff, a
violation carried in by a MOVE or a rename does. What it buys is that a
main-side word now reds main's own run, where it belongs. main.yml
already runs both jobs unscoped on every push, so whole-tree coverage —
including the GOOS=windows cross-lint — is unchanged; only its blast
radius moves.

The wrapper takes its scope from BD_LINT_NEW_FROM_MERGE_BASE, set only
by pr.yml, so `make ci-pr-lint` run by hand still sweeps the tree. That
makes the local wrapper STRICTER than the PR gate rather than equal to
it, which is what LINTING.md and CI_CLEANUP_PLAN.md said before and no
longer would: both now state the two-lane contract and say the local
run's extra strictness is deliberate. Their freshness markers move with
the workflow and wrapper files they are pinned to.

Bead: ga-uwix0.2

---------

Co-authored-by: Julian Knutsen <ci@beads.test>
2026-08-10 04:55:55 -07:00
Julian Knutsen
06b34deba0
ci: retry Dolt image pulls (bd-m0o1z) (#5228) 2026-08-01 08:18:41 -07:00
CI Bot
f373508dfd merge(bd-ilb): OpenAPI v0 spec, types-only codegen and drift gates 2026-07-31 18:34:34 +00:00
CI Bot
e988fd002d feat(httpapi): OpenAPI v0 spec, types-only codegen, and the drift gates (bd-ilb)
Lands the bd serve wire contract and the machinery that keeps it honest. No
runtime behavior: nothing routes, nothing serves, and no CLI surface changes.

internal/httpapi/spec/openapi.v0.yaml is hand-written and is the source of
truth; internal/httpapi/apigen is generated from it with oapi-codegen
types-only (no server stubs, no router), via a go.mod tool directive so
contributors need no extra install.

The decisions this slice fixes, because they are one-way doors:

- No second wire struct. Issue, IssueWithCounts, IssueDetails and
  IssueWithDependencyMetadata are pinned to the canonical Go types with
  x-go-type, so the generator emits type aliases and the CLI's --json, the
  JSONL interchange and the HTTP bodies all marshal one struct. A hand-written
  Go-to-Go mapping layer would recreate the drift disease this epic exists to
  cure. Guarded by a two-way JSON-tag bijection test, not a round-trip fixture:
  a new omitempty field absent from a fixture round-trips cleanly in both
  directions and proves nothing.
- limit=0 means unlimited, matching the CLI exactly, with defaults 50 (list)
  and 100 (ready) documented as the shared constants. The only exception --
  refusal under --allow-non-loopback -- is in the limit description.
- ready returns IssueWithCounts, not bare Issue.
- Unknown query parameters are rejected with 400 invalid_argument naming the
  parameter in a machine-readable extension member: with types-only codegen the
  decoders are hand-written, and Go's silent-ignore default would WIDEN a
  filtered result set under version skew.
- /v0/beads/issues forces (created_at DESC, id ASC) on every request, and the
  spec documents the deliberate divergence from bd list's priority ordering.
- One RFC 9457 problem+json envelope everywhere, with a frozen code vocabulary
  mapped from the sentinels via errors.Is. 5xx bodies carry a static per-code
  detail; the real error goes only to the log, because driver and dial errors
  routinely embed the DSN.
- Only the status codes the six operations need are documented. Every
  documented status+code pair is permanent wire surface.

Two traps found while building this, both now guarded:

- oapi-codegen v2.6.0 silently drops x-go-type from a component that also
  carries allOf. An allOf-composed IssueWithCounts generated
  "type IssueWithCounts = types.Issue" -- the ready endpoint would have shipped
  with the count fields gone. The pinned schemas therefore repeat their
  property lists, and internal/httpapi/pinning.go turns a regression into a
  build failure.
- context.DeadlineExceeded satisfies net.Error, so a tripped request deadline
  would have mapped to 503 db_unavailable instead of a generic 500.

make api-check is the three-part gate (regenerate, diff-or-fail, spec tests)
and runs from scripts/ci/pr-policy.sh, i.e. in a required PR job -- the Main
workflow is perpetually concurrency-cancelled, so a gate living only there
would be unenforced.

The go.mod diff is the tool directive and its closure. The protocol corpus is
untouched.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-31 08:37:34 +00:00
CI Bot
e2d82a54d7 refactor(list): route both bd list paths through internal/workapi and delete list_filter.go (bd-fv4)
Second half of the extraction. cmd/bd/list_filter.go is gone; the direct
path (list.go), the proxied path (list_proxied_server.go), and the four
other consumers the file had grown (search, search_proxied_server, count,
count_proxied_server, graph_apply) call workapi.BuildListFilter /
LoadStoreListConfig / LoadUOWListConfig / ApplyStatusFilter /
ValidStatusList instead.

listInput now embeds workapi.ListParams rather than copying into it. A
50-field flags -> params mapping would be a silent-swap hazard the compiler
cannot see; embedding makes cmd/bd fill the shared struct directly, so
there is one definition of a list query and nothing to keep in sync. The
CLI-only fields (output format, pager, tree/deps rendering, effectiveLimit,
--repo) stay in listInput, which is why ListParams is a subset and not the
whole thing.

applyStatusFilter and validStatusList are exported rather than kept
unexported as the design sketch had them: search.go, search_proxied_server.go
and graph_apply.go already called them, and leaving them behind in cmd/bd
would have forked the status-parsing rules.

The --limit flag now registers workapi.DefaultListLimit. internal/config's
list.limit viper default keeps its own literal 50 - internal/config cannot
import workapi, because workapi imports internal/config for
GetCustomTypesFromYAML.

Boundary enforcement lands with the package, per the design: a
workapi-frontend-boundary depguard rule denying cobra and net/http under
internal/workapi, and a pr-policy.sh grep for the symbol-level half depguard
cannot express (config.GetDirectoryLabels, os.Getenv). Both were verified to
fail on a deliberate violation and then reverted.

Gates: protocol corpus unchanged (whole cmd/bd/protocol package green with
BEADS_PROTOCOL_REQUIRE_DOLT=1, no testdata diff); TestBuildListFilterGolden
35/35 against the filters recorded from the old builder; TestEmbeddedList
52 subtests and TestProxiedServerList 65 subtests green; count, search and
graph-apply suites green; golangci-lint clean on cmd/bd and internal/workapi
apart from the two pre-existing main.go gosec baselines.

Agent-Signature: claude-code-opus-5-unknown-reasoning on behalf of CI Bot
2026-07-31 06:01:48 +00:00
matt wilkie
46417b5837
ci(lint): cross-lint Windows-tagged Go, fix fmt-check exit status, pin golangci-lint (core of #5075) (#5083)
Closes #4991; extracted from PR #5075 per its review (split-merge). The
full PR bundled this fix with substantial CI toolchain-identity/host-binding
machinery; this commit keeps only the reviewed core:

- scripts/ci/pr-lint.sh: after the native golangci-lint pass, add a second
  pass with GOOS=windows GOARCH=amd64 CGO_ENABLED=0 GOWORK=off (skipped if
  the native target already matches), so files guarded by
  //go:build windows && !cgo get linted.
- Makefile fmt-check: stop swallowing gofmt's own exit status - a gofmt
  failure (not just "found unformatted files") now fails the check.
- Pin golangci-lint-action from version: latest to v2.10.1 in
  .github/workflows/pr.yml and .github/workflows/main.yml, and harden the
  lint invocations with --config=.golangci.yml,
  --modules-download-mode=readonly, and GOWORK=off.

.github/workflows/ci-measurements.yml already pinned golangci-lint to
v2.10.1 via `go install ...@v2.10.1`, so no change was needed there.


Agent-Signature: claude-fable-5-medium on behalf of maphew

Co-authored-by: Ewen Cuthiell <ewencuthiell@gmail.com>
2026-07-26 12:41:18 -07:00
coffeegoddd☕️✨
6389546c56 test(proxied): split the six heaviest suites so shards balance under the timeout
The proxied cmd lane is init-bound: each subtest's bd init runs the full
migration chain, so a shard's wall-time tracks its total init count. The six
heaviest suites (Update 56 inits, Show 47, Create/Close 41, Dep 36, Ready 34)
were each a single top-level function, and a function is the atomic unit of
sharding — so no shard split could pull the worst shard below Update's ~169s
(local), which is what kept brushing the 15m budget on CI.

Split each of the six into 2-3 top-level functions (Update/Show ->3, the rest
->2), balanced by init count, by inserting function boundaries between the
already-independent per-subtest blocks — no test logic moves, every t.Run set
is byte-identical to before. Regenerate the 15-shard manifest by greedily
bin-packing every TestProxiedServer* function by init count
(scripts/ci/gen_proxied_shard_manifest.py); the heaviest shard drops from ~56
to ~31 estimated inits, roughly halving the long pole.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-20 15:55:17 -07:00
Chris Sells
52aea3f7e3 docs: go all-in on Mintlify — delete the Docusaurus site and its machinery
Per the decision record: no parallel run and no cutover PR. Removes
website/ (including the four versioned doc snapshots — current-only
versioning; snapshots remain in git history), deploy-docs.yml,
generate-llms-full.sh (Mintlify serves llms.txt natively), the ci-website
package gate (Makefile target, scripts/ci/website.sh, the package-website
jobs and their aggregate-gate entries in pr.yml/main.yml/release.yml, the
ci-measurements suite, detect-package-gates wiring), and the release-time
docs snapshot flow (snapshot-release-docs.sh, check-docs-version.sh, their
call sites in update-versions.sh/check-versions.sh, RELEASING.md section
rewritten for the Mintlify reality).

Drift machinery now covers exactly the Mintlify artifacts:
check-cli-docs-drift.sh pathspecs/fingerprint, docs-autofix-push.sh
allowlist, and check-doc-flags.sh scans drop the website/llms paths. The
beads-docs skill's generated-content and verification sections updated to
the bd-generic + docsmint pipeline.

NOTE for merge time: if branch protection requires the 'Package Gate
(website)' check by name (rather than the aggregate gate), drop it from
the required checks or PRs will wait forever.

Gates: docsync PASS, generate-cli-docs.sh --check PASS, freshness PASS.
2026-07-12 10:37:17 -07:00
Chris Sells
3198395a32 docs(ci): add Mintlify preview, docsync guard, and broken-links workflow
- mint.sh + make docs-dev: local preview of the docs/ Mintlify site
  (Node 22 handling modeled on the Gas City wrapper).
- test/docsync: Go guard keeping docs/ and docs.json in exact
  correspondence — every nav entry has a file, every page is in the nav
  (tiny stub allowlist for paths released bd binaries print), published
  pages use root-relative extensionless links that resolve, and engdocs/
  plus curated root markdown keep exact GitHub-style paths. Wired into
  make check-docs.
- .github/workflows/docs-mintlify.yml: docsync + baseline-aware
  mint broken-links check on PRs touching docs/**.
- Retire scripts/sync-website-docs.sh and its mirror-drift gate: the six
  mirrored files now live once in the Mintlify site; the committed
  Docusaurus mirrors stay frozen so the parallel-run site keeps building.
- Repoint inbound links to moved docs across README, guides, examples,
  npm-package, plugin resources, and Go comments; add docs/SYNC_CONCEPTS.md
  pointer stub (bd's agent templates print that path). Runtime strings in
  cmd/bd (prime.go, store_factory_nocgo.go, init_git_hooks.go) still print
  old paths — covered by stubs, flagged in the PR.
2026-07-12 10:37:07 -07:00
matt wilkie
cea892d43f
docs: publish community tools on website (#4299)
* docs: publish community tools on website

Mirror docs/COMMUNITY_TOOLS.md into Docusaurus so the Pages build publishes it for the default released docs and unreleased docs without relying on manual copy steps.

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

* docs: publish core support docs on website

Mirror Sync Concepts, Labels, Metadata, Uninstalling, and Antivirus docs into Docusaurus and include them in the default released snapshot and LLM bundle.

Clarify that agent execution and verification metadata are examples of metadata as a schema extension point, not native issue fields.

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

* docs: clarify metadata examples

Replace local verification queue metadata with a tracker round-trip example so public metadata docs show upstream-aligned schema extension patterns.

Agent-Signature: codex-gpt-5.5-high on behalf of matt wilkie
---------
2026-06-03 13:44:47 -07:00
Julian Knutsen
9e8d411f71
Add PR CI wrapper command surface (#4211)
* ci: add PR wrapper command surface

* ci: collect wrapper timing in PR checks

* docs: record initial CI wrapper measurements

* ci: add manual measurement workflow

* ci: allow branch measurement dispatch

* ci: keep measuring independent commands after failures

* docs: record branch-dispatched CI measurement

* ci: keep measuring package suites after failures

* docs: record CI measurement batch

* fix: repair CI-measured test failures

* test: make local Go gates hermetic

* ci: add sharded integration measurement lane

* test: fix internal beads integration TestMain

* docs: record fixed integration shard measurement

* ci: add hybrid integration sharding measurement

* ci: speed up cmd/bd test shard discovery

* ci: add 16-way integration sharding measurement

* ci: measure prebuilt cmd bd sharding

* docs: record prebuilt sharding measurement

* docs: design CI build artifact stage

* docs: record repeat prebuilt integration measurement

* ci: add build artifact stage

* ci: reuse build artifact in linux test lane

* ci: promote main linux integration shards

* ci: gate legacy platform tests to main

* ci: satisfy workflow shell lint

* ci: ignore archived migrations in duplicate check

* ci: add package gate wrappers

* test: clean up testing short boundaries

* ci: allow unreleased version docs lag

* ci: gate releases on package checks

* ci: split workflow by tier

* ci: add aggregate PR gates
2026-05-29 18:52:53 -07:00