Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
test: stop the GBRAIN_PGLITE_SNAPSHOT delete leaking across a unit shard (GBRA-79 G6.6)
garrytanc9a0b7eabb75
diff --git a/.github/workflows/test.yml b/.github/workflows/test.ymlindex d8178c7067..f57a1fe817 100644--- a/.github/workflows/test.yml+++ b/.github/workflows/test.yml@@ -717,12 +717,32 @@ jobs:test/fixtures/pglite-snapshot.versionkey: pglite-snapshot-${{ runner.os }}-${{ hashFiles('src/core/*.ts', 'src/core/audit/redact-connection-info.ts', 'src/core/engine-sql/bootstrap.ts', 'src/core/schema-migrations/**', 'src/core/ai/defaults.ts', 'src/core/company-brain/receipt-schema.ts', 'src/core/entities/resolve.ts', 'src/core/facts/withdrawal-schema.ts', 'src/core/facts/relink-schema.ts', 'src/core/google/*.ts', 'src/core/grants/*.ts', 'src/core/minions/tools/brain-allowlist.ts', 'src/core/ops/contract.ts', 'src/core/page-state/*schema.ts', 'src/core/persistence/*.ts', 'src/core/schema-pack/link-inference.ts', 'src/core/schema-pack/redos-guard.ts', 'src/core/search/alias-normalize.ts', 'src/core/search/private-visibility.ts', 'src/core/search/projection-statistics.ts', 'src/core/search/relational-intent.ts', 'src/core/shared-skills/*schema*.ts', 'src/core/ai/decide/schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts', 'src/core/facts/purge-schema.ts', 'src/core/facts/fts-index.ts', 'src/core/eligibility/generation-schema.ts', 'src/core/trust/schema.ts', 'src/core/trust/tier.ts', 'src/core/trust/allow-rules.ts', 'src/core/write-gate-schema.ts', 'src/core/questions/schema.ts', 'src/core/questions/identity.ts', 'src/core/questions/auto-think-migration.ts', 'src/core/loops/loops-schema.ts', 'src/core/postgres-engine/schema-lock-timeout.ts') }}- run: bun install --frozen-lockfile+ # Runner diagnostics (GBRA-79), before and after the shard: cores, load,+ # cumulative steal jiffies and the CPU model. A shard far above its+ # predicted weight (test-shard.sh prints it) with high steal or a+ # different model name is a slow or silently downgraded runner draw,+ # not a test regression; the same shard at low steal is the tests.+ - name: Runner diagnostics (before shard)+ shell: bash+ run: |+ echo "nproc: $(nproc)"+ echo "loadavg: $(cat /proc/loadavg)"+ awk '/^cpu /{print "steal_jiffies", $9}' /proc/stat+ lscpu | grep -m1 'Model name'- name: Run test shard ${{ matrix.shard }}/8shell: bashrun: bun scripts/capture-test-log.ts --job 'test (${{ matrix.shard }})' --out "$RUNNER_TEMP/unit.log" -- bash scripts/test-shard.sh ${{ matrix.shard }} 8env:COVERAGE_DIR: ${{ runner.temp }}/coverageGBRAIN_TEST_RECEIPT_DIR: ${{ runner.temp }}/receipts+ - name: Runner diagnostics (after shard)+ if: always()+ shell: bash+ run: |+ echo "nproc: $(nproc)"+ echo "loadavg: $(cat /proc/loadavg)"+ awk '/^cpu /{print "steal_jiffies", $9}' /proc/stat+ lscpu | grep -m1 'Model name'- name: Upload receiptsif: always()uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 9fa7fc2345..4b0d57e62a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,19 @@ credits are retained; no result has been reassigned to another provider. Originaidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).+## [0.60.183.0] - 2026-10-12++**CI only: three test files stopped turning off the PGLite schema snapshot for every file that ran after them, which was making unit shards cross the 22-minute timeout on an ordinary slow runner. Nothing in gbrain itself changes.**++`test/bootstrap.test.ts`, `test/destructive-guard.test.ts` and `test/schema-bootstrap-coverage.test.ts` test the cold `initSchema()` path, so each deleted `process.env.GBRAIN_PGLITE_SNAPSHOT` at module scope. The `Test` workflow runs a whole unit shard (393 to 489 files) in one `bun test` process (`scripts/test-shard.sh`, one `xargs` batch, which coverage and the executed-test receipts require), so the deletion outlived the file: every in-memory PGLite engine in every later file of that shard skipped the snapshot restore and replayed the full schema instead (`src/core/pglite-engine.ts` takes the cold path whenever the variable is unset), about 3 s per engine and about +350 s per poisoned shard. A poisoned shard at the matrix's worst file composition plus the ordinary 1.35x runner draw seen across 322 shard jobs crosses the 22-minute `timeout-minutes` while every test is still passing, and `test-status` reads the cancellation as a failure. Forced probe on this machine, snapshot active: `bun test ./test/bootstrap.test.ts ./test/graduation-copy.test.ts` ran `graduation-copy` in about 36 s (8.9 s alone) and a trailing probe file saw the variable undefined; after the fix 7.6 s and the variable intact. Behind `destructive-guard`, `wanted-links` went from about 22 s to 7.3 s (8.0 s alone); behind `schema-bootstrap-coverage`, `graduation-copy` from about 35 s to 8.0 s. The 22-minute timeout is unchanged: the post-fix worst composition is the predicted shard weight of about 804 s, times the observed 1.35x maximum runner draw, plus 25 s of setup, about 18.5 min. The committed weights were mined from poisoned runs; GBRA-83 re-mines them from a post-fix run.++### Itemized changes++- The three files save the variable and delete it in `beforeAll` and restore the saved value in `afterAll` (deleting it again when it was unset), so their own tests still run cold and the next file in the process gets the snapshot back. Bun runs the matrix's files one after another in the process, so the `afterAll` restore is enough.+- `scripts/check-test-env-opt-ins.ts` (`check:test-env-opt-ins`, in `verify`) gains the rule `test_env_snapshot_module_scope`: a `delete` of or assignment to `process.env.GBRAIN_PGLITE_SNAPSHOT` outside every function body, in any file the unit matrix loads, fails with Why and Fix text naming the one-process shard runner and the `beforeAll` / `afterAll` shape (or `test/helpers/with-snapshot.ts` per test). `*.serial.test.ts` and `test/e2e/` files run in their own process and `*-preload.ts` files are process-wide by design, so they are exempt. Fixtures `bad-snapshot-leak` and `bad-snapshot-assign` fail and the `good` tree passes under `scripts/guard-self-test.sh`; the guard failed on the pre-fix tree at the three files' exact lines before the hooks landed. Pinned by `test/scripts/test-env-opt-ins-guard.test.ts`.+- `scripts/test-shard.sh` prints the shard's predicted weight beside its `(LPT-balanced)` line, from the new read-only `bun run scripts/sharding.ts --sum` (the same per-file weights and p75 fallback the partition used; `scripts/test-weights.json` is not edited; `test/scripts/sharding.test.ts` pins the sum and the CLI line). The `test` job of `.github/workflows/test.yml` prints `nproc`, `/proc/loadavg`, the cumulative steal jiffies from `/proc/stat` and the CPU model name before the shard and again after it (`if: always()`), so a shard far above its prediction can be read as a slow or silently downgraded runner draw rather than a test regression.+- Docs: `docs/TESTING.md` (snapshot helpers, CI matrix line), `docs/architecture/key-files/ci-health-and-test-guards.md`, `docs/architecture/key-files/tooling-and-tests.md`, `scripts/guards-manifest.tsv`.+## [0.60.182.0] - 2026-10-12**Image pages on a managed multimodal brain get their image vector (#6529).** With `GBRAIN_EMBEDDING_MULTIMODAL=true`, a managed `gbrain sync` now imports image files through the coordinated image importer instead of holding every one as `managed_image_sync_unsupported`, so the page is created with its OCR text, its image vector and its `source_path` in the same publication; holds from earlier syncs are re-screened and imported on the next `gbrain sync --source <id> --no-pull`. `gbrain embed --stale --images` works on a managed brain (it used to be refused by the legacy writer), finds the image pages whose `source_path` was never recorded through their slug, and a plain `gbrain embed --stale` runs that sweep first on a multimodal install. Doctor's new `image_embedding_coverage` check reports the image pages search cannot see, which `embed_coverage_pct` counted as embedded. No migration; the image vector and OCR text are the paid calls the importer already made for `gbrain import`, now also made at sync and sweep time. Image pages whose file is no longer in the checkout are not re-imported: every sweep names the first path it tried, and the explicit `--images` sweep exits non-zero when it could rebuild nothing.diff --git a/docs/TESTING.md b/docs/TESTING.mdindex 6046db371c..6697a4f5d2 100644--- a/docs/TESTING.md+++ b/docs/TESTING.md@@ -576,12 +576,13 @@ replaying the embedded schema + all migrations when the env var`run-unit-parallel.sh`, `test-shard.sh`, `run-slow-tests.sh`,`run-serial-tests.sh`, `run-verify-parallel.sh`, and `run-e2e.sh` (whichre-exports the path as ABSOLUTE — its tests spawn CLI children with varying-cwd); `scripts/ci-local.sh` calls the builder directly. The helper builds/refreshes the snapshot and-exports the env var, no-ops on `GBRAIN_NO_SNAPSHOT=1` or an already-inherited-path, and is non-fatal on build failure — tests fall back to cold init, with-a one-line "active" echo so a silent fallback stays visible in CI logs.-Measured effect: ~3.5x per PGLite-booting file (a cold boot replays every-migration, ~3.1s each on a CI shard). Properties:+cwd); `scripts/ci-local.sh` calls the builder directly. The helper builds or+refreshes the snapshot and exports the env var, no-ops on+`GBRAIN_NO_SNAPSHOT=1` or an inherited path, and is non-fatal on build+failure: tests fall back to cold init, with a one-line "active" echo so a+silent fallback stays visible in CI logs. Measured effect: ~3.5x per+PGLite-booting file (a cold boot replays every migration, ~3.1s each in CI).+Properties:- **Idempotent.** A hash short-circuit exits in ~40ms when the snapshot isfresh, and REBUILDS a stale one. The hash covers the raw file bytes of the@@ -1260,29 +1261,27 @@ there even though they pass on Linux and macOS.### CI vs local: intentionally divergent file sets-- **CI matrix** (`.github/workflows/test.yml`) runs `scripts/test-shard.sh` across 8 shards partitioned by weight-aware LPT bin-packing (`scripts/sharding.ts`; unweighted files get the p75 weight) and includes `*.slow.test.ts` files without a dedicated job (`eval-longmemeval-e2e.slow.test.ts` runs inside the shards; entity-resolve-perf, entity-card-perf, export-scale and brainbench-e2e have dedicated jobs, and the `reconcile-crash-*.slow.test.ts` files runs only in persistence-validation) plus keyless-allowlisted `evals/**/*.test.ts` (`test/scripts/evals-collection.test.ts`). Shards keep planned file order (`test-shard.sh --dry-run-list <i> 8`). Every Bun job activates the PGLite schema snapshot (built in-runner, cached across jobs with the runner's hash check authoritative). Serial files run across four `serial-tests` workers via `bun run test:serial`; `verify` and the BrainBench memory-conformance gate (`scripts/ci-brainbench-gate.sh`, compared against `evals/brainbench/baselines/main.json`) have their own jobs, all aggregated by `test-status`. `e2e.yml` aggregates through `e2e-status`, with jsonb-parity gating Tier 2's token spend; scheduled runs also require the full-corpus lanes. Both aggregates reject failures, cancellations and unexpected skips, and successful test results are never reused. CI is the ground truth for "did everything pass."+- **CI matrix** (`.github/workflows/test.yml`) runs `scripts/test-shard.sh` across 8 shards partitioned by weight-aware LPT bin-packing (`scripts/sharding.ts`; unweighted files get the p75 weight) and includes `*.slow.test.ts` files without a dedicated job (`eval-longmemeval-e2e.slow.test.ts` runs inside the shards; entity-resolve-perf, entity-card-perf, export-scale and brainbench-e2e have dedicated jobs, and the `reconcile-crash-*.slow.test.ts` files runs only in persistence-validation) plus keyless-allowlisted `evals/**/*.test.ts` (`test/scripts/evals-collection.test.ts`). Shards keep planned file order (`test-shard.sh --dry-run-list <i> 8`) and print their predicted weight (`sharding.ts --sum`). Every Bun job activates the PGLite schema snapshot (built in-runner, cached across jobs; the runner's hash check is authoritative). Serial files run across four `serial-tests` workers via `bun run test:serial`; `verify` and the BrainBench memory-conformance gate (`scripts/ci-brainbench-gate.sh`, compared against `evals/brainbench/baselines/main.json`) have their own jobs, all aggregated by `test-status`. `e2e.yml` aggregates through `e2e-status`, with jsonb-parity gating Tier 2's token spend; scheduled runs also require the full-corpus lanes. Both aggregates reject failures, cancellations and unexpected skips, and successful test results are never reused. CI is the ground truth for "did everything pass."- **Local fast loop** (`scripts/run-unit-shard.sh` via the parallel wrapper) uses the same weighted partitioner as CI and EXCLUDES `*.slow.test.ts` AND `*.serial.test.ts`. Each shard runs its complete ordered selection with a fresh Bun process per file, without adding workers. Later groups still run after failures; missing summaries or file-completion evidence fail the shard. Local trades coverage for inner-loop speed; CI catches what local skips.-This divergence is intentional; the two scripts solve different problems.`test/scripts/run-unit-shard.test.ts` pins what the local loop includes, andthat no unit file spawning the CLI through `test/helpers/cli-spawn.ts` pins aper-test timeout below the bunfig default (an explicit `test(name, fn, N)`overrides `--timeout`, so `GBRAIN_TEST_TIMEOUT_MULTIPLIER` never reaches it).`test/scripts/run-unit-parallel.test.ts` pins memory-adaptive concurrency, the-rescue pass and operator-interrupt teardown (Ctrl-C kills every shard-descendant).+rescue pass and operator-interrupt teardown (Ctrl-C kills every descendant).### Coverage lanes and gatesLine coverage is opt-in via `COVERAGE_DIR`: when set, the shell lanes(`scripts/test-shard.sh`, `scripts/run-serial-tests.sh`, `scripts/run-e2e.sh`)-pass `--coverage --coverage-reporter=lcov` to Bun; when unset, the exec line is-byte-identical to a non-coverage run. Every Bun process gets its own coverage+pass `--coverage --coverage-reporter=lcov` to Bun; when unset, the exec line+matches a non-coverage run. Every Bun process gets its own coveragedirectory (`$COVERAGE_DIR/shard`, `serial-$idx`, `e2e-$idx`) because a reuseddirectory silently overwrites `lcov.info`; the shard runner pins xargs to onebatch so an argv overflow fails loudly. Each coverage invocation atomicallycreates its own `COVERAGE_DIR` and refuses an existing one, so a rerun needs a-new path and cannot inherit or delete another run's output. A green lane writes+new path and cannot inherit another run's output. A green lane writes`$COVERAGE_DIR/lane-manifest.json` (`{lane, sha, lcovCount, complete}`); a redrun writes none, which merging treats as an incomplete lane. E2E lanes(`e2e-1` to `e2e-4`, or `e2e` unsharded) also write `executed-files.txt`, and@@ -1540,15 +1539,17 @@ consumer suites:- `wait-for.ts` — `waitFor(predicate, {timeoutMs, intervalMs})` /`waitForValue`. Replaces fixed `setTimeout` sleeps: polls resolve as soon asthe condition holds, and generous deadlines make slow-CI runs LESS flaky- than a tuned sleep, not more.+ than a tuned sleep.- `with-snapshot.ts` — `withColdPglite(fn)`: per-TEST scoped`GBRAIN_PGLITE_SNAPSHOT` opt-out (save/delete/restore);`withSnapshotValue(value, fn)` is the general form (pin any snapshot path- for fn's scope; `undefined` = deleted). Use instead of a- file-level `delete process.env.GBRAIN_PGLITE_SNAPSHOT`, which forces every- engine in the file to cold-boot. Caution: a snapshot-restored engine does- not replay migrations on a later `initSchema()` after a version rewind —- rewind-arc tests need the cold path (see `test/bootstrap.test.ts`).+ for fn's scope; `undefined` = deleted). A module-scope+ `delete process.env.GBRAIN_PGLITE_SNAPSHOT` fails `check:test-env-opt-ins`+ (the shard's one bun process keeps it for later files); a file-wide+ opt-out deletes in `beforeAll`, restores in `afterAll`+ (`test/bootstrap.test.ts`). Caution: a snapshot-restored engine does not+ replay migrations on a later `initSchema()` after a version rewind —+ rewind-arc tests need the cold path.- `reset-pglite.ts#resetPgliteStateNarrow(engine, tables)` — explicit-tabletruncate for hot loops (the full reset clears the whole catalog). Thetable list is REQUIRED — a default would silently under-truncate.diff --git a/docs/architecture/key-files/ci-health-and-test-guards.md b/docs/architecture/key-files/ci-health-and-test-guards.mdindex cfb160c6bd..2b964da46a 100644--- a/docs/architecture/key-files/ci-health-and-test-guards.md+++ b/docs/architecture/key-files/ci-health-and-test-guards.md@@ -16,7 +16,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `scripts/ci-dependency-audit.sh` — runs `bun audit` for the root and `admin/` lockfiles. It blocks (`BLOCKING=true`) on pushes, schedules and dispatches, on lockfile, `patches/` or dependency-field changes, with the `dependency-audit` label, or when the diff cannot be read; elsewhere an advisory is a `::warning::` naming why the run does not block.- `scripts/e2e-provider-key-notice.sh` — e2e.yml's visible-skip step: when `OPENAI_API_KEY` or `ANTHROPIC_API_KEY` is empty, prints a `::warning::` and step-summary line naming the empty secret and the owner-only fix, so a green keyless run is never read as keyed coverage. Exits 0 always.- `scripts/scale/watchdog.ts` — out-of-process phase watchdog for the scale harness. `scripts/scale/run.ts` re-runs itself as a child; the supervisor times the `import`, `extract`, `vectors` and `budgets` phases from the child's `[scale] phase <name> start` lines and kills the child's process group at 1.5x the phase's gate ceiling (`scripts/scale/gates.ts` `phaseLimitsMs`), names the phase, elapsed time and last progress line, then removes the brain home and scale database. `GBRAIN_SCALE_PHASE_LIMIT_MS_<PHASE>` overrides one limit; `GBRAIN_SCALE_SUPERVISED` is the internal handshake. Tests: `test/scripts/scale-watchdog.test.ts`.-- `scripts/check-test-env-opt-ins.ts` + `test/helpers/operator-env-policy.ts` — the opt-in naming rule. The policy (`STRIP_PREFIX`, `KEEP_EXACT`, `KEEP_PREFIX`, `RENAMED`, `isStripped`) is shared by `test/helpers/operator-env-preload.ts`, which deletes stripped `GBRAIN_*` names before any test loads and stops the run with the rename command when an old opt-in name is set, and by the guard (`check:test-env-opt-ins`, in `verify`), which parses test files and fails on a test that gates execution on a stripped name. Test opt-ins are `GBRAIN_TEST_<AREA>_<WHAT>`, paid ones `GBRAIN_TEST_LIVE_<WHAT>`. Tests: `test/scripts/test-env-opt-ins-guard.test.ts`, `test/operator-env-preload.test.ts`.+- `scripts/check-test-env-opt-ins.ts` + `test/helpers/operator-env-policy.ts` — the opt-in naming rule. The policy (`STRIP_PREFIX`, `KEEP_EXACT`, `KEEP_PREFIX`, `RENAMED`, `isStripped`) is shared by `test/helpers/operator-env-preload.ts`, which deletes stripped `GBRAIN_*` names before any test loads and stops the run with the rename command when an old opt-in name is set, and by the guard (`check:test-env-opt-ins`, in `verify`), which parses test files and fails on a test that gates execution on a stripped name. Test opt-ins are `GBRAIN_TEST_<AREA>_<WHAT>`, paid ones `GBRAIN_TEST_LIVE_<WHAT>`. The same guard fails `test_env_snapshot_module_scope`: a `delete` of or assignment to `process.env.GBRAIN_PGLITE_SNAPSHOT` outside every function body in a file the unit matrix loads (`*.serial.test.ts`, `test/e2e/` and `*-preload.ts` are exempt: own process, or process-wide by design). `scripts/test-shard.sh` runs a whole shard in one bun process, so such a change persists for every later file and each of their PGLite engines cold-boots (~3 s); the accepted shape is save+delete in `beforeAll`, restore in `afterAll`, or `test/helpers/with-snapshot.ts` per test. Tests: `test/scripts/test-env-opt-ins-guard.test.ts`, `test/operator-env-preload.test.ts`.- `scripts/check-postgres-lane-coverage.ts` — `check:postgres-lanes` (in `verify`). TypeScript-AST scan of every `test/` file outside `test/e2e/` and `test/fixtures/` for a `DATABASE_URL`-gated PostgreSQL arm (zero-argument `testBackends()`, or a `DATABASE_URL` read used as a condition, connection argument or `database_url` value; `withEnv`-supplied URLs excluded) and a lane that runs it (a workflow step with `DATABASE_URL` naming the file, a `test/e2e/` importer, a `tests/heavy/` script, or a `scripts/e2e-backend-matrix.txt` row). `ALLOWLIST` rows name a reason and TODO; stale rows fail. A `test/postgres-unit-arms.txt` row is a lane; a malformed, duplicate, unsorted, missing-file or arm-less row fails (`postgres_arm_list_invalid`, `postgres_arm_list_stale`). `postgresArm`, `postgresLanes` and `armedFiles` are exported for the stress runner. Tests: `test/scripts/postgres-lane-coverage.test.ts`.- `test/postgres-unit-arms.txt` + `scripts/postgres-unit-arms.ts` + `scripts/postgres-arm-weights.json` — the one list of unit-lane files whose PostgreSQL arm has no other owner (sorted, one path per line, `#` comments). Read by persistence-validation.yml's `unit-postgres-arms` job (`shard <n> <m>`: LPT over the mined per-file weights, p75 fallback; one Bun process per file), the scheduled race hunt and the lane guard. `mine <job.log>…` rewrites the weights from a green run's shard logs (`##[group]<file>` to the next group or endgroup). Tests: `test/scripts/postgres-unit-arms.test.ts`.- `scripts/serial-files.tsv` + `scripts/lib/serial-manifest.ts` — the serial manifest: every `*.serial.test.ts` outside `test/e2e/` with its class (`R1`, `R2`, `global-state`, `exclusive`) and a reason. `checkSerialManifest` (pure) requires the manifest to match the tree exactly, classes to match what the file does (env mutation, `mock.module`, `EXCLUSIVE_FILES`) and reasons to be specific; each failure prints Why/Fix/Docs with `bash scripts/check-test-isolation.sh --as-parallel <file>` as the first step. Tests: `test/scripts/serial-files.test.ts`.diff --git a/docs/architecture/key-files/tooling-and-tests.md b/docs/architecture/key-files/tooling-and-tests.mdindex 48a74ed8f1..d26f93d0eb 100644--- a/docs/architecture/key-files/tooling-and-tests.md+++ b/docs/architecture/key-files/tooling-and-tests.md@@ -80,7 +80,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `scripts/select-e2e.ts` + `scripts/ci-changed-files.sh` + `scripts/ci-doc-checks.sh` — E2E selection. `select-e2e.ts` classifies the changed files (git: committed `origin/master...HEAD`, working tree and untracked-unignored files; or `--changed-files <path|->`) as EMPTY / DOC_ONLY / SRC: DOC_ONLY (root `*.md`, `docs/`, LICENSE, VERSION) selects nothing, everything else selects every `test/e2e/*.test.ts` and prints "E2E narrowing is retired" (a diff map selected all files on 40 of 40 merged PRs). `ci-changed-files.sh` lists a PR's or merge-group entry's files from the GitHub API for `prepare-e2e` and exits 1 on a capped (3000 PR / 300 compare), short or failed list or with no PR context, so the workflow falls back to the whole corpus. `ci-doc-checks.sh` is the doc-only gate `ci:local:diff` and `ci:ubicloud:diff` run (llms freshness, `check:doc-history`, `test/docs-repo-paths.test.ts`, skill refs, privacy guards). Tests: `test/select-e2e.test.ts`, `test/scripts/e2e-wiring.test.ts`, `test/scripts/ci-local-rendering.test.ts`.-- `scripts/sharding.ts` + `scripts/mine-shard-weights.ts` + `scripts/capture-test-log.ts` — shared deterministic weighted partitioning and timing refresh. CLI accepts lane-specific weights; missing entries use p75, equal loads prefer fewer files then shard index, and serial may explicitly opt into warning/fallback on bad advisory weights. `weights:mine --lane unit|serial|e2e` validates completed lane logs before replacement and records run/commit/unit metadata. A GitHub refresh reads one job at a time (a whole-run `gh run view --log` is refused above gh's job cap): unit from each shard's `timings-unit-N` capture artifact, which must record one capture start and a final `complete exit=0`; serial from `gh run view --job <id> --log`. E2E defaults to merging selected-job observations; explicit `--e2e-profile full --run ID` requires a successful source-matched run, pins its attempt/job IDs, resolves basename headers against committed default discovery including the outside-directory parity entry, and replaces the map only after exact disjoint corpus validation. Metadata retains log/corpus hashes; file/stdin sources cannot claim full-profile provenance. Capture preserves stdout/stderr, records timestamped GitHub-format artifacts, forwards cancellation to its owned process group and marks failed runs unmineable. On a failed run under Actions it appends the last 50 failures to the step summary: file, test, backend arm, the first error block and a reproduction command (or the last log lines when no `(fail)` line was printed). Unit and E2E artifact retention is 14 days. `scripts/check-weight-coverage.ts` (`check:weight-coverage`, in verify) fails on a unit/serial/E2E/Ubicloud weight entry naming a missing file and on an unweighted lane share above 5% (unit) or 10% (serial, E2E) only when `GITHUB_EVENT_NAME=schedule`; otherwise the share warns (stdout + step summary) with the lane's miner command. Tests: `test/scripts/check-weight-coverage.test.ts` plus guard self-test fixtures.+- `scripts/sharding.ts` + `scripts/mine-shard-weights.ts` + `scripts/capture-test-log.ts` — shared deterministic weighted partitioning and timing refresh. CLI accepts lane-specific weights; missing entries use p75, equal loads prefer fewer files then shard index, and serial may explicitly opt into warning/fallback on bad advisory weights. `--sum` reads a shard's file list and prints its predicted weight (test-shard.sh prints it beside the `(LPT-balanced)` line; test.yml's unit job prints nproc, loadavg, steal jiffies and the CPU model before and after the shard, so a slow draw is told apart from slow tests). `weights:mine --lane unit|serial|e2e` validates completed lane logs before replacement and records run/commit/unit metadata. A GitHub refresh reads one job at a time (a whole-run `gh run view --log` is refused above gh's job cap): unit from each shard's `timings-unit-N` capture artifact, which must record one capture start and a final `complete exit=0`; serial from `gh run view --job <id> --log`. E2E defaults to merging selected-job observations; explicit `--e2e-profile full --run ID` requires a successful source-matched run, pins its attempt/job IDs, resolves basename headers against committed default discovery including the outside-directory parity entry, and replaces the map only after exact disjoint corpus validation. Metadata retains log/corpus hashes; file/stdin sources cannot claim full-profile provenance. Capture preserves stdout/stderr, records timestamped GitHub-format artifacts, forwards cancellation to its owned process group and marks failed runs unmineable. On a failed run under Actions it appends the last 50 failures to the step summary: file, test, backend arm, the first error block and a reproduction command (or the last log lines when no `(fail)` line was printed). Unit and E2E artifact retention is 14 days. `scripts/check-weight-coverage.ts` (`check:weight-coverage`, in verify) fails on a unit/serial/E2E/Ubicloud weight entry naming a missing file and on an unweighted lane share above 5% (unit) or 10% (serial, E2E) only when `GITHUB_EVENT_NAME=schedule`; otherwise the share warns (stdout + step summary) with the lane's miner command. Tests: `test/scripts/check-weight-coverage.test.ts` plus guard self-test fixtures.- `test/e2e/codex-plugin-install-real.serial.test.ts` + `test/e2e/claude-plugin-install-real.serial.test.ts` — the plugin doors: clean-tree staging (`git archive HEAD`), real marketplace add/plugin add, snapshot + exec-bit + non-root-mcp.json pins, tools/list starter-surface oracle, cold-home fast-fail, --source-guard block/allow, coexistence + removal probes, auth-gated SMOKE turns. CI: the `plugin-doors` job in heavy-tests.yml (pinned binary provisioning + expected-pass-count refuse-green).diff --git a/scripts/check-test-env-opt-ins.ts b/scripts/check-test-env-opt-ins.tsindex 4adaabaf35..f4dcdbd818 100644--- a/scripts/check-test-env-opt-ins.ts+++ b/scripts/check-test-env-opt-ins.ts@@ -17,6 +17,19 @@* The policy (keep-lists, RENAMED map, naming rule) is imported from* test/helpers/operator-env-policy.ts, the module the preload applies.*+ * Second rule (GBRA-79): a file the unit matrix loads (anything scanned that+ * is not `*.serial.test.ts`, not under test/e2e/ and not a `*-preload.ts`)+ * must not delete or assign `process.env.GBRAIN_PGLITE_SNAPSHOT` at module+ * scope. scripts/test-shard.sh runs a whole unit shard (hundreds of files) in+ * ONE bun process, so a module-scope delete persists for every later file in+ * the shard and each of their in-memory PGLite engines falls back to a cold+ * initSchema() (~3 s): three such files cost ≈ +350 s per poisoned shard and+ * pushed shards past the 22-minute job timeout. Serial and E2E files get a+ * process per file, and a preload is process-wide by design+ * (operator-env-preload.ts honours GBRAIN_NO_SNAPSHOT=1 there). The accepted+ * shape is a beforeAll that saves and deletes the value and an afterAll that+ * restores it (or test/helpers/with-snapshot.ts per test).+ ** Seam: GBRAIN_GUARD_ROOT (fixture tree root).*/import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';@@ -30,6 +43,8 @@ const SCAN_DIRS = ['test', 'evals'];const SKIP_DIRS = new Set(['node_modules', 'guards']);const GATE_CALLS = new Set(['skipIf', 'if', 'todoIf', 'runIf']);const TEST_CALL = /^(describe|test|it)(\.(skip|todo|only|if|skipIf))?$/;+const SNAPSHOT_ENV = 'GBRAIN_PGLITE_SNAPSHOT';+const OWN_PROCESS_FILE = /(\.serial\.test\.ts$|-preload\.ts$|(^|\/)test\/e2e\/)/;function tsFiles(dir: string): string[] {if (!existsSync(dir)) return [];@@ -72,6 +87,14 @@ const isAssignmentTarget = (node: ts.Node): boolean => {&& parent.operatorToken.kind <= ts.SyntaxKind.LastAssignment;};+/** Whether `node` sits outside every function body: evaluated once, at module load. */+const atModuleScope = (node: ts.Node): boolean => {+ for (let cur = node.parent; cur; cur = cur.parent) {+ if (ts.isFunctionLike(cur)) return false;+ }+ return true;+};+const contains = (outer: ts.Node | undefined, inner: ts.Node): boolean =>!!outer && inner.pos >= outer.pos && inner.end <= outer.end;@@ -163,29 +186,39 @@ const isDeclarationName = (node: ts.Identifier): boolean => {&& parent.name === node;};-interface Finding { file: string; line: number; name: string }+type Kind = 'stripped' | 'snapshot_module_scope';+interface Finding { kind: Kind; file: string; line: number; name: string; verb?: string }function scanFile(path: string): Finding[] {const text = readFileSync(path, 'utf8');if (!text.includes('GBRAIN_')) return [];const sf = ts.createSourceFile(path, text, ts.ScriptTarget.Latest, true);+ const file = relative(ROOT, path);+ const matrixFile = !OWN_PROCESS_FILE.test(file);const assigned = new Set<string>();const reads: Array<{ node: ts.Node; name: string }> = [];+ const findings: Finding[] = [];+ const lineOf = (node: ts.Node): number => sf.getLineAndCharacterOfPosition(node.getStart(sf)).line + 1;const visit = (node: ts.Node): void => {const name = envName(node);if (name && name.startsWith('GBRAIN_')) {- if (isAssignmentTarget(node)) assigned.add(name);- else reads.push({ node, name });+ if (isAssignmentTarget(node)) {+ assigned.add(name);+ if (matrixFile && name === SNAPSHOT_ENV && atModuleScope(node)) {+ const verb = ts.isDeleteExpression(node.parent) ? 'deletes' : 'assigns';+ findings.push({ kind: 'snapshot_module_scope', file, line: lineOf(node), name, verb });+ }+ } else {+ reads.push({ node, name });+ }}ts.forEachChild(node, visit);};visit(sf);- const findings: Finding[] = [];for (const { node, name } of reads) {if (!isStripped(name) || assigned.has(name) || PRODUCT.has(name)) continue;if (!gates(node, sf, new Set())) continue;- const line = sf.getLineAndCharacterOfPosition(node.getStart(sf)).line + 1;- findings.push({ file: relative(ROOT, path), line, name });+ findings.push({ kind: 'stripped', file, line: lineOf(node), name });}return findings;}@@ -201,13 +234,24 @@ function productNames(): Set<string> {const PRODUCT = productNames();const findings = SCAN_DIRS.flatMap(dir => tsFiles(join(ROOT, dir))).flatMap(scanFile);if (findings.length === 0) {- console.log('✓ test env opt-ins: no test gates execution on a GBRAIN_* name the operator-env scrub strips');+ console.log('✓ test env opt-ins: no test gates execution on a GBRAIN_* name the operator-env scrub strips; no matrix file changes GBRAIN_PGLITE_SNAPSHOT at module scope');process.exit(0);}-for (const f of findings) {- console.error(`FAIL [test_env_opt_in_stripped]: ${f.file}:${f.line} gates execution on ${f.name}, which the operator-env scrub deletes before tests run, so this gate can never fire.`);+const stripped = findings.filter(f => f.kind === 'stripped');+const leaks = findings.filter(f => f.kind === 'snapshot_module_scope');+if (stripped.length > 0) {+ for (const f of stripped) {+ console.error(`FAIL [test_env_opt_in_stripped]: ${f.file}:${f.line} gates execution on ${f.name}, which the operator-env scrub deletes before tests run, so this gate can never fire.`);+ }+ console.error('Why: test/helpers/operator-env-preload.ts strips every GBRAIN_* name outside its keep-lists (test/helpers/operator-env-policy.ts); an opt-in under such a name is a silent skip.');+ console.error('Fix: rename the opt-in to GBRAIN_TEST_<AREA>_<WHAT> (paid: GBRAIN_TEST_LIVE_<WHAT>) and add the old name to RENAMED in test/helpers/operator-env-policy.ts, or add a KEEP_EXACT row there with its reason. GBRAIN_TEST_KEEP_AMBIENT_ENV=1 disables the scrub for local debugging only.');+}+if (leaks.length > 0) {+ for (const f of leaks) {+ console.error(`FAIL [test_env_snapshot_module_scope]: ${f.file}:${f.line} ${f.verb} process.env.${f.name} at module scope, which leaks into every later test file in the same bun process.`);+ }+ console.error('Why: scripts/test-shard.sh runs a whole unit shard (hundreds of files) in ONE bun process, so a module-scope change to GBRAIN_PGLITE_SNAPSHOT persists for every file after this one and each of their in-memory PGLite engines cold-boots initSchema() (~3 s each, about +350 s per poisoned shard) instead of restoring the snapshot; *.serial.test.ts and test/e2e/ files get their own process and *-preload.ts files are process-wide by design, so those are exempt.');+ console.error('Fix: move the change into hooks: beforeAll saves process.env.GBRAIN_PGLITE_SNAPSHOT and deletes it, afterAll restores the saved value (delete it when the saved value was undefined), or scope it per test with withColdPglite / withSnapshotValue from test/helpers/with-snapshot.ts.');}-console.error('Why: test/helpers/operator-env-preload.ts strips every GBRAIN_* name outside its keep-lists (test/helpers/operator-env-policy.ts); an opt-in under such a name is a silent skip.');-console.error('Fix: rename the opt-in to GBRAIN_TEST_<AREA>_<WHAT> (paid: GBRAIN_TEST_LIVE_<WHAT>) and add the old name to RENAMED in test/helpers/operator-env-policy.ts, or add a KEEP_EXACT row there with its reason. GBRAIN_TEST_KEEP_AMBIENT_ENV=1 disables the scrub for local debugging only.');console.error(`Docs: ${ANCHOR}`);process.exit(1);diff --git a/scripts/guards-manifest.tsv b/scripts/guards-manifest.tsvindex 44ddaab90e..f27dce8761 100644--- a/scripts/guards-manifest.tsv+++ b/scripts/guards-manifest.tsv@@ -86,7 +86,7 @@ check-orphan-modules.mjs scanner yes runtime-reachability walk (static+dynamic rcheck-test-placeholders.mjs scanner yes TypeScript AST (CallExpression) scan of test/**/*.test.ts for no-op expect(true)/expect(1) placeholders; path+test+count allowlist (disabled in fixture mode); fixture root via argv/GBRAIN_GUARD_ROOT; in verify CHECKScheck-test-discriminates.sh buildfresh exempt manual per-PR discrimination helper (#3665): reverts named source files to their pre-fix state and runs the named test file to prove it fails without the fix — the test run IS the check; not in verify CHECKS or CIcheck-agent-contract.ts scanner yes agent operator contract v1 (B9): syntax-only TS AST; per-rule shrink-only baselines in scripts/agent-contract-baselines/; registry completeness + code naming never baselined; GBRAIN_GUARD_ROOT seam (baselines from <root>/baselines)-check-test-env-opt-ins.ts scanner yes D7 (GBRA-47): execution-gating process.env.GBRAIN_* reads in test/ and evals/ of names the operator-env preload strips (TS AST); policy shared with test/helpers/operator-env-policy.ts+check-test-env-opt-ins.ts scanner yes D7 (GBRA-47): execution-gating process.env.GBRAIN_* reads in test/ and evals/ of names the operator-env preload strips (TS AST); policy shared with test/helpers/operator-env-policy.ts. GBRA-79: module-scope delete/assignment of GBRAIN_PGLITE_SNAPSHOT in a matrix-loaded file (leaks through the shard's one bun process)check-postgres-lane-coverage.ts scanner yes GBRA-47 D8 (TS AST): a test file outside test/e2e/ with a DATABASE_URL-gated PostgreSQL arm (testBackends(), gated process.env.DATABASE_URL) must be named by a DATABASE_URL workflow step, a test/e2e registerPostgresTests wrapper, a tests/heavy script or the backend matrix; reasoned ALLOWLIST, stale rows failcheck-weight-coverage.ts scanner yes C2 (GBRA-47): weight-map entries naming missing files fail; unweighted share per lane warns, failing only on the scheduled runcheck-recipe-pricing.ts scanner yes X1 (wave 9 lane A, D22): every model a recipe touchpoint lists resolves through isModelPriceable or is named in the recipe's unpriced_models; stale markers fail; GBRAIN_GUARD_ROOT seam reads <root>/recipes.json against the real price tablesdiff --git a/scripts/sharding.ts b/scripts/sharding.tsindex 3c06cfd7d1..513331efe5 100644--- a/scripts/sharding.ts+++ b/scripts/sharding.ts@@ -24,6 +24,15 @@* Uses lane-specific weights. --fallback-on-error warns and uses uniform* weights if the advisory file is malformed (serial runner compatibility).*+ * bun run scripts/sharding.ts --sum [--weights <path>]+ * Read-only diagnostic: reads an already-partitioned file list from+ * stdin and prints its predicted weight (the same per-file weights and+ * p75 fallback `partition` uses) as one line, e.g.+ * `predicted 412.3s over 401 files (37 unweighted at p75 1.2s)`.+ * test-shard.sh prints it beside its "(LPT-balanced)" line so a shard+ * whose measured time is far above the prediction points at the runner+ * or a process-wide slowdown, not at the partition.+ ** Exit codes:* 0 success* 1 internal error (e.g., malformed weights JSON)@@ -218,6 +227,32 @@ export function imbalanceRatio(shards: string[][], weights: WeightMap, fallback:return max / min;}+/**+ * Predicted weight of an already-partitioned file list: the sum of each+ * file's mined weight, with the same p75 fallback `partition` assigns to+ * files absent from the map. Read-only over the weights.+ */+export function predictedWeight(+ files: string[],+ weights: WeightMap,+): { totalMs: number; files: number; unweighted: number; fallbackMs: number } {+ let fallbackMs = computeQuantile(Array.from(weights.values()), 0.75);+ if (fallbackMs === 0) fallbackMs = 1;+ let totalMs = 0;+ let unweighted = 0;+ for (const f of files) {+ const w = weights.get(f);+ if (w === undefined) unweighted++;+ totalMs += w ?? fallbackMs;+ }+ return { totalMs, files: files.length, unweighted, fallbackMs };+}++export function formatPredictedWeight(p: ReturnType<typeof predictedWeight>): string {+ const s = (ms: number) => `${(ms / 1000).toFixed(1)}s`;+ return `predicted ${s(p.totalMs)} over ${p.files} files (${p.unweighted} unweighted at p75 ${s(p.fallbackMs)})`;+}+// ──────────────────────────────────────────────────────────────────────────// CLI// ──────────────────────────────────────────────────────────────────────────@@ -241,17 +276,36 @@ async function main(): Promise<number> {const positional: string[] = [];let weightsPath: string | undefined;let fallbackOnError = false;+ let sumOnly = false;for (let i = 0; i < argv.length; i++) {const arg = argv[i]!;if (arg === "--weights" && argv[i + 1] && !argv[i + 1]!.startsWith("--")) weightsPath = argv[++i];else if (arg === "--fallback-on-error") fallbackOnError = true;+ else if (arg === "--sum") sumOnly = true;else if (arg.startsWith("--")) {console.error(`error: unknown or incomplete option ${arg}`);return 2;} else positional.push(arg);}+ if (sumOnly) {+ if (positional.length !== 0) {+ console.error("usage: bun run scripts/sharding.ts --sum [--weights PATH] (reads the shard's file list from stdin)");+ return 2;+ }+ let weights: WeightMap;+ try {+ weights = loadWeights(weightsPath);+ } catch (e) {+ console.error(`${fallbackOnError ? "warning" : "error"}: ${e instanceof Error ? e.message : String(e)}`);+ if (!fallbackOnError) return 1;+ weights = new Map();+ }+ process.stdout.write(`${formatPredictedWeight(predictedWeight(await readStdinLines(), weights))}\n`);+ return 0;+ }if (positional.length !== 2) {console.error("usage: bun run scripts/sharding.ts <shard-index> <total-shards> [--weights PATH] [--fallback-on-error]");+ console.error(" bun run scripts/sharding.ts --sum [--weights PATH]");console.error(" (reads file list from stdin, one path per line)");return 2;}diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsvindex 359405bb0e..5e7683d733 100644--- a/scripts/structural-suites.tsv+++ b/scripts/structural-suites.tsv@@ -316,7 +316,7 @@ test/scripts/serial-files.test.ts scripts/serial-files.tsv (serial lane manifesttest/scripts/stress-gate.test.ts docs anchors 1 readFileSynctest/scripts/stress-gate.test.ts gate plan 5 readFileSynctest/scripts/stress-plan.test.ts execution profiles 3 readFileSync-test/scripts/test-env-opt-ins-guard.test.ts check-test-env-opt-ins 2 readFileSync+test/scripts/test-env-opt-ins-guard.test.ts check-test-env-opt-ins 5 readFileSynctest/scripts/test-shard.slow.test.ts test-shard.sh — LPT balance contract 5 readFileSynctest/scripts/test-shard.slow.test.ts test-shard.sh — exclusion contract 7 readFileSynctest/search/graph-signals-wire-integration.test.ts v0.40.4 — source-grep regression guard 1 source-surface-helperdiff --git a/scripts/test-shard.sh b/scripts/test-shard.shindex ddb76afe43..2230b93c0c 100755--- a/scripts/test-shard.sh+++ b/scripts/test-shard.sh@@ -119,7 +119,12 @@ SHARD_COUNT=$(printf '%s\n' "$SHARD_FILES" | grep -c '^' || true)# grep -c on empty input returns 0 even with trailing newline edge cases[ -z "$SHARD_FILES" ] && SHARD_COUNT=0-echo "shard $SHARD_INDEX/$TOTAL_SHARDS: ${SHARD_COUNT}/${ALL_COUNT} files (LPT-balanced)"+# Predicted weight of this shard (read-only over scripts/test-weights.json,+# same p75 fallback the partition used). A measured shard far above it is a+# runner or process-wide slowdown (GBRA-79: a leaked GBRAIN_PGLITE_SNAPSHOT+# delete cold-booted every later engine), not a partition problem.+SHARD_WEIGHT=$(printf '%s\n' "$SHARD_FILES" | bun run scripts/sharding.ts --sum 2>/dev/null || echo "predicted weight unavailable")+echo "shard $SHARD_INDEX/$TOTAL_SHARDS: ${SHARD_COUNT}/${ALL_COUNT} files (LPT-balanced); $SHARD_WEIGHT"if [ "$SHARD_COUNT" -eq 0 ]; thenecho "warning: shard $SHARD_INDEX has no files (total shards may exceed file count)" >&2diff --git a/test/bootstrap.test.ts b/test/bootstrap.test.tsindex 7b9f5964bb..3bfae5cf20 100644--- a/test/bootstrap.test.ts+++ b/test/bootstrap.test.ts@@ -19,7 +19,7 @@* what this test exercises.*/-import { describe, test, expect } from 'bun:test';+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { LATEST_VERSION } from '../src/core/migrate.ts';import { readFactsEmbeddingDim } from '../src/core/embedding-dim-check.ts';@@ -28,8 +28,19 @@ import { readFactsEmbeddingDim } from '../src/core/embedding-dim-check.ts';// If GBRAIN_PGLITE_SNAPSHOT is set (ci:local sets it for unit shards), every// PGlite would boot post-initSchema and these assertions ("0 tables on fresh// install", "bootstrap converts pre-v0.18 brain to LATEST") would fail-// trivially. Unset for this file's process.-delete process.env.GBRAIN_PGLITE_SNAPSHOT;+// trivially. Unset for this file's tests and restore it afterwards: a CI+// shard runs hundreds of files in ONE bun process (scripts/test-shard.sh),+// so a module-scope delete would cold-boot every later engine in the shard+// (~3 s each, +350 s per shard; check:test-env-opt-ins pins this shape).+let savedSnapshot: string | undefined;+beforeAll(() => {+ savedSnapshot = process.env.GBRAIN_PGLITE_SNAPSHOT;+ delete process.env.GBRAIN_PGLITE_SNAPSHOT;+});+afterAll(() => {+ if (savedSnapshot === undefined) delete process.env.GBRAIN_PGLITE_SNAPSHOT;+ else process.env.GBRAIN_PGLITE_SNAPSHOT = savedSnapshot;+});describe('PGLiteEngine#applyForwardReferenceBootstrap', () => {test('fact embedding identity bootstrap repairs old and partial schemas without inventing provenance', async () => {diff --git a/test/destructive-guard.test.ts b/test/destructive-guard.test.tsindex 14471a7516..30425e05cd 100644--- a/test/destructive-guard.test.ts+++ b/test/destructive-guard.test.ts@@ -35,8 +35,19 @@ import {} from '../src/core/destructive-guard.ts';// Tier 3 opt-out — these tests need the cold-init schema path so the v33-// migration columns exist on the brain under test.-delete process.env.GBRAIN_PGLITE_SNAPSHOT;+// migration columns exist on the brain under test. Unset for this file's+// tests and restore afterwards: a CI shard runs hundreds of files in ONE bun+// process (scripts/test-shard.sh), so a module-scope delete would cold-boot+// every later engine in the shard (check:test-env-opt-ins pins this shape).+let savedSnapshot: string | undefined;+beforeAll(() => {+ savedSnapshot = process.env.GBRAIN_PGLITE_SNAPSHOT;+ delete process.env.GBRAIN_PGLITE_SNAPSHOT;+});+afterAll(() => {+ if (savedSnapshot === undefined) delete process.env.GBRAIN_PGLITE_SNAPSHOT;+ else process.env.GBRAIN_PGLITE_SNAPSHOT = savedSnapshot;+});async function setupBrain(): Promise<PGLiteEngine> {const engine = new PGLiteEngine();diff --git a/test/fixtures/guards/check-test-env-opt-ins.ts/bad-snapshot-assign/test/snapshot-assign.ts b/test/fixtures/guards/check-test-env-opt-ins.ts/bad-snapshot-assign/test/snapshot-assign.tsnew file mode 100644index 0000000000..416c2448c1--- /dev/null+++ b/test/fixtures/guards/check-test-env-opt-ins.ts/bad-snapshot-assign/test/snapshot-assign.ts@@ -0,0 +1,11 @@+import { describe, test } from 'bun:test';++// The same leak through an assignment inside a module-scope block (no+// function boundary): every later file in the shard sees the new path.+if (process.env.GBRAIN_TEST_FIXTURE_COLD === '1') {+ process.env['GBRAIN_PGLITE_SNAPSHOT'] = '/nonexistent/snapshot.tar';+}++describe('cold init', () => {+ test('boots', () => {});+});diff --git a/test/fixtures/guards/check-test-env-opt-ins.ts/bad-snapshot-leak/test/snapshot-leak.ts b/test/fixtures/guards/check-test-env-opt-ins.ts/bad-snapshot-leak/test/snapshot-leak.tsnew file mode 100644index 0000000000..e4a949c4cf--- /dev/null+++ b/test/fixtures/guards/check-test-env-opt-ins.ts/bad-snapshot-leak/test/snapshot-leak.ts@@ -0,0 +1,9 @@+import { describe, test } from 'bun:test';++// A module-scope delete of the snapshot path: the unit shard runs every file+// in one bun process, so every later file's PGLite cold-boots.+delete process.env.GBRAIN_PGLITE_SNAPSHOT;++describe('cold init', () => {+ test('boots', () => {});+});diff --git a/test/fixtures/guards/check-test-env-opt-ins.ts/good/test/e2e/cold.ts b/test/fixtures/guards/check-test-env-opt-ins.ts/good/test/e2e/cold.tsnew file mode 100644index 0000000000..7a075624d3--- /dev/null+++ b/test/fixtures/guards/check-test-env-opt-ins.ts/good/test/e2e/cold.ts@@ -0,0 +1,8 @@+import { describe, test } from 'bun:test';++// An E2E file runs in its own bun process (scripts/run-e2e.sh); exempt.+delete process.env.GBRAIN_PGLITE_SNAPSHOT;++describe('cold init', () => {+ test('boots', () => {});+});diff --git a/test/fixtures/guards/check-test-env-opt-ins.ts/good/test/no-snapshot-preload.ts b/test/fixtures/guards/check-test-env-opt-ins.ts/good/test/no-snapshot-preload.tsnew file mode 100644index 0000000000..2e3d8841b3--- /dev/null+++ b/test/fixtures/guards/check-test-env-opt-ins.ts/good/test/no-snapshot-preload.ts@@ -0,0 +1,5 @@+// A preload runs before every file in every bun process: process-wide by+// design, so the opt-out switch lives here.+if (process.env.GBRAIN_NO_SNAPSHOT === '1') {+ delete process.env.GBRAIN_PGLITE_SNAPSHOT;+}diff --git a/test/fixtures/guards/check-test-env-opt-ins.ts/good/test/snapshot-hooks.ts b/test/fixtures/guards/check-test-env-opt-ins.ts/good/test/snapshot-hooks.tsnew file mode 100644index 0000000000..d21e689e59--- /dev/null+++ b/test/fixtures/guards/check-test-env-opt-ins.ts/good/test/snapshot-hooks.ts@@ -0,0 +1,17 @@+import { afterAll, beforeAll, describe, test } from 'bun:test';++// The accepted shape: save and delete in beforeAll, restore in afterAll, so+// the next file in the shard's bun process gets the snapshot fast path back.+let savedSnapshot: string | undefined;+beforeAll(() => {+ savedSnapshot = process.env.GBRAIN_PGLITE_SNAPSHOT;+ delete process.env.GBRAIN_PGLITE_SNAPSHOT;+});+afterAll(() => {+ if (savedSnapshot === undefined) delete process.env.GBRAIN_PGLITE_SNAPSHOT;+ else process.env.GBRAIN_PGLITE_SNAPSHOT = savedSnapshot;+});++describe('cold init', () => {+ test('boots', () => {});+});diff --git a/test/schema-bootstrap-coverage.test.ts b/test/schema-bootstrap-coverage.test.tsindex 93490f4134..9fc3242bb4 100644--- a/test/schema-bootstrap-coverage.test.ts+++ b/test/schema-bootstrap-coverage.test.ts@@ -41,14 +41,26 @@* `test/e2e/postgres-bootstrap.test.ts`) to catch step 2 oversights.*/-import { test, expect } from 'bun:test';+import { test, expect, beforeAll, afterAll } from 'bun:test';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { surfaceFileSource } from './helpers/source-surface.ts';// Tier 3 opt-out: this file tests the bootstrap coverage contract explicitly,// running applyForwardReferenceBootstrap against fresh PGlite instances. A-// snapshot-loaded engine would skip the bootstrap entirely.-delete process.env.GBRAIN_PGLITE_SNAPSHOT;+// snapshot-loaded engine would skip the bootstrap entirely. Unset for this+// file's tests and restore afterwards: a CI shard runs hundreds of files in+// ONE bun process (scripts/test-shard.sh), so a module-scope delete would+// cold-boot every later engine in the shard (check:test-env-opt-ins pins+// this shape).+let savedSnapshot: string | undefined;+beforeAll(() => {+ savedSnapshot = process.env.GBRAIN_PGLITE_SNAPSHOT;+ delete process.env.GBRAIN_PGLITE_SNAPSHOT;+});+afterAll(() => {+ if (savedSnapshot === undefined) delete process.env.GBRAIN_PGLITE_SNAPSHOT;+ else process.env.GBRAIN_PGLITE_SNAPSHOT = savedSnapshot;+});// Single home for the bootstrap's source path (moved twice: #4477, then E1// merged both engines' copies — keep every source-pinning test below on onediff --git a/test/scripts/sharding.test.ts b/test/scripts/sharding.test.tsindex f418f8daa3..7eb4b7741c 100644--- a/test/scripts/sharding.test.ts+++ b/test/scripts/sharding.test.ts@@ -8,9 +8,11 @@ import { describe, expect, it } from "bun:test";import {computeMedian,computeQuantile,+ formatPredictedWeight,imbalanceRatio,loadWeights,partition,+ predictedWeight,WeightsLoadError,type WeightMap,} from "../../scripts/sharding.ts";@@ -347,3 +349,47 @@ describe("sharding CLI stdout flush (#5669)", () => {}}, 60_000);});++// GBRA-79 — test-shard.sh prints each shard's predicted weight beside its+// "(LPT-balanced)" line so a measured time far above it reads as a runner or+// process-wide slowdown. The prediction must use the partition's own+// weights and p75 fallback, and the CLI's --sum must print the same line.+describe("predictedWeight / --sum", () => {+ const weights: WeightMap = new Map([+ ["test/a.test.ts", 4000],+ ["test/b.test.ts", 1000],+ ["test/c.test.ts", 2000],+ ["test/d.test.ts", 3000],+ ]);++ it("sums mined weights and gives unknown files the p75 fallback", () => {+ const p = predictedWeight(["test/a.test.ts", "test/b.test.ts", "test/new.test.ts"], weights);+ expect(p).toEqual({ totalMs: 4000 + 1000 + 3000, files: 3, unweighted: 1, fallbackMs: 3000 });+ expect(formatPredictedWeight(p)).toBe("predicted 8.0s over 3 files (1 unweighted at p75 3.0s)");+ });++ it("empty weights predict 1ms per file, matching partition's floor", () => {+ expect(predictedWeight(["x", "y"], new Map())).toEqual({ totalMs: 2, files: 2, unweighted: 2, fallbackMs: 1 });+ });++ it("the CLI prints the line for the file list on stdin and refuses positional shard arguments", async () => {+ const dir = mkdtempSync(join(tmpdir(), "shard-sum-"));+ const weightsPath = join(dir, "weights.json");+ writeFileSync(weightsPath, JSON.stringify(Object.fromEntries(weights)), "utf8");+ const cli = join(import.meta.dir, "../../scripts/sharding.ts");+ try {+ const ok = Bun.spawn([process.execPath, cli, "--sum", "--weights", weightsPath], {+ stdin: new TextEncoder().encode("test/a.test.ts\ntest/new.test.ts\n"), stdout: "pipe", stderr: "pipe",+ });+ const [out, err, code] = await Promise.all([new Response(ok.stdout).text(), new Response(ok.stderr).text(), ok.exited]);+ expect({ code, err, out }).toEqual({ code: 0, err: "", out: "predicted 7.0s over 2 files (1 unweighted at p75 3.0s)\n" });++ const bad = Bun.spawn([process.execPath, cli, "--sum", "1", "8", "--weights", weightsPath], {+ stdin: new TextEncoder().encode("test/a.test.ts\n"), stdout: "pipe", stderr: "pipe",+ });+ expect(await bad.exited).toBe(2);+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });+});diff --git a/test/scripts/test-env-opt-ins-guard.test.ts b/test/scripts/test-env-opt-ins-guard.test.tsindex 683191e81a..0dff7b1443 100644--- a/test/scripts/test-env-opt-ins-guard.test.ts+++ b/test/scripts/test-env-opt-ins-guard.test.ts@@ -3,11 +3,15 @@* GBRAIN_* opt-in the operator-env preload strips is a silent skip. The* guard-self-test harness proves the bad fixtures fail and the good one* passes; this file pins the agent-facing output (Why / Fix / Docs, with an- * anchor that exists) and that the real tree is clean.+ * anchor that exists) and that the real tree is clean. The same guard's+ * second rule (GBRA-79): a module-scope delete/assignment of+ * GBRAIN_PGLITE_SNAPSHOT in a file the unit matrix loads leaks through the+ * shard's single bun process and cold-boots every later PGLite engine.*/import { describe, expect, test } from 'bun:test';import { spawnSync } from 'node:child_process';-import { readFileSync } from 'node:fs';+import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';import { join, resolve } from 'node:path';const REPO = resolve(import.meta.dir, '..', '..');@@ -37,6 +41,42 @@ describe('check-test-env-opt-ins', () => {expect(headings).toContain(anchor!);});+ test('a module-scope GBRAIN_PGLITE_SNAPSHOT delete or assignment in a matrix file names the one-process shard runner and the hook shape', () => {+ const leak = run(join(FIXTURES, 'bad-snapshot-leak'));+ expect(leak.status).toBe(1);+ expect(leak.stderr).toContain('FAIL [test_env_snapshot_module_scope]: test/snapshot-leak.ts:5 deletes process.env.GBRAIN_PGLITE_SNAPSHOT at module scope');+ expect(leak.stderr).toMatch(/^Why: scripts\/test-shard\.sh runs a whole unit shard .* in ONE bun process.*cold-boots initSchema\(\)/m);+ expect(leak.stderr).toMatch(/^Fix: .*beforeAll saves process\.env\.GBRAIN_PGLITE_SNAPSHOT and deletes it, afterAll restores the saved value.*with-snapshot\.ts/m);+ expect(leak.stderr).not.toContain('test_env_opt_in_stripped');+ expect(leak.stderr).toMatch(/^Docs: docs\/TESTING\.md#test-isolation-lint-and-helpers$/m);++ const assign = run(join(FIXTURES, 'bad-snapshot-assign'));+ expect(assign.status).toBe(1);+ expect(assign.stderr).toContain('FAIL [test_env_snapshot_module_scope]: test/snapshot-assign.ts:6 assigns process.env.GBRAIN_PGLITE_SNAPSHOT at module scope');+ });++ test('hook-scoped, e2e and preload snapshot changes pass', () => {+ const r = run(join(FIXTURES, 'good'));+ expect(r.stderr).toBe('');+ expect(r.status).toBe(0);+ });++ test('a *.serial.test.ts file may delete the snapshot at module scope (own bun process)', () => {+ // Written to a temp root, not test/fixtures/guards/: the serial runner+ // collects every *.serial.test.ts under test/ and would run a fixture.+ // The source is assembled so check-test-isolation's R1 grep does not read+ // this test file itself as mutating process.env.+ const moduleScopeDelete = ['delete process', 'env.GBRAIN_PGLITE_SNAPSHOT;\n'].join('.');+ const root = mkdtempSync(join(tmpdir(), 'opt-ins-serial-'));+ mkdirSync(join(root, 'test'), { recursive: true });+ writeFileSync(join(root, 'test', 'cold.serial.test.ts'), moduleScopeDelete);+ writeFileSync(join(root, 'test', 'cold.test.ts'), moduleScopeDelete);+ const r = run(root);+ expect(r.status).toBe(1);+ expect(r.stderr).toContain('FAIL [test_env_snapshot_module_scope]: test/cold.test.ts:1 deletes');+ expect(r.stderr).not.toContain('cold.serial.test.ts');+ });+test('the real tree is clean', () => {const r = run();expect(r.stderr).toBe('');