Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

docs: E2E selection, backend-matrix ownership, weight ratchet and verify battery for the S6 CI changes

garrytanad6857374682
diff --git a/AGENTS.md b/AGENTS.md
index cfaeb5de37..f3537cfbbf 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -203,14 +203,14 @@ writing or reviewing an operation, consult `src/core/operations.ts` for the cont
Easiest path: `bun run ci:local` runs the full CI gate inside Docker (gitleaks,
guards + typecheck, then 4-shard parallel unit + E2E against four pgvector
containers plus a transaction-mode PgBouncer; unit phase keeps `DATABASE_URL`
-unset) and tears down. Use `bun run ci:local:diff` for the
-diff-aware subset during fast iteration on a focused branch. Requires Docker
+unset) and tears down. `bun run ci:local:diff` checks a doc-only diff in
+seconds (gitleaks plus the doc checks) and runs the full gate otherwise. Requires Docker
(Docker Desktop / OrbStack / Colima) and `gitleaks` (`brew install gitleaks`).
Fastest path, with a Ubicloud token (`UBICLOUD_API_KEY` or
`UBICLOUD_API_TOKEN`): `bun run ci:ubicloud` runs the same gate across ten
ephemeral VMs in about five minutes, uncommitted edits included
-(`ci:ubicloud:diff` for the diff-aware subset). See "Ubicloud fan-out" in
+(`ci:ubicloud:diff` for the doc-only fast path). See "Ubicloud fan-out" in
[`docs/TESTING.md`](./docs/TESTING.md).
Manual path: `bun test` plus the E2E lifecycle described in `./CLAUDE.md` (spin
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index ec7536542d..5484100876 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -255,10 +255,10 @@ the authoring gate. See [Source reads in tests](docs/TESTING.md#source-reads-in-
```bash
bun run ci:local # full gate: gitleaks + guards/typecheck + 4-shard parallel unit + E2E
-bun run ci:local:diff # gate with diff-aware E2E selector
-bun run ci:select-e2e # print which E2E files the selector would run
+bun run ci:local:diff # doc-only diff: gitleaks + doc checks; otherwise the full gate
+bun run ci:select-e2e # print the E2E files the diff selects (nothing for doc-only, else all)
bun run ci:ubicloud # the same gate fanned out across ephemeral Ubicloud VMs (~5 min)
-bun run ci:ubicloud:diff # Ubicloud gate with the diff-aware E2E selector
+bun run ci:ubicloud:diff # Ubicloud gate with the same doc-only fast path
```
`ci:local` spins up four pgvector services plus a transaction-mode PgBouncer via
@@ -273,8 +273,11 @@ on host (`brew install gitleaks`). Override the postgres host port with
uncommitted edits included; see "Ubicloud fan-out" in
[`docs/TESTING.md`](docs/TESTING.md).
-Fail-closed selector: an unmapped `src/` change runs ALL E2E files. Hand-tune
-narrower mappings via `scripts/e2e-test-map.ts`.
+E2E selection runs every E2E file for any change that is not doc-only; diff
+narrowing is retired because a typical E2E file imports most of `src/`. A
+doc-only diff still runs llms freshness, the KEY_FILES byte caps, documented
+paths, skill references and the privacy guards (`scripts/ci-doc-checks.sh`).
+See [E2E selection](docs/TESTING.md#e2e-selection).
### PR-side security checks
diff --git a/docs/RELEASING.md b/docs/RELEASING.md
index 9ddfb50093..680704a661 100644
--- a/docs/RELEASING.md
+++ b/docs/RELEASING.md
@@ -19,10 +19,9 @@ Two equivalent paths:
than PR CI's four-file Tier 1 job; closer to what nightly Tier 1 catches. Spins
up + tears down postgres automatically via `docker-compose.ci.yml`. Override
the host port with `GBRAIN_CI_PG_PORT=5435 bun run ci:local` if 5434 collides.
-- `bun run ci:local:diff` runs only the E2E files matched by the diff selector
- (`scripts/select-e2e.ts`), falling back to ALL E2E files on unmapped src/
- paths or schema/skills/package.json changes. Fast iteration during a focused
- branch.
+- `bun run ci:local:diff` checks a doc-only diff in seconds (gitleaks plus
+ `scripts/ci-doc-checks.sh`) and runs the full gate for any other diff: E2E
+ narrowing is retired (see docs/TESTING.md "E2E selection").
- `bun run ci:ubicloud` (and `ci:ubicloud:diff`) runs the same lanes across ten
ephemeral Ubicloud VMs in about five minutes instead of one Docker host. Needs
`UBICLOUD_API_KEY` or `UBICLOUD_API_TOKEN`; see "Ubicloud fan-out" in
diff --git a/docs/TESTING.md b/docs/TESTING.md
index cb10969bad..4bac2beccd 100644
--- a/docs/TESTING.md
+++ b/docs/TESTING.md
@@ -239,9 +239,8 @@ Recorded ownership changes:
reconciliation crash boundaries" step runs both files by name and uploads the
crash manifests, unchanged. Both files are in `E2E_EXCLUSIONS`
(`PERSISTENCE_VALIDATION_OWNED` in `scripts/e2e-matrix.ts`), so PR
- `selected-e2e` does not run them a second time; `scripts/select-e2e.ts`
- prints `excluded: <file> (owned by persistence-validation.yml)` on stderr when
- a mapped source changes. The nightly full-corpus E2E run and the local gates
+ `selected-e2e` does not run them a second time; `scripts/e2e-matrix.ts`
+ prints `excluded: <file> (owned by persistence-validation.yml)` on stderr. The nightly full-corpus E2E run and the local gates
(`ci:local`, `ci:ubicloud`, their `:diff` forms) still run them. Run them
locally with the same command the workflow uses, with `DATABASE_URL`
exported for the test database from "E2E test DB lifecycle":
@@ -355,9 +354,8 @@ Delete or merge a test only with evidence, recorded in the PR body:
gate, per "Coverage responsibilities before consolidation" above.
4. Remove the deleted file's entries from `scripts/ubicloud/weights.json`,
`scripts/test-weights.json`, `scripts/serial-weights.json` and
- `scripts/e2e-weights.json`, grep `scripts/`, `.github/`,
- `scripts/e2e-test-map.ts` and `test/fixtures/e2e-unmapped-baseline.txt` for
- the path, and regenerate `scripts/structural-suites.tsv`
+ `scripts/e2e-weights.json` (`bun run check:weight-coverage` fails on a
+ leftover), grep `scripts/` and `.github/` for the path, and regenerate `scripts/structural-suites.tsv`
(`bun scripts/classify-tests.ts`).
Evidence cases:
@@ -392,10 +390,10 @@ Test command tiers, each with a clear scope:
| Command | What it runs | Wallclock | When to use |
|---|---|---|---|
| `bun run test` | Parallel unit-test fast loop. Sharded fan-out via `scripts/run-unit-parallel.sh` (default 4 shards — CPU-detected, clamped to a max of 8; 4 limits local PGLite WASM-init contention; GitHub CI uses 8 unit shards), then a serial pass over `*.serial.test.ts`. Excludes `*.slow.test.ts` and `test/e2e/*`. No pre-checks, no typecheck. Builds/refreshes the PGLite schema snapshot BEFORE the shard fan-out and exports `GBRAIN_PGLITE_SNAPSHOT` so PGLite-booting files restore a baked schema instead of replaying every migration (~3.5x per booting file; see "PGLite schema snapshot" below). Opt out: `GBRAIN_NO_SNAPSHOT=1`. Memory-safe by default: total concurrency (shards × intra-shard width) is capped to available memory at `GBRAIN_TEST_MEM_PER_FILE_MB` (default 1536 — a PGLite WASM instance) per concurrent slot, shedding INTRA-SHARD width first and shards only after it (bun's `--max-concurrency` bounds only `test.concurrent` tests — 1 file in the corpus — so intra width is nearly free to shed, while every dropped shard removes a whole bun process of real fan-out; shedding shards first would collapse a 16GB box to a serial 1×4 run, measured 3.25× slower than 4×1 on the same machine). Two phantom-failure classes are automatically re-run serially (the rescue pass): failures carrying the WASM out-of-memory signature, and shards killed externally (SIGTERM/SIGKILL well before the shard timeout — sibling workspaces' process cleanup, memory jetsam). On machines without coreutils `timeout`, the fallback watchdog drops a `.watchdog` sentinel before TERMing a shard at the cap so the WEDGED/EXIT-HANG classifier stays reachable there (a bare rc=143 would otherwise read as a plain failure). Phantoms pass serially and the run goes green with an `oom_rescued` note; real failures fail again serially and stay red. Knobs: `GBRAIN_TEST_NO_MEM_ADAPT=1`, `GBRAIN_TEST_NO_OOM_FALLBACK=1`, `GBRAIN_TEST_MAX_CONCURRENCY` (intra-shard, default 4), `GBRAIN_TEST_SHARD_TIMEOUT` / `GBRAIN_TEST_SHARD_KILL_AFTER`, plus `--shards N` / `--max-concurrency N` / `--dry-run` script args. | a few minutes on a Mac dev box | Inner edit loop. Default. |
-| `bun run verify` | CI's authoritative pre-test gate set, fanned out by `scripts/run-verify-parallel.sh` through a bounded worker pool (default `detect_cpus`; override `GBRAIN_VERIFY_MAX_PARALLEL`) with the heavy checks ordered first (typecheck, the two compile-embed checks, admin build, fuzz bundles, guard self-tests, the PGLite-booting chronicle eval check, whole-tree greps). The battery includes the deterministic `check:eval-chronicle` eval gate; `check:eval-canary` is deliberately NOT in the battery (its test-file twin `test/eval-canary.test.ts` spawns the identical runner in the unit matrix, and CI's verify job and matrix always run together — the package script stays for on-demand runs, so `verify`-only local callers should know the canary rides the unit lane instead). The `CHECKS` array in that script is the single source of truth — CI literally calls `bun run verify` in a dedicated job. | ~50s (pool-bounded; longest check dominates) | Before pushing; before `/ship`. |
+| `bun run verify` | CI's authoritative pre-test gate set, fanned out by `scripts/run-verify-parallel.sh` through a bounded worker pool (default `detect_cpus`; override `GBRAIN_VERIFY_MAX_PARALLEL`) with the heavy checks ordered first (typecheck, the two compile-embed checks, admin build, fuzz bundles, guard self-tests, whole-tree greps). `check:eval-chronicle` and `check:eval-canary` are deliberately NOT in the battery (their test-file twins `test/eval-chronicle.test.ts` and `test/eval-canary.test.ts` run the identical evals in the unit matrix, and CI's verify job and matrix always run together — the package scripts stay for on-demand runs, so `verify`-only local callers should know both evals ride the unit lane instead). The `CHECKS` array in that script is the single source of truth — CI literally calls `bun run verify` in a dedicated job. | ~50s (pool-bounded; longest check dominates) | Before pushing; before `/ship`. |
| `bun run test:full` | `verify && bun run test && bun run test:slow && [smart e2e]`. Smart e2e runs only when `DATABASE_URL` is set and propagates its failure; otherwise it prints a skip notice to stderr. Use `ci:local` to provision the databases and require PgBouncer execution. | ~3-5min depending on slow + e2e | Pre-merge sanity, before opening a PR. |
-| `bun run ci:local` | Independent host gitleaks scans, then frozen dependencies, guards/typecheck, the complete serial and slow lanes, and four unit/E2E shards inside Docker. Each E2E shard has its own pgvector database; selected PgBouncer tests must execute against the transaction-mode pooler. Unit, serial, and slow lanes have database URL overrides unset. Any failed stage fails the command. Complete shard logs survive container teardown under `.context/ci-local-shards/`. `ci:local:diff` narrows E2E selection; `--no-shard` runs unit/E2E sequentially. Doc-only diffs still require successful gitleaks scans. | Depends on the full corpus | Full local gate before shipping. |
-| `bun run ci:ubicloud` | The `ci:local` lanes (gitleaks, guards/typecheck, serial, slow, unit, all E2E with required PgBouncer execution) fanned out across ephemeral Ubicloud VMs from one heaviest-first work queue; `ci:ubicloud:diff` narrows E2E like `ci:local:diff`. Needs `UBICLOUD_API_KEY` or `UBICLOUD_API_TOKEN`, no local Docker. See "Ubicloud fan-out" below. | ~5 min (floor: the longest single file) | Full gate before shipping when a Ubicloud token is available. |
+| `bun run ci:local` | Independent host gitleaks scans, then frozen dependencies, guards/typecheck, the complete serial and slow lanes, and four unit/E2E shards inside Docker. Each E2E shard has its own pgvector database; selected PgBouncer tests must execute against the transaction-mode pooler. Unit, serial, and slow lanes have database URL overrides unset. Any failed stage fails the command. Complete shard logs survive container teardown under `.context/ci-local-shards/`. `ci:local:diff` runs only gitleaks and the doc checks on a doc-only diff and the full gate otherwise; `--no-shard` runs unit/E2E sequentially. Doc-only diffs still require successful gitleaks scans. | Depends on the full corpus | Full local gate before shipping. |
+| `bun run ci:ubicloud` | The `ci:local` lanes (gitleaks, guards/typecheck, serial, slow, unit, all E2E with required PgBouncer execution) fanned out across ephemeral Ubicloud VMs from one heaviest-first work queue; `ci:ubicloud:diff` takes the same doc-only fast path as `ci:local:diff`. Needs `UBICLOUD_API_KEY` or `UBICLOUD_API_TOKEN`, no local Docker. See "Ubicloud fan-out" below. | ~5 min (floor: the longest single file) | Full gate before shipping when a Ubicloud token is available. |
| `bun run test:slow` | Just the `*.slow.test.ts` set (intentional cold-path correctness checks). | seconds-to-minutes | When touching slow-path code. |
| `bun run test:serial` | Just the `*.serial.test.ts` set (cross-file-contention quarantine; one bun process per file for true module-registry isolation), run through a POOL of concurrent per-file processes — the isolation is per-process, not per-machine. Dispatch is heaviest-first (LPT) from the advisory `scripts/serial-weights.json` (seconds; mined from the `.context/serial-durations.txt` table each run banks; absent/corrupt weights fall back to discovery order, absent keys to the corpus p75 — scheduling only, never correctness; LPT order + the corrupt-weights fail-soft are pinned by `test/scripts/run-serial-pool.test.ts`). Pool defaults to `min(detect_cpus, 4)` then memory-adapts (same doctrine as the parallel runner); a small growth-guarded set of files (machine-global state or contention-critical timing — see the justified `EXCLUSIVE_FILES` list in `scripts/run-serial-tests.sh`, capped at 3 by `test/scripts/serial-files.test.ts`) runs on a sequential EXCLUSIVE lane after the pool. Per-test timeout 120s (pooled contention headroom); each pooled file is wall-clock-killed at 300s (`timeout -k`, exit-hang containment). `SHARD=N/M` partitions pooled files by duration; the three exclusive files run only on shard 1. Unset runs the complete corpus. Routing variables are cleared before tests start, so nested runners remain independent. Externally-killed files (exit 143/137 or a missing exit sentinel — sibling-workspace cleanup, memory jetsam) get ONE sequential rescue re-run, mirroring the parallel runner's doctrine: phantoms stay green with a rescue note, real failures stay red. Prints per-file PASS lines plus a top-10 slowest-files list. Knobs: `GBRAIN_SERIAL_POOL=N` (explicit pool width — bypasses the memory clamp; `1` restores fully-sequential), `GBRAIN_SERIAL_FILE_TIMEOUT`. | a few minutes for all ~220 files at pool=4 | Debugging quarantined files; CI's serial-tests job. |
| `bun run test:e2e` | Real Postgres E2E. Requires Docker + `DATABASE_URL`. Sequential within a shard; `SHARD=N/M` fans out against separate databases (ci-local runs 4 containers). Activates the PGLite snapshot like every other runner (per-file cold-path opt-outs where the test asserts the path TO post-initSchema state), exporting it as an ABSOLUTE path so CLI children spawned with varying cwd still find it. | ~5-10min | Pre-ship; nightly. |
@@ -484,7 +482,7 @@ start, so a busy project shrinks the fleet instead of failing. Pass `--vms 10`
only when the quota is idle. Slow-lane items run `test/export-scale.slow.test.ts`
at the pull-request scale (`GBRAIN_TEST_EXPORT_SCALE_PAGES=10001`). `--lanes` runs a
subset, `--keep` leaves the VMs up for debugging, and `--diff` follows
-`ci:local:diff` (a doc-only diff runs gitleaks alone). The corpus is roughly
+`ci:local:diff` (a doc-only diff runs the doc checks and gitleaks alone). The corpus is roughly
8,000 seconds of test compute at that density, so 80 slots finish everything
but the longest files about two minutes after setup; more slots per VM add CPU
contention that slows timing-sensitive files without shortening the run. Wall time is bounded
@@ -904,7 +902,7 @@ evidence for a change before it merges. `test.yml`'s security matrix,
### Keeping CI partitions balanced
Required CI runs eight weighted unit workers, four serial workers with bounded
-per-file pools, and up to four selected E2E workers. E2E selection and exclusions
+per-file pools, and up to eight selected E2E workers. E2E selection and exclusions
run once before setup; the resulting file lists are frozen and executed against
separate Postgres services. An explicit empty selection launches no tests;
selection errors, failed workers, cancellations, and unexpected skips fail the
@@ -920,7 +918,10 @@ on a preceding file to create shared tables. Bootstrap is a separate timed CI
step and must be included in end-to-end comparisons.
Refresh after a large test wave or when the longest shard repeatedly exceeds
-the mean shard execution time by 25%:
+the mean shard execution time by 25%. `bun run check:weight-coverage` (in
+`verify`) fails on an entry naming a missing file and, when a lane's unweighted
+share passes 5% (unit) or 10% (serial, E2E), warns on pull requests and pushes
+and fails the scheduled run, printing the lane's miner command:
```bash
bun run weights:mine --lane unit --run <successful-test-run>
@@ -962,6 +963,27 @@ completeness. Compare cold and warm caches separately. Snapshot timings and
partition estimates are projections until matched workflow runs confirm them;
successful test results are never cached.
+### E2E selection
+
+`prepare-e2e` reads the pull request's changed files from the GitHub API
+(`scripts/ci-changed-files.sh`, shallow checkout) and passes them to
+`scripts/select-e2e.ts`: a doc-only change selects nothing, every other change
+selects every `test/e2e/*.test.ts`. Diff narrowing is retired: a typical E2E
+file imports most of `src/`, so a file-to-test map selected every file on 40 of
+40 merged pull requests. An incomplete list (more than 3000 files, a compare
+capped at 300, an API error, no pull request or merge-group context) fails
+closed to the whole corpus. `scripts/e2e-matrix.ts` then drops
+`E2E_EXCLUSIONS`, the files a named job owns, printing each owner: Tier 1's
+named files, `tier1-backend-matrix` for every `test/e2e/` row of
+`scripts/e2e-backend-matrix.txt` (direct Postgres and PgBouncer, so Selected
+E2E's direct-only run was a duplicate; ownership moved there in the
+2026-10-04 wave), persistence-validation.yml and the live-key lanes.
+`test/scripts/e2e-wiring.test.ts` requires every excluded file to have a named
+owner. Locally, `ci:local:diff` and `ci:ubicloud:diff` run gitleaks and
+`scripts/ci-doc-checks.sh` (llms freshness, KEY_FILES byte caps, documented
+paths, skill references, privacy guards) on a doc-only diff and the full gate
+otherwise, printing "E2E narrowing is retired".
+
### Refactor wave 1 goldens
Outputs captured on master before refactor wave 1 moves any code live under
@@ -1401,10 +1423,9 @@ cannot ship silently. All allowlists below are shrink-only unless noted.
string. Anti-vacuity is mandatory: each op's control call must SEE the
cross-source marker before its scoped assertions count; an op that can't
be driven is an explicit counted SKIP disposition, never a silent pass.
-- `test/scripts/e2e-wiring.test.ts` — every `test/e2e/*.test.ts` must be
- claimed by a PR-time lane (a `scripts/e2e-test-map.ts` row, a workflow
- mention, or the shrink-only `test/fixtures/e2e-unmapped-baseline.txt`),
- and every map entry must point at a real file (typo guard).
+- `test/scripts/e2e-wiring.test.ts` — every `test/e2e/*.test.ts` runs in
+ Selected E2E or is in `E2E_EXCLUSIONS` with a named owning job, and every
+ exclusion names a real file.
- `test/engine-surface-coverage.test.ts` — two-way census of the
`BrainEngine` interface against the PGLite prototype (new methods force a
visible list edit) plus a runtime `UNCALLED` ratchet scanning the whole
@@ -1510,10 +1531,9 @@ non-`GBRAIN_`-prefixed so the hermetic env scrub keeps them.
**Two corpora.**
-- **PR corpus** (`prCorpus`) — the 15 coverage-collecting lanes in
+- **PR corpus** (`prCorpus`) — the 14 coverage-collecting lanes in
`.github/workflows/test.yml`: the 8 matrix shards, four `serial-tests` partitions, and the
- three dedicated slow jobs (`slow-eval-longmemeval`,
- `slow-entity-resolve-perf`, `slow-brainbench-e2e`). Deterministic (runs identically on every PR); this
+ two dedicated slow jobs (`slow-entity-resolve-perf`, `slow-brainbench-e2e`). Deterministic (runs identically on every PR); this
is the corpus the gates run against.
- **fullCorpus** — nightly or explicit manual opt-in in `.github/workflows/e2e.yml`:
`coverage-full-{unit,serial,slow,e2e}` + `coverage-full-report`. Fully
@@ -1936,7 +1956,7 @@ Unit tests and what they cover:
- `test/bootstrap.test.ts` — bootstrap contract: no-op on fresh install, idempotent across two `initSchema()` calls, no-op on modern brain that already has every probed column, full bootstrap path on a simulated legacy brain, fresh-install regression guard, legacy `links` shape coverage.
- `test/schema-bootstrap-coverage.test.ts` — CI guard covering BOTH embedded schema blobs: neither may forward-reference state its engine's bootstrap can't create, and a reference covered on one blob is NOT automatically covered on the other (`dream_verdicts` exists only in the Postgres blob). PGLite half: `REQUIRED_BOOTSTRAP_COVERAGE` lists every forward reference in `PGLITE_SCHEMA_SQL`; the test fails loudly if `applyForwardReferenceBootstrap` skips one (extend both arrays when adding a column-with-index to the embedded schema blob). Also parses `src/core/migrate.ts` source text for every `ALTER TABLE ... ADD COLUMN` (top-level `sql:`, `sqlFor.{postgres,pglite}` overrides, AND handler-body `engine.runMigration(N, \`ALTER TABLE ...\`)`) and asserts each (table, column) pair is covered by the bootstrap OR by the schema blob's CREATE TABLE bodies — catching the column-only forward-reference class (e.g. `sources.archived`, `oauth_clients.source_id`) that a CREATE INDEX parser alone can't see. Postgres half (the class-closure gate): parses every CREATE INDEX column reference in `SCHEMA_SQL` and requires each to be in the blob's CREATE TABLE body AND not migration-added, or probed + ALTERed by `src/core/engine-sql/bootstrap.ts` (the single bootstrap both engines run; the PGLite half reads it minus its `dialect-only:postgres` regions) — a column that is both in the blob's CREATE TABLE and migration-added is still a forward reference for pre-existing brains, where `CREATE TABLE IF NOT EXISTS` no-ops and the blob's CREATE INDEX wedges `initSchema` before migrations can help. This gate is parser-driven (no registry to extend); intentional non-probes go in `POSTGRES_INDEX_REF_EXEMPTIONS` with a rationale. Honest scope: CREATE INDEX column references only — constraints, views, and trigger bodies are a filed TODOS.md follow-up. `parseBaseTableColumns` strips SQL line + block comments before identifying column names so commented-out lines don't hide adjacent columns.
- `test/dream-verdict-cache-ttl.test.ts` — `dream_verdicts` TTL contract on PGLite: put assigns the default TTL, expired rows miss on read and only they are swept, re-judging via upsert refreshes a nearly-expired row, the migration backfill derives expiry from `judged_at` idempotently, and a NULL-expiry row (the pre-backfill upgrade window) reads as a hit and survives the sweep — the locally-runnable pin for the NULL-tolerant read predicate both engines share.
-- `test/helpers/schema-diff.ts` + `test/helpers/schema-diff.test.ts` + `test/e2e/schema-drift.test.ts` — cross-engine schema parity gate. Helper exports pure `snapshotSchema(query)` / `diffSnapshots(pg, pglite, opts)` / `formatDiffForFailure(diff)` / `isCleanDiff(diff)` over a four-tuple per column (`data_type`, `udt_name`, `is_nullable`, `column_default`). E2E test spins up fresh PGLite + Postgres, runs `engine.initSchema()` on each, snapshots `information_schema.columns`, then diffs. 2-table allowlist (`files`, `file_migration_ledger`) — every other Postgres table must reach PGLite via `PGLITE_SCHEMA_SQL` or a migration's `sqlFor.pglite` branch. Sentinels for `oauth_clients`, `mcp_request_log`, `access_tokens`, `eval_candidates` give tighter blame messages. Skips without `DATABASE_URL`. Wired into `scripts/e2e-test-map.ts` so changes to `src/schema.sql`, the PGLite schema façade or its generated template, or the migration runner trigger it. The failure message names every drift with a paste-ready hint pointing at `src/schema.sql` (or its TS fragment) plus `bun run build:schema`, a PGLite rule in `scripts/build-schema.ts`, or a migration's `sqlFor.pglite` branch.
+- `test/helpers/schema-diff.ts` + `test/helpers/schema-diff.test.ts` + `test/e2e/schema-drift.test.ts` — cross-engine schema parity gate. Helper exports pure `snapshotSchema(query)` / `diffSnapshots(pg, pglite, opts)` / `formatDiffForFailure(diff)` / `isCleanDiff(diff)` over a four-tuple per column (`data_type`, `udt_name`, `is_nullable`, `column_default`). E2E test spins up fresh PGLite + Postgres, runs `engine.initSchema()` on each, snapshots `information_schema.columns`, then diffs. 2-table allowlist (`files`, `file_migration_ledger`) — every other Postgres table must reach PGLite via `PGLITE_SCHEMA_SQL` or a migration's `sqlFor.pglite` branch. Sentinels for `oauth_clients`, `mcp_request_log`, `access_tokens`, `eval_candidates` give tighter blame messages. Skips without `DATABASE_URL`. The failure message names every drift with a paste-ready hint pointing at `src/schema.sql` (or its TS fragment) plus `bun run build:schema`, a PGLite rule in `scripts/build-schema.ts`, or a migration's `sqlFor.pglite` branch.
- `test/schema-catalog-golden.test.ts` + `test/e2e/schema-catalog-golden.test.ts` — refactor wave 1 E4 catalog goldens (`test/fixtures/goldens/catalog/`). `snapshotCatalog(query)` in `test/helpers/schema-diff.ts` pins columns with ordinal position, defaults, full index definitions, constraints incl. CHECK text, triggers, function signature + body sha256, views, policies, grants (connecting role placeholdered), RLS flags, sequences and extension names; extension-owned objects are excluded. Captured at three configs (`CATALOG_CONFIGS` in `test/helpers/schema-catalog.ts`: default OpenAI/1536, 4096 dims which skips the chunk and halfvec HNSW indexes, `GBRAIN_FTS_LANGUAGE=portuguese`) on PGLite engine init, the PGLite schema blob without migrations, Postgres engine init (fresh throwaway database per capture) and Postgres `db.initSchema()`, plus an optional PgBouncer arm. Every capture runs twice through the `schema-catalog-lines-v1` normalizer. PGLite master-vs-branch compares ordinals (the goldens pin them); PG ↔ PGLite parity stays name-based. Regenerate deliberately with `GBRAIN_TEST_UPDATE_GOLDENS=1`.
- `test/pglite-upgrade-replay.test.ts` — refactor wave 1 EO3: opens the pinned master-built PGLite brain (`test/fixtures/goldens/pglite-upgrade-replay/brain.tar.gz` + `MANIFEST.json`, rebuilt only on master with `bun scripts/build-pglite-upgrade-fixture.ts`) with current code and asserts the catalog before boot equals the E4 golden, the post-boot catalog is pinned, corpus rows and fingerprint survive, and a restart + repeat `initSchema()` is a no-op (no migrations, identical catalog, unchanged relation/constraint/function OIDs; the triggers the blob recreates on every boot are pinned).
- `test/setup-branching.test.ts` — setup flow.
@@ -2107,8 +2127,8 @@ PGLite-only E2E files are a TODOS.md item decided from the pilot measurement.
Source files whose only E2E owner moved (`src/commands/claw-test.ts`,
`src/core/claw-test/**`, `src/core/brain-resolver.ts`, `src/commands/mounts.ts`,
`src/commands/connect.ts`, `src/core/connect-probe.ts`,
-`src/commands/embed-facts-delegate.ts`) no longer have an `E2E_TEST_MAP` row,
-so a change to them selects all E2E (fail-closed); their owners run in every PR.
+`src/commands/embed-facts-delegate.ts`) select all E2E like every other
+code change; their owners run in every PR.
| Former path | New path | Lane | Command | Lane reason |
|---|---|---|---|---|
@@ -2170,13 +2190,13 @@ E2E tests live in `test/e2e/` and run against real Postgres+pgvector (require `D
- `test/e2e/http-transport.test.ts` — `gbrain serve --http` end-to-end against real Postgres: bearer auth round-trip, `last_used_at` SQL-level debounce, `mcp_request_log` row insertion on success and auth_failed paths, `/health` DB-down → 503 (DB-probing health check), and the dispatch round-trip with a real operation. Skips without `DATABASE_URL`.
- `test/e2e/serve-http-oauth.test.ts` — real-Postgres E2E against `gbrain serve --http` with full OAuth 2.1. Spawns a subprocess server, registers a client via the CLI, mints `client_credentials` tokens, exercises the `/mcp` JSON-RPC pipeline. Real DCR `/register` HTTP-level response-shape test (asserts `typeof body.client_id_issued_at === 'number'` over the wire, RFC 7591 §3.2.1); real CLI subprocess test for `revoke-client` (registers → mints token → revokes via `execSync` → asserts token rejected at `/mcp` → asserts re-run exits 1); server fixture flips on `--enable-dcr` so `/register` is reachable. **bun execSync env-inheritance contract:** bun's `execSync` does NOT inherit env mutations done via `process.env.X = ...`, only OS-level env from before bun started. helpers.ts loads `.env.testing` and sets `DATABASE_URL` via `process.env` mutation, which is invisible to subprocesses unless `env: { ...process.env }` is passed explicitly — every subprocess call in this file passes `env: { ...process.env }`. The same contract applies to the sibling sync/cycle/dream/claw-test E2Es. `afterAll` cleanup is guarded on `clientId` (won't throw if `beforeAll` failed before registration); cleanup errors surface to stderr without throwing so real test failures aren't masked. Also covers the trust boundary: an HTTP MCP `submit_job` for `name: "shell"` MUST reject with a permission error (request handler sets `remote: true` and `submit_job`'s protected-name guard fires), and the same guard rejects subagent submission. Skips without `DATABASE_URL`.
- `test/e2e/sync-parallel.test.ts` — `DATABASE_URL`-gated. 60-file Postgres sync at concurrency=4 imports all + no connection leak (probes `pg_stat_activity` before/after to confirm worker engines disconnected). 120-file serial-vs-parallel benchmark prints `SYNC_PARALLEL_BENCH N files | serial=Xms | parallel(4)=Yms | speedup=Zx`. Asserts parallel ≤ serial × 1.5 (CI-noise tolerant; not a strict speedup gate).
-- `test/e2e/multi-source-bug-class.test.ts` — PGLite in-memory regression suite pinning every multi-source bug site: `listAllPageRefs` ordering by `(source_id, slug)`, `getPage` with sourceId picks the right `(source, slug)` row, `extract-takes` processes both overlapping `people/alice` rows independently, `listPages` filters correctly with `PageFilters.sourceId`, `addLinksBatch` with `from/to_source_id` targets the right rows, `validateSourceId` rejects path traversal, reverse-write disk layout uses `brainDir/.sources/<id>/<slug>.md` for non-default sources, `copyMigrationSources` lands source metadata before overlapping-slug pages. No `DATABASE_URL` needed. Wired into `scripts/e2e-test-map.ts` so changes to extract-takes / patterns / synthesize / embed / extract / migrate-engine auto-trigger it.
+- `test/e2e/multi-source-bug-class.test.ts` — PGLite in-memory regression suite pinning every multi-source bug site: `listAllPageRefs` ordering by `(source_id, slug)`, `getPage` with sourceId picks the right `(source, slug)` row, `extract-takes` processes both overlapping `people/alice` rows independently, `listPages` filters correctly with `PageFilters.sourceId`, `addLinksBatch` with `from/to_source_id` targets the right rows, `validateSourceId` rejects path traversal, reverse-write disk layout uses `brainDir/.sources/<id>/<slug>.md` for non-default sources, `copyMigrationSources` lands source metadata before overlapping-slug pages. No `DATABASE_URL` needed.
- `test/e2e/migrate-engine-sources-postgres.test.ts` — `DATABASE_URL`-gated companion for `gbrain migrate --to`: migrates a PGLite brain carrying two non-default sources with overlapping slugs into real Postgres and asserts `copyMigrationSources` created every `sources` FK parent (config JSONB intact, not double-encoded) before any page write. Unit-level manifest identity (crash manifest resumes only against the SAME target; legacy engine-only manifests start fresh) is `test/migrate-engine-resume.test.ts`.
- `test/e2e/facts-fence-reconcile-postgres.test.ts` — `DATABASE_URL`-gated round-trip for the escape-aware fence parser: renders a `## Facts` fence whose cells carry literal pipes, backslashes (Windows paths), and empty cells via `renderFactsTable`, runs the wipe-and-reinsert reconcile (`runExtractFacts`) on real Postgres, and asserts every cell survives byte-identically with no column shift.
- `test/e2e/source-isolation-pglite.test.ts` — PGLite in-memory regression suite pinning the source-isolation seal at two layers. Engine layer: `searchKeyword` / `searchVector` / `searchKeywordChunks` / `listPages` / `getPage` / `traverseGraph` / `traversePaths` apply `sourceId` (scalar fast path) and `sourceIds` (array path) correctly across both engines. Op-handler layer: routes through `sourceScopeOpts(ctx)` so a `read+write`-scoped OAuth client bound to `--source dept-x` cannot see rows from neighboring sources via `search`, `query`, `list_pages`, `get_page`, or `find_experts`. Covers both `ctx.sourceId` (single-source clients) and `ctx.auth.allowedSources` (federated_read clients) precedence; federated array wins over scalar wins over nothing. No `DATABASE_URL` needed.
- `test/e2e/think-source-isolation-pglite.test.ts` — PGLite in-memory suite pinning the `think` gather stage's source scope: seeds three sources with cross-source links and embedded takes, then asserts `runGather` under a federated `sourceIds` grant (and under a scalar `sourceId`) keeps every stream — hybrid retrieval, takes keyword + vector (`searchTakes`/`searchTakesVector`), and the `traversePaths` graph walk — inside the grant while still reaching authorized neighboring sources. No `DATABASE_URL` needed.
- `test/e2e/skill-brain-first.test.ts` — doctor reports `skill_brain_first` check with structured issues; `--fix --dry-run` previews insertion without writing; `--fix` applies the canonical Convention callout idempotently; `brain_first: exempt` frontmatter resolves the warn; `brain_first_typo` surfaces a paste-ready hint; audit JSONL records `detected` / `resolved` / `fixed` transitions; stable brain emits 0 audit lines/run.
-- Journey suites (each claimed by an `scripts/e2e-test-map.ts` row; DATABASE_URL-gated unless noted): `migrate-engine-pglite-to-postgres.test.ts` (whole-brain `runMigrateEngine` transfer incl. the child-process failure arm — config not flipped), `takes-write-ops-postgres.test.ts` (takes op layer + `withPageLock` serialization), `propose-takes-jsonb-postgres.test.ts` + `calibration-profile-write.test.ts` (JSONB bind shape on real Postgres), `engine-parity-cjk.test.ts` (cross-engine CJK keyword parity on an identical corpus — both engines route `hasCJK()` queries through the shared ILIKE builder in `src/core/search/cjk-keyword-sql.ts`; top-slug agreement, chunk-grain parity, mixed-query AND semantics, nonexistent-term strictness), `code-edges-read-parity.test.ts` / `ontology-merge-parity.test.ts` / `chronicle-event-projection-parity.test.ts` / `health-parity-postgres.test.ts` (read-path + getHealth parity), `sync-sigkill-resume-postgres.test.ts` (real SIGKILL mid-sync; DB-polled checkpoint, stranded-lock reclaim, exactly-once resume), `serve-http-source-grant.test.ts` (legacy no-grant federated widening vs granted confinement over real `/mcp`), `autopilot-linux-lifecycle.serial.test.ts` (PATH-shimmed crontab/systemctl arc, hermetic), and the thin-client daily-driver verb extension inside `thin-client.test.ts`.
+- Journey suites (DATABASE_URL-gated unless noted): `migrate-engine-pglite-to-postgres.test.ts` (whole-brain `runMigrateEngine` transfer incl. the child-process failure arm — config not flipped), `takes-write-ops-postgres.test.ts` (takes op layer + `withPageLock` serialization), `propose-takes-jsonb-postgres.test.ts` + `calibration-profile-write.test.ts` (JSONB bind shape on real Postgres), `engine-parity-cjk.test.ts` (cross-engine CJK keyword parity on an identical corpus — both engines route `hasCJK()` queries through the shared ILIKE builder in `src/core/search/cjk-keyword-sql.ts`; top-slug agreement, chunk-grain parity, mixed-query AND semantics, nonexistent-term strictness), `code-edges-read-parity.test.ts` / `ontology-merge-parity.test.ts` / `chronicle-event-projection-parity.test.ts` / `health-parity-postgres.test.ts` (read-path + getHealth parity), `sync-sigkill-resume-postgres.test.ts` (real SIGKILL mid-sync; DB-polled checkpoint, stranded-lock reclaim, exactly-once resume), `serve-http-source-grant.test.ts` (legacy no-grant federated widening vs granted confinement over real `/mcp`), `autopilot-linux-lifecycle.serial.test.ts` (PATH-shimmed crontab/systemctl arc, hermetic), and the thin-client daily-driver verb extension inside `thin-client.test.ts`.
- Tier 2 (`test/e2e/skills.test.ts`) requires OpenClaw + API keys, runs nightly in CI.
- `test/claw-test.slow.test.ts` (slow lane since the lane-move pilot) also covers live mode token-free via shim agents (`OPENCLAW_BIN=<sh script>`): the success-oracle break path (a do-nothing agent FAILS), the E0 child-friction merge surviving tempdir cleanup, and the upgrade staging + schema-version probe.
- If `.env.testing` doesn't exist in this directory, check sibling worktrees: `find ../ -maxdepth 2 -name .env.testing -print -quit` and copy it here if found.
diff --git a/docs/architecture/key-files/tooling-and-tests.md b/docs/architecture/key-files/tooling-and-tests.md
index 271868aa62..66a8746655 100644
--- a/docs/architecture/key-files/tooling-and-tests.md
+++ b/docs/architecture/key-files/tooling-and-tests.md
@@ -3,7 +3,7 @@
[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.
Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
-- `test/e2e/migration-wave-*.test.ts` + `test/helpers/migration-wave-*.ts` — isolated both-engine acceptance for phase-boundary lease loss, oversized-healing rollback, prepared embedding/withdrawal ordering, archived-source refusal, incompatible-model publication, failed partial migration and reopened retrieval, malformed provider batches, and actual SIGKILL around durable authorization reservation/dispatch. Fixtures prove their PostgreSQL database differs from the supplied test base. Providers and reranker pricing are synthetic; phase takeovers are controlled injections, not exhaustive schedules. `scripts/e2e-test-map.ts` routes affected migration, projection and engine changes to these suites.
+- `test/e2e/migration-wave-*.test.ts` + `test/helpers/migration-wave-*.ts` — isolated both-engine acceptance for phase-boundary lease loss, oversized-healing rollback, prepared embedding/withdrawal ordering, archived-source refusal, incompatible-model publication, failed partial migration and reopened retrieval, malformed provider batches, and actual SIGKILL around durable authorization reservation/dispatch. Fixtures prove their PostgreSQL database differs from the supplied test base. Providers and reranker pricing are synthetic; phase takeovers are controlled injections, not exhaustive schedules.
- `test/safety-wave-coverage-export-ledger.test.ts` + `test/safety-wave-coverage-invocation-inheritance.test.ts` — export ledger capacity/read-failure and source-binding contracts, plus nested invocation allowance, settlement and async-isolation checks. These pure fixtures supplement, rather than replace, real-engine snapshot and process-crash acceptance.
@@ -44,7 +44,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `scripts/classify-tests.ts` + `scripts/structural-suites.tsv` — suite-level behavioral-vs-structural test classification (the intent axis described in docs/TESTING.md "File taxonomy"). Content-based detectors — repo-anchored `readFileSync`/`Bun.file` readers, exec-scan grep windows over `src|scripts|docs`, and the `doctorSource()`/`doctorFileSource()` helpers — mark a suite STRUCTURAL when its assertions read repo source/doc text rather than executing product code; tmpdir-anchored reads don't count, and files with detectors but no attributable suite land in an `unknown` bucket emitted as comment rows (surfaced, never silently dropped). Modes: bare = rewrite the TSV; `--check` = byte-for-byte regenerate-and-diff freshness (wired as `bun run check:structural-manifest` in `bun run verify` via `scripts/check-structural-manifest.sh`); `--summary` = counts only. Fix misclassifications in the detector list, never by hand-editing the TSV. `render-coverage-summary.ts` consumes the TSV for the behavioral-vs-structural line in the CI coverage report.
-- `scripts/e2e-matrix.ts` — freezes selected E2E paths after existing named/live exclusions into at most four weighted partitions. Explicit empty sentinel is the only no-op; malformed/missing input fails. Workers validate paths and filesystem confinement, pass argv directly, clear inherited SHARD and register cancellation handlers before spawning, retaining any signal received before the child handle is available. `prepare-e2e` and every worker are required by e2e-status; each worker owns Postgres. Pinned by `test/scripts/e2e-matrix.test.ts` and workflow wiring tests.
+- `scripts/e2e-matrix.ts` — freezes selected E2E paths after the named-job, live-key, persistence-validation and backend-matrix exclusions (`E2E_EXCLUSIONS`; every `test/e2e/` row of `scripts/e2e-backend-matrix.txt` belongs to the `tier1-backend-matrix` job) into at most eight weighted partitions, printing each excluded file's owner. Explicit empty sentinel is the only no-op; malformed/missing input fails. Workers validate paths and filesystem confinement, pass argv directly, clear inherited SHARD and register cancellation handlers before spawning, retaining any signal received before the child handle is available. `prepare-e2e` and every worker are required by e2e-status; each worker owns Postgres. Pinned by `test/scripts/e2e-matrix.test.ts` and workflow wiring tests.
- `.github/workflows/e2e.yml` + `scripts/verify-nightly-e2e.ts` — full E2E discovery runs on four weighted, independent Postgres workers, sequential fresh Bun processes within each. Schedules and explicit default-false `full_corpus` manual dispatches share the same full-profile jobs, aggregation, reports and receipts; ordinary selection is unchanged and full manual runs have their own concurrency group. Each worker bootstraps its guarded service schema through `setupLegacyEmbeddingDB()` under a keyless temporary home before tests. No selected-lane exclusions apply. Workers publish distinct `e2e-N` coverage manifests and successful executed-file receipts; full-profile `e2e-status` requires successful job results plus exact, disjoint, same-commit partitions. The advisory report validates those receipts before merging all four multi-file LCOV lanes. Coverage count is not executed-file count: skip-only files may emit no LCOV. `test/scripts/nightly-e2e.test.ts`, `e2e-runner.test.ts`, `ci-gates.test.ts` and `merge-lcov.test.ts` pin discovery, isolation, failure/cancellation, artifacts and completeness. See docs/TESTING.md for cross-lane coverage responsibilities.
@@ -58,7 +58,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `scripts/llms-config.ts` + `scripts/build-llms.ts` — Generator for `llms.txt` (llmstxt.org-spec web index) + `llms-full.txt` (inlined single-fetch bundle). Curated config drives both. Run `bun run build:llms` after adding a new doc. `LLMS_REPO_BASE` env lets forks regenerate with their own URL base. `FULL_SIZE_BUDGET` (600KB) caps the inline bundle; generator WARNs if exceeded. Committed output has no runtime consumer; committed for GitHub browsing and fork-safe fetching.
-- `scripts/merge-lcov.ts` + `scripts/coverage-diff-gate.ts` + `scripts/coverage-baseline-gate.ts` + `scripts/update-coverage-baseline.ts` + `scripts/render-coverage-summary.ts` + `scripts/coverage-gate-exemptions.txt` + `scripts/coverage-baseline.json` — the coverage measurement + gating cluster; the operating guide is docs/TESTING.md "Coverage lanes and gates". `merge-lcov.ts` walks artifact dirs for `lcov.info` + `lane-manifest.json`, sums DA hits per file:line, normalizes paths repo-relative, and emits a merged lcov + summary JSON (src-only totals/per-dir/per-file, the `lineHits` extension the diff gate consumes, and never-loaded src files as count + sorted list — deliberately never a percentage, since physical lines ≠ executable lines); `--manifest-expect` pins the lane set; SHA, duplicate identities, and actual per-lane LCOV counts are validated (`--sha` supports offline artifacts), and a missing/incomplete lane or a `shard` lane with `lcovCount != 1` (the xargs-batching tripwire) marks the summary `degraded: true` — still exit 0 (degraded is data, and both gates go report-only on it). `coverage-diff-gate.ts` gates added/changed gate-scoped lines (non-test, non-generated `src/**.ts`) at ≥80% covered plus zero changed-but-never-loaded files; report-only unless `COVERAGE_GATE_ENFORCE=1`; a `[coverage-exempt: reason]` commit trailer passes with a loud warning; `coverage-gate-exemptions.txt` rows (exact path or trailing-`/` prefix; SHRINK-ONLY — additions need a graduation review) are excluded from the gate but still reported (`[e2e-exempt]` / `[subprocess-undercount]`); exit contract: 0 = pass or report-only, 1 = fail while enforcing, 2 = infrastructure error (never conflated with a coverage verdict). `coverage-baseline-gate.ts` reads the baseline via `git show origin/master:scripts/coverage-baseline.json` (never the working tree, so a PR can't weaken its own bar) and compares corpus-matched sections only (`--corpus prCorpus|fullCorpus`), failing on >0.5pp global or >1.0pp per-dir drops; `provisional: true` in the baseline (the current state — both corpus sections unseeded) keeps it report-only regardless of enforcement; `update-coverage-baseline.ts` writes the working-tree baseline (per-file detail limited to the committed `watchlist`) and `--promote` flips `provisional: false`. `render-coverage-summary.ts` renders the summary JSON as markdown on stdout for `$GITHUB_STEP_SUMMARY`, including the behavioral-vs-structural counts from `scripts/structural-suites.tsv`. Wiring: 15 PR-corpus lanes in test.yml (8 matrix shards + four serial partitions + the three dedicated slow jobs) upload `coverage-*` artifacts and the advisory `coverage-report` job merges + renders + runs both gates report-only (deliberately absent from `test-status`/`cache-write` until graduation); scheduled or explicitly dispatched `coverage-full-{unit,serial,slow,e2e}` + `coverage-full-report` in e2e.yml produce the self-contained fullCorpus number (full e2e glob included) and the `coverage-full-merged` trend artifact. Collection is `COVERAGE_DIR`-opt-in in `test-shard.sh`/`run-serial-tests.sh`/`run-e2e.sh` — unique coverage dir per bun process (a reused dir overwrites `lcov.info`), lane manifest written only on a green run, `run-e2e.sh` requires an ABSOLUTE `COVERAGE_DIR` and honors `E2E_FILE_TIMEOUT_SECS` (both deliberately non-`GBRAIN_`-prefixed to survive the hermetic env scrub). Bun/JSC emits line records only (function coverage is informational) and no subprocess coverage, so `src/cli.ts` undercounts. Pinned by `test/scripts/merge-lcov.test.ts`, `test/scripts/coverage-diff-gate.test.ts`, `test/scripts/render-coverage-summary.test.ts`.
+- `scripts/merge-lcov.ts` + `scripts/coverage-diff-gate.ts` + `scripts/coverage-baseline-gate.ts` + `scripts/update-coverage-baseline.ts` + `scripts/render-coverage-summary.ts` + `scripts/coverage-gate-exemptions.txt` + `scripts/coverage-baseline.json` — the coverage measurement + gating cluster; the operating guide is docs/TESTING.md "Coverage lanes and gates". `merge-lcov.ts` walks artifact dirs for `lcov.info` + `lane-manifest.json`, sums DA hits per file:line, normalizes paths repo-relative, and emits a merged lcov + summary JSON (src-only totals/per-dir/per-file, the `lineHits` extension the diff gate consumes, and never-loaded src files as count + sorted list — deliberately never a percentage, since physical lines ≠ executable lines); `--manifest-expect` pins the lane set; SHA, duplicate identities, and actual per-lane LCOV counts are validated (`--sha` supports offline artifacts), and a missing/incomplete lane or a `shard` lane with `lcovCount != 1` (the xargs-batching tripwire) marks the summary `degraded: true` — still exit 0 (degraded is data, and both gates go report-only on it). `coverage-diff-gate.ts` gates added/changed gate-scoped lines (non-test, non-generated `src/**.ts`) at ≥80% covered plus zero changed-but-never-loaded files; report-only unless `COVERAGE_GATE_ENFORCE=1`; a `[coverage-exempt: reason]` commit trailer passes with a loud warning; `coverage-gate-exemptions.txt` rows (exact path or trailing-`/` prefix; SHRINK-ONLY — additions need a graduation review) are excluded from the gate but still reported (`[e2e-exempt]` / `[subprocess-undercount]`); exit contract: 0 = pass or report-only, 1 = fail while enforcing, 2 = infrastructure error (never conflated with a coverage verdict). `coverage-baseline-gate.ts` reads the baseline via `git show origin/master:scripts/coverage-baseline.json` (never the working tree, so a PR can't weaken its own bar) and compares corpus-matched sections only (`--corpus prCorpus|fullCorpus`), failing on >0.5pp global or >1.0pp per-dir drops; `provisional: true` in the baseline (the current state — both corpus sections unseeded) keeps it report-only regardless of enforcement; `update-coverage-baseline.ts` writes the working-tree baseline (per-file detail limited to the committed `watchlist`) and `--promote` flips `provisional: false`. `render-coverage-summary.ts` renders the summary JSON as markdown on stdout for `$GITHUB_STEP_SUMMARY`, including the behavioral-vs-structural counts from `scripts/structural-suites.tsv`. Wiring: 14 PR-corpus lanes in test.yml (8 matrix shards + four serial partitions + the two dedicated slow jobs) upload `coverage-*` artifacts and the advisory `coverage-report` job merges + renders + runs both gates report-only (deliberately absent from `test-status`/`cache-write` until graduation); scheduled or explicitly dispatched `coverage-full-{unit,serial,slow,e2e}` + `coverage-full-report` in e2e.yml produce the self-contained fullCorpus number (full e2e glob included) and the `coverage-full-merged` trend artifact. Collection is `COVERAGE_DIR`-opt-in in `test-shard.sh`/`run-serial-tests.sh`/`run-e2e.sh` — unique coverage dir per bun process (a reused dir overwrites `lcov.info`), lane manifest written only on a green run, `run-e2e.sh` requires an ABSOLUTE `COVERAGE_DIR` and honors `E2E_FILE_TIMEOUT_SECS` (both deliberately non-`GBRAIN_`-prefixed to survive the hermetic env scrub). Bun/JSC emits line records only (function coverage is informational) and no subprocess coverage, so `src/cli.ts` undercounts. Pinned by `test/scripts/merge-lcov.test.ts`, `test/scripts/coverage-diff-gate.test.ts`, `test/scripts/render-coverage-summary.test.ts`.
- `scripts/persistence/{harness,schedules,worker,validate,failure-diagnostics}.ts` — executable concurrency gate using real journal/coordinator APIs: 1,000 seeded schedules per engine, eight actual process-kill publication boundaries, and 10,000 writes from four producer processes. Each phase owns a temporary disk PGLite datastore or a fresh test Postgres database. Independent accounting queries verify conservation; every soak receipt is compared to its canonical snapshot and file. JSON manifests separate actual counts and latency measurements from the configured Linux/Bun CI matrix. Failed runs preserve private fixtures and collect bounded, allowlisted request/queue/owner diagnostics without changing deadlines or hiding the original error. Cleanup commands read the existing test URL from the environment. The PGLite loopback endpoint is a fixture transport, not production authentication coverage. Contract and commands: `scripts/persistence/README.md`; smoke entries: `test/persistence-chaos.slow.test.ts`, `test/e2e/persistence-chaos.test.ts`; diagnostic/retention contracts: `test/persistence-failure-diagnostics.test.ts`.
@@ -68,14 +68,14 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `scripts/r1-namedthing-rerank-ab.ts` — Phase C′ rule R1 receipt: balanced reranker ON vs OFF on NamedThingBench, paired per query, in ONE in-memory PGLite brain seeded ONCE with real embeddings (`seedNamedThingCorpus`; `--relational` adds `relational/corpus.ts` + its 38 `RELATIONAL_QUESTIONS`, which with the fixture's own `graph-relationship` query are the 39 relational questions the receipt reports beside the 11 non-relational core queries). Arms are applied with `engine.setConfig` (`ARM_PINS`: OFF = `search.mode balanced`, `search.reranker.enabled false`, `search.autocut false`; ON adds `search.reranker.enabled true` + `search.reranker.model voyage:rerank-2.5`; autocut pinned off in both by default — a rerank-only comparison — and `--autocut on|off` is an overlay applied to BOTH arms through `applyArmPins(engine, arm, overlay)` so the ON arm can run in the pre-R2 shipped balanced shape (autocut on) without changing the pinned defaults the tests pin), so bare `hybridSearch` resolves them the way a production balanced brain would; scoring reuses `runRetrievalQuality`/`evaluateGate` (no local hit@k). Per query it records deduped top-3, the rank-1 `evidence`/`create_safety` tier, finite-`rerank_score` row count and the `degraded` stamp. INVARIANTS: readiness (`rerankerReadinessForEngine`) is checked BEFORE any spend and the ON arm must show no `reranker_skipped`/`rerank_passthrough` stage and ≥1 reranked row per non-empty query, else exit 2 (fail-open would silently turn ON into OFF); embedding degradation (`embed_unavailable`/`embed_timeout`/`vector_arm_failed`) in a live arm is exit 2 too; `--embed-cache PATH` (`installEmbedCache`) makes both arms see byte-identical query vectors and the receipt says whether that held (`identical_query_vectors`). `r1Verdict` is pure: PASS iff hit@1 losses == 0 and hit@3 losses ≤ 1, losses counted per query (OFF hit, ON miss) and never offset by wins; create_safety downgrades are counted and named, not gated. A pass-through rerank transport tees the API-echoed model id + usage into the receipt. `--stub-embed` is the hermetic dry run (embed transport throws, OFF arm only, ON reported as skipped — needs `VOYAGE_API_KEY`). `--json` carries `_meta.metric_glossary` (`hit@1`, `hit@3`, `mrr`, `create_safety`); exit 0 PASS/dry-run · 1 FAIL · 2 integrity/usage. Receipt (shipped `balanced`, `voyage:rerank-2.5`): the 11 core queries show 0 hit@1 / 0 hit@3 losses in every cell; the 39 relational queries WITHOUT the relational re-pin fell hit@1 21→3 (19 losses) and hit@3 27→5 (22 losses) — R1 FAIL; WITH `search.relational_rerank_pin` at its default 3 (measured with `--autocut on`, the shape that shipped before rule R2 turned autocut off) 0 losses, hit@1 21/39 and hit@3 27/39 — R1 PASS, the balanced reranker stays ON. `--relational-pin N|off` overlays `search.relational_rerank_pin` on BOTH arms: the no-pin cell is `--relational-pin off` (or `0`); the default cell omits the flag and resolves the bundle default 3 exactly as production does. Pinned by `test/r1-namedthing-rerank-ab.test.ts`.
-- `scripts/run-e2e.sh` — Sequential E2E runner. Accepts an optional argv-driven file list (used by `ci:local:diff`) and a `--dry-run-list` flag that prints the resolved file list and exits (used by `ci-local.sh`'s startup smoke-test). Falls back to `test/e2e/*.test.ts` plus `test/phantom-redirect-engine-parity.test.ts` when invoked with no args (the phantom-redirect Postgres arm is only reachable through a DATABASE_URL-bearing lane; the unit wrappers strip the URL, so this lane must carry it). This wrapper is the database-URL opt-in boundary: it exports `GBRAIN_TEST_ALLOW_DATABASE_URL=1` so the bunfig preload guard (`test/helpers/database-url-guard-preload.ts`) lets the run start, unsets `GBRAIN_DATABASE_URL` (the e2e suite runs on `DATABASE_URL` only — an ambient `GBRAIN_DATABASE_URL` would pass the opt-in yet reach CLI-subprocess paths with no name floor), and its GBRAIN_* env scrub preserves `GBRAIN_E2E_ALLOW_DB` so the name-floor escape hatch the guard's own error message names stays usable. It also preserves `GBRAIN_CI_DISABLE_TEST_ENV_FILE=1`, keeping CI runs from loading checkout-local `.env.testing` credentials after the shell-to-Bun handoff. It also exports `GBRAIN_TEST_KEEP_PROVIDER_KEYS=1` so the unit-lane provider-key strip preload (`test/helpers/provider-keys-preload.ts`) leaves the real keys that live embed/parity e2e tests skip-gate on. Each file runs under a gtimeout/timeout wedge backstop (default signal: SIGTERM — the bun test child installs no JS-level handler for it, so kernel-default termination applies) — 180s default, with a per-file override for known-slow files (`skills.test.ts` gets 420s: the real ingest-skill run replays every migration, so its floor grows as master adds migrations); the cap is a wedge backstop, not a per-test budget, and bare `bun` (no outer cap) is the fallback when neither timeout binary is installed. It activates the PGLite schema snapshot like the other runners: sources `scripts/lib/test-env.sh` + `ensure_pglite_snapshot` after the `--dry-run-list` early exit (list mode stays instant; non-fatal on build failure), re-exports `GBRAIN_PGLITE_SNAPSHOT` as an ABSOLUTE path (e2e tests spawn CLI subprocesses with varying cwd — a relative path silently misses the tar there), and its env keep-list preserves the var; e2e files that assert the path TO post-`initSchema()` state carry per-file `delete process.env.GBRAIN_PGLITE_SNAPSHOT` opt-outs with one-line reasons. Each file pass records an executed-test receipt (below) that keeps its native JUnit report; processes still running with a file's HOME after its bun process exits are killed and named, and a HOME that still cannot be removed fails that file by name while the partition continues. `executed-files.txt` lists every attempted file, pass or fail; `lane-manifest.json` (`complete:true`) is written only on a green run.
+- `scripts/run-e2e.sh` — Sequential E2E runner. Accepts an optional argv-driven file list (used by the Selected E2E workers) and a `--dry-run-list` flag that prints the resolved file list and exits (used by `ci-local.sh`'s startup smoke-test). Falls back to `test/e2e/*.test.ts` plus `test/phantom-redirect-engine-parity.test.ts` when invoked with no args (the phantom-redirect Postgres arm is only reachable through a DATABASE_URL-bearing lane; the unit wrappers strip the URL, so this lane must carry it). This wrapper is the database-URL opt-in boundary: it exports `GBRAIN_TEST_ALLOW_DATABASE_URL=1` so the bunfig preload guard (`test/helpers/database-url-guard-preload.ts`) lets the run start, unsets `GBRAIN_DATABASE_URL` (the e2e suite runs on `DATABASE_URL` only — an ambient `GBRAIN_DATABASE_URL` would pass the opt-in yet reach CLI-subprocess paths with no name floor), and its GBRAIN_* env scrub preserves `GBRAIN_E2E_ALLOW_DB` so the name-floor escape hatch the guard's own error message names stays usable. It also preserves `GBRAIN_CI_DISABLE_TEST_ENV_FILE=1`, keeping CI runs from loading checkout-local `.env.testing` credentials after the shell-to-Bun handoff. It also exports `GBRAIN_TEST_KEEP_PROVIDER_KEYS=1` so the unit-lane provider-key strip preload (`test/helpers/provider-keys-preload.ts`) leaves the real keys that live embed/parity e2e tests skip-gate on. Each file runs under a gtimeout/timeout wedge backstop (default signal: SIGTERM — the bun test child installs no JS-level handler for it, so kernel-default termination applies) — 180s default, with a per-file override for known-slow files (`skills.test.ts` gets 420s: the real ingest-skill run replays every migration, so its floor grows as master adds migrations); the cap is a wedge backstop, not a per-test budget, and bare `bun` (no outer cap) is the fallback when neither timeout binary is installed. It activates the PGLite schema snapshot like the other runners: sources `scripts/lib/test-env.sh` + `ensure_pglite_snapshot` after the `--dry-run-list` early exit (list mode stays instant; non-fatal on build failure), re-exports `GBRAIN_PGLITE_SNAPSHOT` as an ABSOLUTE path (e2e tests spawn CLI subprocesses with varying cwd — a relative path silently misses the tar there), and its env keep-list preserves the var; e2e files that assert the path TO post-`initSchema()` state carry per-file `delete process.env.GBRAIN_PGLITE_SNAPSHOT` opt-outs with one-line reasons. Each file pass records an executed-test receipt (below) that keeps its native JUnit report; processes still running with a file's HOME after its bun process exits are killed and named, and a HOME that still cannot be removed fails that file by name while the partition continues. `executed-files.txt` lists every attempted file, pass or fail; `lane-manifest.json` (`complete:true`) is written only on a green run.
- `scripts/lib/test-env.sh` receipts (`receipts_init`, `receipt_begin`, `receipt_end`, `receipt_empty`) + `scripts/run-with-receipt.sh` + `scripts/ci-executed-counts.ts` — executed-test receipts and the identity ledger. With `GBRAIN_TEST_RECEIPT_DIR` set, every bun invocation a runner makes (test-shard, run-unit-shard per file, run-unit-parallel rescue passes, run-serial-tests pooled and rescue runs, run-slow-tests, run-e2e per file pass, and CI's bare `bun test` steps through `run-with-receipt.sh <lane> <tag> -- bun test ...`) writes `<id>.receipt` (lane, kind primary/rerun/rescue, shard/of, arm, sha, run id and attempt, exit), `<id>.files` and Bun's JUnit report; the runner unsets the variables so tests and nested runners never inherit them (`GBRAIN_TEST_RECEIPT_LANE` overrides the default lane). `run-unit-parallel.sh` writes receipts by default under `.context/test-receipts/`. `run-verify-parallel.sh` records each check as pass, fail, timeout or skip (a self-skipping check prints `GBRAIN_CHECK_SKIPPED: <reason>`) in `outcomes.tsv` and a JUnit receipt, and keeps its logs on failure. `ci-executed-counts.ts --head-run <id>[,<id>] [--base-run ...]` (or `--head-dir/--base-dir`) accounts for every test by (lane, file, test, arm): repeated names inside a file are numbered by occurrence, a later rerun/rescue supersedes earlier attempts for its files, and missing, truncated or prior-attempt receipts, missing shards, empty lanes and missing artifacts make the result `incomplete` (exit 1). Each base identity that no longer executes must match a row of the expected-deltas TSV (`--deltas`; retire with evidence, move, skip, job), or the tool prints the row to add. test.yml and e2e.yml upload `receipts-<lane>` artifacts and run it report-only in their `executed-receipts` jobs (e2e also prints the missing-provider-key skip count). Tests: `test/scripts/ci-executed-counts.test.ts`, `test/scripts/run-with-receipt.test.ts`.
Every file needs a fresh parent-owned native JUnit report, its selected-file header and matching final console totals; zero exit alone or a nested child's summary cannot establish completion. All-skipped reports remain valid and explicit. Coverage runs atomically claim a new destination, refusing existing paths without deleting their contents, and write `executed-files.txt` plus a same-commit manifest only after all selected files succeed. `SHARD=N/M` produces lane `e2e-N`; unsharded runs retain `e2e`. The per-file LCOV directories remain independent, and the nightly validator accounts for every partition without equating LCOV count with executed-file count.
-- `scripts/select-e2e.ts` + `scripts/e2e-test-map.ts` — Diff-aware E2E test selector. Reads three git sources (committed `origin/master...HEAD`, working-tree `HEAD`, and `git ls-files --others --exclude-standard` for untracked NOT-gitignored files), classifies as EMPTY / DOC_ONLY / SRC. Fail-closed: EMPTY → all files; DOC_ONLY (every path matches the README/CLAUDE/AGENTS/CHANGELOG/TODOS allowlist) → empty stdout; SRC → escape-hatch paths (schema, package.json, skills/) trigger all, else the hand-tuned `E2E_TEST_MAP` glob narrows, and an unmapped src/ change still emits ALL files (never silently nothing). Pure-function exports `selectTests`, `classify`, `matchGlob`. `bun run ci:select-e2e` prints the current selection on stdout. `test/select-e2e.test.ts` covers all 4 branches plus 3 guards (skills/, untracked files, unmapped src/) — 24 cases.
+- `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. 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/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. 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/llms-full.txt b/llms-full.txt
index bf63b87dd2..0cf93f3351 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -1844,14 +1844,14 @@ writing or reviewing an operation, consult `src/core/operations.ts` for the cont
Easiest path: `bun run ci:local` runs the full CI gate inside Docker (gitleaks,
guards + typecheck, then 4-shard parallel unit + E2E against four pgvector
containers plus a transaction-mode PgBouncer; unit phase keeps `DATABASE_URL`
-unset) and tears down. Use `bun run ci:local:diff` for the
-diff-aware subset during fast iteration on a focused branch. Requires Docker
+unset) and tears down. `bun run ci:local:diff` checks a doc-only diff in
+seconds (gitleaks plus the doc checks) and runs the full gate otherwise. Requires Docker
(Docker Desktop / OrbStack / Colima) and `gitleaks` (`brew install gitleaks`).
Fastest path, with a Ubicloud token (`UBICLOUD_API_KEY` or
`UBICLOUD_API_TOKEN`): `bun run ci:ubicloud` runs the same gate across ten
ephemeral VMs in about five minutes, uncommitted edits included
-(`ci:ubicloud:diff` for the diff-aware subset). See "Ubicloud fan-out" in
+(`ci:ubicloud:diff` for the doc-only fast path). See "Ubicloud fan-out" in
[`docs/TESTING.md`](./docs/TESTING.md).
Manual path: `bun test` plus the E2E lifecycle described in `./CLAUDE.md` (spin