Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
test(ci): split the long-pole graduation, reconcile-crash and write-attribution files; wire them into CI; seed weights
garrytanf618b792d1fb
diff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.ymlindex 5c421092f4..b4315e9019 100644--- a/.github/workflows/e2e.yml+++ b/.github/workflows/e2e.yml@@ -364,7 +364,7 @@ jobs:# Excluded from the selected matrix (scripts/e2e-matrix.ts) so they# run once. Named files only, no glob.shell: bash- run: bash scripts/run-e2e.sh test/e2e/graduation-cli.test.ts test/e2e/graduation-clients.test.ts test/e2e/graduation-crash.test.ts test/e2e/graduation-faults.test.ts test/e2e/graduation-legacy-copy.test.ts+ run: bash scripts/run-e2e.sh test/e2e/graduation-cli.test.ts test/e2e/graduation-cli-topologies.test.ts test/e2e/graduation-cli-history.test.ts test/e2e/graduation-cli-zero-mutation-1.test.ts test/e2e/graduation-cli-zero-mutation-2.test.ts test/e2e/graduation-cli-zero-mutation-3.test.ts test/e2e/graduation-clients.test.ts test/e2e/graduation-clients-serve.test.ts test/e2e/graduation-crash-run-1.test.ts test/e2e/graduation-crash-run-2.test.ts test/e2e/graduation-crash-run-3.test.ts test/e2e/graduation-crash-rollback-1.test.ts test/e2e/graduation-crash-rollback-2.test.ts test/e2e/graduation-faults.test.ts test/e2e/graduation-legacy-copy.test.tsenv:DATABASE_URL: postgresql://postgres:postgres@localhost:5432/gbrain_testGBRAIN_PGBOUNCER_URL: postgresql://postgres:postgres@localhost:55433/gbrain_test?prepare=false@@ -754,7 +754,7 @@ jobs:- run: bun test test/export-scale.slow.test.ts --timeout=900000 --coverage --coverage-reporter=lcov --coverage-dir=${{ runner.temp }}/coverage/slow-eenv:GBRAIN_TEST_EXPORT_SCALE_PAGES: '10001'- - run: bun test test/reconcile-crash.slow.test.ts --timeout=180000 --coverage --coverage-reporter=lcov --coverage-dir=${{ runner.temp }}/coverage/slow-f+ - run: bun test test/reconcile-crash-*.slow.test.ts --timeout=180000 --coverage --coverage-reporter=lcov --coverage-dir=${{ runner.temp }}/coverage/slow-f- name: Write coverage lane manifestrun: |printf '{"lane":"slow","sha":"%s","lcovCount":%s,"complete":true}\n' \diff --git a/.github/workflows/persistence-validation.yml b/.github/workflows/persistence-validation.ymlindex 31625d28db..3549fc0716 100644--- a/.github/workflows/persistence-validation.yml+++ b/.github/workflows/persistence-validation.yml@@ -417,7 +417,7 @@ jobs:if [ '${{ matrix.engine }}' = 'postgres' ]; thenbun --no-env-file test --timeout=180000 test/e2e/reconcile-crash.test.ts test/e2e/reconcile-crash-unactivated.test.tselse- env -u DATABASE_URL -u GBRAIN_DATABASE_URL bun --no-env-file test --timeout=180000 test/reconcile-crash.slow.test.ts+ env -u DATABASE_URL -u GBRAIN_DATABASE_URL bun --no-env-file test --timeout=180000 test/reconcile-crash-*.slow.test.tsfi- name: Upload reconciliation crash manifestsif: always()diff --git a/docs/TESTING.md b/docs/TESTING.mdindex 72ca297dd0..ff7da4c0a5 100644--- a/docs/TESTING.md+++ b/docs/TESTING.md@@ -412,7 +412,7 @@ Test command tiers, each with a clear scope:| `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, whole-tree greps), then the self-timed `SOLO_CHECKS` alone ([why](operations/verify-and-nightly-e2e.md#verify-solo-checks)). Two evals ride the unit lane instead ([why](operations/verify-and-nightly-e2e.md#evals-in-the-unit-lane)). The `CHECKS` array in that script is the single source of truth — CI literally calls `bun run verify` in a dedicated job. | ~65-85s | 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` 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 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 | 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` | The `*.serial.test.ts` set listed in `scripts/serial-files.tsv`, one Bun process per file, run through a pool of concurrent per-file processes (`min(detect_cpus, 4)`, memory-adapted) heaviest-first from `scripts/serial-weights.json` (absent weights fall back to the corpus p75; scheduling only). The `EXCLUSIVE_FILES` in `scripts/run-serial-tests.sh` (machine-global state, at most 3) run sequentially after the pool, on shard 1 only. Per-test timeout 120s; each pooled file is killed at 300s. `SHARD=N/M` partitions pooled files by duration. Externally killed files get one sequential rescue run. Knobs: `GBRAIN_SERIAL_POOL=N` (`1` is fully sequential), `GBRAIN_SERIAL_FILE_TIMEOUT`. | a few minutes 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. |@@ -463,7 +463,7 @@ A sleeping machine kills the run with no signal, so teardown never runs: on Capy`ci:ubicloud` as a watched background operation. After any interrupted run, check`ubi-runner.sh list --mine` and reap leftovers with `down NAME` (or `gc HOURS`, own VMs only).-The project quota is 256 vCPUs, shared with PR CI, and one full gate takes 64.+The project quota is 512 vCPUs, shared with PR CI; a full gate takes 64, or 160 when it is free.In a multi-lane wave, lanes run `ci:ubicloud:diff` or targeted suites (`buntest <files>`, `--lanes`); only the integrator runs the full gate.@@ -1259,7 +1259,7 @@ 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 `reconcile-crash.slow.test.ts` runs only in persistence-validation) plus keyless-allowlisted `evals/**/*.test.ts` (`test/scripts/evals-collection.test.ts`). 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 run only in persistence-validation) plus keyless-allowlisted `evals/**/*.test.ts` (`test/scripts/evals-collection.test.ts`). 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."- **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.diff --git a/scripts/e2e-backend-matrix.txt b/scripts/e2e-backend-matrix.txtindex c5c48ec111..515f295a91 100644--- a/scripts/e2e-backend-matrix.txt+++ b/scripts/e2e-backend-matrix.txt@@ -48,6 +48,7 @@ test/e2e/evidence-delivery-parity.test.tstest/e2e/apply-migrations-orchestration-lock.test.tstest/e2e/postgres-poisoned-connection.test.tstest/e2e/write-attribution-postgres.test.ts+test/e2e/write-attribution-timeline-10k-postgres.test.tstest/e2e/write-attribution-read-parity.test.tstest/e2e/feedback-parity.test.tstest/e2e/mentions-parity.test.tsdiff --git a/scripts/e2e-matrix.ts b/scripts/e2e-matrix.tsindex a2a8044b31..159c6d4d76 100644--- a/scripts/e2e-matrix.ts+++ b/scripts/e2e-matrix.ts@@ -43,8 +43,18 @@ export const E2E_EXCLUSIONS = new Set(['test/e2e/voyage-multimodal.test.ts',// Engine graduation: run once by tier1's graduation step (direct Postgres + PgBouncer).'test/e2e/graduation-cli.test.ts',+ 'test/e2e/graduation-cli-topologies.test.ts',+ 'test/e2e/graduation-cli-history.test.ts',+ 'test/e2e/graduation-cli-zero-mutation-1.test.ts',+ 'test/e2e/graduation-cli-zero-mutation-2.test.ts',+ 'test/e2e/graduation-cli-zero-mutation-3.test.ts','test/e2e/graduation-clients.test.ts',- 'test/e2e/graduation-crash.test.ts',+ 'test/e2e/graduation-clients-serve.test.ts',+ 'test/e2e/graduation-crash-run-1.test.ts',+ 'test/e2e/graduation-crash-run-2.test.ts',+ 'test/e2e/graduation-crash-run-3.test.ts',+ 'test/e2e/graduation-crash-rollback-1.test.ts',+ 'test/e2e/graduation-crash-rollback-2.test.ts','test/e2e/graduation-faults.test.ts','test/e2e/graduation-legacy-copy.test.ts',...PERSISTENCE_VALIDATION_OWNED,diff --git a/scripts/e2e-weights.json b/scripts/e2e-weights.jsonindex c5fceaf982..a824e140b5 100644--- a/scripts/e2e-weights.json+++ b/scripts/e2e-weights.json@@ -141,6 +141,19 @@"test/e2e/global-basename-pglite.test.ts": 2230,"test/e2e/google-attachments-postgres.test.ts": 34520,"test/e2e/google-loops-recovery-postgres.test.ts": 10230,+ "test/e2e/graduation-cli-history.test.ts": 180000,+ "test/e2e/graduation-cli-topologies.test.ts": 52000,+ "test/e2e/graduation-cli-zero-mutation-1.test.ts": 128000,+ "test/e2e/graduation-cli-zero-mutation-2.test.ts": 126000,+ "test/e2e/graduation-cli-zero-mutation-3.test.ts": 129000,+ "test/e2e/graduation-cli.test.ts": 75000,+ "test/e2e/graduation-clients-serve.test.ts": 60000,+ "test/e2e/graduation-clients.test.ts": 140000,+ "test/e2e/graduation-crash-rollback-1.test.ts": 91000,+ "test/e2e/graduation-crash-rollback-2.test.ts": 72000,+ "test/e2e/graduation-crash-run-1.test.ts": 120000,+ "test/e2e/graduation-crash-run-2.test.ts": 101000,+ "test/e2e/graduation-crash-run-3.test.ts": 105000,"test/e2e/grandfather-projection-postgres.test.ts": 13090,"test/e2e/graph-quality.test.ts": 2230,"test/e2e/graph-signals-engine.test.ts": 1386,@@ -385,6 +398,8 @@"test/e2e/worker-readiness-cli.test.ts": 4010,"test/e2e/workspace-generic-compat.test.ts": 379,"test/e2e/worktree-refresh-postgres.test.ts": 22420,+ "test/e2e/write-attribution-postgres.test.ts": 60000,+ "test/e2e/write-attribution-timeline-10k-postgres.test.ts": 145000,"test/e2e/write-contract-conformance.test.ts": 47450,"test/e2e/zombie-reaping.test.ts": 9600,"test/phantom-redirect-engine-parity.test.ts": 2500diff --git a/scripts/persistence/README.md b/scripts/persistence/README.mdindex 21508b7e69..88dd175584 100644--- a/scripts/persistence/README.md+++ b/scripts/persistence/README.md@@ -315,7 +315,7 @@ backups, ordinary mutations after repair, and competing publications.HTTP and stdio PGLite owners before and after activation, restarts the owner, andindependently reads the newly remembered private fact and provenance.-`test/reconcile-crash.slow.test.ts` and `test/e2e/reconcile-crash*.test.ts` kill real+`test/reconcile-crash-*.slow.test.ts` and `test/e2e/reconcile-crash*.test.ts` kill realprocesses at all eight publication boundaries with activation off/on. PostgreSQLuses one file per activation state to stay within the unchanged per-file cap. Optional`GBRAIN_TEST_RECONCILE_CRASH_MANIFEST_DIR` retains executed-case evidence.@@ -551,17 +551,23 @@ seed and size (`GBRAIN_GRADUATION_FIXTURE_CACHE`, default`~/.cache/gbrain-graduation-fixtures`). A restore re-homes paths and ownerstamps and marks sources synced, so the source doctor stays green.-The E2E suites drive the real CLI in child processes:-`graduation-crash` (SIGKILL at every run and rollback boundary),-`graduation-faults` (ENOSPC on a tmpfs tablespace, which needs Docker;-password rotation; DDL route mismatch), `graduation-clients` (older-releases, respawned and resident serve, stale CLI and MCP configs) and-`graduation-cli` (agent flow, zero-mutation `--plan`/`--status`, `--force`,-PgBouncer through `GBRAIN_PGBOUNCER_URL`, a NOSUPERUSER role, the 1k round-trip). Kill and pause points come from `graduationBoundary()` hooks that only+The E2E suites drive the real CLI in child processes, each split into files+of about two minutes or less so CI queues spread them:+`graduation-crash-run-N` and `graduation-crash-rollback-N` (SIGKILL at every+run and rollback boundary), `graduation-faults` (ENOSPC on a tmpfs+tablespace, which needs Docker; password rotation; DDL route mismatch),+`graduation-clients` (older releases) and `graduation-clients-serve`+(respawned and resident serve, stale CLI and MCP configs), and+`graduation-cli` (agent flow, `--force`), `graduation-cli-topologies`+(PgBouncer through `GBRAIN_PGBOUNCER_URL`, a NOSUPERUSER role),+`graduation-cli-history` (the 1k round trip) and+`graduation-cli-zero-mutation-N` (zero-mutation `--plan`/`--status`, each+file probing a share of the custody boundaries). Kill and pause points come+from `graduationBoundary()` hooks that only`test/helpers/graduation-hooks-preload.ts` registers. Older release binaries-are built once per tag under `GBRAIN_OLDER_RELEASE_DIR`. The crash suite takes-about 40 seconds per case, so run it with `GBRAIN_E2E_FILE_TIMEOUT=3600`.+are built once per tag under `GBRAIN_OLDER_RELEASE_DIR`. A crash case takes+about 16 seconds; `scripts/run-e2e.sh` gives every graduation file four times+its per-file cap.`scripts/persistence/graduation-ttv.ts` records the commands and wall timefrom the first plan to a green doctor, the run's phase timings and queryp50/p95 on both engines. The 1k-page gate is five minutes;diff --git a/scripts/run-e2e.sh b/scripts/run-e2e.shindex afef6aaa9b..d280a5820c 100755--- a/scripts/run-e2e.sh+++ b/scripts/run-e2e.sh@@ -446,9 +446,8 @@ for f in "${files[@]}"; do# word-splitting into extra gtimeout arguments or breaking the 4x math.case "$file_timeout" in ''|*[!0-9]*) file_timeout=180 ;; esaccase "$f" in- */skills.test.ts|*/serve-http-multi-agent.test.ts|*/graduation-cli.test.ts|*/graduation-clients.test.ts|*/graduation-faults.test.ts|*/graduation-copy.test.ts|*/graduation-legacy-copy.test.ts) file_timeout=$((file_timeout * 4)) ;;- # One graduation per custody and rollback boundary (~30 SIGKILL-and-resume cases of ~15 s each).- */graduation-crash.test.ts) file_timeout=$((file_timeout * 10)) ;;+ # graduation-crash-*: one graduation per custody or rollback boundary (5-6 SIGKILL-and-resume cases of ~16 s per file).+ */skills.test.ts|*/serve-http-multi-agent.test.ts|*/graduation-cli*.test.ts|*/graduation-crash-*.test.ts|*/graduation-faults.test.ts|*/graduation-copy.test.ts|*/graduation-legacy-copy.test.ts) file_timeout=$((file_timeout * 4)) ;;esacif command -v gtimeout >/dev/null 2>&1; thenTIMEOUT_CMD="gtimeout $file_timeout"diff --git a/scripts/stress/plan.ts b/scripts/stress/plan.tsindex 65edd88343..cb04762735 100644--- a/scripts/stress/plan.ts+++ b/scripts/stress/plan.ts@@ -51,7 +51,10 @@ export const SPECIAL_FILES: Record<string, Partial<Profile>> = {'test/entity-card-perf.slow.test.ts': { timeoutMs: 300_000 },'test/eval-brainbench-e2e.slow.test.ts': { timeoutMs: 300_000 },'test/persistence-skill-old-binary.slow.test.ts': { timeoutMs: 180_000, prereq: 'old-binary' },- 'test/reconcile-crash.slow.test.ts': { timeoutMs: 180_000 },+ 'test/reconcile-crash-unactivated-1.slow.test.ts': { timeoutMs: 180_000 },+ 'test/reconcile-crash-unactivated-2.slow.test.ts': { timeoutMs: 180_000 },+ 'test/reconcile-crash-activated-1.slow.test.ts': { timeoutMs: 180_000 },+ 'test/reconcile-crash-activated-2.slow.test.ts': { timeoutMs: 180_000 },'test/persistence-crash-robot.slow.test.ts': { timeoutMs: 300_000 },};diff --git a/scripts/test-shard.sh b/scripts/test-shard.shindex 9fff38a018..3e954a1f90 100755--- a/scripts/test-shard.sh+++ b/scripts/test-shard.sh@@ -73,7 +73,7 @@ receipts_init unit# keep-in-matrix bar.# export-scale.slow.test.ts (571s at its 100,001-page master scale) rides the# slow-entity-resolve-perf job, which sets GBRAIN_TEST_EXPORT_SCALE_PAGES per-# event. reconcile-crash.slow.test.ts (244s) is not duplicated here: the+# event. reconcile-crash-*.slow.test.ts (244s) is not duplicated here: the# persistence-validation invariants job already runs it on PGLite for every# event, before and after activation.# evals/ is included: its *.test.ts files (eval-harness unit tests) were@@ -88,7 +88,7 @@ ALL_FILES=$(find test evals -name '*.test.ts' \-not -name 'entity-card-perf.slow.test.ts' \-not -name 'eval-brainbench-e2e.slow.test.ts' \-not -name 'export-scale.slow.test.ts' \- -not -name 'reconcile-crash.slow.test.ts' \+ -not -name 'reconcile-crash-*.slow.test.ts' \-not -path 'test/e2e/*' | sort)if [ -z "$ALL_FILES" ]; thendiff --git a/scripts/ubicloud/weights.json b/scripts/ubicloud/weights.jsonindex f2464bc1bd..15db6a23de 100644--- a/scripts/ubicloud/weights.json+++ b/scripts/ubicloud/weights.json@@ -151,6 +151,20 @@"e2e:test/e2e/global-basename-pglite.test.ts": 2002,"e2e:test/e2e/google-attachments-postgres.test.ts": 32028,"e2e:test/e2e/google-loops-recovery-postgres.test.ts": 8122,+ "e2e:test/e2e/graduation-cli-history.test.ts": 180000,+ "e2e:test/e2e/graduation-cli-topologies.test.ts": 52000,+ "e2e:test/e2e/graduation-cli-zero-mutation-1.test.ts": 128000,+ "e2e:test/e2e/graduation-cli-zero-mutation-2.test.ts": 126000,+ "e2e:test/e2e/graduation-cli-zero-mutation-3.test.ts": 129000,+ "e2e:test/e2e/graduation-cli.test.ts": 75000,+ "e2e:test/e2e/graduation-clients-serve.test.ts": 60000,+ "e2e:test/e2e/graduation-clients.test.ts": 140000,+ "e2e:test/e2e/graduation-copy.test.ts": 150000,+ "e2e:test/e2e/graduation-crash-rollback-1.test.ts": 91000,+ "e2e:test/e2e/graduation-crash-rollback-2.test.ts": 72000,+ "e2e:test/e2e/graduation-crash-run-1.test.ts": 120000,+ "e2e:test/e2e/graduation-crash-run-2.test.ts": 101000,+ "e2e:test/e2e/graduation-crash-run-3.test.ts": 105000,"e2e:test/e2e/grandfather-projection-postgres.test.ts": 5531,"e2e:test/e2e/graph-quality.test.ts": 2270,"e2e:test/e2e/graph-signals-engine.test.ts": 984,@@ -398,8 +412,9 @@"e2e:test/e2e/worker-readiness-cli.test.ts": 2770,"e2e:test/e2e/workspace-generic-compat.test.ts": 853,"e2e:test/e2e/worktree-refresh-postgres.test.ts": 24897,- "e2e:test/e2e/write-attribution-postgres.test.ts": 19235,+ "e2e:test/e2e/write-attribution-postgres.test.ts": 60000,"e2e:test/e2e/write-attribution-read-parity.test.ts": 6332,+ "e2e:test/e2e/write-attribution-timeline-10k-postgres.test.ts": 145000,"e2e:test/e2e/write-contract-conformance.test.ts": 41092,"e2e:test/e2e/zombie-reaping.test.ts": 9601,"e2e:test/phantom-redirect-engine-parity.test.ts": 4491,@@ -763,7 +778,10 @@"slow:test/persistence-skill-crash.slow.test.ts": 29521,"slow:test/persistence-skill-old-binary.slow.test.ts": 309,"slow:test/planner-stats-import.slow.test.ts": 12549,- "slow:test/reconcile-crash.slow.test.ts": 227520,+ "slow:test/reconcile-crash-activated-1.slow.test.ts": 61000,+ "slow:test/reconcile-crash-activated-2.slow.test.ts": 61000,+ "slow:test/reconcile-crash-unactivated-1.slow.test.ts": 61000,+ "slow:test/reconcile-crash-unactivated-2.slow.test.ts": 61000,"slow:test/reindex-markdown-persistence.slow.test.ts": 92098,"slow:test/scripts/scale-harness.slow.test.ts": 11420,"slow:test/scripts/test-shard.slow.test.ts": 1179,diff --git a/src/core/persistence/engine-graduation.types.ts b/src/core/persistence/engine-graduation.types.tsindex de227fa976..c514cc9171 100644--- a/src/core/persistence/engine-graduation.types.ts+++ b/src/core/persistence/engine-graduation.types.ts@@ -447,7 +447,7 @@ export type GraduationErrorCode = typeof GRADUATION_ERROR_CODES[number];/*** Custody boundaries, in run order, that the orchestrator announces with* `graduationBoundary(name)` right after the step's durable write commits.- * The crash suite (test/e2e/graduation-crash.test.ts) SIGKILLs the real CLI+ * The crash suite (test/e2e/graduation-crash-*.test.ts) SIGKILLs the real CLI* at each one, and the zero-mutation suite pauses there to poll --status.* `table_copied` fires after each table's copy transaction commits and* `batch_copied` after each committed batch inside a table, both withdiff --git a/test/e2e/graduation-cli-history.test.ts b/test/e2e/graduation-cli-history.test.tsnew file mode 100644index 0000000000..6d4177ab4b--- /dev/null+++ b/test/e2e/graduation-cli-history.test.ts@@ -0,0 +1,59 @@+/**+ * Engine graduation of the 1k-page history fixture: verify green, every+ * history table and row identical on the target, the queued request committed+ * and the delayed effect still queued, with the plan-to-green-doctor clock+ * under five minutes. Split from graduation-cli.test.ts+ * (test/helpers/graduation-cli-cases.ts).+ */+import { describe, expect } from 'bun:test';+import { HISTORY_FIXTURE_TABLES } from '../../scripts/persistence/history-fixture.ts';+import { custodyPaths, DATABASE_URL, gbrain, graduationTest, planHashOf, TARGET_ENV } from '../helpers/graduation-e2e.ts';+import { useGraduationCases } from '../helpers/graduation-cli-cases.ts';+import { doctorFailures, historyCase, withSource, withTarget } from '../helpers/graduation-scenarios.ts';+import { canonicalRows } from '../fixtures/graduation/legacy-brain.ts';++const { cleanups } = useGraduationCases();++describe.skipIf(!DATABASE_URL)('graduation: 1k-page history round trip', () => {+ graduationTest('1,000 pages with history graduate with verify green and the plan-to-green-doctor clock under five minutes', async () => {+ const { fx, target } = await historyCase('history-1k', 1000);+ cleanups.push(() => target.close());+ const env = { [TARGET_ENV]: target.url };+ const t0 = Date.now();+ const plan = await gbrain(['migrate', '--to', 'postgres', '--url-env', TARGET_ENV, '--json'], { home: fx.home, env });+ expect(plan.code).toBe(3);+ const run = await gbrain(['migrate', '--to', 'postgres', '--url-env', TARGET_ENV, '--yes', '--expect', String(planHashOf(plan.json)), '--json'],+ { home: fx.home, env, timeoutMs: 1_800_000 });+ expect({ code: run.code, stderr: run.code === 0 ? '' : run.stderr.slice(-3000) }).toEqual({ code: 0, stderr: '' });+ const doctor = await doctorFailures(fx.home);+ const wallMs = Date.now() - t0;+ expect(doctor.failing).toEqual([]);+ console.log(JSON.stringify({ graduation_1k: { wall_ms: wallMs, fixture: fx.report, timings: run.json?.receipt?.timings ?? run.json?.timings ?? null } }));+ expect(wallMs).toBeLessThan(5 * 60_000);++ const retained = custodyPaths(fx.dataDir).graduated[0];+ const outputs = fx.outputs as { queuedRequestId: string; delayedEffectId: string };+ const sourceSide = await withSource(fx, async source => {+ const counts: Record<string, number> = {};+ for (const table of HISTORY_FIXTURE_TABLES) counts[table] = Number((await source.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM ${table}`))[0].n);+ const rows: Record<string, string[]> = {};+ for (const table of ['pages', 'page_versions', 'facts', 'takes', 'fact_withdrawals', 'content_chunks', 'access_tokens', 'oauth_clients', 'oauth_tokens']) rows[table] = await canonicalRows(source, table);+ return { counts, rows };+ }, retained);+ await withTarget(target.url, async t => {+ for (const table of HISTORY_FIXTURE_TABLES) {+ const n = Number((await t.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM ${table}`))[0].n);+ expect({ table, n }).toEqual({ table, n: sourceSide.counts[table] });+ }+ for (const [table, rows] of Object.entries(sourceSide.rows)) {+ const got = await canonicalRows(t, table);+ const first = got.findIndex((row, i) => row !== rows[i]);+ expect({ table, length: got.length, first }).toEqual({ table, length: rows.length, first: -1 });+ }+ const [queued] = await t.executeRaw<{ state: string }>('SELECT state FROM persistence_requests WHERE request_id=$1::uuid', [outputs.queuedRequestId]);+ expect(queued.state).toBe('committed');+ const [delayed] = await t.executeRaw<{ state: string }>('SELECT state FROM persistence_effects WHERE id=$1', [outputs.delayedEffectId]);+ expect(delayed.state).toBe('queued');+ });+ }, 1_800_000);+});diff --git a/test/e2e/graduation-cli-topologies.test.ts b/test/e2e/graduation-cli-topologies.test.tsnew file mode 100644index 0000000000..25a2bc2433--- /dev/null+++ b/test/e2e/graduation-cli-topologies.test.ts@@ -0,0 +1,72 @@+/**+ * Engine graduation over the connection topologies a hosted brain uses:+ * transaction-mode PgBouncer with DDL on the direct route, and a hosted-style+ * NOSUPERUSER role (`disable_trigger` bypass recorded in the receipt, every+ * user trigger re-enabled), plus a forced bypass on a superuser target.+ * Split from graduation-cli.test.ts (test/helpers/graduation-cli-cases.ts).+ */+import { describe, expect, test } from 'bun:test';+import postgres from '#postgres';+import { DATABASE_URL, gbrain, graduationTest, graduationTestIf, hostedRoleTarget, passwordOf, pooledUrl } from '../helpers/graduation-e2e.ts';+import { useGraduationCases } from '../helpers/graduation-cli-cases.ts';+import { expectGraduated, planAndRun } from '../helpers/graduation-scenarios.ts';++const { cleanups, fresh } = useGraduationCases();++describe.skipIf(!DATABASE_URL)('graduation: connection topologies', () => {+ graduationTestIf(!process.env.GBRAIN_PGBOUNCER_URL)('through transaction-mode PgBouncer with DDL on the direct route', async () => {+ const c = await fresh('pgbouncer');+ const pooled = pooledUrl(c.target)!;+ const { argv, env } = await planAndRun(c, { url: pooled, env: { GBRAIN_DIRECT_DATABASE_URL: c.target.url } });+ const run = await gbrain(argv, { home: c.fx.home, env, timeoutMs: 900_000 });+ expect({ code: run.code, stderr: run.code === 0 ? '' : run.stderr.slice(-3000) }).toEqual({ code: 0, stderr: '' });+ await expectGraduated(c, 'pgbouncer');+ }, 900_000);++ test('the hosted-style role is a real constraint: no session_replication_role, but it owns what it creates', async () => {+ const hosted = await hostedRoleTarget();+ cleanups.push(() => hosted.close());+ const sql = postgres(hosted.url, { max: 1, prepare: false, onnotice: () => {} });+ try {+ const replica = await sql.begin(tx => tx.unsafe('SET LOCAL session_replication_role = replica')).then(() => 'allowed', e => String((e as { code?: string }).code));+ expect(replica).toBe('42501');+ await sql.unsafe('CREATE TABLE probe(id int primary key); ALTER TABLE probe DISABLE TRIGGER USER; DROP TABLE probe');+ const [ext] = await sql.unsafe<{ n: number }[]>(`SELECT count(*)::int AS n FROM pg_extension WHERE extname='vector'`);+ expect(Number(ext.n)).toBe(1);+ } finally { await sql.end(); }+ const oldUrl = hosted.url;+ const rotated = await hosted.rotatePassword();+ expect(passwordOf(rotated)).not.toBe(passwordOf(oldUrl));+ const stale = postgres(oldUrl, { max: 1, prepare: false, onnotice: () => {}, connect_timeout: 5 });+ expect(await stale.unsafe('SELECT 1').then(() => 'connected', e => String((e as { code?: string }).code))).toBe('28P01');+ await stale.end();+ const fresh = postgres(rotated, { max: 1, prepare: false, onnotice: () => {} });+ expect((await fresh.unsafe<{ n: number }[]>('SELECT 1 AS n'))[0].n).toBe(1);+ await fresh.end();+ });++ graduationTest('as a hosted-style NOSUPERUSER role: the disable-trigger fallback, every user trigger re-enabled', async () => {+ const hosted = await hostedRoleTarget();+ const c = await fresh('hosted-role', hosted);+ const { argv, env } = await planAndRun(c, { url: hosted.url });+ const run = await gbrain(argv, { home: c.fx.home, env, timeoutMs: 900_000 });+ expect({ code: run.code, stderr: run.code === 0 ? '' : run.stderr.slice(-3000) }).toEqual({ code: 0, stderr: '' });+ expect(JSON.stringify(run.json)).toContain('disable_trigger');+ await expectGraduated(c, 'hosted role');+ const sql = postgres(hosted.url, { max: 1, prepare: false, onnotice: () => {} });+ try {+ const disabled = await sql.unsafe<{ t: string }[]>(`SELECT c.relname || '.' || t.tgname AS t FROM pg_trigger t JOIN pg_class c ON c.oid=t.tgrelid+ JOIN pg_namespace n ON n.oid=c.relnamespace WHERE n.nspname='public' AND NOT t.tgisinternal AND t.tgenabled <> 'O'`);+ expect(disabled.map(r => r.t)).toEqual([]);+ } finally { await sql.end(); }+ }, 900_000);++ graduationTest('--trigger-bypass disable-trigger is honoured on a superuser target and recorded', async () => {+ const c = await fresh('forced-bypass');+ const { argv, env } = await planAndRun(c, { extra: ['--trigger-bypass', 'disable-trigger'] });+ const run = await gbrain(argv, { home: c.fx.home, env, timeoutMs: 900_000 });+ expect(run.code).toBe(0);+ expect(JSON.stringify(run.json)).toContain('disable_trigger');+ await expectGraduated(c, 'forced disable-trigger');+ }, 900_000);+});diff --git a/test/e2e/graduation-cli-zero-mutation-1.test.ts b/test/e2e/graduation-cli-zero-mutation-1.test.tsnew file mode 100644index 0000000000..4e92e9bc0e--- /dev/null+++ b/test/e2e/graduation-cli-zero-mutation-1.test.ts@@ -0,0 +1,9 @@+/**+ * `gbrain migrate --plan` and `--status` perform zero mutations: polled at+ * every custody boundary of a paused graduation and after a SIGKILL at+ * `verified`, neither changes a byte or a row. One graduation per file; this+ * file probes part 1 of the boundaries (test/helpers/graduation-cli-cases.ts).+ */+import { zeroMutationSuite } from '../helpers/graduation-cli-cases.ts';++zeroMutationSuite(1);diff --git a/test/e2e/graduation-cli-zero-mutation-2.test.ts b/test/e2e/graduation-cli-zero-mutation-2.test.tsnew file mode 100644index 0000000000..95f3baa7d1--- /dev/null+++ b/test/e2e/graduation-cli-zero-mutation-2.test.ts@@ -0,0 +1,9 @@+/**+ * `gbrain migrate --plan` and `--status` perform zero mutations: polled at+ * every custody boundary of a paused graduation and after a SIGKILL at+ * `verified`, neither changes a byte or a row. One graduation per file; this+ * file probes part 2 of the boundaries (test/helpers/graduation-cli-cases.ts).+ */+import { zeroMutationSuite } from '../helpers/graduation-cli-cases.ts';++zeroMutationSuite(2);diff --git a/test/e2e/graduation-cli-zero-mutation-3.test.ts b/test/e2e/graduation-cli-zero-mutation-3.test.tsnew file mode 100644index 0000000000..f2a1a9df8f--- /dev/null+++ b/test/e2e/graduation-cli-zero-mutation-3.test.ts@@ -0,0 +1,9 @@+/**+ * `gbrain migrate --plan` and `--status` perform zero mutations: polled at+ * every custody boundary of a paused graduation and after a SIGKILL at+ * `verified`, neither changes a byte or a row. One graduation per file; this+ * file probes part 3 of the boundaries (test/helpers/graduation-cli-cases.ts).+ */+import { zeroMutationSuite } from '../helpers/graduation-cli-cases.ts';++zeroMutationSuite(3);diff --git a/test/e2e/graduation-cli.test.ts b/test/e2e/graduation-cli.test.tsindex d9a0225bcb..4a7e05da5a 100644--- a/test/e2e/graduation-cli.test.ts+++ b/test/e2e/graduation-cli.test.ts@@ -10,41 +10,27 @@* doctor is green; existing tokens and OAuth clients authorize; over MCP a* recall, a write, a replay of that write's request id (same outcome, no new* row) and a grant-denied call behave as before.- * - `--plan` and `--status` perform zero mutations, polled at every custody- * boundary and after a crash.* - `--force` binds the target's destructive snapshot: a page added between* preview and confirmation refuses with `preview_changed`.- * - The same legacy round trip through PgBouncer (DDL on the direct route) and- * as a NOSUPERUSER role (`disable_trigger` bypass recorded in the receipt).- * - The 1k-page history fixture round trip with the plan-to-green-doctor- * clock under five minutes.+ * The rest of the contract is split across files so CI can run them side by+ * side (test/helpers/graduation-cli-cases.ts): connection topologies+ * (graduation-cli-topologies), the 1k-page history round trip+ * (graduation-cli-history) and zero-mutation `--plan`/`--status` polling+ * (graduation-cli-zero-mutation-N).* Not covered elsewhere: unit tests cover the plan document and the state* machine without a real target.*/-import { afterAll, describe, expect, test } from 'bun:test';-import { rmSync } from 'node:fs';+import { describe, expect } from 'bun:test';import { join } from 'node:path';-import postgres from '#postgres';-import { HISTORY_FIXTURE_TABLES } from '../../scripts/persistence/history-fixture.ts';import {- codeOf, custodyPaths, DATABASE_URL, digestChanges, fixOf, freePort, gbrain, graduationTest, graduationTestIf, hostedRoleTarget, mcpHttpCall, passwordLeaks, passwordOf,- planHashOf, pooledUrl, release, startGbrain, stateDigest, TARGET_ENV, waitForEvent, type GbrainResult,+ codeOf, DATABASE_URL, digestChanges, fixOf, freePort, gbrain, graduationTest, mcpHttpCall, passwordLeaks, passwordOf,+ planHashOf, startGbrain, stateDigest, TARGET_ENV, type GbrainResult,} from '../helpers/graduation-e2e.ts';-import {- doctorFailures, expectGraduated, failingChecks, historyCase, legacyCase, planAndRun, scratchRoot, targetRowState, withSource, withTarget, type Case,-} from '../helpers/graduation-scenarios.ts';-import { canonicalRows, loadLegacyExpected } from '../fixtures/graduation/legacy-brain.ts';+import { useGraduationCases } from '../helpers/graduation-cli-cases.ts';+import { expectGraduated, failingChecks, planAndRun, targetRowState, withTarget } from '../helpers/graduation-scenarios.ts';+import { loadLegacyExpected } from '../fixtures/graduation/legacy-brain.ts';-const cleanups: (() => Promise<void>)[] = [];-afterAll(async () => {- for (const cleanup of cleanups.reverse()) await cleanup().catch(() => {});- rmSync(scratchRoot, { recursive: true, force: true });-});-async function fresh(name: string, target?: Case['target']): Promise<Case> {- const c = await legacyCase(name, target);- cleanups.push(() => c.target.close());- return c;-}+const { fresh } = useGraduationCases();describe.skipIf(!DATABASE_URL)('graduation: agent workflow', () => {graduationTest('plan -> ask_user -> --yes --expect -> green doctor, then MCP recall, write, replay and a denied grant', async () => {@@ -110,41 +96,6 @@ describe.skipIf(!DATABASE_URL)('graduation: agent workflow', () => {}, 1_200_000);});-describe.skipIf(!DATABASE_URL)('graduation: --plan and --status are zero-mutation', () => {- graduationTest('polled at every custody boundary and after a crash, neither changes a byte or a row', async () => {- const c = await fresh('zero-mutation');- const { argv, env } = await planAndRun(c);- const child = startGbrain(argv, { home: c.fx.home, env, hooks: { events: c.events, pause: ['*'] } });- const seen: string[] = [];- const probe = async (label: string) => {- const before = await stateDigest(c.fx.dir, c.target.url);- const status = await gbrain(['migrate', '--status', '--json'], { home: c.fx.home });- expect({ label, code: status.code }).toEqual({ label, code: 0 });- await gbrain(['migrate', '--to', 'postgres', '--url-env', TARGET_ENV, '--plan', '--json'], { home: c.fx.home, env });- // Not the poll's writes: the paused run's own kernel-lock heartbeat (.gbrain-lock/lock, every 30 s) and Bun's runtime install cache under the test HOME.- const changes = digestChanges(before, await stateDigest(c.fx.dir, c.target.url))- .filter(change => !change.includes('boundary-events.jsonl') && !change.includes('.gbrain-lock/lock') && !change.includes('/.bun/install/cache/'));- expect({ label, changes }).toEqual({ label, changes: [] });- };- for (let ordinal = 1; ; ordinal++) {- const paused = await waitForEvent(c.events, e => e.event === 'paused' && e.ordinal === ordinal, child).catch(() => null);- if (!paused) break;- seen.push(paused.boundary);- await probe(`${paused.boundary}#${ordinal}`);- if (paused.boundary === 'verified') {- child.kill('SIGKILL');- await child.exited;- await probe('after a SIGKILL at verified');- break;- }- release(c.events, ordinal);- }- expect(seen).toEqual(expect.arrayContaining(['quiesced', 'drained', 'target_fenced', 'table_copied', 'copied', 'verified']));- expect((await gbrain(['migrate', '--resume', '--json'], { home: c.fx.home, timeoutMs: 900_000 })).code).toBe(0);- await expectGraduated(c, 'after zero-mutation polling');- }, 1_200_000);-});-describe.skipIf(!DATABASE_URL)('graduation: target emptiness and --force', () => {graduationTest('a target the user already initialised counts as empty', async () => {const c = await fresh('pre-initialised');@@ -190,106 +141,3 @@ describe.skipIf(!DATABASE_URL)('graduation: target emptiness and --force', () =>});}, 900_000);});--describe.skipIf(!DATABASE_URL)('graduation: connection topologies', () => {- graduationTestIf(!process.env.GBRAIN_PGBOUNCER_URL)('through transaction-mode PgBouncer with DDL on the direct route', async () => {- const c = await fresh('pgbouncer');- const pooled = pooledUrl(c.target)!;- const { argv, env } = await planAndRun(c, { url: pooled, env: { GBRAIN_DIRECT_DATABASE_URL: c.target.url } });- const run = await gbrain(argv, { home: c.fx.home, env, timeoutMs: 900_000 });- expect({ code: run.code, stderr: run.code === 0 ? '' : run.stderr.slice(-3000) }).toEqual({ code: 0, stderr: '' });- await expectGraduated(c, 'pgbouncer');- }, 900_000);-- test('the hosted-style role is a real constraint: no session_replication_role, but it owns what it creates', async () => {- const hosted = await hostedRoleTarget();- cleanups.push(() => hosted.close());- const sql = postgres(hosted.url, { max: 1, prepare: false, onnotice: () => {} });- try {- const replica = await sql.begin(tx => tx.unsafe('SET LOCAL session_replication_role = replica')).then(() => 'allowed', e => String((e as { code?: string }).code));- expect(replica).toBe('42501');- await sql.unsafe('CREATE TABLE probe(id int primary key); ALTER TABLE probe DISABLE TRIGGER USER; DROP TABLE probe');- const [ext] = await sql.unsafe<{ n: number }[]>(`SELECT count(*)::int AS n FROM pg_extension WHERE extname='vector'`);- expect(Number(ext.n)).toBe(1);- } finally { await sql.end(); }- const oldUrl = hosted.url;- const rotated = await hosted.rotatePassword();- expect(passwordOf(rotated)).not.toBe(passwordOf(oldUrl));- const stale = postgres(oldUrl, { max: 1, prepare: false, onnotice: () => {}, connect_timeout: 5 });- expect(await stale.unsafe('SELECT 1').then(() => 'connected', e => String((e as { code?: string }).code))).toBe('28P01');- await stale.end();- const fresh = postgres(rotated, { max: 1, prepare: false, onnotice: () => {} });- expect((await fresh.unsafe<{ n: number }[]>('SELECT 1 AS n'))[0].n).toBe(1);- await fresh.end();- });-- graduationTest('as a hosted-style NOSUPERUSER role: the disable-trigger fallback, every user trigger re-enabled', async () => {- const hosted = await hostedRoleTarget();- const c = await fresh('hosted-role', hosted);- const { argv, env } = await planAndRun(c, { url: hosted.url });- const run = await gbrain(argv, { home: c.fx.home, env, timeoutMs: 900_000 });- expect({ code: run.code, stderr: run.code === 0 ? '' : run.stderr.slice(-3000) }).toEqual({ code: 0, stderr: '' });- expect(JSON.stringify(run.json)).toContain('disable_trigger');- await expectGraduated(c, 'hosted role');- const sql = postgres(hosted.url, { max: 1, prepare: false, onnotice: () => {} });- try {- const disabled = await sql.unsafe<{ t: string }[]>(`SELECT c.relname || '.' || t.tgname AS t FROM pg_trigger t JOIN pg_class c ON c.oid=t.tgrelid- JOIN pg_namespace n ON n.oid=c.relnamespace WHERE n.nspname='public' AND NOT t.tgisinternal AND t.tgenabled <> 'O'`);- expect(disabled.map(r => r.t)).toEqual([]);- } finally { await sql.end(); }- }, 900_000);-- graduationTest('--trigger-bypass disable-trigger is honoured on a superuser target and recorded', async () => {- const c = await fresh('forced-bypass');- const { argv, env } = await planAndRun(c, { extra: ['--trigger-bypass', 'disable-trigger'] });- const run = await gbrain(argv, { home: c.fx.home, env, timeoutMs: 900_000 });- expect(run.code).toBe(0);- expect(JSON.stringify(run.json)).toContain('disable_trigger');- await expectGraduated(c, 'forced disable-trigger');- }, 900_000);-});--describe.skipIf(!DATABASE_URL)('graduation: 1k-page history round trip', () => {- graduationTest('1,000 pages with history graduate with verify green and the plan-to-green-doctor clock under five minutes', async () => {- const { fx, target } = await historyCase('history-1k', 1000);- cleanups.push(() => target.close());- const env = { [TARGET_ENV]: target.url };- const t0 = Date.now();- const plan = await gbrain(['migrate', '--to', 'postgres', '--url-env', TARGET_ENV, '--json'], { home: fx.home, env });- expect(plan.code).toBe(3);- const run = await gbrain(['migrate', '--to', 'postgres', '--url-env', TARGET_ENV, '--yes', '--expect', String(planHashOf(plan.json)), '--json'],- { home: fx.home, env, timeoutMs: 1_800_000 });- expect({ code: run.code, stderr: run.code === 0 ? '' : run.stderr.slice(-3000) }).toEqual({ code: 0, stderr: '' });- const doctor = await doctorFailures(fx.home);- const wallMs = Date.now() - t0;- expect(doctor.failing).toEqual([]);- console.log(JSON.stringify({ graduation_1k: { wall_ms: wallMs, fixture: fx.report, timings: run.json?.receipt?.timings ?? run.json?.timings ?? null } }));- expect(wallMs).toBeLessThan(5 * 60_000);-- const retained = custodyPaths(fx.dataDir).graduated[0];- const outputs = fx.outputs as { queuedRequestId: string; delayedEffectId: string };- const sourceSide = await withSource(fx, async source => {- const counts: Record<string, number> = {};- for (const table of HISTORY_FIXTURE_TABLES) counts[table] = Number((await source.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM ${table}`))[0].n);- const rows: Record<string, string[]> = {};- for (const table of ['pages', 'page_versions', 'facts', 'takes', 'fact_withdrawals', 'content_chunks', 'access_tokens', 'oauth_clients', 'oauth_tokens']) rows[table] = await canonicalRows(source, table);- return { counts, rows };- }, retained);- await withTarget(target.url, async t => {- for (const table of HISTORY_FIXTURE_TABLES) {- const n = Number((await t.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM ${table}`))[0].n);- expect({ table, n }).toEqual({ table, n: sourceSide.counts[table] });- }- for (const [table, rows] of Object.entries(sourceSide.rows)) {- const got = await canonicalRows(t, table);- const first = got.findIndex((row, i) => row !== rows[i]);- expect({ table, length: got.length, first }).toEqual({ table, length: rows.length, first: -1 });- }- const [queued] = await t.executeRaw<{ state: string }>('SELECT state FROM persistence_requests WHERE request_id=$1::uuid', [outputs.queuedRequestId]);- expect(queued.state).toBe('committed');- const [delayed] = await t.executeRaw<{ state: string }>('SELECT state FROM persistence_effects WHERE id=$1', [outputs.delayedEffectId]);- expect(delayed.state).toBe('queued');- });- }, 1_800_000);-});-diff --git a/test/e2e/graduation-clients-serve.test.ts b/test/e2e/graduation-clients-serve.test.tsnew file mode 100644index 0000000000..5942852df0--- /dev/null+++ b/test/e2e/graduation-clients-serve.test.ts@@ -0,0 +1,109 @@+/**+ * Engine graduation versus the brain's serve processes and stale clients:+ * a respawned stdio or HTTP serve exits with `graduation_in_progress`, writes+ * nothing and takes no lock; a resident serve hands the source over within+ * 30 s; a stale CLI config and a stale MCP config each recover by running the+ * refusal's fix once. Split from graduation-clients.test.ts (shared steps:+ * test/helpers/graduation-clients-cases.ts).+ */+import { afterAll, describe, expect } from 'bun:test';+import { existsSync, readFileSync } from 'node:fs';+import { join } from 'node:path';+import {+ codeOf, DATABASE_URL, digestChanges, fixOf, freePort, gbrain, graduationTest, leakNeedle, mcpStdioSession, passwordOf, release, startGbrain, stateDigest, waitForEvent,+} from '../helpers/graduation-e2e.ts';+import { closeCases, findFix, fresh, runFix, staleHome } from '../helpers/graduation-clients-cases.ts';+import { expectGraduated, planAndRun } from '../helpers/graduation-scenarios.ts';++afterAll(closeCases);++describe.skipIf(!DATABASE_URL)('graduation: serve processes', () => {+ graduationTest('a serve respawned mid-copy (stdio and http) exits with graduation_in_progress, writes nothing, takes no lock', async () => {+ const c = await fresh('respawn-serve');+ const { argv, env } = await planAndRun(c, { extra: ['--batch-size', '2'] });+ const child = startGbrain(argv, { home: c.fx.home, env, hooks: { events: c.events, pause: ['batch_copied@pages'] } });+ const paused = await waitForEvent(c.events, e => e.event === 'paused', child);+ const watched = async () => {+ const d = await stateDigest(c.fx.dataDir, c.target.url);+ for (const path of [`${c.fx.dataDir}.gbrain-graduation.json`, join(c.fx.home, '.gbrain', 'graduation-manifest.json'), join(c.fx.home, '.gbrain', 'config.json')]) {+ d.files[path] = existsSync(path) ? readFileSync(path, 'utf8') : '(absent)';+ }+ return d;+ };+ const before = await watched();+ const stdio = await mcpStdioSession({ home: c.fx.home, timeoutMs: 60_000 });+ const stdioExit = await Promise.race([stdio.exited, Bun.sleep(45_000).then(() => null)]);+ expect(stdioExit).not.toBeNull();+ expect(stdioExit!.code).not.toBe(0);+ expect(`${stdioExit!.stdout}${stdioExit!.stderr}`).toContain('graduation_in_progress');+ const http = await gbrain(['serve', '--http', '--port', String(freePort())], { home: c.fx.home, timeoutMs: 60_000 });+ expect(http.code).not.toBe(0);+ expect(http.signal).toBeNull();+ expect(`${http.stdout}${http.stderr}`).toContain('graduation_in_progress');+ expect(digestChanges(before, await watched())).toEqual([]);+ release(c.events, paused.ordinal!);+ const done = await child.exited;+ expect({ code: done.code, stderr: done.code === 0 ? '' : done.stderr.slice(-3000) }).toEqual({ code: 0, stderr: '' });+ await expectGraduated(c, 'after respawned serves');+ }, 900_000);++ graduationTest('a resident stdio serve hands the source over through the intent marker; no manual stop', async () => {+ const c = await fresh('live-serve');+ const serve = await mcpStdioSession({ home: c.fx.home, timeoutMs: 900_000 });+ const before = await serve.call('get_page', { slug: 'people/alice-example', source_id: 'default' });+ expect(before?.error).toBeUndefined();+ const { argv, env } = await planAndRun(c);+ const run = await gbrain(argv, { home: c.fx.home, env, timeoutMs: 900_000 });+ expect({ code: run.code, stderr: run.code === 0 ? '' : run.stderr.slice(-3000) }).toEqual({ code: 0, stderr: '' });+ const served = await Promise.race([serve.exited, Bun.sleep(30_000).then(() => null)]);+ expect(served).not.toBeNull();+ expect(`${served!.stdout}${served!.stderr}`).toContain('graduation_in_progress');+ expect(JSON.stringify(run.json)).toMatch(/restart|mcp/i);+ await expectGraduated(c, 'after live-serve hand-off', { liveWork: true });+ const relaunched = await mcpStdioSession({ home: c.fx.home });+ const after = await relaunched.call('get_page', { slug: 'people/alice-example', source_id: 'default' });+ await relaunched.close();+ expect(after?.error).toBeUndefined();+ }, 900_000);+});++describe.skipIf(!DATABASE_URL)('graduation: stale clients recover in one step', () => {+ graduationTest('a stale CLI config gets engine_graduated with a fix that works when run once', async () => {+ const c = await fresh('stale-cli');+ const { argv, env } = await planAndRun(c);+ expect((await gbrain(argv, { home: c.fx.home, env, timeoutMs: 900_000 })).code).toBe(0);+ const home = staleHome(c);+ const refused = await gbrain(['query', 'acme', '--json'], { home });+ expect(refused.code).not.toBe(0);+ expect(codeOf(refused.json)).toBe('engine_graduated');+ const fix = fixOf(refused.json)!;+ expect(['run', 'tell_user_to_run']).toContain(fix.next);+ expect(JSON.stringify(fix)).not.toContain(leakNeedle(passwordOf(c.target.url)));+ const fixed = await runFix(fix, home, c);+ expect({ code: fixed.code, stderr: fixed.code === 0 ? '' : fixed.stderr.slice(-1500) }).toEqual({ code: 0, stderr: '' });+ const retried = await gbrain(['get', 'people/alice-example', '--source', 'default'], { home });+ expect({ code: retried.code, stderr: retried.code === 0 ? '' : retried.stderr.slice(-1500) }).toEqual({ code: 0, stderr: '' });+ expect(retried.stdout).toContain('Alice-example');+ }, 900_000);++ graduationTest('a stale MCP server config surfaces engine_graduated through the MCP host and recovers after one fix', async () => {+ const c = await fresh('stale-mcp');+ const { argv, env } = await planAndRun(c);+ expect((await gbrain(argv, { home: c.fx.home, env, timeoutMs: 900_000 })).code).toBe(0);+ const home = staleHome(c);+ const stale = await mcpStdioSession({ home });+ const reply = await stale.call('get_page', { slug: 'people/alice-example', source_id: 'default' });+ const exited = await stale.close();+ const text = `${JSON.stringify(reply)}${exited.stdout}${exited.stderr}`;+ expect(text).toContain('engine_graduated');+ const fix = findFix(reply);+ expect(fix).not.toBeNull();+ const fixed = await runFix(fix!, home, c);+ expect(fixed.code).toBe(0);+ const relaunched = await mcpStdioSession({ home });+ const after = await relaunched.call('get_page', { slug: 'people/alice-example', source_id: 'default' });+ await relaunched.close();+ expect(after?.error).toBeUndefined();+ expect(JSON.stringify(after)).toContain('Alice-example');+ }, 900_000);+});diff --git a/test/e2e/graduation-clients.test.ts b/test/e2e/graduation-clients.test.tsindex 0f3c22a209..6ec5f9877a 100644--- a/test/e2e/graduation-clients.test.ts+++ b/test/e2e/graduation-clients.test.ts@@ -19,21 +19,22 @@* writes nothing and takes no lock; a resident serve hands off within 30 s.* - A stale CLI config and a stale MCP config each recover by running the* refusal's fix once.+ * Serve processes and stale clients run in graduation-clients-serve.test.ts+ * (shared steps: test/helpers/graduation-clients-cases.ts).* Not covered elsewhere: these are the only multi-process client tests.* Older binaries are built once per tag (test/helpers/graduation-e2e.ts* `olderReleaseBinary`, cached under GBRAIN_OLDER_RELEASE_DIR).*/import { afterAll, beforeAll, describe, expect, test } from 'bun:test';-import { chmodSync, closeSync, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, statSync, writeFileSync, writeSync, constants } from 'node:fs';-import { dirname, join } from 'node:path';-import type { Tombstone } from '../../src/core/persistence/engine-graduation.types.ts';+import { readFileSync, statSync } from 'node:fs';+import { join } from 'node:path';import {- codeOf, custodyPaths, leakNeedle, passwordOf, DATABASE_URL, digestChanges, fixOf, freePort, gbrain, graduationTest, mcpStdioSession, olderReleaseBinary,- previousReleaseTags, release, REPO, startGbrain, stateDigest, TARGET_ENV, waitForEvent, type GbrainResult,+ codeOf, custodyPaths, DATABASE_URL, digestChanges, fixOf, gbrain, graduationTest, olderReleaseBinary,+ previousReleaseTags, release, startGbrain, stateDigest, waitForEvent, type GbrainResult,} from '../helpers/graduation-e2e.ts';-import { configuredEngine, expectGraduated, legacyCase, planAndRun, scratchRoot, targetRowState, withTarget, type Case } from '../helpers/graduation-scenarios.ts';+import { closeCases, fresh, staleHome } from '../helpers/graduation-clients-cases.ts';+import { configuredEngine, expectGraduated, planAndRun, targetRowState, withTarget } from '../helpers/graduation-scenarios.ts';-const cases: Case[] = [];let older: { tag: string; binary: string }[] = [];let olderError: string | null = null;@@ -42,56 +43,7 @@ beforeAll(() => {catch (error) { olderError = String(error); }}, 900_000);-afterAll(async () => {- for (const c of cases) await c.target.close().catch(() => {});- rmSync(scratchRoot, { recursive: true, force: true });-});--async function fresh(name: string): Promise<Case> {- const c = await legacyCase(name);- cases.push(c);- return c;-}--/** A second GBRAIN_HOME whose copied config still routes to the PGLite path (a stale client on this machine). */-function staleHome(c: Case): string {- const home = join(c.fx.dir, 'stale-home');- mkdirSync(join(home, '.gbrain'), { recursive: true });- writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({ engine: 'pglite', database_path: c.fx.dataDir, embedding_disabled: true }, null, 2), { mode: 0o600 });- return home;-}--/** `gbrain` on PATH for running a refusal's shell `fix.command` exactly as an agent would. */-function shimPath(c: Case): string {- const bin = join(c.fx.dir, 'shim-bin');- mkdirSync(bin, { recursive: true });- writeFileSync(join(bin, 'gbrain'), `#!/bin/sh\nexec "${process.execPath}" --no-env-file "${join(REPO, 'src', 'cli.ts')}" "$@"\n`);- chmodSync(join(bin, 'gbrain'), 0o755);- return `${bin}:${process.env.PATH}`;-}--/** Run a refusal's fix once: `fix.argv` through the CLI, or the shell `fix.command`. */-/** The first rendered fix (`next` run or tell_user_to_run) anywhere in an MCP reply, including JSON-encoded text content. */-function findFix(value: unknown): Record<string, any> | null {- if (typeof value === 'string') { try { return findFix(JSON.parse(value)); } catch { return null; } }- if (!value || typeof value !== 'object') return null;- const record = value as Record<string, any>;- if ((record.next === 'run' || record.next === 'tell_user_to_run') && Array.isArray(record.argv)) return record;- for (const child of Object.values(record)) { const found = findFix(child); if (found) return found; }- return null;-}--async function runFix(fix: Record<string, any>, home: string, c: Case): Promise<GbrainResult> {- const env = { [TARGET_ENV]: c.target.url, PATH: shimPath(c) };- // An agent fills `<name>` argv placeholders from fix.inputs (the user supplies the target URL).- const filled = Array.isArray(fix.argv) ? (fix.argv as string[]).map(a => a === '<target_url>' ? c.target.url : a) : null;- if (filled && filled[0] === 'gbrain') return gbrain(filled.slice(1), { home, env });- expect(typeof fix.command).toBe('string');- const child = Bun.spawn(['sh', '-c', fix.command], { env: { ...process.env, ...env, HOME: home, GBRAIN_HOME: home, DATABASE_URL: '', GBRAIN_DATABASE_URL: '' }, stdout: 'pipe', stderr: 'pipe' });- const [stdout, stderr] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text()]);- await child.exited;- return { code: child.exitCode ?? -1, signal: null, stdout, stderr, json: null, ms: 0 };-}+afterAll(closeCases);/** The Tombstone contract written by hand (O_EXCL, 0600, fsync file + parent), for the pre-integration half. */@@ -208,95 +160,3 @@ describe.skipIf(!DATABASE_URL)('graduation: older released binaries', () => {await expectGraduated(c, 'after fenced probes');}, 900_000);});--describe.skipIf(!DATABASE_URL)('graduation: serve processes', () => {- graduationTest('a serve respawned mid-copy (stdio and http) exits with graduation_in_progress, writes nothing, takes no lock', async () => {- const c = await fresh('respawn-serve');- const { argv, env } = await planAndRun(c, { extra: ['--batch-size', '2'] });- const child = startGbrain(argv, { home: c.fx.home, env, hooks: { events: c.events, pause: ['batch_copied@pages'] } });- const paused = await waitForEvent(c.events, e => e.event === 'paused', child);- const watched = async () => {- const d = await stateDigest(c.fx.dataDir, c.target.url);- for (const path of [`${c.fx.dataDir}.gbrain-graduation.json`, join(c.fx.home, '.gbrain', 'graduation-manifest.json'), join(c.fx.home, '.gbrain', 'config.json')]) {- d.files[path] = existsSync(path) ? readFileSync(path, 'utf8') : '(absent)';- }- return d;- };- const before = await watched();- const stdio = await mcpStdioSession({ home: c.fx.home, timeoutMs: 60_000 });- const stdioExit = await Promise.race([stdio.exited, Bun.sleep(45_000).then(() => null)]);- expect(stdioExit).not.toBeNull();- expect(stdioExit!.code).not.toBe(0);- expect(`${stdioExit!.stdout}${stdioExit!.stderr}`).toContain('graduation_in_progress');- const http = await gbrain(['serve', '--http', '--port', String(freePort())], { home: c.fx.home, timeoutMs: 60_000 });- expect(http.code).not.toBe(0);- expect(http.signal).toBeNull();- expect(`${http.stdout}${http.stderr}`).toContain('graduation_in_progress');- expect(digestChanges(before, await watched())).toEqual([]);- release(c.events, paused.ordinal!);- const done = await child.exited;- expect({ code: done.code, stderr: done.code === 0 ? '' : done.stderr.slice(-3000) }).toEqual({ code: 0, stderr: '' });- await expectGraduated(c, 'after respawned serves');- }, 900_000);-- graduationTest('a resident stdio serve hands the source over through the intent marker; no manual stop', async () => {- const c = await fresh('live-serve');- const serve = await mcpStdioSession({ home: c.fx.home, timeoutMs: 900_000 });- const before = await serve.call('get_page', { slug: 'people/alice-example', source_id: 'default' });- expect(before?.error).toBeUndefined();- const { argv, env } = await planAndRun(c);- const run = await gbrain(argv, { home: c.fx.home, env, timeoutMs: 900_000 });- expect({ code: run.code, stderr: run.code === 0 ? '' : run.stderr.slice(-3000) }).toEqual({ code: 0, stderr: '' });- const served = await Promise.race([serve.exited, Bun.sleep(30_000).then(() => null)]);- expect(served).not.toBeNull();- expect(`${served!.stdout}${served!.stderr}`).toContain('graduation_in_progress');- expect(JSON.stringify(run.json)).toMatch(/restart|mcp/i);- await expectGraduated(c, 'after live-serve hand-off', { liveWork: true });- const relaunched = await mcpStdioSession({ home: c.fx.home });- const after = await relaunched.call('get_page', { slug: 'people/alice-example', source_id: 'default' });- await relaunched.close();- expect(after?.error).toBeUndefined();- }, 900_000);-});--describe.skipIf(!DATABASE_URL)('graduation: stale clients recover in one step', () => {- graduationTest('a stale CLI config gets engine_graduated with a fix that works when run once', async () => {- const c = await fresh('stale-cli');- const { argv, env } = await planAndRun(c);- expect((await gbrain(argv, { home: c.fx.home, env, timeoutMs: 900_000 })).code).toBe(0);- const home = staleHome(c);- const refused = await gbrain(['query', 'acme', '--json'], { home });- expect(refused.code).not.toBe(0);- expect(codeOf(refused.json)).toBe('engine_graduated');- const fix = fixOf(refused.json)!;- expect(['run', 'tell_user_to_run']).toContain(fix.next);- expect(JSON.stringify(fix)).not.toContain(leakNeedle(passwordOf(c.target.url)));- const fixed = await runFix(fix, home, c);- expect({ code: fixed.code, stderr: fixed.code === 0 ? '' : fixed.stderr.slice(-1500) }).toEqual({ code: 0, stderr: '' });- const retried = await gbrain(['get', 'people/alice-example', '--source', 'default'], { home });- expect({ code: retried.code, stderr: retried.code === 0 ? '' : retried.stderr.slice(-1500) }).toEqual({ code: 0, stderr: '' });- expect(retried.stdout).toContain('Alice-example');- }, 900_000);-- graduationTest('a stale MCP server config surfaces engine_graduated through the MCP host and recovers after one fix', async () => {- const c = await fresh('stale-mcp');- const { argv, env } = await planAndRun(c);- expect((await gbrain(argv, { home: c.fx.home, env, timeoutMs: 900_000 })).code).toBe(0);- const home = staleHome(c);- const stale = await mcpStdioSession({ home });- const reply = await stale.call('get_page', { slug: 'people/alice-example', source_id: 'default' });- const exited = await stale.close();- const text = `${JSON.stringify(reply)}${exited.stdout}${exited.stderr}`;- expect(text).toContain('engine_graduated');- const fix = findFix(reply);- expect(fix).not.toBeNull();- const fixed = await runFix(fix!, home, c);- expect(fixed.code).toBe(0);- const relaunched = await mcpStdioSession({ home });- const after = await relaunched.call('get_page', { slug: 'people/alice-example', source_id: 'default' });- await relaunched.close();- expect(after?.error).toBeUndefined();- expect(JSON.stringify(after)).toContain('Alice-example');- }, 900_000);-});-diff --git a/test/e2e/graduation-crash-rollback-1.test.ts b/test/e2e/graduation-crash-rollback-1.test.tsnew file mode 100644index 0000000000..95f7776020--- /dev/null+++ b/test/e2e/graduation-crash-rollback-1.test.ts@@ -0,0 +1,29 @@+/**+ * Engine graduation crash custody, part of the suite documented in+ * graduation-crash-run-1.test.ts (test/helpers/graduation-crash-cases.ts).+ */+import { afterAll, expect } from 'bun:test';+import { GRADUATION_ROLLBACK_BOUNDARIES } from '../../src/core/persistence/engine-graduation.types.ts';+import { closeCases, fresh, graduate, rollbackKillSuite } from '../helpers/graduation-crash-cases.ts';+import { codeOf, fixOf, gbrain, graduationTest } from '../helpers/graduation-e2e.ts';+import { configuredEngine, rollback, targetFenceTriggers, targetRowState } from '../helpers/graduation-scenarios.ts';++afterAll(closeCases);++rollbackKillSuite(GRADUATION_ROLLBACK_BOUNDARIES.slice(0, 4), () => {+ graduationTest('a target fact withdrawal or token revocation makes rollback refuse finally, even with --yes', async () => {+ const c = await fresh('rollback-security');+ await graduate(c);+ const revoke = await gbrain(['auth', 'revoke', 'legacy-fixture-live'], { home: c.fx.home });+ expect(revoke.code).toBe(0);+ const { first } = await rollback(c, { confirm: false });+ expect(first.code).toBe(1);+ expect(codeOf(first.json)).toBe('graduation_rollback_writes_lost');+ expect(fixOf(first.json)?.next).toBe('report');+ const forced = await gbrain(['migrate', '--rollback-to-source', '--yes', '--expect', 'any', '--json'], { home: c.fx.home });+ expect(forced.code).not.toBe(0);+ expect(await targetRowState(c.target.url)).toBe('authoritative');+ expect(await targetFenceTriggers(c.target.url)).toBe(0);+ expect(configuredEngine(c.fx).engine).toBe('postgres');+ }, 900_000);+});diff --git a/test/e2e/graduation-crash-rollback-2.test.ts b/test/e2e/graduation-crash-rollback-2.test.tsnew file mode 100644index 0000000000..f92aa72f88--- /dev/null+++ b/test/e2e/graduation-crash-rollback-2.test.ts@@ -0,0 +1,25 @@+/**+ * Engine graduation crash custody, part of the suite documented in+ * graduation-crash-run-1.test.ts (test/helpers/graduation-crash-cases.ts).+ */+import { afterAll, expect } from 'bun:test';+import { GRADUATION_ROLLBACK_BOUNDARIES } from '../../src/core/persistence/engine-graduation.types.ts';+import { closeCases, fresh, graduate, rollbackKillSuite } from '../helpers/graduation-crash-cases.ts';+import { graduationTest } from '../helpers/graduation-e2e.ts';+import { authority, rollback, targetFenceTriggers, withTarget } from '../helpers/graduation-scenarios.ts';++afterAll(closeCases);++rollbackKillSuite(GRADUATION_ROLLBACK_BOUNDARIES.slice(4), () => {+ graduationTest('rollback with no post-cutover writes restores the source exactly and leaves the target fenced', async () => {+ const c = await fresh('rollback-clean');+ await graduate(c);+ const { first, confirmed } = await rollback(c);+ expect((confirmed ?? first).code).toBe(0);+ const a = await authority(c);+ expect({ source: a.source, target: a.target }).toEqual({ source: true, target: false });+ expect(await targetFenceTriggers(c.target.url)).toBeGreaterThan(0);+ const blocked = await withTarget(c.target.url, t => t.executeRaw(`INSERT INTO config(key,value) VALUES('graduation.stray','x')`).then(() => 'written', e => String(e)));+ expect(blocked).toContain('graduation');+ }, 900_000);+});diff --git a/test/e2e/graduation-crash-run-1.test.ts b/test/e2e/graduation-crash-run-1.test.tsnew file mode 100644index 0000000000..7adb953102--- /dev/null+++ b/test/e2e/graduation-crash-run-1.test.ts@@ -0,0 +1,32 @@+/**+ * Engine graduation crash custody (PGLite -> Postgres 16).+ *+ * Protects: "exactly one authoritative engine at every instant, across+ * crashes" (plan §3.3, §6.2, §13). The real CLI run is SIGKILLed at every+ * custody boundary it announces (quiesce, drain, fence, mid-table and+ * table-boundary copy, verify, each cutover sub-step, around the routing flip)+ * and at every rollback substep. After each kill: no instant with two+ * writable engines; `--status` reports without mutating; a clean process with+ * no target environment variable resumes from the 0600 manifest; the end+ * state is graduated (or rolled back) with every expected.json expectation,+ * one row per request id, the queued request replaying its stored outcome,+ * and a green target doctor.+ * Regressions it catches: a step whose durable write is not ordered before+ * its effect (e.g. tombstone before rename, authority before tombstone),+ * reconciliation that restarts from routing instead of the manifest, a+ * resume that re-runs terminal requests, a rollback that strands the live+ * brain or restores authority after approval.+ * Not covered elsewhere: the orchestrator's unit tests run in-process without+ * kills. Production seam: `graduationBoundary()` hooks, inert unless the+ * crash preload registers them.+ * Split across graduation-crash-run-{1,2,3} and graduation-crash-rollback-{1,2}+ * (test/helpers/graduation-crash-cases.ts) so CI can run them side by side;+ * this file kills the first run boundaries.+ * Runtime: about 16 s per case.+ */+import { afterAll } from 'bun:test';+import { closeCases, RUN_KILLS, runKillSuite } from '../helpers/graduation-crash-cases.ts';++afterAll(closeCases);++runKillSuite(RUN_KILLS.slice(0, 6));diff --git a/test/e2e/graduation-crash-run-2.test.ts b/test/e2e/graduation-crash-run-2.test.tsnew file mode 100644index 0000000000..a48a969460--- /dev/null+++ b/test/e2e/graduation-crash-run-2.test.ts@@ -0,0 +1,32 @@+/**+ * Engine graduation crash custody, part of the suite documented in+ * graduation-crash-run-1.test.ts (test/helpers/graduation-crash-cases.ts).+ */+import { afterAll, expect } from 'bun:test';+import { closeCases, fresh, killAt, RUN_KILLS, runKillSuite } from '../helpers/graduation-crash-cases.ts';+import { gbrain, graduationTest } from '../helpers/graduation-e2e.ts';+import { authority, configuredEngine, withTarget } from '../helpers/graduation-scenarios.ts';++afterAll(closeCases);++runKillSuite(RUN_KILLS.slice(6, 11), () => {+ graduationTest('kill after authority, a target client writes before the routing flip, resume keeps the write and finishes routing', async () => {+ const c = await fresh('first-write-before-flip');+ await killAt(c, 'authoritative');+ expect(configuredEngine(c.fx).engine).toBe('pglite');+ const a = await authority(c);+ expect({ source: a.source, target: a.target }).toEqual({ source: false, target: true });+ // Another client already configured with the target URL (a second machine) writes first.+ const other = `${c.fx.dir}/other-client`;+ const put = await gbrain(['put', 'notes/first-post-cutover', '--source', 'default'],+ { home: other, env: { GBRAIN_DATABASE_URL: c.target.url }, stdin: '---\ntype: note\ntitle: First post-cutover write\n---\n\nWritten on the target before routing flipped.\n' });+ expect({ code: put.code, stderr: put.code === 0 ? '' : put.stderr.slice(-2000) }).toEqual({ code: 0, stderr: '' });+ const resumed = await gbrain(['migrate', '--resume', '--json'], { home: c.fx.home, timeoutMs: 600_000 });+ expect(resumed.code).toBe(0);+ expect(configuredEngine(c.fx).engine).toBe('postgres');+ await withTarget(c.target.url, async t => {+ const [page] = await t.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM pages WHERE source_id='default' AND slug='notes/first-post-cutover' AND deleted_at IS NULL`);+ expect(Number(page.n)).toBe(1);+ });+ }, 900_000);+});diff --git a/test/e2e/graduation-crash-run-3.test.ts b/test/e2e/graduation-crash-run-3.test.tsnew file mode 100644index 0000000000..59d252ac12--- /dev/null+++ b/test/e2e/graduation-crash-run-3.test.ts@@ -0,0 +1,40 @@+/**+ * Engine graduation crash custody, part of the suite documented in+ * graduation-crash-run-1.test.ts (test/helpers/graduation-crash-cases.ts).+ */+import { afterAll, expect } from 'bun:test';+import { closeCases, fresh, graduate, RUN_KILLS, runKillSuite } from '../helpers/graduation-crash-cases.ts';+import { codeOf, fixOf, gbrain, graduationTest, startGbrain, stateOf } from '../helpers/graduation-e2e.ts';+import { targetRowState, withTarget } from '../helpers/graduation-scenarios.ts';++afterAll(closeCases);++runKillSuite(RUN_KILLS.slice(11), () => {+ graduationTest('SIGKILL right after the first post-cutover write commits: the write survives, rollback lists it as user data', async () => {+ const c = await fresh('first-write-kill');+ await graduate(c);+ const writer = startGbrain(['put', 'notes/killed-after-commit', '--source', 'default'],+ { home: c.fx.home, stdin: '---\ntype: note\ntitle: Killed after commit\n---\n\nCommitted, then the writer died.\n' });+ const deadline = Date.now() + 120_000;+ for (;;) {+ const committed = await withTarget(c.target.url, t => t.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM persistence_requests+ WHERE slug='notes/killed-after-commit' AND state='committed'`));+ if (Number(committed[0].n) === 1) break;+ if (Date.now() > deadline) throw new Error('the post-cutover write never committed');+ await Bun.sleep(10);+ }+ writer.kill('SIGKILL');+ await writer.exited;+ const status = await gbrain(['migrate', '--status', '--json'], { home: c.fx.home });+ expect(stateOf(status.json)).toBe('graduated');+ const refused = await gbrain(['migrate', '--rollback-to-source', '--json'], { home: c.fx.home });+ expect(refused.code).toBe(3);+ expect(codeOf(refused.json)).toBe('graduation_rollback_writes_lost');+ expect(fixOf(refused.json)?.next).toBe('ask_user');+ expect(JSON.stringify(refused.json)).toContain('pages');+ // The refusal returned the target to authority; a normal client still writes.+ expect(await targetRowState(c.target.url)).toBe('authoritative');+ const put = await gbrain(['put', 'notes/after-refusal', '--source', 'default'], { home: c.fx.home, stdin: 'after refusal\n' });+ expect(put.code).toBe(0);+ }, 900_000);+});diff --git a/test/e2e/graduation-crash.test.ts b/test/e2e/graduation-crash.test.tsdeleted file mode 100644index c8fe4eef04..0000000000--- a/test/e2e/graduation-crash.test.ts+++ /dev/null@@ -1,215 +0,0 @@-/**- * Engine graduation crash custody (PGLite -> Postgres 16).- *- * Protects: "exactly one authoritative engine at every instant, across- * crashes" (plan §3.3, §6.2, §13). The real CLI run is SIGKILLed at every- * custody boundary it announces (quiesce, drain, fence, mid-table and- * table-boundary copy, verify, each cutover sub-step, around the routing flip)- * and at every rollback substep. After each kill: no instant with two- * writable engines; `--status` reports without mutating; a clean process with- * no target environment variable resumes from the 0600 manifest; the end- * state is graduated (or rolled back) with every expected.json expectation,- * one row per request id, the queued request replaying its stored outcome,- * and a green target doctor.- * Regressions it catches: a step whose durable write is not ordered before- * its effect (e.g. tombstone before rename, authority before tombstone),- * reconciliation that restarts from routing instead of the manifest, a- * resume that re-runs terminal requests, a rollback that strands the live- * brain or restores authority after approval.- * Not covered elsewhere: the orchestrator's unit tests run in-process without- * kills. Production seam: `graduationBoundary()` hooks, inert unless the- * crash preload registers them.- * Runtime: about 40 s per case; run with GBRAIN_E2E_FILE_TIMEOUT=3600.- */-import { afterAll, describe, expect } from 'bun:test';-import { rmSync } from 'node:fs';-import { GRADUATION_ROLLBACK_BOUNDARIES, GRADUATION_RUN_BOUNDARIES } from '../../src/core/persistence/engine-graduation.types.ts';-import { codeOf, DATABASE_URL, fixOf, gbrain, graduationTest, planHashOf, readEvents, startGbrain, stateOf, TARGET_ENV, waitForEvent } from '../helpers/graduation-e2e.ts';-import {- authority, configuredEngine, expectAtMostOneWriter, expectGraduated, legacyCase, manifestState, planAndRun, rollback, scratchRoot,- targetFenceTriggers, targetRowState, withSource, withTarget, type Case,-} from '../helpers/graduation-scenarios.ts';--const cases: Case[] = [];-afterAll(async () => {- for (const c of cases) await c.target.close().catch(() => {});- rmSync(scratchRoot, { recursive: true, force: true });-});--async function fresh(name: string): Promise<Case> {- const c = await legacyCase(name);- cases.push(c);- return c;-}--/** Start the confirmed run paused at `pause`, wait for it, SIGKILL it. */-async function killAt(c: Case, pause: string, extra: string[] = []): Promise<void> {- const { argv, env } = await planAndRun(c, { extra });- const child = startGbrain(argv, { home: c.fx.home, env, hooks: { events: c.events, pause: [pause] }, timeoutMs: 600_000 });- await waitForEvent(c.events, e => e.event === 'paused', child);- child.kill('SIGKILL');- const result = await child.exited;- expect(result.signal).toBe('SIGKILL');-}--/** Graduate to completion with no kill. */-async function graduate(c: Case): Promise<void> {- const { argv, env } = await planAndRun(c);- const run = await gbrain(argv, { home: c.fx.home, env, timeoutMs: 900_000 });- expect({ code: run.code, stderr: run.code === 0 ? '' : run.stderr.slice(-3000) }).toEqual({ code: 0, stderr: '' });-}--/** Start the rollback as an agent would (confirming with the hash if asked), paused at `boundary`, then SIGKILL it. */-async function killRollbackAt(c: Case, boundary: string): Promise<void> {- const hooks = { events: c.events, pause: [boundary] };- let child = startGbrain(['migrate', '--rollback-to-source', '--json'], { home: c.fx.home, hooks });- const paused = await waitForEvent(c.events, e => e.event === 'paused', child).then(() => true, () => false);- if (!paused) {- const first = await child.exited;- expect(first.code).toBe(3);- child = startGbrain(['migrate', '--rollback-to-source', '--yes', '--expect', String(planHashOf(first.json)), '--json'], { home: c.fx.home, hooks });- await waitForEvent(c.events, e => e.event === 'paused' && e.boundary === boundary, child);- }- child.kill('SIGKILL');- await child.exited;-}--/** Every run boundary, with the copy boundaries pinned to a multi-batch table (pages at --batch-size 2). */-const RUN_KILLS: { pause: string; label: string }[] = GRADUATION_RUN_BOUNDARIES.map(b =>- b === 'batch_copied' ? { pause: 'batch_copied@pages', label: 'mid-table (first committed batch of pages)' }- : b === 'table_copied' ? { pause: 'table_copied@pages', label: 'table boundary (pages committed)' }- : { pause: b, label: b });--describe.skipIf(!DATABASE_URL)('graduation: SIGKILL at every custody boundary', () => {- for (const { pause, label } of RUN_KILLS) {- graduationTest(`kill at ${label}: at most one writer, status read-only, clean-process resume graduates`, async () => {- const c = await fresh(`kill-${pause.replace(/[@]/g, '-')}`);- await killAt(c, pause, ['--batch-size', '2']);- expect(readEvents(c.events).filter(e => e.event === 'boundary').at(-1)?.boundary).toBe(pause.split('@')[0]);- await expectAtMostOneWriter(c, `after kill at ${pause}`);-- const status = await gbrain(['migrate', '--status', '--json'], { home: c.fx.home });- expect(status.code).toBe(0);- // `graduated` is announced after its own durable write, so a kill there already reads graduated.- if (pause !== 'graduated') expect(stateOf(status.json)).not.toBe('graduated');-- // No target URL in the environment: resume reads the 0600 manifest's recorded identities.- const resumed = await gbrain(['migrate', '--resume', '--json'], { home: c.fx.home, env: { [TARGET_ENV]: undefined }, timeoutMs: 900_000 });- expect({ code: resumed.code, stderr: resumed.code === 0 ? '' : resumed.stderr.slice(-3000) }).toEqual({ code: 0, stderr: '' });- await expectGraduated(c, `kill at ${pause}`);- }, 900_000);- }-- graduationTest('kill after authority, a target client writes before the routing flip, resume keeps the write and finishes routing', async () => {- const c = await fresh('first-write-before-flip');- await killAt(c, 'authoritative');- expect(configuredEngine(c.fx).engine).toBe('pglite');- const a = await authority(c);- expect({ source: a.source, target: a.target }).toEqual({ source: false, target: true });- // Another client already configured with the target URL (a second machine) writes first.- const other = `${c.fx.dir}/other-client`;- const put = await gbrain(['put', 'notes/first-post-cutover', '--source', 'default'],- { home: other, env: { GBRAIN_DATABASE_URL: c.target.url }, stdin: '---\ntype: note\ntitle: First post-cutover write\n---\n\nWritten on the target before routing flipped.\n' });- expect({ code: put.code, stderr: put.code === 0 ? '' : put.stderr.slice(-2000) }).toEqual({ code: 0, stderr: '' });- const resumed = await gbrain(['migrate', '--resume', '--json'], { home: c.fx.home, timeoutMs: 600_000 });- expect(resumed.code).toBe(0);- expect(configuredEngine(c.fx).engine).toBe('postgres');- await withTarget(c.target.url, async t => {- const [page] = await t.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM pages WHERE source_id='default' AND slug='notes/first-post-cutover' AND deleted_at IS NULL`);- expect(Number(page.n)).toBe(1);- });- }, 900_000);-- graduationTest('SIGKILL right after the first post-cutover write commits: the write survives, rollback lists it as user data', async () => {- const c = await fresh('first-write-kill');- await graduate(c);- const writer = startGbrain(['put', 'notes/killed-after-commit', '--source', 'default'],- { home: c.fx.home, stdin: '---\ntype: note\ntitle: Killed after commit\n---\n\nCommitted, then the writer died.\n' });- const deadline = Date.now() + 120_000;- for (;;) {- const committed = await withTarget(c.target.url, t => t.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM persistence_requests- WHERE slug='notes/killed-after-commit' AND state='committed'`));- if (Number(committed[0].n) === 1) break;- if (Date.now() > deadline) throw new Error('the post-cutover write never committed');- await Bun.sleep(10);- }- writer.kill('SIGKILL');- await writer.exited;- const status = await gbrain(['migrate', '--status', '--json'], { home: c.fx.home });- expect(stateOf(status.json)).toBe('graduated');- const refused = await gbrain(['migrate', '--rollback-to-source', '--json'], { home: c.fx.home });- expect(refused.code).toBe(3);- expect(codeOf(refused.json)).toBe('graduation_rollback_writes_lost');- expect(fixOf(refused.json)?.next).toBe('ask_user');- expect(JSON.stringify(refused.json)).toContain('pages');- // The refusal returned the target to authority; a normal client still writes.- expect(await targetRowState(c.target.url)).toBe('authoritative');- const put = await gbrain(['put', 'notes/after-refusal', '--source', 'default'], { home: c.fx.home, stdin: 'after refusal\n' });- expect(put.code).toBe(0);- }, 900_000);-});--describe.skipIf(!DATABASE_URL)('graduation: SIGKILL at every rollback substep', () => {- for (const boundary of GRADUATION_ROLLBACK_BOUNDARIES) {- graduationTest(`kill at ${boundary}: reconciliation ${boundary === 'rollback_fenced' ? 'restores target authority' : 'rolls forward to the source'}`, async () => {- const c = await fresh(`rollback-${boundary}`);- await graduate(c);- await killRollbackAt(c, boundary);- await expectAtMostOneWriter(c, `after kill at ${boundary}`);- const status = await gbrain(['migrate', '--status', '--json'], { home: c.fx.home });- expect(status.code).toBe(0);-- const resumed = await gbrain(['migrate', '--resume', '--json'], { home: c.fx.home, timeoutMs: 600_000 });- expect({ code: resumed.code, stderr: resumed.code === 0 ? '' : resumed.stderr.slice(-3000) }).toEqual({ code: 0, stderr: '' });- const a = await authority(c);- if (boundary === 'rollback_fenced') {- // Not yet approved: the live brain stays on the target.- expect({ source: a.source, target: a.target }).toEqual({ source: false, target: true });- expect(configuredEngine(c.fx).engine).toBe('postgres');- const put = await gbrain(['put', 'notes/after-fenced-crash', '--source', 'default'], { home: c.fx.home, stdin: 'still live\n' });- expect(put.code).toBe(0);- } else {- // Approved: never back to target authority; the source is live again.- expect({ source: a.source, target: a.target }).toEqual({ source: true, target: false });- expect(configuredEngine(c.fx).engine).toBe('pglite');- expect(await targetFenceTriggers(c.target.url)).toBeGreaterThan(0);- expect(manifestState(c.fx)).toBe('rolled_back');- const put = await gbrain(['put', 'notes/after-rollback', '--source', 'default'], { home: c.fx.home, stdin: 'back on pglite\n' });- expect(put.code).toBe(0);- await withSource(c.fx, async source => {- const [row] = await source.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM pages WHERE slug IN ('notes/queued-request','notes/after-rollback')`);- expect(Number(row.n)).toBe(2);- });- }- }, 900_000);- }-- graduationTest('a target fact withdrawal or token revocation makes rollback refuse finally, even with --yes', async () => {- const c = await fresh('rollback-security');- await graduate(c);- const revoke = await gbrain(['auth', 'revoke', 'legacy-fixture-live'], { home: c.fx.home });- expect(revoke.code).toBe(0);- const { first } = await rollback(c, { confirm: false });- expect(first.code).toBe(1);- expect(codeOf(first.json)).toBe('graduation_rollback_writes_lost');- expect(fixOf(first.json)?.next).toBe('report');- const forced = await gbrain(['migrate', '--rollback-to-source', '--yes', '--expect', 'any', '--json'], { home: c.fx.home });- expect(forced.code).not.toBe(0);- expect(await targetRowState(c.target.url)).toBe('authoritative');- expect(await targetFenceTriggers(c.target.url)).toBe(0);- expect(configuredEngine(c.fx).engine).toBe('postgres');- }, 900_000);-- graduationTest('rollback with no post-cutover writes restores the source exactly and leaves the target fenced', async () => {- const c = await fresh('rollback-clean');- await graduate(c);- const { first, confirmed } = await rollback(c);- expect((confirmed ?? first).code).toBe(0);- const a = await authority(c);- expect({ source: a.source, target: a.target }).toEqual({ source: true, target: false });- expect(await targetFenceTriggers(c.target.url)).toBeGreaterThan(0);- const blocked = await withTarget(c.target.url, t => t.executeRaw(`INSERT INTO config(key,value) VALUES('graduation.stray','x')`).then(() => 'written', e => String(e)));- expect(blocked).toContain('graduation');- }, 900_000);-});-diff --git a/test/e2e/write-attribution-postgres.test.ts b/test/e2e/write-attribution-postgres.test.tsindex 1785fc90d2..9981d887ae 100644--- a/test/e2e/write-attribution-postgres.test.ts+++ b/test/e2e/write-attribution-postgres.test.ts@@ -5,14 +5,15 @@ import { hasDatabase } from './helpers.ts';// settings and BEFORE ROW triggers, run direct and through transaction-mode// PgBouncer (scripts/e2e-backend-matrix.txt). The legacy file covers the// unmanaged transactional writers (F1c); the write-attribution-<family> files-// cover the writers Foundations 2 routed (Lane C).+// cover the writers Foundations 2 routed (Lane C). The 10k-page timeline run+// is its own file (write-attribution-timeline-10k-postgres.test.ts) so a CI+// queue can run it beside this one.if (hasDatabase()) {await import('../write-attribution.test.ts');await import('../write-attribution-legacy.test.ts');await import('../write-attribution-import.test.ts');await import('../write-attribution-sync.test.ts');await import('../write-attribution-timeline.test.ts');- await import('../write-attribution-timeline-10k.slow.test.ts');await import('../write-attribution-facts-takes.test.ts');await import('../write-attribution-cycle.test.ts');await import('../write-attribution-schema-pack.test.ts');diff --git a/test/e2e/write-attribution-timeline-10k-postgres.test.ts b/test/e2e/write-attribution-timeline-10k-postgres.test.tsnew file mode 100644index 0000000000..e0306bc762--- /dev/null+++ b/test/e2e/write-attribution-timeline-10k-postgres.test.ts@@ -0,0 +1,12 @@+import { test } from 'bun:test';+import { hasDatabase } from './helpers.ts';++// Foundations 1 write attribution on Postgres for `extract timeline --source+// db` at 10k pages (bounded per-batch transactions), direct and through+// transaction-mode PgBouncer (scripts/e2e-backend-matrix.txt). Split from+// write-attribution-postgres.test.ts.+if (hasDatabase()) {+ await import('../write-attribution-timeline-10k.slow.test.ts');+} else {+ test.skip('write attribution on Postgres requires DATABASE_URL', () => {});+}diff --git a/test/helpers/graduation-cli-cases.ts b/test/helpers/graduation-cli-cases.tsnew file mode 100644index 0000000000..40c606a556--- /dev/null+++ b/test/helpers/graduation-cli-cases.ts@@ -0,0 +1,74 @@+/**+ * Shared by the graduation-cli*.test.ts suites, one agent-workflow suite split+ * into files so a CI queue can run them side by side (each file is its own+ * process with its own scratch root and fixture cache):+ * graduation-cli.test.ts agent workflow, target emptiness and --force+ * graduation-cli-topologies.test.ts PgBouncer, hosted-style role, forced bypass+ * graduation-cli-history.test.ts 1k-page history round trip+ * graduation-cli-zero-mutation-N.test.ts --plan/--status polled at every custody+ * boundary; file N of ZERO_MUTATION_PARTS probes the boundaries whose pause+ * ordinal is N modulo the part count, so together they probe every one.+ */+import { afterAll, describe, expect } from 'bun:test';+import { rmSync } from 'node:fs';+import { DATABASE_URL, digestChanges, gbrain, graduationTest, release, startGbrain, stateDigest, TARGET_ENV, waitForEvent } from './graduation-e2e.ts';+import { expectGraduated, legacyCase, planAndRun, scratchRoot, type Case } from './graduation-scenarios.ts';++export const ZERO_MUTATION_PARTS = 3;++/** Fresh legacy cases whose targets (and any registered cleanup) are torn down after the file. */+export function useGraduationCases() {+ const cleanups: (() => Promise<void>)[] = [];+ afterAll(async () => {+ for (const cleanup of cleanups.reverse()) await cleanup().catch(() => {});+ rmSync(scratchRoot, { recursive: true, force: true });+ });+ async function fresh(name: string, target?: Case['target']): Promise<Case> {+ const c = await legacyCase(name, target);+ cleanups.push(() => c.target.close());+ return c;+ }+ return { cleanups, fresh };+}++/**+ * One graduation paused at every custody boundary and SIGKILLed at `verified`;+ * this part probes its share of the pauses, then the post-crash state.+ */+export function zeroMutationSuite(part: number): void {+ const { fresh } = useGraduationCases();+ describe.skipIf(!DATABASE_URL)('graduation: --plan and --status are zero-mutation', () => {+ graduationTest(`polled at every custody boundary (part ${part} of ${ZERO_MUTATION_PARTS}) and after a crash, neither changes a byte or a row`, async () => {+ const c = await fresh('zero-mutation');+ const { argv, env } = await planAndRun(c);+ const child = startGbrain(argv, { home: c.fx.home, env, hooks: { events: c.events, pause: ['*'] } });+ const seen: string[] = [];+ const probe = async (label: string) => {+ const before = await stateDigest(c.fx.dir, c.target.url);+ const status = await gbrain(['migrate', '--status', '--json'], { home: c.fx.home });+ expect({ label, code: status.code }).toEqual({ label, code: 0 });+ await gbrain(['migrate', '--to', 'postgres', '--url-env', TARGET_ENV, '--plan', '--json'], { home: c.fx.home, env });+ // Not the poll's writes: the paused run's own kernel-lock heartbeat (.gbrain-lock/lock, every 30 s) and Bun's runtime install cache under the test HOME.+ const changes = digestChanges(before, await stateDigest(c.fx.dir, c.target.url))+ .filter(change => !change.includes('boundary-events.jsonl') && !change.includes('.gbrain-lock/lock') && !change.includes('/.bun/install/cache/'));+ expect({ label, changes }).toEqual({ label, changes: [] });+ };+ for (let ordinal = 1; ; ordinal++) {+ const paused = await waitForEvent(c.events, e => e.event === 'paused' && e.ordinal === ordinal, child).catch(() => null);+ if (!paused) break;+ seen.push(paused.boundary);+ if (ordinal % ZERO_MUTATION_PARTS === part % ZERO_MUTATION_PARTS) await probe(`${paused.boundary}#${ordinal}`);+ if (paused.boundary === 'verified') {+ child.kill('SIGKILL');+ await child.exited;+ await probe('after a SIGKILL at verified');+ break;+ }+ release(c.events, ordinal);+ }+ expect(seen).toEqual(expect.arrayContaining(['quiesced', 'drained', 'target_fenced', 'table_copied', 'copied', 'verified']));+ expect((await gbrain(['migrate', '--resume', '--json'], { home: c.fx.home, timeoutMs: 900_000 })).code).toBe(0);+ await expectGraduated(c, 'after zero-mutation polling');+ }, 1_200_000);+ });+}diff --git a/test/helpers/graduation-clients-cases.ts b/test/helpers/graduation-clients-cases.tsnew file mode 100644index 0000000000..b77f6dc885--- /dev/null+++ b/test/helpers/graduation-clients-cases.ts@@ -0,0 +1,64 @@+/**+ * Shared by the graduation-clients*.test.ts suites (older released binaries in+ * graduation-clients.test.ts; serve processes and stale clients in+ * graduation-clients-serve.test.ts): fresh legacy cases, a stale client home+ * on this machine, and running a refusal's fix exactly as an agent would.+ */+import { expect } from 'bun:test';+import { chmodSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { gbrain, REPO, TARGET_ENV, type GbrainResult } from './graduation-e2e.ts';+import { legacyCase, scratchRoot, type Case } from './graduation-scenarios.ts';++const cases: Case[] = [];+/** afterAll hook for every clients file: close each case's target and remove the scratch root. */+export async function closeCases(): Promise<void> {+ for (const c of cases) await c.target.close().catch(() => {});+ rmSync(scratchRoot, { recursive: true, force: true });+}++export async function fresh(name: string): Promise<Case> {+ const c = await legacyCase(name);+ cases.push(c);+ return c;+}++/** A second GBRAIN_HOME whose copied config still routes to the PGLite path (a stale client on this machine). */+export function staleHome(c: Case): string {+ const home = join(c.fx.dir, 'stale-home');+ mkdirSync(join(home, '.gbrain'), { recursive: true });+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({ engine: 'pglite', database_path: c.fx.dataDir, embedding_disabled: true }, null, 2), { mode: 0o600 });+ return home;+}++/** `gbrain` on PATH for running a refusal's shell `fix.command` exactly as an agent would. */+export function shimPath(c: Case): string {+ const bin = join(c.fx.dir, 'shim-bin');+ mkdirSync(bin, { recursive: true });+ writeFileSync(join(bin, 'gbrain'), `#!/bin/sh\nexec "${process.execPath}" --no-env-file "${join(REPO, 'src', 'cli.ts')}" "$@"\n`);+ chmodSync(join(bin, 'gbrain'), 0o755);+ return `${bin}:${process.env.PATH}`;+}++/** Run a refusal's fix once: `fix.argv` through the CLI, or the shell `fix.command`. */+/** The first rendered fix (`next` run or tell_user_to_run) anywhere in an MCP reply, including JSON-encoded text content. */+export function findFix(value: unknown): Record<string, any> | null {+ if (typeof value === 'string') { try { return findFix(JSON.parse(value)); } catch { return null; } }+ if (!value || typeof value !== 'object') return null;+ const record = value as Record<string, any>;+ if ((record.next === 'run' || record.next === 'tell_user_to_run') && Array.isArray(record.argv)) return record;+ for (const child of Object.values(record)) { const found = findFix(child); if (found) return found; }+ return null;+}++export async function runFix(fix: Record<string, any>, home: string, c: Case): Promise<GbrainResult> {+ const env = { [TARGET_ENV]: c.target.url, PATH: shimPath(c) };+ // An agent fills `<name>` argv placeholders from fix.inputs (the user supplies the target URL).+ const filled = Array.isArray(fix.argv) ? (fix.argv as string[]).map(a => a === '<target_url>' ? c.target.url : a) : null;+ if (filled && filled[0] === 'gbrain') return gbrain(filled.slice(1), { home, env });+ expect(typeof fix.command).toBe('string');+ const child = Bun.spawn(['sh', '-c', fix.command], { env: { ...process.env, ...env, HOME: home, GBRAIN_HOME: home, DATABASE_URL: '', GBRAIN_DATABASE_URL: '' }, stdout: 'pipe', stderr: 'pipe' });+ const [stdout, stderr] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text()]);+ await child.exited;+ return { code: child.exitCode ?? -1, signal: null, stdout, stderr, json: null, ms: 0 };+}diff --git a/test/helpers/graduation-crash-cases.ts b/test/helpers/graduation-crash-cases.tsnew file mode 100644index 0000000000..7f3f0c75ea--- /dev/null+++ b/test/helpers/graduation-crash-cases.ts@@ -0,0 +1,133 @@+/**+ * Shared by the graduation-crash-*.test.ts suites: one crash-custody suite+ * (PGLite -> Postgres 16) split into files so a CI queue can run them side by+ * side. Every file is its own process with its own scratch root and fixture+ * cache; together they kill the real CLI at every run boundary+ * (graduation-crash-run-N) and every rollback substep+ * (graduation-crash-rollback-N). What each kill must leave behind is+ * documented in test/e2e/graduation-crash-run-1.test.ts.+ */+import { describe, expect } from 'bun:test';+import { rmSync } from 'node:fs';+import { GRADUATION_RUN_BOUNDARIES } from '../../src/core/persistence/engine-graduation.types.ts';+import { DATABASE_URL, gbrain, graduationTest, planHashOf, readEvents, startGbrain, stateOf, TARGET_ENV, waitForEvent } from './graduation-e2e.ts';+import {+ authority, configuredEngine, expectAtMostOneWriter, expectGraduated, legacyCase, manifestState, planAndRun, scratchRoot,+ targetFenceTriggers, withSource, type Case,+} from './graduation-scenarios.ts';++const cases: Case[] = [];+/** afterAll hook for every crash file: close each case's target and remove the scratch root. */+export async function closeCases(): Promise<void> {+ for (const c of cases) await c.target.close().catch(() => {});+ rmSync(scratchRoot, { recursive: true, force: true });+}++export async function fresh(name: string): Promise<Case> {+ const c = await legacyCase(name);+ cases.push(c);+ return c;+}++/** Start the confirmed run paused at `pause`, wait for it, SIGKILL it. */+export async function killAt(c: Case, pause: string, extra: string[] = []): Promise<void> {+ const { argv, env } = await planAndRun(c, { extra });+ const child = startGbrain(argv, { home: c.fx.home, env, hooks: { events: c.events, pause: [pause] }, timeoutMs: 600_000 });+ await waitForEvent(c.events, e => e.event === 'paused', child);+ child.kill('SIGKILL');+ const result = await child.exited;+ expect(result.signal).toBe('SIGKILL');+}++/** Graduate to completion with no kill. */+export async function graduate(c: Case): Promise<void> {+ const { argv, env } = await planAndRun(c);+ const run = await gbrain(argv, { home: c.fx.home, env, timeoutMs: 900_000 });+ expect({ code: run.code, stderr: run.code === 0 ? '' : run.stderr.slice(-3000) }).toEqual({ code: 0, stderr: '' });+}++/** Start the rollback as an agent would (confirming with the hash if asked), paused at `boundary`, then SIGKILL it. */+export async function killRollbackAt(c: Case, boundary: string): Promise<void> {+ const hooks = { events: c.events, pause: [boundary] };+ let child = startGbrain(['migrate', '--rollback-to-source', '--json'], { home: c.fx.home, hooks });+ const paused = await waitForEvent(c.events, e => e.event === 'paused', child).then(() => true, () => false);+ if (!paused) {+ const first = await child.exited;+ expect(first.code).toBe(3);+ child = startGbrain(['migrate', '--rollback-to-source', '--yes', '--expect', String(planHashOf(first.json)), '--json'], { home: c.fx.home, hooks });+ await waitForEvent(c.events, e => e.event === 'paused' && e.boundary === boundary, child);+ }+ child.kill('SIGKILL');+ await child.exited;+}++/** Every run boundary, with the copy boundaries pinned to a multi-batch table (pages at --batch-size 2). */+export const RUN_KILLS: { pause: string; label: string }[] = GRADUATION_RUN_BOUNDARIES.map(b =>+ b === 'batch_copied' ? { pause: 'batch_copied@pages', label: 'mid-table (first committed batch of pages)' }+ : b === 'table_copied' ? { pause: 'table_copied@pages', label: 'table boundary (pages committed)' }+ : { pause: b, label: b });++/** SIGKILL at each of `kills` (a slice of RUN_KILLS), then a clean-process resume. */+export function runKillSuite(kills: typeof RUN_KILLS, more: () => void = () => {}): void {+ describe.skipIf(!DATABASE_URL)('graduation: SIGKILL at every custody boundary', () => {+ for (const { pause, label } of kills) {+ graduationTest(`kill at ${label}: at most one writer, status read-only, clean-process resume graduates`, async () => {+ const c = await fresh(`kill-${pause.replace(/[@]/g, '-')}`);+ await killAt(c, pause, ['--batch-size', '2']);+ expect(readEvents(c.events).filter(e => e.event === 'boundary').at(-1)?.boundary).toBe(pause.split('@')[0]);+ await expectAtMostOneWriter(c, `after kill at ${pause}`);++ const status = await gbrain(['migrate', '--status', '--json'], { home: c.fx.home });+ expect(status.code).toBe(0);+ // `graduated` is announced after its own durable write, so a kill there already reads graduated.+ if (pause !== 'graduated') expect(stateOf(status.json)).not.toBe('graduated');++ // No target URL in the environment: resume reads the 0600 manifest's recorded identities.+ const resumed = await gbrain(['migrate', '--resume', '--json'], { home: c.fx.home, env: { [TARGET_ENV]: undefined }, timeoutMs: 900_000 });+ expect({ code: resumed.code, stderr: resumed.code === 0 ? '' : resumed.stderr.slice(-3000) }).toEqual({ code: 0, stderr: '' });+ await expectGraduated(c, `kill at ${pause}`);+ }, 900_000);+ }+ more();+ });+}++/** SIGKILL at each of `boundaries` (a slice of GRADUATION_ROLLBACK_BOUNDARIES), then reconciliation. */+export function rollbackKillSuite(boundaries: readonly string[], more: () => void = () => {}): void {+ describe.skipIf(!DATABASE_URL)('graduation: SIGKILL at every rollback substep', () => {+ for (const boundary of boundaries) {+ graduationTest(`kill at ${boundary}: reconciliation ${boundary === 'rollback_fenced' ? 'restores target authority' : 'rolls forward to the source'}`, async () => {+ const c = await fresh(`rollback-${boundary}`);+ await graduate(c);+ await killRollbackAt(c, boundary);+ await expectAtMostOneWriter(c, `after kill at ${boundary}`);+ const status = await gbrain(['migrate', '--status', '--json'], { home: c.fx.home });+ expect(status.code).toBe(0);++ const resumed = await gbrain(['migrate', '--resume', '--json'], { home: c.fx.home, timeoutMs: 600_000 });+ expect({ code: resumed.code, stderr: resumed.code === 0 ? '' : resumed.stderr.slice(-3000) }).toEqual({ code: 0, stderr: '' });+ const a = await authority(c);+ if (boundary === 'rollback_fenced') {+ // Not yet approved: the live brain stays on the target.+ expect({ source: a.source, target: a.target }).toEqual({ source: false, target: true });+ expect(configuredEngine(c.fx).engine).toBe('postgres');+ const put = await gbrain(['put', 'notes/after-fenced-crash', '--source', 'default'], { home: c.fx.home, stdin: 'still live\n' });+ expect(put.code).toBe(0);+ } else {+ // Approved: never back to target authority; the source is live again.+ expect({ source: a.source, target: a.target }).toEqual({ source: true, target: false });+ expect(configuredEngine(c.fx).engine).toBe('pglite');+ expect(await targetFenceTriggers(c.target.url)).toBeGreaterThan(0);+ expect(manifestState(c.fx)).toBe('rolled_back');+ const put = await gbrain(['put', 'notes/after-rollback', '--source', 'default'], { home: c.fx.home, stdin: 'back on pglite\n' });+ expect(put.code).toBe(0);+ await withSource(c.fx, async source => {+ const [row] = await source.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM pages WHERE slug IN ('notes/queued-request','notes/after-rollback')`);+ expect(Number(row.n)).toBe(2);+ });+ }+ }, 900_000);+ }+ more();+ });+}diff --git a/test/helpers/reconcile-crash-cases.ts b/test/helpers/reconcile-crash-cases.tsnew file mode 100644index 0000000000..cfbd3d349d--- /dev/null+++ b/test/helpers/reconcile-crash-cases.ts@@ -0,0 +1,27 @@+/**+ * Disk-PGLite reconciliation SIGKILL cases, shared by the+ * test/reconcile-crash-{unactivated,activated}-{1,2}.slow.test.ts files: every+ * crash boundary before and after activation, split four ways so a CI queue+ * can run them side by side (each case is an independent worker process).+ */+import { expect, test } from 'bun:test';+import { CRASH_BOUNDARIES, runReconcileCrashCase } from '../fixtures/reconcile-crash-worker.ts';++/** The half (1 or 2) of CRASH_BOUNDARIES a file covers. */+export function crashBoundaries(half: 1 | 2): (typeof CRASH_BOUNDARIES)[number][] {+ const mid = Math.ceil(CRASH_BOUNDARIES.length / 2);+ return half === 1 ? CRASH_BOUNDARIES.slice(0, mid) : CRASH_BOUNDARIES.slice(mid);+}++export function reconcileCrashTests(enabled: boolean, boundaries: (typeof CRASH_BOUNDARIES)[number][]): void {+ for (const boundary of boundaries) {+ test(`disk PGLite reconciliation survives SIGKILL/${boundary}, activation=${enabled}`, async () => {+ const result = await runReconcileCrashCase({ kind: 'pglite', boundary, enabled });+ expect(result).toMatchObject({ status: 'passed', boundary, enabled, killed_signal: 'SIGKILL',+ committed_requests: 1, added_versions: 1, normal_apply_replay: true, originals_retained: true,+ receipt_unchanged: true, recovery_cleared: true, staging_cleaned: true, topology_unchanged: true, counters_conserved: true });+ if (boundary === 'staging_flushed') expect(result.flushed_before_rename_verified).toBe(true);+ if (boundary === 'after_response') expect(result.response_read_before_kill).toBe(true);+ }, 180_000);+ }+}diff --git a/test/reconcile-crash-activated-1.slow.test.ts b/test/reconcile-crash-activated-1.slow.test.tsnew file mode 100644index 0000000000..a1a12a0fd1--- /dev/null+++ b/test/reconcile-crash-activated-1.slow.test.ts@@ -0,0 +1,4 @@+// Disk-PGLite reconciliation survives SIGKILL at crash boundaries, activation=true, half 1 of the boundaries (test/helpers/reconcile-crash-cases.ts).+import { crashBoundaries, reconcileCrashTests } from './helpers/reconcile-crash-cases.ts';++reconcileCrashTests(true, crashBoundaries(1));diff --git a/test/reconcile-crash-activated-2.slow.test.ts b/test/reconcile-crash-activated-2.slow.test.tsnew file mode 100644index 0000000000..164b0882b0--- /dev/null+++ b/test/reconcile-crash-activated-2.slow.test.ts@@ -0,0 +1,4 @@+// Disk-PGLite reconciliation survives SIGKILL at crash boundaries, activation=true, half 2 of the boundaries (test/helpers/reconcile-crash-cases.ts).+import { crashBoundaries, reconcileCrashTests } from './helpers/reconcile-crash-cases.ts';++reconcileCrashTests(true, crashBoundaries(2));diff --git a/test/reconcile-crash-unactivated-1.slow.test.ts b/test/reconcile-crash-unactivated-1.slow.test.tsnew file mode 100644index 0000000000..a59a381f95--- /dev/null+++ b/test/reconcile-crash-unactivated-1.slow.test.ts@@ -0,0 +1,4 @@+// Disk-PGLite reconciliation survives SIGKILL at crash boundaries, activation=false, half 1 of the boundaries (test/helpers/reconcile-crash-cases.ts).+import { crashBoundaries, reconcileCrashTests } from './helpers/reconcile-crash-cases.ts';++reconcileCrashTests(false, crashBoundaries(1));diff --git a/test/reconcile-crash-unactivated-2.slow.test.ts b/test/reconcile-crash-unactivated-2.slow.test.tsnew file mode 100644index 0000000000..b44ab821e8--- /dev/null+++ b/test/reconcile-crash-unactivated-2.slow.test.ts@@ -0,0 +1,4 @@+// Disk-PGLite reconciliation survives SIGKILL at crash boundaries, activation=false, half 2 of the boundaries (test/helpers/reconcile-crash-cases.ts).+import { crashBoundaries, reconcileCrashTests } from './helpers/reconcile-crash-cases.ts';++reconcileCrashTests(false, crashBoundaries(2));diff --git a/test/reconcile-crash.slow.test.ts b/test/reconcile-crash.slow.test.tsdeleted file mode 100644index fed783aa89..0000000000--- a/test/reconcile-crash.slow.test.ts+++ /dev/null@@ -1,13 +0,0 @@-import { expect, test } from 'bun:test';-import { CRASH_BOUNDARIES, runReconcileCrashCase } from './fixtures/reconcile-crash-worker.ts';--for (const enabled of [false, true]) for (const boundary of CRASH_BOUNDARIES) {- test(`disk PGLite reconciliation survives SIGKILL/${boundary}, activation=${enabled}`, async () => {- const result = await runReconcileCrashCase({ kind: 'pglite', boundary, enabled });- expect(result).toMatchObject({ status: 'passed', boundary, enabled, killed_signal: 'SIGKILL',- committed_requests: 1, added_versions: 1, normal_apply_replay: true, originals_retained: true,- receipt_unchanged: true, recovery_cleared: true, staging_cleaned: true, topology_unchanged: true, counters_conserved: true });- if (boundary === 'staging_flushed') expect(result.flushed_before_rename_verified).toBe(true);- if (boundary === 'after_response') expect(result.response_read_before_kill).toBe(true);- }, 180_000);-}diff --git a/test/scripts/test-shard.slow.test.ts b/test/scripts/test-shard.slow.test.tsindex 2434a0349b..67c7fb0cfe 100644--- a/test/scripts/test-shard.slow.test.ts+++ b/test/scripts/test-shard.slow.test.ts@@ -91,7 +91,9 @@ describe('test-shard.sh — exclusion contract', () => {it('runs export-scale and reconcile-crash exactly once per event outside the unit matrix', () => {const allFiles = [1, 2, 3, 4].flatMap(s => dryRunList(s, 4));expect(allFiles).not.toContain('test/export-scale.slow.test.ts');- expect(allFiles).not.toContain('test/reconcile-crash.slow.test.ts');+ const reconcileCrash = require('fs').readdirSync(resolve(REPO_ROOT, 'test')).filter((f: string) => /^reconcile-crash-.*\.slow\.test\.ts$/.test(f));+ expect(reconcileCrash.length).toBe(4);+ for (const file of reconcileCrash) expect(allFiles).not.toContain(`test/${file}`);const fs = require('fs');const yaml = require('js-yaml');const workflow = yaml.load(fs.readFileSync(resolve(REPO_ROOT, '.github/workflows/test.yml'), 'utf8'));@@ -101,7 +103,7 @@ describe('test-shard.sh — exclusion contract', () => {const persistence = yaml.load(fs.readFileSync(resolve(REPO_ROOT, '.github/workflows/persistence-validation.yml'), 'utf8'));expect(persistence.jobs.reconciliation.strategy.matrix.engine).toContain('pglite');expect(persistence.jobs.reconciliation.steps.some((step: { run?: string }) =>- step.run?.includes('test/reconcile-crash.slow.test.ts'))).toBe(true);+ step.run?.includes('test/reconcile-crash-*.slow.test.ts'))).toBe(true);});it('INCLUDES *.slow.test.ts files (CI matrix is where slow files run)', () => {diff --git a/test/write-attribution-timeline-10k.slow.test.ts b/test/write-attribution-timeline-10k.slow.test.tsindex a54d07dd43..4d351fee89 100644--- a/test/write-attribution-timeline-10k.slow.test.ts+++ b/test/write-attribution-timeline-10k.slow.test.ts@@ -9,7 +9,7 @@** Fails if the extraction stops chunking or writes outside* maintenanceTransaction. Runs on PGLite (`bun run test:slow`), and on- * Postgres through test/e2e/write-attribution-postgres.test.ts.+ * Postgres through test/e2e/write-attribution-timeline-10k-postgres.test.ts.*/import { afterAll, beforeAll, describe, expect, test } from 'bun:test';import { PGLiteEngine } from '../src/core/pglite-engine.ts';