Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

v0.47.7.0 perf(tests): the test-infra speed wave — 3× local suite, shed-order fix, brainbench tiering, e2e snapshot activation (#4717)

Garry Tanaa820c7f9934
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index 6e836b4f62..ca12036d8f 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain",
- "version": "0.47.6.0",
+ "version": "0.47.7.0",
"description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.",
"author": {
"name": "Garry Tan",
diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json
index cabcf5125b..aaf62a057d 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain",
- "version": "0.47.6.0",
+ "version": "0.47.7.0",
"description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.",
"author": {
"name": "Garry Tan",
diff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.yml
index 492c77a102..42651b91c4 100644
--- a/.github/workflows/e2e.yml
+++ b/.github/workflows/e2e.yml
@@ -94,7 +94,31 @@ jobs:
path: ~/.bun/install/cache
key: bun-cache-${{ runner.os }}-${{ hashFiles('bun.lock') }}
restore-keys: bun-cache-${{ runner.os }}-
+ # PGLite snapshot (restore-only; test.yml's serial-tests job saves).
+ # run-e2e.sh builds it when absent/stale — this just avoids paying the
+ # build once per job. KEY: byte-identical with the homes in test.yml.
+ - uses: actions/cache/restore@5a3ec84eff668545956fd18022155c47e93e2684 # v4.2.3
+ with:
+ path: |
+ test/fixtures/pglite-snapshot.tar
+ test/fixtures/pglite-snapshot.version
+ key: pglite-snapshot-${{ runner.os }}-${{ hashFiles('src/core/migrate.ts', 'src/core/pglite-schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts') }}
- run: bun install --frozen-lockfile
+ # This job runs bare `bun test` (not run-e2e.sh), so the snapshot must
+ # be activated here or the restored tar is never read (the engine gates
+ # on the env var). Absolutized for varying-cwd CLI children.
+ - name: Ensure PGLite snapshot (build-or-validate, non-fatal)
+ run: |
+ . scripts/lib/test-env.sh
+ ensure_pglite_snapshot jsonb-parity
+ # Export absolute (CLI children spawn with varying cwd); keep an
+ # already-absolute inherited path as-is; export nothing on build failure.
+ if [ -n "${GBRAIN_PGLITE_SNAPSHOT:-}" ]; then
+ case "$GBRAIN_PGLITE_SNAPSHOT" in
+ /*) echo "GBRAIN_PGLITE_SNAPSHOT=$GBRAIN_PGLITE_SNAPSHOT" >> "$GITHUB_ENV" ;;
+ *) echo "GBRAIN_PGLITE_SNAPSHOT=$PWD/$GBRAIN_PGLITE_SNAPSHOT" >> "$GITHUB_ENV" ;;
+ esac
+ fi
- name: Require DATABASE_URL (no silent skip)
env:
DATABASE_URL: postgresql://postgres:postgres@localhost:5432/gbrain_test
@@ -166,6 +190,15 @@ jobs:
path: ~/.bun/install/cache
key: bun-cache-${{ runner.os }}-${{ hashFiles('bun.lock') }}
restore-keys: bun-cache-${{ runner.os }}-
+ # PGLite snapshot (restore-only; test.yml's serial-tests job saves).
+ # run-e2e.sh builds it when absent/stale — this just avoids paying the
+ # build once per job. KEY: byte-identical with the homes in test.yml.
+ - uses: actions/cache/restore@5a3ec84eff668545956fd18022155c47e93e2684 # v4.2.3
+ with:
+ path: |
+ test/fixtures/pglite-snapshot.tar
+ test/fixtures/pglite-snapshot.version
+ key: pglite-snapshot-${{ runner.os }}-${{ hashFiles('src/core/migrate.ts', 'src/core/pglite-schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts') }}
- run: bun install --frozen-lockfile
- name: Select and run diff-relevant E2E files
env:
@@ -231,7 +264,29 @@ jobs:
path: ~/.bun/install/cache
key: bun-cache-${{ runner.os }}-${{ hashFiles('bun.lock') }}
restore-keys: bun-cache-${{ runner.os }}-
+ # PGLite snapshot (restore-only; test.yml's serial-tests job saves).
+ # run-e2e.sh builds it when absent/stale — this just avoids paying the
+ # build once per job. KEY: byte-identical with the homes in test.yml.
+ - uses: actions/cache/restore@5a3ec84eff668545956fd18022155c47e93e2684 # v4.2.3
+ with:
+ path: |
+ test/fixtures/pglite-snapshot.tar
+ test/fixtures/pglite-snapshot.version
+ key: pglite-snapshot-${{ runner.os }}-${{ hashFiles('src/core/migrate.ts', 'src/core/pglite-schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts') }}
- run: bun install --frozen-lockfile
+ # Bare `bun test` job — activate the restored snapshot (see jsonb-parity).
+ - name: Ensure PGLite snapshot (build-or-validate, non-fatal)
+ run: |
+ . scripts/lib/test-env.sh
+ ensure_pglite_snapshot tier1
+ # Export absolute (CLI children spawn with varying cwd); keep an
+ # already-absolute inherited path as-is; export nothing on build failure.
+ if [ -n "${GBRAIN_PGLITE_SNAPSHOT:-}" ]; then
+ case "$GBRAIN_PGLITE_SNAPSHOT" in
+ /*) echo "GBRAIN_PGLITE_SNAPSHOT=$GBRAIN_PGLITE_SNAPSHOT" >> "$GITHUB_ENV" ;;
+ *) echo "GBRAIN_PGLITE_SNAPSHOT=$PWD/$GBRAIN_PGLITE_SNAPSHOT" >> "$GITHUB_ENV" ;;
+ esac
+ fi
- name: Run Tier 1 E2E tests
# job-isolation rides tier1 deliberately: e2e.yml runs only explicitly
# NAMED files (no glob) — an unwired e2e file is silent coverage loss.
@@ -331,7 +386,29 @@ jobs:
path: ~/.bun/install/cache
key: bun-cache-${{ runner.os }}-${{ hashFiles('bun.lock') }}
restore-keys: bun-cache-${{ runner.os }}-
+ # PGLite snapshot (restore-only; test.yml's serial-tests job saves).
+ # run-e2e.sh builds it when absent/stale — this just avoids paying the
+ # build once per job. KEY: byte-identical with the homes in test.yml.
+ - uses: actions/cache/restore@5a3ec84eff668545956fd18022155c47e93e2684 # v4.2.3
+ with:
+ path: |
+ test/fixtures/pglite-snapshot.tar
+ test/fixtures/pglite-snapshot.version
+ key: pglite-snapshot-${{ runner.os }}-${{ hashFiles('src/core/migrate.ts', 'src/core/pglite-schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts') }}
- run: bun install --frozen-lockfile
+ # Bare `bun test` job — activate the restored snapshot (see jsonb-parity).
+ - name: Ensure PGLite snapshot (build-or-validate, non-fatal)
+ run: |
+ . scripts/lib/test-env.sh
+ ensure_pglite_snapshot tier2
+ # Export absolute (CLI children spawn with varying cwd); keep an
+ # already-absolute inherited path as-is; export nothing on build failure.
+ if [ -n "${GBRAIN_PGLITE_SNAPSHOT:-}" ]; then
+ case "$GBRAIN_PGLITE_SNAPSHOT" in
+ /*) echo "GBRAIN_PGLITE_SNAPSHOT=$GBRAIN_PGLITE_SNAPSHOT" >> "$GITHUB_ENV" ;;
+ *) echo "GBRAIN_PGLITE_SNAPSHOT=$PWD/$GBRAIN_PGLITE_SNAPSHOT" >> "$GITHUB_ENV" ;;
+ esac
+ fi
- name: Install OpenClaw
# Bound + retry the install: a transient npm/registry stall here used to
# hang unbounded and (since the v0.42.50.0 job timeout) burn the entire
@@ -490,6 +567,13 @@ jobs:
- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2
with:
bun-version: 1.3.13
+ # PGLite snapshot (restore-only; test.yml's serial-tests job saves).
+ - uses: actions/cache/restore@5a3ec84eff668545956fd18022155c47e93e2684 # v4.2.3
+ with:
+ path: |
+ test/fixtures/pglite-snapshot.tar
+ test/fixtures/pglite-snapshot.version
+ key: pglite-snapshot-${{ runner.os }}-${{ hashFiles('src/core/migrate.ts', 'src/core/pglite-schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts') }}
- run: bun install
- name: Full e2e glob with coverage (all files, incl. engine-parity)
# run-e2e.sh redirects HOME, so COVERAGE_DIR must be absolute; its
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
index 2d5a3682cc..9d17a96d4c 100644
--- a/.github/workflows/test.yml
+++ b/.github/workflows/test.yml
@@ -194,9 +194,10 @@ jobs:
# not once per job per run. This job SAVES; verify + matrix + slow jobs
# restore-only. The key is an approximation on purpose: it only has to
# be a superset-trigger of real schema changes.
- # KEY HAS 5 HOMES in this file (this save + 4 restores: verify, matrix,
- # slow-eval, slow-perf) — edit all together, or drift shows up only as
- # silent rebuild cost.
+ # KEY HAS 11 HOMES (this save + 5 restores here: verify, matrix,
+ # slow-eval, slow-perf, slow-brainbench; + 5 restores in e2e.yml:
+ # jsonb-parity, selected-e2e, tier1, tier2, coverage-full-e2e) — edit
+ # all together, or drift shows up only as silent rebuild cost.
- uses: actions/cache@5a3ec84eff668545956fd18022155c47e93e2684 # v4.2.3
with:
path: |
@@ -265,6 +266,64 @@ jobs:
if-no-files-found: ignore
overwrite: true
+ slow-brainbench-e2e:
+ # Dedicated runner for the BrainBench CLI e2e file. At 98s mined it was
+ # the matrix's single heaviest atom (10% of the whole corpus weight) and
+ # the hard floor on shard-count scaling; a Phase-2 rewrite (spawn batching
+ # + deleting the CI-gate-duplicated full-corpus test) cut it to ~72s
+ # local, still far past the ~40s keep-in-matrix bar. Same pattern as
+ # slow-eval-longmemeval above.
+ needs: cache-check
+ if: needs.cache-check.outputs.hit != 'true'
+ runs-on: ubuntu-latest
+ timeout-minutes: 12
+ steps:
+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
+ - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2
+ with:
+ bun-version: 1.3.13
+ - uses: actions/cache/restore@5a3ec84eff668545956fd18022155c47e93e2684 # v4.2.3
+ with:
+ path: ~/.bun/install/cache
+ key: bun-cache-${{ runner.os }}-${{ hashFiles('bun.lock') }}
+ restore-keys: bun-cache-${{ runner.os }}-
+ - uses: actions/cache/restore@5a3ec84eff668545956fd18022155c47e93e2684 # v4.2.3
+ with:
+ path: |
+ test/fixtures/pglite-snapshot.tar
+ test/fixtures/pglite-snapshot.version
+ key: pglite-snapshot-${{ runner.os }}-${{ hashFiles('src/core/migrate.ts', 'src/core/pglite-schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts') }}
+ - run: bun install --frozen-lockfile
+ - name: Ensure PGLite snapshot (build-or-validate, non-fatal)
+ # Absolutized: this file's batch jobs spawn CLI children with varying
+ # cwd (the outside-cwd case) where a relative path would silently miss.
+ run: |
+ . scripts/lib/test-env.sh
+ ensure_pglite_snapshot slow-brainbench
+ # Export absolute (CLI children spawn with varying cwd); keep an
+ # already-absolute inherited path as-is; export nothing on build failure.
+ if [ -n "${GBRAIN_PGLITE_SNAPSHOT:-}" ]; then
+ case "$GBRAIN_PGLITE_SNAPSHOT" in
+ /*) echo "GBRAIN_PGLITE_SNAPSHOT=$GBRAIN_PGLITE_SNAPSHOT" >> "$GITHUB_ENV" ;;
+ *) echo "GBRAIN_PGLITE_SNAPSHOT=$PWD/$GBRAIN_PGLITE_SNAPSHOT" >> "$GITHUB_ENV" ;;
+ esac
+ fi
+ - run: bun test test/eval-brainbench-e2e.slow.test.ts --timeout=300000 --coverage --coverage-reporter=lcov --coverage-dir=${{ runner.temp }}/coverage/slowbrainbench
+ - name: Write coverage lane manifest
+ run: |
+ printf '{"lane":"slowbrainbench","sha":"%s","lcovCount":%s,"complete":true}\n' \
+ "$GITHUB_SHA" "$(find "$RUNNER_TEMP/coverage" -name lcov.info | wc -l | tr -d ' ')" \
+ > "$RUNNER_TEMP/coverage/lane-manifest.json"
+ - name: Upload coverage (slow-brainbench lane)
+ if: always()
+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
+ with:
+ name: coverage-slowbrainbench
+ path: ${{ runner.temp }}/coverage
+ retention-days: 14
+ if-no-files-found: ignore
+ overwrite: true
+
brainbench:
# BrainBench memory-conformance gate (Cathedral 2). Hermetic: in-memory
# PGLite, zero API keys, ~15s for the full 141-fixture × 3-harness run.
@@ -440,7 +499,7 @@ jobs:
# exactly the moment the (degraded) report matters most.
# ──────────────────────────────────────────────────────────────────────
coverage-report:
- needs: [cache-check, serial-tests, slow-eval-longmemeval, slow-entity-resolve-perf, test]
+ needs: [cache-check, serial-tests, slow-eval-longmemeval, slow-entity-resolve-perf, slow-brainbench-e2e, test]
if: always() && needs.cache-check.outputs.hit != 'true'
runs-on: ubuntu-latest
timeout-minutes: 10
@@ -468,7 +527,7 @@ jobs:
bun scripts/merge-lcov.ts \
--out-lcov "$RUNNER_TEMP/coverage-merged/lcov.info" \
--out-json "$RUNNER_TEMP/coverage-merged/summary.json" \
- --manifest-expect shard-1,shard-2,shard-3,shard-4,shard-5,shard-6,shard-7,shard-8,shard-9,shard-10,serial,sloweval,slowperf \
+ --manifest-expect shard-1,shard-2,shard-3,shard-4,shard-5,shard-6,shard-7,shard-8,shard-9,shard-10,serial,sloweval,slowperf,slowbrainbench \
"$RUNNER_TEMP/coverage-artifacts"
- name: Coverage summary → step summary
run: bun scripts/render-coverage-summary.ts --summary "$RUNNER_TEMP/coverage-merged/summary.json" --structural scripts/structural-suites.tsv >> "$GITHUB_STEP_SUMMARY"
@@ -504,7 +563,7 @@ jobs:
# entry written when tests hadn't actually passed).
# ──────────────────────────────────────────────────────────────────────
cache-write:
- needs: [cache-check, gitleaks, verify, serial-tests, slow-eval-longmemeval, slow-entity-resolve-perf, brainbench, test]
+ needs: [cache-check, gitleaks, verify, serial-tests, slow-eval-longmemeval, slow-entity-resolve-perf, slow-brainbench-e2e, brainbench, test]
if: success() && needs.cache-check.outputs.hit != 'true'
runs-on: ubuntu-latest
timeout-minutes: 5
@@ -527,7 +586,7 @@ jobs:
# Branch protection (when configured) gates on this single job name.
# ──────────────────────────────────────────────────────────────────────
test-status:
- needs: [cache-check, gitleaks, verify, serial-tests, slow-eval-longmemeval, slow-entity-resolve-perf, brainbench, test]
+ needs: [cache-check, gitleaks, verify, serial-tests, slow-eval-longmemeval, slow-entity-resolve-perf, slow-brainbench-e2e, brainbench, test]
if: always()
runs-on: ubuntu-latest
timeout-minutes: 5
@@ -540,16 +599,17 @@ jobs:
SERIAL="${{ needs.serial-tests.result }}"
SLOW_EVAL="${{ needs.slow-eval-longmemeval.result }}"
SLOW_PERF="${{ needs.slow-entity-resolve-perf.result }}"
+ SLOW_BRAINBENCH="${{ needs.slow-brainbench-e2e.result }}"
BRAINBENCH="${{ needs.brainbench.result }}"
TEST="${{ needs.test.result }}"
echo "cache-check.hit=$HIT"
- echo "gitleaks=$GITLEAKS verify=$VERIFY serial-tests=$SERIAL slow-eval-longmemeval=$SLOW_EVAL slow-entity-resolve-perf=$SLOW_PERF brainbench=$BRAINBENCH test=$TEST"
+ echo "gitleaks=$GITLEAKS verify=$VERIFY serial-tests=$SERIAL slow-eval-longmemeval=$SLOW_EVAL slow-entity-resolve-perf=$SLOW_PERF slow-brainbench-e2e=$SLOW_BRAINBENCH brainbench=$BRAINBENCH test=$TEST"
if [ "$HIT" = "true" ]; then
echo "✓ cache HIT for hash ${{ needs.cache-check.outputs.hash }} — CI green"
exit 0
fi
# Cache miss: every gated job must have succeeded.
- for r in "$GITLEAKS" "$VERIFY" "$SERIAL" "$SLOW_EVAL" "$SLOW_PERF" "$BRAINBENCH" "$TEST"; do
+ for r in "$GITLEAKS" "$VERIFY" "$SERIAL" "$SLOW_EVAL" "$SLOW_PERF" "$SLOW_BRAINBENCH" "$BRAINBENCH" "$TEST"; do
if [ "$r" != "success" ]; then
echo "✗ gated job did not succeed (got $r) — CI fail"
exit 1
diff --git a/BOOTSTRAP_FOR_AGENTS.md b/BOOTSTRAP_FOR_AGENTS.md
index e763fb59d2..ac4cb876cb 100644
--- a/BOOTSTRAP_FOR_AGENTS.md
+++ b/BOOTSTRAP_FOR_AGENTS.md
@@ -1,4 +1,4 @@
-<!-- gbrain-runbook-stamp: 0.47.6.0 -->
+<!-- gbrain-runbook-stamp: 0.47.7.0 -->
<!-- This stamp must equal the VERSION file at every release; CI enforces it
(scripts/check-bootstrap-tag.sh). `gbrain bootstrap status` compares it to
the installed binary and warns on skew. -->
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 93eaa8e313..d52c40308f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,79 @@
All notable changes to GBrain will be documented in this file.
+## [0.47.7.0] - 2026-08-30
+
+**The test-infra speed wave: the local suite runs up to 3× faster on
+memory-constrained machines and comes back green on machines it used to fail
+on, the CI matrix sheds its heaviest atom,
+and the e2e lane finally gets the schema-snapshot fast path every other lane
+already had.**
+
+### Fixed
+
+- **`bun run test` no longer collapses to a single shard on 16GB machines.**
+ The memory-adaptive runner shed shards before intra-shard width, but bun's
+ `--max-concurrency` only bounds `test.concurrent` tests (one file in the
+ corpus uses it) — so a common dev box ran the whole suite serially behind a
+ 12000s watchdog, measured 3.25× slower than the same box at 4 shards. Width
+ sheds first now, and a new pinned test keeps it that way.
+- **Machines without coreutils `timeout` no longer hard-fail on watchdog
+ kills.** The fallback watchdog now drops a sentinel before TERMing a shard,
+ so the WEDGED/EXIT-HANG classifier is reachable there instead of a bare
+ rc=143 failure (regression-pinned).
+- **A long-registered shard flake is fixed at the root.** The extract-atoms
+ chunk-embed suite failed under shard parallelism because a neighbor's
+ provider key baked into the AI gateway's captured env snapshot survived the
+ neighbor's own cleanup; the suite now pins a keyless gateway and asserts its
+ own hermeticity. Two other registered flakes were verified already fixed and
+ their entries closed.
+- **Tests that assert "this must fail" now skip visibly on hosts that can't
+ make it fail.** Sandboxes with non-enforcing filesystems (permission bits
+ ignored), no crontab, or a git PATH shim that pollutes stderr previously
+ produced eight hard-red failures; environment probes turn those into
+ explicit skips while CI keeps full coverage.
+
+### Changed
+
+- **The unit suite's slowest files were rewritten into minimal forms with
+ assertion parity.** Thirteen files keep every test and every assertion while
+ running 1.2-8.6× faster (batched CLI spawns through a bounded pool, condition
+ polling instead of fixed sleeps, one engine + reset instead of per-test
+ boots, a build-once git fixture). Four attempted rewrites were reverted
+ with documented cause rather than shipped at risk.
+- **The BrainBench CLI e2e file moved to the slow tier with its own CI job.**
+ At 98s mined it was 10% of the whole matrix's weight and capped shard
+ scaling; post-rewrite it runs its independent CLI calls once through a
+ width-2 pool, and its in-process full-corpus duplicate of the CI brainbench
+ gate was removed.
+- **The serial lane dispatches heaviest-first.** A new advisory
+ `scripts/serial-weights.json` (mined from each run's banked durations)
+ drives LPT ordering; corrupt or missing weights fall back to discovery
+ order, never affecting correctness.
+- **`bun run test:e2e` activates the PGLite schema snapshot** like every other
+ runner (exported absolute so spawned CLI children find it), with explicit
+ per-file cold-path opt-outs for the suites that assert the path TO
+ post-init state. The e2e CI jobs restore the snapshot cache and activate it
+ too.
+- **`bun run verify` dropped its one genuinely duplicated check** (the
+ retrieval canary rides the unit matrix via its test file; the package
+ script remains for on-demand runs) and its worst timeout-flake exposure
+ with it.
+- **New shared test helpers** for contributors: `cli-spawn` (hermetic
+ async CLI spawns + bounded batching + memoized help calls), `wait-for`
+ (condition polling), `with-snapshot` (scoped cold-boot opt-out),
+ `resetPgliteStateNarrow` (explicit-table resets), `git-fixture`
+ (build-once repos), and environment probes (`fs-perms`,
+ `git-stderr-probe`). The speed helpers each ship with their own unit test
+ (the two environment probes are exercised through their consumer suites);
+ docs/TESTING.md carries the reach-for guide.
+
+To take advantage of v0.47.7.0: `gbrain upgrade`, then in the repo the fast
+loop is the same `bun run test` — just faster and honest about environment
+skips. Contributors writing tests: read the "Speed + environment helpers"
+section of docs/TESTING.md before hand-rolling spawn wrappers, sleeps, or
+permission-dependent assertions.
+
## [0.47.6.0] - 2026-08-29
**The community fix wave: takes work on Postgres again, sync deletions get a
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 11cd768f5a..0c9696f7c4 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -103,7 +103,7 @@ lifecycle is [`docs/TESTING.md`](docs/TESTING.md). The short version:
bun run test # parallel 4-shard fan-out (memory-adaptive) + serial post-pass; PGLite snapshot default-on
bun test test/markdown.test.ts # specific unit test
-# Pre-push gate (40+ parallel checks + typecheck)
+# Pre-push gate (50+ parallel checks + typecheck)
bun run verify
# Pre-merge sanity (everything CI runs)
@@ -111,7 +111,7 @@ bun run test:full # verify + parallel unit + slow + smart e2e
# Slow / serial / e2e in isolation
bun run test:slow # *.slow.test.ts only (cold-path correctness)
-bun run test:serial # *.serial.test.ts only (--max-concurrency=1)
+bun run test:serial # *.serial.test.ts only (pooled per-file processes, heaviest-first)
bun run test:e2e # real-Postgres E2E (requires DATABASE_URL)
# E2E setup (Postgres with pgvector)
@@ -134,7 +134,7 @@ the database name must carry "test" as a word segment (like `gbrain_test`
above) or destructive tests refuse to run — opt a differently-named database
in one-shot with `GBRAIN_E2E_ALLOW_DB=<name>`.
-Use `bun run verify` before pushing. It runs 40+ guard checks in parallel
+Use `bun run verify` before pushing. It runs 50+ guard checks in parallel
(`scripts/run-verify-parallel.sh`), including: banned fork-name leaks
(`scripts/check-privacy.sh`), `JSON.stringify(x)::jsonb` interpolation
patterns (`scripts/check-jsonb-pattern.sh`), `\r` progress bleed to stdout
diff --git a/TODOS.md b/TODOS.md
index 295ceb7102..34027e2029 100644
--- a/TODOS.md
+++ b/TODOS.md
@@ -1730,15 +1730,68 @@ review-deferred, not fix-now). Grouped by component.
### Test infra (master-owned)
-- [ ] **P1 — test/extract-atoms-chunk-embed.test.ts flakes under parallel
- shards.** **What:** deflake the extract-atoms chunk-embed suite when run in
- parallel shards. **Why:** it fails under shard parallelism but passes alone
- — a shard-ordering trap for every future branch. **Context:** failure
- signature: extraction returns status 'warn' with ALL transcripts skipped
- (0 processed) → count assertions fail; env-coupling suspected — the same
- withEnv class fixed in token-budget.test.ts this wave. Pre-existing on
- master; owned there, not by any feature branch. **Effort:** small.
- **Priority:** P1.
+- [ ] **P1 — Test-infra pass Ships 2+3: serial burn-down, e2e lane moves + CI
+ sharding, weights re-mine.** **What:** the approved test-infra plan
+ (`~/.claude/plans/system-instruction-you-are-working-sprightly-bee.md`, Ship 1
+ landed as the v0.47.7.0 wave) deliberately split into 3 ships for regression
+ attribution. Remaining: Phase 4 serial-lane burn-down (38 rename-safe
+ no-marker files + ~75 env-only `withEnv()` conversions — candidate lists with
+ per-file justifications were computed and banked in the Ship-1 session;
+ recompute mechanically: no `mock.module`, no R1 env mutation, no
+ launchTty/process.exitCode/port/timing rationale in the header), Phase 5
+ moving the ~52 PGLite-only `test/e2e/` files into the unit matrix (behavioral
+ move criterion: direct PGLite ctor + no e2e/helpers import + no
+ hasDatabase/DATABASE_URL gate + header read; lockstep: e2e-test-map rows,
+ e2e-unmapped-baseline shrink, classify-tests, seeded weights) + 4-way
+ `SHARD=N/M` matrix for `selected-e2e`/`coverage-full-e2e` with one postgres
+ service per matrix job, and Phase 6 `mine-shard-weights` re-mine (381 files
+ unweighted; add a `weights:mine` package script + documented cadence) then
+ matrix 10→12. Graduated batch gates: 5×-green first batch per class, 2×+CI
+ after. **Why:** the remaining ~half of the measured win: serial lane 220→~130
+ files, e2e 60-min worst-case lane → ~15-25 min, honest weights. **Effort:** L
+ (spread over 2 ships).
+- [ ] **P2 — Phase-2 tail: seven minimal-test targets the v0.47.7.0 wave
+ didn't reach.** **What:** same rewrite classes, unattempted: (1)
+ `test/destructive-guard.test.ts:39` + (2)
+ `test/schema-bootstrap-coverage.test.ts:48` file-level snapshot opt-outs →
+ scoped `withColdPglite` (audit which tests genuinely need cold boots — the
+ bootstrap.test.ts attempt showed version-rewind arcs DO need them; a
+ snapshot-restored engine does not replay migrations after a rewind); (3)
+ `test/migrate.test.ts` 14-engine + (4) `test/sync.test.ts` 4-engine
+ consolidation to shared beforeAll engines + resets (sync also has 39 git
+ execSync sites → `test/helpers/git-fixture.ts`, and a 1100ms sleep →
+ `waitFor`); (5) `test/doctor-pglite-scratch-probe.test.ts` route 3 of 4 real
+ scratch boots through its own `probeFn` seam (:238-298 proves it); (6)
+ `test/apply-migrations-list-db-state` and (7) `test/process-watchdog`
+ .test/.serial pair merges where assertions overlap. **Why:** ~15-25s more off
+ the unit lane using helpers that now exist (`with-snapshot`, `git-fixture`,
+ `wait-for`); several also burn down `scripts/check-test-isolation.allowlist`
+ rows. **Effort:** S-M.
+- [ ] **P3 — serial-pool-overlaps-parallel-shards.** **What:** run the serial
+ pool concurrently with the parallel shards in `run-unit-parallel.sh` instead
+ of after the barrier. **Why deferred:** the OOM-rescue verdict pipeline
+ assumes shard aggregation ran first (`EXTERNAL_KILL_ANY` gates serial rescue
+ eligibility), and both runners independently claim the full memory budget —
+ a restructure, not a tweak; post-burn-down the serial tail is small anyway.
+- [ ] **P3 — e2e tier2/jsonb-parity decoupling.** **What:** `tier2` waits on
+ `jsonb-parity` (the token-spend gate) — up to 15 min of serialization; inline
+ a fast pre-flight instead. Preserve the hard-fail-on-missing-DATABASE_URL
+ property. **Effort:** S.
+
+- [x] **P1 — test/extract-atoms-chunk-embed.test.ts flakes under parallel
+ shards.** DONE (test-infra perf wave): root cause was NOT live-env coupling
+ but the gateway singleton's captured env SNAPSHOT — the preload configures
+ with `env: {...process.env}`, so a shard-neighbor's provider key (e.g.
+ `test/claw-test-cli.test.ts`'s `oai-must-not-leak`) baked into the gateway
+ survives the neighbor's own env restore, flips `isAvailable('embedding')`
+ true, the atom import fires a real embed inside withBudgetTracker,
+ `reserve()` throws BudgetExhausted(no_pricing), and every work item skips →
+ status 'warn' / 0 processed (the signature verbatim). Fix: keyless
+ `configureGateway({env:{}})` pin in the PGLite describe's beforeAll +
+ `resetGateway()` in afterAll + a self-asserting
+ `expect(isAvailable('embedding')).toBe(false)` hermeticity pin — same
+ pattern as test/ambient-recall.test.ts (which also gained the missing
+ `resetGateway()` cleanup in the same change).
### Hygiene dedupe batch (single entry — take together)
@@ -4164,7 +4217,14 @@ fixtures + scaling-skills tutorial. Two findings deferred:
tests prove parser output, integration tests prove reachability, and the
current docs don't bridge the two cleanly. Doc-only follow-up.
-- [ ] **P1 flake — audit-writer.test.ts week-boundary failure.** Caught
+- [x] **P1 flake — audit-writer.test.ts week-boundary failure.** DONE — both
+ halves of the prescribed move already landed: src half in `ca68633f`
+ (`fileDate` derived from the event's own `ts`, not wall-clock, at
+ `src/core/audit/audit-writer.ts` computeFilename call site) and test half
+ in `0b7efd35` (the hardcoded `2026-05-22` replaced with real `now` + direct
+ week-file writes). The remaining Monday-straddle case works BECAUSE of the
+ src fix (a Sunday `ts` routes to the previous week's file, which
+ readRecent's two-file walk covers). Original filing: Caught
during ship of v0.41.7.0. Test at `test/audit/audit-writer.test.ts:229`
("returns events from current week, filtered by ts cutoff") fails when
real UTC date is in a different ISO week than the test's hardcoded
@@ -4579,7 +4639,8 @@ outside-voice triage on the reshaped plan.
speedup pass: an in-repo canonical qrels target now exists (`gbrain eval gate`
with the deterministic embedder option against `test/fixtures/eval-baselines/
qrels-search.json`; runner `scripts/run-eval-canary.ts`, CI-gated via
- check:eval-canary, ledger `.gbrain-evals/eval-results.jsonl`). What remains
+ `test/eval-canary.test.ts` in the unit matrix with `check:eval-canary` as
+ the on-demand package script, ledger `.gbrain-evals/eval-results.jsonl`). What remains
here is only the sibling-repo REGRESSION baseline (.baseline.ndjson for the
jaccard/top1 gate) — the correctness-gate half is done.
@@ -4788,7 +4849,7 @@ contributor traps.
## v0.41+ master flake follow-ups (filed during v0.40.8.0 ship)
-- [ ] **(P3) — Audit other gateway-mutating tests for missing afterAll cleanup.** v0.40.8.0 added `afterAll(() => resetGateway())` to `test/ai/gateway.test.ts` and quarantined `test/ai/header-transport.test.ts` as `.serial.test.ts`. Two other files mutate gateway state without an explicit cleanup hook: `test/ai/rerank.test.ts`, `test/gateway-embed-model-override.test.ts`. They haven't surfaced flakes yet (different test sequences), but they're the same risk class. Add `afterAll(() => resetGateway())` to both for defense-in-depth, or quarantine if they prove racy under future parallelism changes.
+- [x] **(P3) — Audit other gateway-mutating tests for missing afterAll cleanup.** DONE (stale as originally written + swept): the two named files already carry cleanup (`test/ai/rerank.test.ts` afterEach→resetGateway; `test/gateway-embed-model-override.test.ts` beforeEach/afterEach→resetGateway). The one live instance found by a fresh sweep — `test/ambient-recall.test.ts` configuring a keyless gateway with no reset anywhere — gained `afterAll(() => resetGateway())` in the test-infra perf wave.
## v0.40.4 adversarial review LOW findings — captured for v0.41+
- [ ] **Codex L1**: `gbrain search stats --days N` underreports for N > 7. audit-writer.ts reads only current + previous ISO week (~14 days). `--days 30` silently shows ~2 weeks of failure events. Fix shape: extend readRecent to walk N/7 weeks dynamically OR cap user input with a clear message.
@@ -4805,7 +4866,7 @@ contributor traps.
## Pre-existing flake on master (noticed during v0.40.4 ship)
-- [ ] **`test/search/embedding-column.test.ts:466,489,522` — `isCacheSafe` returns false when run after gateway-state-mutating siblings in shard 2.** Confirmed pre-existing on master (`git stash` + `SHARD=2/8 bash scripts/run-unit-shard.sh` reproduces 3 fails on a clean working tree). Symptom: `isCacheSafe(default-named-column, empty-cfg)` expects `gwDims=1536` but reads `1280` (the post-v0.37.11.0 ZeroEntropy default). Some test in the shard before embedding-column.test.ts initializes the gateway with the PGLite-default ZeroEntropy/1280 config and leaves it that way. Either: (a) embedding-column.test.ts grows a `beforeEach` that calls `__setEmbedTransportForTests`-style reset, (b) the offending sibling adds an `afterAll(reset)`, or (c) embedding-column.test.ts becomes `*.serial.test.ts` to quarantine. Three test files in shard 2 touch gateway state via PGLite engine connects: `restart-sweep.test.ts`, `init-mode-picker.test.ts`, `doctor.test.ts`. Tests pass in isolation (50/50); only fail under shard-2 ordering. v0.40.4 ships through this flake — not introduced by the wave.
+- [x] **`test/search/embedding-column.test.ts:466,489,522` — `isCacheSafe` returns false when run after gateway-state-mutating siblings in shard 2.** DONE: closed by option (c) — the file was renamed to `test/search/embedding-column.serial.test.ts` in `ca68633f` (v0.41.2.0), giving it its own bun process; entry left open pointed at a filename that no longer exists. If the file is ever un-quarantined, add `beforeEach(() => resetGateway())` (NOT `__unconfigureGatewayForTests` — that falls through to the ZE/1280 defaults; `resetGateway` re-applies the preload's OpenAI/1536 baseline). Original filing: Confirmed pre-existing on master (`git stash` + `SHARD=2/8 bash scripts/run-unit-shard.sh` reproduces 3 fails on a clean working tree). Symptom: `isCacheSafe(default-named-column, empty-cfg)` expects `gwDims=1536` but reads `1280` (the post-v0.37.11.0 ZeroEntropy default). Some test in the shard before embedding-column.test.ts initializes the gateway with the PGLite-default ZeroEntropy/1280 config and leaves it that way. Either: (a) embedding-column.test.ts grows a `beforeEach` that calls `__setEmbedTransportForTests`-style reset, (b) the offending sibling adds an `afterAll(reset)`, or (c) embedding-column.test.ts becomes `*.serial.test.ts` to quarantine. Three test files in shard 2 touch gateway state via PGLite engine connects: `restart-sweep.test.ts`, `init-mode-picker.test.ts`, `doctor.test.ts`. Tests pass in isolation (50/50); only fail under shard-2 ordering. v0.40.4 ships through this flake — not introduced by the wave.
## v0.40.4 graph signals — deferred follow-ups (v0.41+)
diff --git a/VERSION b/VERSION
index 46e7aacd7d..d892f19e59 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-0.47.6.0
+0.47.7.0
\ No newline at end of file
diff --git a/docker-compose.ci.yml b/docker-compose.ci.yml
index bdb96d3fcc..86b08dba31 100644
--- a/docker-compose.ci.yml
+++ b/docker-compose.ci.yml
@@ -13,7 +13,7 @@
# isolate the Linux container's deps from the host's darwin-arm64 deps and
# keep bun + postgres data warm across runs.
#
-# Why 4 postgres services: bun's E2E suite shares one DB across 36 files and
+# Why 4 postgres services: bun's E2E suite shares one DB across the e2e glob and
# uses TRUNCATE CASCADE in setupDB(). Running files in parallel against ONE DB
# races (file A's TRUNCATE clobbers file B's fixture import). 4 separate DBs
# remove the race; we shard the file list 1/4..4/4 and run shards in parallel.
diff --git a/docs/TESTING.md b/docs/TESTING.md
index e9b786f6b4..be888ee57e 100644
--- a/docs/TESTING.md
+++ b/docs/TESTING.md
@@ -11,12 +11,12 @@ Seven test command tiers, each with a clear scope:
| Command | What it runs | Wallclock | When to use |
|---|---|---|---|
-| `bun run test` | Parallel unit-test fast loop. Sharded fan-out via `scripts/run-unit-parallel.sh` (default 4 shards — CPU-detected, clamped to a max of 8; 4 matches CI's fan-out and avoids PGLite WASM-init contention), then a serial pass over `*.serial.test.ts`. Excludes `*.slow.test.ts` and `test/e2e/*`. No pre-checks, no typecheck. Builds/refreshes the PGLite schema snapshot BEFORE the shard fan-out and exports `GBRAIN_PGLITE_SNAPSHOT` so PGLite-booting files restore a baked schema instead of replaying every migration (~3.5x per booting file; see "PGLite schema snapshot" below). Opt out: `GBRAIN_NO_SNAPSHOT=1`. Memory-safe by default: total concurrency (shards × intra-shard files) is capped to available memory at `GBRAIN_TEST_MEM_PER_FILE_MB` (default 1536 — a PGLite WASM instance) per concurrent file, and two phantom-failure classes are automatically re-run serially (the rescue pass): failures carrying the WASM out-of-memory signature, and shards killed externally (SIGTERM/SIGKILL well before the shard timeout — sibling workspaces' process cleanup, memory jetsam). Phantoms pass serially and the run goes green with an `oom_rescued` note; real failures fail again serially and stay red. Knobs: `GBRAIN_TEST_NO_MEM_ADAPT=1`, `GBRAIN_TEST_NO_OOM_FALLBACK=1`, `GBRAIN_TEST_MAX_CONCURRENCY` (intra-shard, default 4), `GBRAIN_TEST_SHARD_TIMEOUT` / `GBRAIN_TEST_SHARD_KILL_AFTER`, plus `--shards N` / `--max-concurrency N` / `--dry-run` script args. | a few minutes on a Mac dev box | Inner edit loop. Default. |
-| `bun run verify` | CI's authoritative pre-test gate set, fanned out by `scripts/run-verify-parallel.sh` through a bounded worker pool (default `detect_cpus`; override `GBRAIN_VERIFY_MAX_PARALLEL`) with the heavy checks ordered first (typecheck, the two compile-embed checks, admin build, fuzz bundles, guard self-tests, the PGLite-booting eval checks, whole-tree greps). The battery includes the deterministic `check:eval-chronicle` and `check:eval-canary` eval gates. The `CHECKS` array in that script is the single source of truth — CI literally calls `bun run verify` in a dedicated job. | ~40s (pool-bounded; longest check dominates) | Before pushing; before `/ship`. |
+| `bun run test` | Parallel unit-test fast loop. Sharded fan-out via `scripts/run-unit-parallel.sh` (default 4 shards — CPU-detected, clamped to a max of 8; 4 matches CI's fan-out and avoids PGLite WASM-init contention), then a serial pass over `*.serial.test.ts`. Excludes `*.slow.test.ts` and `test/e2e/*`. No pre-checks, no typecheck. Builds/refreshes the PGLite schema snapshot BEFORE the shard fan-out and exports `GBRAIN_PGLITE_SNAPSHOT` so PGLite-booting files restore a baked schema instead of replaying every migration (~3.5x per booting file; see "PGLite schema snapshot" below). Opt out: `GBRAIN_NO_SNAPSHOT=1`. Memory-safe by default: total concurrency (shards × intra-shard width) is capped to available memory at `GBRAIN_TEST_MEM_PER_FILE_MB` (default 1536 — a PGLite WASM instance) per concurrent slot, shedding INTRA-SHARD width first and shards only after it (bun's `--max-concurrency` bounds only `test.concurrent` tests — 1 file in the corpus — so intra width is nearly free to shed, while every dropped shard removes a whole bun process of real fan-out; the old shards-first order collapsed a 16GB box to a serial 1×4 run, measured 3.25× slower than 4×1 on the same machine). Two phantom-failure classes are automatically re-run serially (the rescue pass): failures carrying the WASM out-of-memory signature, and shards killed externally (SIGTERM/SIGKILL well before the shard timeout — sibling workspaces' process cleanup, memory jetsam). On machines without coreutils `timeout`, the fallback watchdog drops a `.watchdog` sentinel before TERMing a shard at the cap so the WEDGED/EXIT-HANG classifier stays reachable there (a bare rc=143 used to read as a plain failure). Phantoms pass serially and the run goes green with an `oom_rescued` note; real failures fail again serially and stay red. Knobs: `GBRAIN_TEST_NO_MEM_ADAPT=1`, `GBRAIN_TEST_NO_OOM_FALLBACK=1`, `GBRAIN_TEST_MAX_CONCURRENCY` (intra-shard, default 4), `GBRAIN_TEST_SHARD_TIMEOUT` / `GBRAIN_TEST_SHARD_KILL_AFTER`, plus `--shards N` / `--max-concurrency N` / `--dry-run` script args. | a few minutes on a Mac dev box | Inner edit loop. Default. |
+| `bun run verify` | CI's authoritative pre-test gate set, fanned out by `scripts/run-verify-parallel.sh` through a bounded worker pool (default `detect_cpus`; override `GBRAIN_VERIFY_MAX_PARALLEL`) with the heavy checks ordered first (typecheck, the two compile-embed checks, admin build, fuzz bundles, guard self-tests, the PGLite-booting chronicle eval check, whole-tree greps). The battery includes the deterministic `check:eval-chronicle` eval gate; `check:eval-canary` is deliberately NOT in the battery (its test-file twin `test/eval-canary.test.ts` spawns the identical runner in the unit matrix, and CI's verify job and matrix always run together — the package script stays for on-demand runs, so `verify`-only local callers should know the canary rides the unit lane instead). The `CHECKS` array in that script is the single source of truth — CI literally calls `bun run verify` in a dedicated job. | ~50s (pool-bounded; longest check dominates) | Before pushing; before `/ship`. |
| `bun run test:full` | `verify && bun run test && bun run test:slow && [smart e2e]`. The local equivalent of "everything CI runs." Smart e2e: runs e2e only when `DATABASE_URL` is set; else loud skip notice to stderr. | ~3-5min depending on slow + e2e | Pre-merge sanity, before opening a PR. |
| `bun run test:slow` | Just the `*.slow.test.ts` set (intentional cold-path correctness checks). | seconds-to-minutes | When touching slow-path code. |
-| `bun run test:serial` | Just the `*.serial.test.ts` set (cross-file-contention quarantine; one bun process per file for true module-registry isolation), run through a POOL of concurrent per-file processes — the isolation is per-process, not per-machine. Pool defaults to `min(detect_cpus, 4)` then memory-adapts (same doctrine as the parallel runner); a small growth-guarded set of files (machine-global state or contention-critical timing — see the justified `EXCLUSIVE_FILES` list in `scripts/run-serial-tests.sh`, capped at 3 by `test/scripts/serial-files.test.ts`) runs on a sequential EXCLUSIVE lane after the pool. Per-test timeout 120s (pooled contention headroom); each pooled file is wall-clock-killed at 300s (`timeout -k`, exit-hang containment). Externally-killed files (exit 143/137 or a missing exit sentinel — sibling-workspace cleanup, memory jetsam) get ONE sequential rescue re-run, mirroring the parallel runner's doctrine: phantoms stay green with a rescue note, real failures stay red. Prints per-file PASS lines plus a top-10 slowest-files list. Knobs: `GBRAIN_SERIAL_POOL=N` (explicit pool width — bypasses the memory clamp; `1` restores fully-sequential), `GBRAIN_SERIAL_FILE_TIMEOUT`. | ~2.5min for all ~140 files at pool=4 (was ~8.5min sequential) | Debugging quarantined files; CI's serial-tests job. |
-| `bun run test:e2e` | Real Postgres E2E. Requires Docker + `DATABASE_URL`. Sequential. | ~5-10min | Pre-ship; nightly. |
+| `bun run test:serial` | Just the `*.serial.test.ts` set (cross-file-contention quarantine; one bun process per file for true module-registry isolation), run through a POOL of concurrent per-file processes — the isolation is per-process, not per-machine. Dispatch is heaviest-first (LPT) from the advisory `scripts/serial-weights.json` (seconds; mined from the `.context/serial-durations.txt` table each run banks; absent/corrupt weights fall back to discovery order, absent keys to the corpus p75 — scheduling only, never correctness; LPT order + the corrupt-weights fail-soft are pinned by `test/scripts/run-serial-pool.test.ts`). Pool defaults to `min(detect_cpus, 4)` then memory-adapts (same doctrine as the parallel runner); a small growth-guarded set of files (machine-global state or contention-critical timing — see the justified `EXCLUSIVE_FILES` list in `scripts/run-serial-tests.sh`, capped at 3 by `test/scripts/serial-files.test.ts`) runs on a sequential EXCLUSIVE lane after the pool. Per-test timeout 120s (pooled contention headroom); each pooled file is wall-clock-killed at 300s (`timeout -k`, exit-hang containment). Externally-killed files (exit 143/137 or a missing exit sentinel — sibling-workspace cleanup, memory jetsam) get ONE sequential rescue re-run, mirroring the parallel runner's doctrine: phantoms stay green with a rescue note, real failures stay red. Prints per-file PASS lines plus a top-10 slowest-files list. Knobs: `GBRAIN_SERIAL_POOL=N` (explicit pool width — bypasses the memory clamp; `1` restores fully-sequential), `GBRAIN_SERIAL_FILE_TIMEOUT`. | a few minutes for all ~220 files at pool=4 | Debugging quarantined files; CI's serial-tests job. |
+| `bun run test:e2e` | Real Postgres E2E. Requires Docker + `DATABASE_URL`. Sequential within a shard; `SHARD=N/M` fans out against separate databases (ci-local runs 4 containers). Activates the PGLite snapshot like every other runner (per-file cold-path opt-outs where the test asserts the path TO post-initSchema state), exporting it as an ABSOLUTE path so CLI children spawned with varying cwd still find it. | ~5-10min | Pre-ship; nightly. |
| `bun run test:compile-smoke` | Self-update integrity verify under a REAL `bun build --compile` binary, offline (sets `GBRAIN_SELFUPDATE_COMPILE_SMOKE=1`). The unit suite mocks the network seams; this proves the dependency-free crypto/base64/JSON verify path survives compilation — the failure mode `sigstore-js` would have hit. | ~5s (one compile) | When touching `src/core/binary-self-update.ts`; pre-ship on self-update changes. |
There is no `check:all` script anymore — it was a second, hand-synced guard
@@ -37,8 +37,9 @@ replaying the embedded schema + all migrations when the env var
`ensure_pglite_snapshot` helper in `scripts/lib/test-env.sh` (also home of
`detect_cpus` and `detect_available_mem_mb`), sourced by
`run-unit-parallel.sh`, `test-shard.sh`, `run-slow-tests.sh`,
-`run-serial-tests.sh`, and `run-verify-parallel.sh`; `scripts/ci-local.sh`
-calls the builder directly. The helper builds/refreshes the snapshot and
+`run-serial-tests.sh`, `run-verify-parallel.sh`, and `run-e2e.sh` (which
+re-exports the path as ABSOLUTE — its tests spawn CLI children with varying
+cwd); `scripts/ci-local.sh` calls the builder directly. The helper builds/refreshes the snapshot and
exports the env var, no-ops on `GBRAIN_NO_SNAPSHOT=1` or an already-inherited
path, and is non-fatal on build failure — tests fall back to cold init, with
a one-line "active" echo so a silent fallback stays visible in CI logs.
@@ -149,7 +150,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 10 matrix shards partitioned by weight-aware LPT bin-packing (`scripts/sharding.ts`; files with no mined weight fall back to the p75 file weight so a new unweighted file can't silently unbalance a shard) and INCLUDES `*.slow.test.ts` (the two outlier slow files run as dedicated jobs alongside the matrix) plus `evals/**/*.test.ts` (keyless-allowlist-gated — `test/scripts/evals-collection.test.ts`). Each shard's bun process is bounded by `--max-concurrency` (`GBRAIN_TEST_MAX_CONCURRENCY`, default 4). Every bun-test job — matrix shards, serial-tests, verify, the slow/eval jobs — activates the PGLite schema snapshot (built in-runner via `scripts/lib/test-env.sh`; the brainbench gate brings its own in-memory PGLite and skips it; the ~42MB tar is also cached across jobs via actions/cache, with the runner's own hash check staying authoritative). CI EXCLUDES `*.serial.test.ts` from the shards and runs them in the pooled `serial-tests` job via `bun run test:serial` — one bun process per file preserves the `mock.module` quarantine; the pool runs those processes concurrently. `bun run verify` gets its own job too, as does the BrainBench memory-conformance gate (`brainbench` job → `scripts/ci-brainbench-gate.sh`, hermetic in-memory PGLite, ~15s), which compares HEAD's fresh run against master's committed baseline (`evals/brainbench/baselines/main.json`) — the `test-status` aggregate checks its result explicitly. E2E (`.github/workflows/e2e.yml`) mirrors the content-hash skip in its own `e2e-pass-<hash>` namespace (scheduled nightly runs are exempt and always run), runs tier1 and tier2 in parallel with the jsonb-parity job in front of tier2 as the token-spend gate, and aggregates through `e2e-status`. CI is the ground truth for "did everything pass."
+- **CI matrix** (`.github/workflows/test.yml`) runs `scripts/test-shard.sh` across 10 matrix shards partitioned by weight-aware LPT bin-packing (`scripts/sharding.ts`; files with no mined weight fall back to the p75 file weight so a new unweighted file can't silently unbalance a shard) and INCLUDES `*.slow.test.ts` (the three outlier slow files — longmemeval, entity-resolve-perf, brainbench-e2e — run as dedicated jobs alongside the matrix) plus `evals/**/*.test.ts` (keyless-allowlist-gated — `test/scripts/evals-collection.test.ts`). Each shard's bun process is bounded by `--max-concurrency` (`GBRAIN_TEST_MAX_CONCURRENCY`, default 4). Every bun-test job — matrix shards, serial-tests, verify, the slow/eval jobs — activates the PGLite schema snapshot (built in-runner via `scripts/lib/test-env.sh`; the brainbench gate brings its own in-memory PGLite and skips it; the ~42MB tar is also cached across jobs via actions/cache, with the runner's own hash check staying authoritative). CI EXCLUDES `*.serial.test.ts` from the shards and runs them in the pooled `serial-tests` job via `bun run test:serial` — one bun process per file preserves the `mock.module` quarantine; the pool runs those processes concurrently. `bun run verify` gets its own job too, as does the BrainBench memory-conformance gate (`brainbench` job → `scripts/ci-brainbench-gate.sh`, hermetic in-memory PGLite, ~15s), which compares HEAD's fresh run against master's committed baseline (`evals/brainbench/baselines/main.json`) — the `test-status` aggregate checks its result explicitly. E2E (`.github/workflows/e2e.yml`) mirrors the content-hash skip in its own `e2e-pass-<hash>` namespace (scheduled nightly runs are exempt and always run), runs tier1 and tier2 in parallel with the jsonb-parity job in front of tier2 as the token-spend gate, and aggregates through `e2e-status`. CI is the ground truth for "did everything pass."
- **Local fast loop** (`scripts/run-unit-shard.sh` via the parallel wrapper) uses round-robin-by-index sharding and EXCLUDES `*.slow.test.ts` AND `*.serial.test.ts`. Local trades coverage for inner-loop speed; CI catches what local skips.
This divergence is intentional. Don't try to make them equal — the two scripts deliberately solve different problems. The regression test at `test/scripts/run-unit-shard.test.ts` pins what the local fast loop should and shouldn't include; `test/scripts/run-unit-parallel.test.ts` pins the wrapper's memory-adaptive concurrency and the OOM/external-kill serial rescue pass.
@@ -176,9 +177,10 @@ non-`GBRAIN_`-prefixed so the hermetic env scrub keeps them.
**Two corpora.**
-- **PR corpus** (`prCorpus`) — the 13 coverage-collecting lanes in
+- **PR corpus** (`prCorpus`) — the 14 coverage-collecting lanes in
`.github/workflows/test.yml`: the 10 matrix shards, `serial-tests`, and the
- two dedicated slow jobs. Deterministic (runs identically on every PR); this
+ three dedicated slow jobs (`slow-eval-longmemeval`,
+ `slow-entity-resolve-perf`, `slow-brainbench-e2e`). Deterministic (runs identically on every PR); this
is the corpus the gates run against.
- **fullCorpus** — nightly, schedule-only in `.github/workflows/e2e.yml`:
`coverage-full-{unit,serial,slow,e2e}` + `coverage-full-report`. Fully
@@ -231,7 +233,7 @@ with both corpus sections unseeded. `scripts/update-coverage-baseline.ts
(per-file detail limited to the baseline's `watchlist`); `--promote` flips
`provisional: false` at graduation.
-**CI wiring.** The 13 PR lanes upload `coverage-*` artifacts; the advisory
+**CI wiring.** The 14 PR lanes upload `coverage-*` artifacts; the advisory
`coverage-report` job downloads + merges (`COVERAGE_CORPUS=prCorpus`), renders
`scripts/render-coverage-summary.ts` to the step summary (including the
behavioral-vs-structural counts from `scripts/structural-suites.tsv`), and
@@ -387,6 +389,44 @@ await withEnv({ A: '1', B: '2', C: undefined }, fn);
`withEnv` saves the prior value of every key it touches and restores via try/finally — including when the callback throws. **It is cross-test safe but NOT intra-file concurrent-safe.** `process.env` is process-global; two `test.concurrent()` calls in the same file both touching the same key will race. Files using `withEnv` stay outside the `test.concurrent()` codemod's eligibility filter.
+#### Speed + environment helpers (`test/helpers/`)
+
+Reach for these before hand-rolling; the five speed helpers each have their
+own unit test, and the two environment probes are exercised through their
+consumer suites:
+
+- `cli-spawn.ts` — `runCli(argv, opts)` (async, hermetic env, timeout-killed),
+ `runCliBatch(argvs, {width})` (bounded pool, DEFAULT WIDTH 2 — the cap is
+ per-invocation and 4 shards × width multiplies CLI children machine-wide;
+ each child can boot a ~1.5GB PGLite), `runCliMemo` (argv-keyed memo for
+ read-only calls like `--help`; `clearCliMemo()` drops the memo when a test
+ mutates what a memoized call would observe). Replaces the per-file spawn wrappers; a file
+ of N independent sequential spawns becomes one width-2 batch in `beforeAll`.
+- `wait-for.ts` — `waitFor(predicate, {timeoutMs, intervalMs})` /
+ `waitForValue`. Replaces fixed `setTimeout` sleeps: polls resolve as soon as
+ the condition holds, and generous deadlines make slow-CI runs LESS flaky
+ than a tuned sleep, not more.
+- `with-snapshot.ts` — `withColdPglite(fn)`: per-TEST scoped
+ `GBRAIN_PGLITE_SNAPSHOT` opt-out (save/delete/restore);
+ `withSnapshotValue(value, fn)` is the general form (pin any snapshot path
+ for fn's scope; `undefined` = deleted). Use instead of a
+ file-level `delete process.env.GBRAIN_PGLITE_SNAPSHOT`, which forces every
+ engine in the file to cold-boot. Caution: a snapshot-restored engine does
+ not replay migrations on a later `initSchema()` after a version rewind —
+ rewind-arc tests need the cold path (see `test/bootstrap.test.ts`).
+- `reset-pglite.ts#resetPgliteStateNarrow(engine, tables)` — explicit-table
+ truncate for hot loops (the full reset truncates the whole catalog). The
+ table list is REQUIRED — a default would silently under-truncate.
+- `git-fixture.ts` — `makeGitFixture(dir)`: build-once git repo +
+ `reset()`/`commitAll()` between tests, replacing per-test `git init` chains.
+- `fs-perms.ts` — `permsEnforced()` / `crontabAvailable()` probes: some hosts
+ (FUSE/overlay sandboxes, root) don't enforce permission bits or lack a
+ crontab; tests asserting "this write MUST fail" / "cron registered" use
+ `test.skipIf(!probe())` so they skip visibly there and still run in CI.
+- `git-stderr-probe.ts` — `gitStderrLeads()`: skips raw-git-stderr-slice
+ assertions behind ambient git PATH shims that print their own diagnostics
+ first (e.g. Conductor's auth-broker wrapper).
+
#### When to quarantine instead of fix
Rename to `*.serial.test.ts` when:
@@ -520,7 +560,7 @@ Unit tests and what they cover:
- `test/query-intent-legacy.test.ts` — query intent classification: entity/temporal/event/general (pre-concept behavior pins). `test/query-intent-concept.test.ts` — the `concept` intent: definitional/landscape cue detection, the proper-noun / quoted-phrase / sub-3-word guards, vector-lean weight routing.
- `test/eval.test.ts` — retrieval metrics: `precisionAtK`, `recallAtK`, `mrr`, `ndcgAtK`, `parseQrels`.
- `test/brainbench-fixtures.test.ts` / `test/brainbench-generator.test.ts` / `test/brainbench-metrics.test.ts` / `test/brainbench-continuity.test.ts` / `test/brainbench-writeback.test.ts` / `test/brainbench-adapters.test.ts` / `test/brainbench-scoreboard.test.ts` — the BrainBench memory-conformance unit suites (`src/eval/brainbench/`): fixture loader/validator + the sealed-gold seal (a `gold` key inside a fixture must reject) and committed-corpus integrity; generator determinism (the committed corpus is exactly what `gen.ts` produces, holdout discipline, category counts); metric formulas over hand-built turn rows (zero should-retrieve turns, empty injections, acceptable-vs-gold asymmetry, micro-averaging); cross-harness continuity (writer's decision persists through the production write-back pipeline, reader recalls on the SAME brain); write-back grading the PRODUCTION conversation→facts pipeline via the injected gold extractor; adapter seam contracts over hermetic PGLite (budget caps, suppression modes); scoreboard + gate governance (baseline determinism, count-aware gating, corpus-bless modes, justification flow, isolation gates-at-zero). `test/brainbench-floors.test.ts` — the pre-registered quality floors as executable assertions against the committed baseline (a baseline bless can't bank a threshold violation).
-- `test/eval-brainbench-e2e.test.ts` — BrainBench CLI end-to-end via subprocess against a small tmp corpus: the literal exit codes (0 pass / 1 regression / 2 error-or-inconclusive — the CI product), `--out` artifact validity incl. `_meta.metric_glossary`, byte-deterministic `--update-baseline`, anti-vacuous-pass, and the `eval run-all` in-process wiring.
+- `test/eval-brainbench-e2e.slow.test.ts` — BrainBench CLI end-to-end via subprocess against a small tmp corpus: the literal exit codes (0 pass / 1 regression / 2 error-or-inconclusive — the CI product), `--out` artifact validity incl. `_meta.metric_glossary`, byte-deterministic `--update-baseline`, anti-vacuous-pass, and the `eval run-all` once-per-sweep record. Slow-tiered with its own CI job (`slow-brainbench-e2e`); independent CLI runs execute once through a width-2 pool in `beforeAll`. The in-process full-corpus completion test was deleted as duplicative — CI's `brainbench` gate runs the committed corpus fresh on every PR and its baseline compare is the fixtures-hash drift guard.
- `test/check-resolvable.test.ts` — resolver reachability, MECE overlap, gap detection, proximity-based DRY detection, `extractDelegationTargets` coverage.
- `test/dry-fix.test.ts` — auto-fix: three shape-aware expander pure-function tests; five guards (working-tree-dirty, no-git-backup, inside-code-fence, already-delegated within 40 lines, ambiguous-multi-match, block-is-callout).
- `test/doctor-fix.test.ts` — `gbrain doctor --fix` CLI integration: dry-run preview, apply path, JSON output shape.
diff --git a/docs/architecture/KEY_FILES.md b/docs/architecture/KEY_FILES.md
index d0ea4727ed..87980a55f5 100644
--- a/docs/architecture/KEY_FILES.md
+++ b/docs/architecture/KEY_FILES.md
@@ -113,7 +113,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `src/commands/reindex-aliases.ts` — `gbrain reindex --aliases [--limit N] [--dry-run] [--json] [--source <id>]`: backfills the free-text alias layer for EXISTING pages whose frontmatter `aliases:` predate the alias table (the import-time projection covers new + changed pages). Reads each page's frontmatter `aliases:`, writes via `engine.setPageAliases`. Idempotent + convergent (setPageAliases replaces a page's alias set) so no op-checkpoint needed; walks `listAllPageRefs` (cheap cross-source enumeration), `--source` narrows. Pinned by `test/search/reindex-aliases.test.ts`.
- `src/eval/retrieval-quality/harness.ts` + `src/commands/eval-retrieval-quality.ts` + `test/fixtures/retrieval-quality/namedthing.jsonl` — NamedThingBench, the retrieval-quality eval that makes the named-thing-miss incident impossible to reintroduce silently. Seven query families, each a distinct failure class: `title-substring` (the direct regression), `generic-to-named` (tourist label → named thing), `alias-synonym` (declared alias / romanization → canonical), `multi-chunk-dilution` (one strong chunk among many weak — stresses max-pool), `short-vs-rich`, `graph-relationship` (guardrail), `hard-negative` (precision guard, must NOT return a page). `gbrain eval retrieval-quality <fixture.jsonl>` runs it with hard gates (e.g. title-substring Hit@1 ≥ 0.95, alias Hit@1 ≥ 0.98, multi-chunk-dilution Hit@3 = 1.0). Pure: caller injects a `SearchFn` (CLI uses `hybridSearch`, tests stub) so it's engine-agnostic. Metric glossary entries (`hit@1`/`hit@3`) added to `src/core/eval/metric-glossary.ts`. Pinned by `test/eval-retrieval-quality.test.ts` + `test/retrieval-quality-harness.test.ts`.
- `docs/architecture/RETRIEVAL.md` + `docs/architecture/RETRIEVAL_MAXPOOL_INCIDENT.md` — retrieval-pipeline architecture reference + the named-thing-miss incident write-up (root cause, the five-layer fix, the eval that pins it).
-- `src/eval/brainbench/` + `src/commands/eval-brainbench.ts` — BrainBench, the cross-harness memory conformance suite (`gbrain eval brainbench`; methodology in `docs/eval/BRAINBENCH.md`). `types.ts` carries the PUBLISHED interchange shapes (fixture/gold/result/baseline — mirrored as JSON Schemas in `evals/brainbench/schema/`; breaking changes bump the schema versions). `fixtures.ts`: strict loader/validator + corpus `fixtures_hash` (covers fixture AND gold files); a `gold` key inside a fixture turn is a validation error — gold is SEALED in the gold dir and adapters only ever see sanitized `PublicTurn`s. `seed.ts`: fail-fast hermetic seeding (`importFromContent` noEmbed + NULL-embedding `insertFact`; any non-`imported` status ⇒ `SeedError` ⇒ fixture `seed_failed` ⇒ run exit 2). `adapters/shared.ts`: ONE `runReflexPipeline` all three adapters drive with declarative config (pointer budget, suppression mode) — cross-harness comparability is structural; `openclaw.ts` (seam `production`, the shipped pipeline), `claude-code.ts` (seam `production`; drives the shipped `gbrain hook user-prompt` path end-to-end — fixture turns become `UserPromptSubmit` stdin JSON, synthesized Claude Code JSONL transcripts feed the real window parse + cross-turn dedupe, and resolution rides a run-scoped resolve-IPC server with the real shared secret; bench-pinned deviations disclosed in `docs/eval/BRAINBENCH.md`: generous `userPromptDeadlineMs`, push-failure banner suppressed), `codex.ts` (seam `contract`; static entity-index preamble whose slugs deliberately don't count as injections + ≤1 per-turn fragment; fixture conversations round-trip through the real rollout format + the shipped parser `src/core/transcripts/codex.ts` for turn selection — fragment DELIVERY remains harness-shaped until a shipped codex injection path lands). `metrics/`: know-to-ask (+false-fire anti-gaming companion), push (micro-averaged P/R), write-back (drives the PRODUCTION conversation→facts pipeline via the injectable-extractor seam; gold extractor in CI, real extractor under `--llm`), continuity (writer→reader pairs on a shared brain through DIFFERENT adapters; pointer-injection OR stored-fact keyword probe). `harness.ts`: ONE in-memory PGLite per run + `resetTables` between fixtures (longmemeval engine-sharing pattern); read-only suites share one seeding across all adapters; emits per-(harness×suite) cells + re-scoreable turn rows; `source_isolation_violations` counted per turn and gated at zero. `scoreboard.ts`: markdown render, canonical diff-stable committed baseline (4-decimal rounding, sorted keys, receipts excluded), `compareBaselines` with main-baseline governance — same-hash count-aware gate vs corpus-bless mode (the committed baseline must byte-match the run; regressions vs main require a `justification`). The CLI brings its own PGLite (cli.ts routes before connectEngine), writes `--out` as the canonical CI artifact, and terminates via an explicit grace-tick `process.exit(verdict)` (0 pass / 1 regression / 2 error) because PGLite stomps `process.exitCode` and Bun discards queued stdout on exit. `runBrainBenchCore()` is the in-process entry `eval run-all` uses (one record per sweep, `EvalRunRecord` schema_version 3, `mode: 'n/a'`). Pinned by `test/brainbench-*.test.ts` + `test/eval-brainbench-e2e.test.ts`.
+- `src/eval/brainbench/` + `src/commands/eval-brainbench.ts` — BrainBench, the cross-harness memory conformance suite (`gbrain eval brainbench`; methodology in `docs/eval/BRAINBENCH.md`). `types.ts` carries the PUBLISHED interchange shapes (fixture/gold/result/baseline — mirrored as JSON Schemas in `evals/brainbench/schema/`; breaking changes bump the schema versions). `fixtures.ts`: strict loader/validator + corpus `fixtures_hash` (covers fixture AND gold files); a `gold` key inside a fixture turn is a validation error — gold is SEALED in the gold dir and adapters only ever see sanitized `PublicTurn`s. `seed.ts`: fail-fast hermetic seeding (`importFromContent` noEmbed + NULL-embedding `insertFact`; any non-`imported` status ⇒ `SeedError` ⇒ fixture `seed_failed` ⇒ run exit 2). `adapters/shared.ts`: ONE `runReflexPipeline` all three adapters drive with declarative config (pointer budget, suppression mode) — cross-harness comparability is structural; `openclaw.ts` (seam `production`, the shipped pipeline), `claude-code.ts` (seam `production`; drives the shipped `gbrain hook user-prompt` path end-to-end — fixture turns become `UserPromptSubmit` stdin JSON, synthesized Claude Code JSONL transcripts feed the real window parse + cross-turn dedupe, and resolution rides a run-scoped resolve-IPC server with the real shared secret; bench-pinned deviations disclosed in `docs/eval/BRAINBENCH.md`: generous `userPromptDeadlineMs`, push-failure banner suppressed), `codex.ts` (seam `contract`; static entity-index preamble whose slugs deliberately don't count as injections + ≤1 per-turn fragment; fixture conversations round-trip through the real rollout format + the shipped parser `src/core/transcripts/codex.ts` for turn selection — fragment DELIVERY remains harness-shaped until a shipped codex injection path lands). `metrics/`: know-to-ask (+false-fire anti-gaming companion), push (micro-averaged P/R), write-back (drives the PRODUCTION conversation→facts pipeline via the injectable-extractor seam; gold extractor in CI, real extractor under `--llm`), continuity (writer→reader pairs on a shared brain through DIFFERENT adapters; pointer-injection OR stored-fact keyword probe). `harness.ts`: ONE in-memory PGLite per run + `resetTables` between fixtures (longmemeval engine-sharing pattern); read-only suites share one seeding across all adapters; emits per-(harness×suite) cells + re-scoreable turn rows; `source_isolation_violations` counted per turn and gated at zero. `scoreboard.ts`: markdown render, canonical diff-stable committed baseline (4-decimal rounding, sorted keys, receipts excluded), `compareBaselines` with main-baseline governance — same-hash count-aware gate vs corpus-bless mode (the committed baseline must byte-match the run; regressions vs main require a `justification`). The CLI brings its own PGLite (cli.ts routes before connectEngine), writes `--out` as the canonical CI artifact, and terminates via an explicit grace-tick `process.exit(verdict)` (0 pass / 1 regression / 2 error) because PGLite stomps `process.exitCode` and Bun discards queued stdout on exit. `runBrainBenchCore()` is the in-process entry `eval run-all` uses (one record per sweep, `EvalRunRecord` schema_version 3, `mode: 'n/a'`). Pinned by `test/brainbench-*.test.ts` + `test/eval-brainbench-e2e.slow.test.ts`.
- `evals/brainbench/` — the committed BrainBench corpus: 141 fixtures (135 generated + 6 hand-authored spike) / 241 gold-annotated turns across 7 categories (kta-pos/kta-neg/push/write-back/continuity/multi-source/adversarial), ~15% holdout (excluded from the CI gate, scored in published `--include-holdout` runs). `generator/gen.ts` rebuilds the corpus byte-identically (Mulberry32, seed 42; whole-cloth fictional universe from curated synthetic name pools so scenario privacy is structural; prose is template-synthesized with PRNG-selected variants — deliberately no LLM pass, difficulty stays controlled; several know-to-ask variants intentionally exercise documented v1 reflex limits so the baseline measures the roadmap). `gold/` is sealed; `schema/` is the foreign-runner contract (gbrain-evals drives the suite as a subprocess via `--fixtures DIR --gold DIR --json --out FILE`); `baselines/main.json` is the committed gate baseline; `_ledger.json` records counts/seed/rebuild command. CI: the `.github/workflows/test.yml` `brainbench` job + `scripts/ci-brainbench-gate.sh` (fetches MAIN's baseline via `git show origin/master:…` — a PR cannot rewrite what it's compared against; first-landing path runs ungated) + `scripts/render-brainbench-delta.ts` (compact step-summary/PR-body delta block from the `--out` artifact). Privacy: `scripts/check-synthetic-corpus-privacy.sh` scans `evals/brainbench/{fixtures,gold}` in `bun run verify`.
- `src/core/types.ts` extension + `src/core/operations.ts:search` + `src/core/import-file.ts` + `src/cli.ts` + `src/core/search/telemetry.ts` — the wiring layer for the retrieval cathedral. `SearchResult` gains `evidence`, `create_safety`, `title_match_boost`, `alias_hit` (all optional; evidence/create_safety reference the union types in `evidence.ts`). The `search` MCP op uses a cheap-hybrid path by default and accepts a per-call `mode` (conservative|balanced|tokenmax) honored ONLY for trusted/local callers (`resolvePerCallMode(ctx, ...)` — remote callers use the configured mode so a remote provider can't force tokenmax spend); every search path stamps evidence fail-soft. `importFromContent` projects frontmatter `aliases:` into `page_aliases` via `normalizeAliasList` + `engine.setPageAliases` so new + changed pages register aliases at ingest. `src/cli.ts` adds the `gbrain search diagnose` dispatch (lazy import) and reconciles the `search` CLI path with the cheap-hybrid op. `src/core/search/telemetry.ts` extends the rollup with the rank-1 base_score drift signal (sum/count + 3 coarse buckets, aggregate not per-query), surfaced via `gbrain search stats`, backed by migration v111's `search_telemetry` columns. Tests: `test/cli-search-dispatch.test.ts`, `test/search/per-call-mode.test.ts`, `test/search/telemetry-rank1.test.ts`, `test/search/title-boost-stage.test.ts`, `test/search/alias-hop.test.ts`, `test/search/evidence.test.ts`, `test/search/searchvector-maxpool.test.ts`, `test/search/pre-migration-failopen.test.ts`.
- `src/commands/eval.ts` — `gbrain eval` command: single-run table + A/B config comparison. Sub-subcommand dispatch on `args[0]` routes `gbrain eval export` + `gbrain eval prune` + `gbrain eval replay` into session-capture handlers; bare `gbrain eval --qrels …` fall-through preserves the legacy IR-metrics flow. `gbrain eval cross-modal` is in the dispatch (the user-facing path is the cli.ts no-DB branch — `src/commands/eval.ts:cross-modal` only fires when callers re-enter with an existing engine).
@@ -127,7 +127,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `src/commands/eval-export.ts` — streams `eval_candidates` rows as NDJSON to stdout with `schema_version: 1` prefix on every line. EPIPE-safe, progress heartbeats on stderr, stable id-desc tiebreaker so `--since` windows never dupe/miss rows.
- `src/commands/eval-prune.ts` — explicit retention cleanup. Requires `--older-than DUR`. `--dry-run` reports would-delete count.
- `src/commands/eval-replay.ts` — contributor-facing replay tool. Reads NDJSON from `gbrain eval export`, re-runs each captured `query` / `search` op against the current brain, computes set-Jaccard@k between captured + current `retrieved_slugs`, top-1 stability rate, and latency Δ. Stable JSON shape (`schema_version: 1`) for CI gating; human mode prints a regression table. Pure Bun, zero new deps. The dev-loop half of BrainBench-Real. See `docs/eval-bench.md`. `parseNdjson` skips lines where `_kind === 'baseline_metadata'` so `gbrain bench publish` baselines parse cleanly without the metadata header polluting row counts. Exports `replayCore(engine, opts): Promise<{summary, results}>` + `ReplaySummary` type so `gbrain eval gate` calls replay in-process (NOT subprocess — avoids gbrain-version-drift for source-tree CI). CLI `runEvalReplay` wraps `replayCore`.
-- `src/core/bench/baseline-file.ts` + `src/core/bench/qrels-file.ts` + `src/core/bench/correctness-gate.ts` + `src/commands/bench-publish.ts` + `src/commands/eval-gate.ts` — the eval-loop wave. `gbrain bench publish --from <captured.ndjson> --to <X.baseline.ndjson>` writes a baseline (stamps stable `query_hash` per row; metadata header carries `_kind: 'baseline_metadata'` + thresholds + `source_hash` + `baseline_mean_latency_ms`; deterministic sort by `(tool_name, query_hash)`; strict: empty=fail, dupes=fail with paste-ready hint, `--to` exists=refuse without `--force`). `gbrain eval gate [--baseline X] [--qrels Y]` is the two-gate dispatcher (regression gate via in-process `replayCore`, correctness gate via bare `hybridSearch` for determinism, both must pass when both flags set, exit 0 PASS / 1 FAIL / 2 USAGE). Source-id-aware: `bench publish` dedup key is `(tool_name, source_ids, query_hash)`; qrels compare keys are `${source_id}::${slug}` everywhere (closes the multi-source bug class at the file-shape layer). Latency math: `(baseline + delta) / baseline <= multiplier`. Fail-closed: ANY in-process throw flips verdict to fail with named breach in `breaches[]` — never silently exit 0. `.qrels.json` preserves the 12-row `test/fixtures/eval-baselines/qrels-search.json` fixture (slug-only `relevant_slugs` + `first_relevant_slug` auto-promote to `source_id='default'`) AND supports the federated shape (explicit `relevant: [{source_id, slug}]` + `expected_top1`). `correctness-gate.ts` runs each qrels query via bare `hybridSearch`; per-query throw recorded as `errored: true` and flagged as gate failure. Audit JSONL at `~/.gbrain/audit/bench-publish-YYYY-Www.jsonl`. Hermetic mode: `--embedder deterministic` (correctness gate ONLY — rejected with `--baseline`, requires `--qrels`) embeds each query as the qrels fixture's basis vector via `src/eval/deterministic-embed.ts` (`basisEmbedding` unit vectors; FNV-1a-derived fallback dim for off-fixture query texts) and threads it into bare `hybridSearch` through the `queryEmbedFn` seam — no API keys, no network; bare `hybridSearch` neither reads nor writes the semantic query cache (both live in `hybridSearchCached`), so deterministic runs cannot poison cached production results. `scripts/run-eval-canary.ts` (`check:eval-canary`, wired into `bun run verify` + CI) is the hermetic CLI retrieval canary built on it: boots a throwaway PGLite brain under a temp GBRAIN_HOME, seeds the qrels fixture corpus (the expected-top1 page carries its query text in `timeline` too — page-grain FTS indexes title(A) + timeline(C) only, `compiled_truth` is deliberately unindexed), spawns the REAL CLI with engine-reroute/provider env stripped, and asserts exit 0 + metric floors; `--record` additionally appends an EvalRunRecord-shaped line to `.gbrain-evals/eval-results.jsonl`. Honest scope: the canary gates the hybrid ranking pipeline (keyword/title/alias arms + RRF against gold qrels) with synthetic vectors — semantic-embedding regressions remain the keyed eval suites' job. Pinned by `test/bench/baseline-file.test.ts`, `test/bench/qrels-file.test.ts`, `test/bench/correctness-gate.test.ts`, `test/bench-publish.test.ts`, `test/eval-gate.test.ts`, `test/eval-canary.test.ts`, `test/eval-replay-metadata-skip.test.ts`, `test/cycle/nightly-probe-adapters.test.ts`, `test/autopilot-nightly-probe-wiring.test.ts`, `test/e2e/eval-loop.test.ts`.
+- `src/core/bench/baseline-file.ts` + `src/core/bench/qrels-file.ts` + `src/core/bench/correctness-gate.ts` + `src/commands/bench-publish.ts` + `src/commands/eval-gate.ts` — the eval-loop wave. `gbrain bench publish --from <captured.ndjson> --to <X.baseline.ndjson>` writes a baseline (stamps stable `query_hash` per row; metadata header carries `_kind: 'baseline_metadata'` + thresholds + `source_hash` + `baseline_mean_latency_ms`; deterministic sort by `(tool_name, query_hash)`; strict: empty=fail, dupes=fail with paste-ready hint, `--to` exists=refuse without `--force`). `gbrain eval gate [--baseline X] [--qrels Y]` is the two-gate dispatcher (regression gate via in-process `replayCore`, correctness gate via bare `hybridSearch` for determinism, both must pass when both flags set, exit 0 PASS / 1 FAIL / 2 USAGE). Source-id-aware: `bench publish` dedup key is `(tool_name, source_ids, query_hash)`; qrels compare keys are `${source_id}::${slug}` everywhere (closes the multi-source bug class at the file-shape layer). Latency math: `(baseline + delta) / baseline <= multiplier`. Fail-closed: ANY in-process throw flips verdict to fail with named breach in `breaches[]` — never silently exit 0. `.qrels.json` preserves the 12-row `test/fixtures/eval-baselines/qrels-search.json` fixture (slug-only `relevant_slugs` + `first_relevant_slug` auto-promote to `source_id='default'`) AND supports the federated shape (explicit `relevant: [{source_id, slug}]` + `expected_top1`). `correctness-gate.ts` runs each qrels query via bare `hybridSearch`; per-query throw recorded as `errored: true` and flagged as gate failure. Audit JSONL at `~/.gbrain/audit/bench-publish-YYYY-Www.jsonl`. Hermetic mode: `--embedder deterministic` (correctness gate ONLY — rejected with `--baseline`, requires `--qrels`) embeds each query as the qrels fixture's basis vector via `src/eval/deterministic-embed.ts` (`basisEmbedding` unit vectors; FNV-1a-derived fallback dim for off-fixture query texts) and threads it into bare `hybridSearch` through the `queryEmbedFn` seam — no API keys, no network; bare `hybridSearch` neither reads nor writes the semantic query cache (both live in `hybridSearchCached`), so deterministic runs cannot poison cached production results. `scripts/run-eval-canary.ts` (`check:eval-canary` package script, on-demand; in CI the same runner executes via `test/eval-canary.test.ts` in the unit matrix — it was removed from the verify battery as pure double work) is the hermetic CLI retrieval canary built on it: boots a throwaway PGLite brain under a temp GBRAIN_HOME, seeds the qrels fixture corpus (the expected-top1 page carries its query text in `timeline` too — page-grain FTS indexes title(A) + timeline(C) only, `compiled_truth` is deliberately unindexed), spawns the REAL CLI with engine-reroute/provider env stripped, and asserts exit 0 + metric floors; `--record` additionally appends an EvalRunRecord-shaped line to `.gbrain-evals/eval-results.jsonl`. Honest scope: the canary gates the hybrid ranking pipeline (keyword/title/alias arms + RRF against gold qrels) with synthetic vectors — semantic-embedding regressions remain the keyed eval suites' job. Pinned by `test/bench/baseline-file.test.ts`, `test/bench/qrels-file.test.ts`, `test/bench/correctness-gate.test.ts`, `test/bench-publish.test.ts`, `test/eval-gate.test.ts`, `test/eval-canary.test.ts`, `test/eval-replay-metadata-skip.test.ts`, `test/cycle/nightly-probe-adapters.test.ts`, `test/autopilot-nightly-probe-wiring.test.ts`, `test/e2e/eval-loop.test.ts`.
- `src/core/cycle/nightly-probe-adapters.ts` — bridges the autopilot's object-shape `NightlyProbeDeps` to the argv-shape `runEvalLongMemEval` + `runEvalCrossModal` CLI functions. Cross-modal adapter argv MUST include `--output summaryPath` (without it the summary lands at the default receipt path and the adapter reads nothing from `summaryPath`). In-process invocation (NOT subprocess) — avoids gbrain-version-drift for source-tree CI. Pinned by `test/cycle/nightly-probe-adapters.test.ts` (incl. argv-shape regression for the `--output` requirement).
- `test/eval-replay-gate.test.ts` + `test/fixtures/eval-baselines/qrels-search.json` — hermetic retrieval qrels gate running in the standard PR unit-shard CI matrix (`.github/workflows/test.yml`, NOT the fixed-file E2E workflow). Uses the canonical PGLite block (test-isolation R3+R4) and the basis-vector embedding pattern from `test/e2e/search-quality.test.ts:23-28` for fully hermetic retrieval. The qrels fixture (12 queries) uses PLACEHOLDER names only (alice-example, widget-co-example, etc. — privacy rule) and embeds each query at a deterministic basis dimension so retrieval is reproducible. Each query lists `relevant_slugs[]` + `first_relevant_slug`; the test computes `top1_match_rate` (top-1 == first_relevant) and `recall@10` (fraction of relevant_slugs in top-10), asserting both meet floors (defaults `>= 0.80` and `>= 0.85`). Env-overridable floors `GBRAIN_REPLAY_GATE_TOP1_FLOOR` / `GBRAIN_REPLAY_GATE_RECALL_FLOOR` (via `withEnv()` per R1). Refresh discipline: when ranking changes intentionally move expected slugs, edit `qrels-search.json` directly with a `Why:` line in the commit body or the gate degrades to rubber-stamp. Pinned by `test/eval-replay-gate.test.ts` (incl. a privacy-grep regression guard against real-name reintroduction).
- `src/core/cycle/nightly-quality-probe.ts` + `src/core/audit-quality-probe.ts` + `test/fixtures/longmemeval-nightly.jsonl` + `test/nightly-quality-probe.test.ts` — opt-in nightly cross-modal quality probe. The phase runs `gbrain eval longmemeval --by-type` against the committed 10-question placeholder fixture, pipes output through `gbrain eval cross-modal --batch --max-usd 5 --yes`, and writes one event per run to `~/.gbrain/audit/quality-probe-YYYY-Www.jsonl` (ISO-week-rotated, mirrors `audit-slug-fallback.ts`; honors `GBRAIN_AUDIT_DIR`). Default DISABLED — opt-in via `gbrain config set autopilot.nightly_quality_probe.enabled true` (prevents surprise API spend). 24h rate limit (pure `shouldRunNightly(now, recentEvents, windowMs?)`) skips with audit row `outcome: rate_limited`. Embedding-key short-circuit: longmemeval needs `gateway.embedQuery()`, so the phase exits early with `outcome: no_embedding_key` + stderr warn when no provider configured. Full DI surface via `NightlyProbeDeps` (`isEnabled`, `hasEmbeddingProvider`, `resolveMaxUsd`, `resolveRepoRoot`, `runLongMemEval`, `runCrossModalBatch`, `now`) so the unit test stubs every external effect. Cost ceiling: $5/run × 30 nights ≈ $150/month worst-case; expected ~$10.50/month. New `nightly_quality_probe_health` doctor check (`src/commands/doctor.ts`, right after `slug_fallback_audit`) reads last 7 days: SKIPPED when flag off (with enable command); OK when enabled + all PASS; WARN on any FAIL / ERROR / BUDGET_EXCEEDED with per-outcome counts. Pinned by `test/nightly-quality-probe.test.ts`.
@@ -409,13 +409,13 @@ v0.46: the `sync` handler forwards `job.data.github_item` ({repo, number, kind})
- `scripts/check-jsonb-params.mjs` — AST-lite CI guard for the POSITIONAL jsonb double-encode form the template grep above misses: an `executeRaw`/`executeRawDirect`/`.unsafe()` call whose balanced arg span binds `JSON.stringify(x)` into a bare `$N::jsonb` cast (the #2339 class). Walks each call's balanced span respecting strings/templates/comments, handles generic-typed calls (`executeRaw<T>(`), and allows the sanctioned forms (`$N::text::jsonb`, `$N::text[]`, `executeRawJsonb`, `sql.json`, an inline `jsonb-guard-ok` comment). PGLite's native `db.query` is deliberately not scanned (it parses text→jsonb, so the bug can't occur there). Heuristic by design (whole-span correlation; can't see a `JSON.stringify` assigned to a variable before the call) — the real backstop is the DATABASE_URL-gated e2e parity tests. Scan roots overridable via argv for its self-test (`test/check-jsonb-params.test.ts`).
- `scripts/check-source-id-projection.sh` — CI grep guard for the multi-source bug class. Greps `src/core/postgres-engine.ts` + `src/core/pglite-engine.ts` for `SELECT.*FROM pages` projections matching the `rowToPage` feeder shape (id + slug + type + title) and fails if `source_id` is missing. `Page.source_id` is required at the type level; a projection dropping the column produces `Page` rows with `source_id: undefined` while TypeScript's `: string` lies about it. Wired into `bun run verify`.
- `scripts/guards-manifest.tsv` + `scripts/guard-self-test.sh` — THE single registry of `scripts/check-*` CI guards (52 guards) and its self-test harness. Every guard is classified `scanner` (greps/parses repo sources — must eventually carry fixtures), `buildfresh`, or `repostate` (exempt-with-reason, not fixture-tested). `guard-self-test.sh` (`bun run check:guard-self-test`, wired into `bun run verify`) runs each `selftest=yes` scanner against known-bad (must exit non-zero) and known-good (must pass) fixture trees under `test/fixtures/guards/<guard>/{bad,good}/` via the `GBRAIN_GUARD_ROOT` env seam, and fails the build when a new `scripts/check-*` script is missing from the manifest — so a guard whose pattern rots into a permanently-green no-op fails CI instead of masquerading as coverage. The manifest replaces the second hand-synced REGISTRY copy (package.json's `check:all` chain — deleted); it registers and classifies guards but does not itself schedule them — `run-verify-parallel.sh`'s `CHECKS` array remains the execution list, and a registered guard is not automatically wired into verify. New guard = new manifest row (+ fixtures if scanner) + a `CHECKS` entry if it should gate pushes.
-- `scripts/merge-lcov.ts` + `scripts/coverage-diff-gate.ts` + `scripts/coverage-baseline-gate.ts` + `scripts/update-coverage-baseline.ts` + `scripts/render-coverage-summary.ts` + `scripts/coverage-gate-exemptions.txt` + `scripts/coverage-baseline.json` — the coverage measurement + gating cluster; the operating guide is docs/TESTING.md "Coverage lanes and gates". `merge-lcov.ts` walks artifact dirs for `lcov.info` + `lane-manifest.json`, sums DA hits per file:line, normalizes paths repo-relative, and emits a merged lcov + summary JSON (src-only totals/per-dir/per-file, the `lineHits` extension the diff gate consumes, and never-loaded src files as count + sorted list — deliberately never a percentage, since physical lines ≠ executable lines); `--manifest-expect` pins the lane set, and a missing/incomplete lane or a `shard` lane with `lcovCount != 1` (the xargs-batching tripwire) marks the summary `degraded: true` — still exit 0 (degraded is data, and both gates go report-only on it). `coverage-diff-gate.ts` gates added/changed gate-scoped lines (non-test, non-generated `src/**.ts`) at ≥80% covered plus zero changed-but-never-loaded files; report-only unless `COVERAGE_GATE_ENFORCE=1`; a `[coverage-exempt: reason]` commit trailer passes with a loud warning; `coverage-gate-exemptions.txt` rows (exact path or trailing-`/` prefix; SHRINK-ONLY — additions need a graduation review) are excluded from the gate but still reported (`[e2e-exempt]` / `[subprocess-undercount]`); exit contract: 0 = pass or report-only, 1 = fail while enforcing, 2 = infrastructure error (never conflated with a coverage verdict). `coverage-baseline-gate.ts` reads the baseline via `git show origin/master:scripts/coverage-baseline.json` (never the working tree, so a PR can't weaken its own bar) and compares corpus-matched sections only (`--corpus prCorpus|fullCorpus`), failing on >0.5pp global or >1.0pp per-dir drops; `provisional: true` in the baseline (the current state — both corpus sections unseeded) keeps it report-only regardless of enforcement; `update-coverage-baseline.ts` writes the working-tree baseline (per-file detail limited to the committed `watchlist`) and `--promote` flips `provisional: false`. `render-coverage-summary.ts` renders the summary JSON as markdown on stdout for `$GITHUB_STEP_SUMMARY`, including the behavioral-vs-structural counts from `scripts/structural-suites.tsv`. Wiring: 13 PR-corpus lanes in test.yml (10 matrix shards + serial + the two dedicated slow jobs) upload `coverage-*` artifacts and the advisory `coverage-report` job merges + renders + runs both gates report-only (deliberately absent from `test-status`/`cache-write` until graduation); schedule-only `coverage-full-{unit,serial,slow,e2e}` + `coverage-full-report` in e2e.yml produce the self-contained nightly fullCorpus number (full e2e glob included) and the `coverage-full-merged` trend artifact. Collection is `COVERAGE_DIR`-opt-in in `test-shard.sh`/`run-serial-tests.sh`/`run-e2e.sh` — unique coverage dir per bun process (a reused dir overwrites `lcov.info`), lane manifest written only on a green run, `run-e2e.sh` requires an ABSOLUTE `COVERAGE_DIR` and honors `E2E_FILE_TIMEOUT_SECS` (both deliberately non-`GBRAIN_`-prefixed to survive the hermetic env scrub). Bun/JSC emits line records only (function coverage is informational) and no subprocess coverage, so `src/cli.ts` undercounts. Pinned by `test/scripts/merge-lcov.test.ts`, `test/scripts/coverage-diff-gate.test.ts`, `test/scripts/render-coverage-summary.test.ts`.
+- `scripts/merge-lcov.ts` + `scripts/coverage-diff-gate.ts` + `scripts/coverage-baseline-gate.ts` + `scripts/update-coverage-baseline.ts` + `scripts/render-coverage-summary.ts` + `scripts/coverage-gate-exemptions.txt` + `scripts/coverage-baseline.json` — the coverage measurement + gating cluster; the operating guide is docs/TESTING.md "Coverage lanes and gates". `merge-lcov.ts` walks artifact dirs for `lcov.info` + `lane-manifest.json`, sums DA hits per file:line, normalizes paths repo-relative, and emits a merged lcov + summary JSON (src-only totals/per-dir/per-file, the `lineHits` extension the diff gate consumes, and never-loaded src files as count + sorted list — deliberately never a percentage, since physical lines ≠ executable lines); `--manifest-expect` pins the lane set, and a missing/incomplete lane or a `shard` lane with `lcovCount != 1` (the xargs-batching tripwire) marks the summary `degraded: true` — still exit 0 (degraded is data, and both gates go report-only on it). `coverage-diff-gate.ts` gates added/changed gate-scoped lines (non-test, non-generated `src/**.ts`) at ≥80% covered plus zero changed-but-never-loaded files; report-only unless `COVERAGE_GATE_ENFORCE=1`; a `[coverage-exempt: reason]` commit trailer passes with a loud warning; `coverage-gate-exemptions.txt` rows (exact path or trailing-`/` prefix; SHRINK-ONLY — additions need a graduation review) are excluded from the gate but still reported (`[e2e-exempt]` / `[subprocess-undercount]`); exit contract: 0 = pass or report-only, 1 = fail while enforcing, 2 = infrastructure error (never conflated with a coverage verdict). `coverage-baseline-gate.ts` reads the baseline via `git show origin/master:scripts/coverage-baseline.json` (never the working tree, so a PR can't weaken its own bar) and compares corpus-matched sections only (`--corpus prCorpus|fullCorpus`), failing on >0.5pp global or >1.0pp per-dir drops; `provisional: true` in the baseline (the current state — both corpus sections unseeded) keeps it report-only regardless of enforcement; `update-coverage-baseline.ts` writes the working-tree baseline (per-file detail limited to the committed `watchlist`) and `--promote` flips `provisional: false`. `render-coverage-summary.ts` renders the summary JSON as markdown on stdout for `$GITHUB_STEP_SUMMARY`, including the behavioral-vs-structural counts from `scripts/structural-suites.tsv`. Wiring: 14 PR-corpus lanes in test.yml (10 matrix shards + serial + the three dedicated slow jobs) upload `coverage-*` artifacts and the advisory `coverage-report` job merges + renders + runs both gates report-only (deliberately absent from `test-status`/`cache-write` until graduation); schedule-only `coverage-full-{unit,serial,slow,e2e}` + `coverage-full-report` in e2e.yml produce the self-contained nightly fullCorpus number (full e2e glob included) and the `coverage-full-merged` trend artifact. Collection is `COVERAGE_DIR`-opt-in in `test-shard.sh`/`run-serial-tests.sh`/`run-e2e.sh` — unique coverage dir per bun process (a reused dir overwrites `lcov.info`), lane manifest written only on a green run, `run-e2e.sh` requires an ABSOLUTE `COVERAGE_DIR` and honors `E2E_FILE_TIMEOUT_SECS` (both deliberately non-`GBRAIN_`-prefixed to survive the hermetic env scrub). Bun/JSC emits line records only (function coverage is informational) and no subprocess coverage, so `src/cli.ts` undercounts. Pinned by `test/scripts/merge-lcov.test.ts`, `test/scripts/coverage-diff-gate.test.ts`, `test/scripts/render-coverage-summary.test.ts`.
- `scripts/check-module-size.sh` + `scripts/module-size-limits.tsv` — the module-size ratchet (`bun run check:module-size`, wired into `bun run verify`). The TSV commits a per-file `wc -l` ceiling (`path max_lines policy note`); four rules, all violations reported before a single exit 1: a file above its ceiling fails (raise a ceiling only as a conscious TSV edit); a ceiling more than 50 lines above the measured size fails (stale slack after a shrink — lower it so the ratchet holds); a TSV row whose path no longer exists fails (remove the row); an unlisted `src/**/*.ts` (excluding `*.generated.ts`/`*.test.ts`) above the 1500-line new-file cap fails (split it or add a row). Policy `region-exempt` (only `src/core/migrate.ts`) counts lines OUTSIDE the append-only `export const MIGRATIONS = [` … `];` region, so the migrations array grows freely while the surrounding runner logic stays ratcheted. Self-test seams: `GBRAIN_GUARD_ROOT`, `GBRAIN_MODULE_SIZE_SLACK`, `GBRAIN_MODULE_SIZE_NEWFILE_CAP`.
- `scripts/classify-tests.ts` + `scripts/structural-suites.tsv` — suite-level behavioral-vs-structural test classification (the intent axis described in docs/TESTING.md "File taxonomy"). Content-based detectors — repo-anchored `readFileSync`/`Bun.file` readers, exec-scan grep windows over `src|scripts|docs`, and the `doctorSource()`/`doctorFileSource()` helpers — mark a suite STRUCTURAL when its assertions read repo source/doc text rather than executing product code; tmpdir-anchored reads don't count, and files with detectors but no attributable suite land in an `unknown` bucket emitted as comment rows (surfaced, never silently dropped). Modes: bare = rewrite the TSV; `--check` = byte-for-byte regenerate-and-diff freshness (wired as `bun run check:structural-manifest` in `bun run verify` via `scripts/check-structural-manifest.sh`); `--summary` = counts only. Fix misclassifications in the detector list, never by hand-editing the TSV. `render-coverage-summary.ts` consumes the TSV for the behavioral-vs-structural line in the CI coverage report.
-- `scripts/build-pglite-snapshot.ts` — `bun run build:pglite-snapshot`: bakes a post-`initSchema()` PGLite data dir into `test/fixtures/pglite-snapshot.tar` + a version file (schema hash line, then `dims=`/`model=` lines recording the embedding shape it was baked with). Idempotent (hash short-circuit ~40ms when fresh; rebuilds stale) and concurrency-safe (atomic `mkdir` lock at `test/fixtures/.pglite-snapshot.lock` with staleness-verified takeover — a live lock is never stolen; tar written first, version file last, so a crash can't leave a fresh-looking torn fixture; waiter bounded by `GBRAIN_SNAPSHOT_LOCK_TIMEOUT_MS`, default 120000; an exhausted waiter facing a still-live lock proceeds unlocked as a last resort — the loader's hash/shape gate validates the version file, not the tar bytes). Called through the shared `ensure_pglite_snapshot` helper in `scripts/lib/test-env.sh` (also home of `detect_cpus` + `detect_available_mem_mb`; sourced by `run-unit-parallel.sh`, `test-shard.sh`, `run-slow-tests.sh`, `run-serial-tests.sh`, and `run-verify-parallel.sh` — default-on, opt out `GBRAIN_NO_SNAPSHOT=1`, no-op when a parent already exported the path, non-fatal on build failure with a one-line "active" echo so a silent cold-init fallback stays visible) and directly by `scripts/ci-local.sh`; every caller exports `GBRAIN_PGLITE_SNAPSHOT`. The loader side is `tryLoadSnapshot` + `computeSnapshotSchemaHash` (exported from `src/core/pglite-engine.ts`): the hash folds `PGLITE_SCHEMA_SQL`, every migration's `sql` + `sqlFor.pglite`, AND each migration `handler`'s function source (handler-only migrations are invisible to a sql-only hash); any hash or embedding-shape mismatch warns once and falls through to normal cold init — the snapshot is an optimization, never authoritative. The loader memoizes per process: the schema hash computes once (MIGRATIONS + PGLITE_SCHEMA_SQL are static for the process lifetime) and the version file + ~42MB tar are read once per (path, process) instead of once per engine construction (a full suite constructs 600+ engines); a terminally-unusable path (missing/stale/torn) memoizes as null and is never retried, the tar blob loads lazily only after the FIRST caller passes the shape gate, and the dims/model shape gate itself is deliberately NOT memoized (tests reconfigure the gateway mid-process — a mismatched engine must still fall back to cold init). Accepted limitation: a snapshot rewritten mid-process is not observed; the only writer runs before test fan-out. Test seams `__snapshotMemoStatsForTests`/`__resetSnapshotMemoForTests`. Pinned by `test/snapshot-shape-guard.test.ts`.
+- `scripts/build-pglite-snapshot.ts` — `bun run build:pglite-snapshot`: bakes a post-`initSchema()` PGLite data dir into `test/fixtures/pglite-snapshot.tar` + a version file (schema hash line, then `dims=`/`model=` lines recording the embedding shape it was baked with). Idempotent (hash short-circuit ~40ms when fresh; rebuilds stale) and concurrency-safe (atomic `mkdir` lock at `test/fixtures/.pglite-snapshot.lock` with staleness-verified takeover — a live lock is never stolen; tar written first, version file last, so a crash can't leave a fresh-looking torn fixture; waiter bounded by `GBRAIN_SNAPSHOT_LOCK_TIMEOUT_MS`, default 120000; an exhausted waiter facing a still-live lock proceeds unlocked as a last resort — the loader's hash/shape gate validates the version file, not the tar bytes). Called through the shared `ensure_pglite_snapshot` helper in `scripts/lib/test-env.sh` (also home of `detect_cpus` + `detect_available_mem_mb`; sourced by `run-unit-parallel.sh`, `test-shard.sh`, `run-slow-tests.sh`, `run-serial-tests.sh`, `run-verify-parallel.sh`, and `run-e2e.sh` — default-on, opt out `GBRAIN_NO_SNAPSHOT=1`, no-op when a parent already exported the path, non-fatal on build failure with a one-line "active" echo so a silent cold-init fallback stays visible) and directly by `scripts/ci-local.sh`; every caller exports `GBRAIN_PGLITE_SNAPSHOT`. The loader side is `tryLoadSnapshot` + `computeSnapshotSchemaHash` (exported from `src/core/pglite-engine.ts`): the hash folds `PGLITE_SCHEMA_SQL`, every migration's `sql` + `sqlFor.pglite`, AND each migration `handler`'s function source (handler-only migrations are invisible to a sql-only hash); any hash or embedding-shape mismatch warns once and falls through to normal cold init — the snapshot is an optimization, never authoritative. The loader memoizes per process: the schema hash computes once (MIGRATIONS + PGLITE_SCHEMA_SQL are static for the process lifetime) and the version file + ~42MB tar are read once per (path, process) instead of once per engine construction (a full suite constructs 600+ engines); a terminally-unusable path (missing/stale/torn) memoizes as null and is never retried, the tar blob loads lazily only after the FIRST caller passes the shape gate, and the dims/model shape gate itself is deliberately NOT memoized (tests reconfigure the gateway mid-process — a mismatched engine must still fall back to cold init). Accepted limitation: a snapshot rewritten mid-process is not observed; the only writer runs before test fan-out. Test seams `__snapshotMemoStatsForTests`/`__resetSnapshotMemoForTests`. Pinned by `test/snapshot-shape-guard.test.ts`.
- `docker-compose.ci.yml` + `scripts/ci-local.sh` — Local CI gate. `bun run ci:local` spins up four `pgvector/pgvector:pg16` services (postgres-1..4) + `oven/bun:1` with named volumes (`gbrain-ci-pg-data-{1..4}`, `gbrain-ci-node-modules`, `gbrain-ci-bun-cache`), runs gitleaks on host, smoke-tests `scripts/run-e2e.sh` argv handling, runs guards + typecheck, then the Tier 1 default: 4-shard parallel unit + E2E (`xargs -P4`, one Postgres per shard; unit phase keeps `DATABASE_URL` unset). `--no-shard` falls back to the legacy unsharded sequential flow (debug aid); `--diff` runs the diff-aware selector unsharded. Also runs a `pgbouncer` service (`edoburu/pgbouncer`, `POOL_MODE: transaction`, `AUTH_TYPE: plain` — pg16 stores SCRAM verifiers, so the userlist must hold the plaintext password; `IGNORE_STARTUP_PARAMETERS` whitelists gbrain's `statement_timeout`/`idle_in_transaction_session_timeout` startup params the way the Supabase pooler does) fronting postgres-1 on host port `GBRAIN_CI_PGBOUNCER_PORT` (default 6543); every E2E invocation exports `GBRAIN_PGBOUNCER_URL` (pooled; dedicated `gbrain_pgbouncer` database so it never races the `gbrain_test` TRUNCATE fixtures) + `GBRAIN_PGBOUNCER_DIRECT_URL`, consumed by `test/e2e/pgbouncer-teardown.test.ts` — the transaction-mode teardown bug class (#1972/#2015/#2084) reproduced in the local gate instead of only in production. `--no-pull` skips upstream pulls; `--clean` nukes named volumes. Postgres host port defaults to 5434; override with `GBRAIN_CI_PG_PORT=NNNN`. Stronger gate than PR CI's 2-file Tier 1 set.
- `scripts/select-e2e.ts` + `scripts/e2e-test-map.ts` — Diff-aware E2E test selector. Reads three git sources (committed `origin/master...HEAD`, working-tree `HEAD`, and `git ls-files --others --exclude-standard` for untracked NOT-gitignored files), classifies as EMPTY / DOC_ONLY / SRC. Fail-closed: EMPTY → all files; DOC_ONLY (every path matches the README/CLAUDE/AGENTS/CHANGELOG/TODOS allowlist) → empty stdout; SRC → escape-hatch paths (schema, package.json, skills/) trigger all, else the hand-tuned `E2E_TEST_MAP` glob narrows, and an unmapped src/ change still emits ALL files (never silently nothing). Pure-function exports `selectTests`, `classify`, `matchGlob`. `bun run ci:select-e2e` prints the current selection on stdout. `test/select-e2e.test.ts` covers all 4 branches plus 3 regression guards (skills/, untracked files, unmapped src/) — 24 cases.
-- `scripts/run-e2e.sh` — Sequential E2E runner. Accepts an optional argv-driven file list (used by `ci:local:diff`) and a `--dry-run-list` flag that prints the resolved file list and exits (used by `ci-local.sh`'s startup smoke-test). Falls back to `test/e2e/*.test.ts` plus `test/phantom-redirect-engine-parity.test.ts` when invoked with no args (the phantom-redirect Postgres arm is only reachable through a DATABASE_URL-bearing lane; the unit wrappers strip the URL per #3485, so this lane must carry it). This wrapper is the database-URL opt-in boundary (#3485): it exports `GBRAIN_TEST_ALLOW_DATABASE_URL=1` so the bunfig preload guard (`test/helpers/database-url-guard-preload.ts`) lets the run start, unsets `GBRAIN_DATABASE_URL` (the e2e suite runs on `DATABASE_URL` only — an ambient `GBRAIN_DATABASE_URL` would pass the opt-in yet reach CLI-subprocess paths with no name floor), and its GBRAIN_* env scrub preserves `GBRAIN_E2E_ALLOW_DB` so the name-floor escape hatch the guard's own error message names stays usable. It also exports `GBRAIN_TEST_KEEP_PROVIDER_KEYS=1` so the unit-lane provider-key strip preload (`test/helpers/provider-keys-preload.ts`) leaves the real keys that live embed/parity e2e tests skip-gate on. Each file runs under a gtimeout/timeout wedge backstop (default signal: SIGTERM — the bun test child installs no JS-level handler for it, so kernel-default termination applies) — 180s default, with a per-file override for known-slow files (`skills.test.ts` gets 420s: the real ingest-skill run replays every migration, so its floor grows as master adds migrations); the cap is a wedge backstop, not a per-test budget, and bare `bun` (no outer cap) is the fallback when neither timeout binary is installed.
+- `scripts/run-e2e.sh` — Sequential E2E runner. Accepts an optional argv-driven file list (used by `ci:local:diff`) and a `--dry-run-list` flag that prints the resolved file list and exits (used by `ci-local.sh`'s startup smoke-test). Falls back to `test/e2e/*.test.ts` plus `test/phantom-redirect-engine-parity.test.ts` when invoked with no args (the phantom-redirect Postgres arm is only reachable through a DATABASE_URL-bearing lane; the unit wrappers strip the URL per #3485, so this lane must carry it). This wrapper is the database-URL opt-in boundary (#3485): it exports `GBRAIN_TEST_ALLOW_DATABASE_URL=1` so the bunfig preload guard (`test/helpers/database-url-guard-preload.ts`) lets the run start, unsets `GBRAIN_DATABASE_URL` (the e2e suite runs on `DATABASE_URL` only — an ambient `GBRAIN_DATABASE_URL` would pass the opt-in yet reach CLI-subprocess paths with no name floor), and its GBRAIN_* env scrub preserves `GBRAIN_E2E_ALLOW_DB` so the name-floor escape hatch the guard's own error message names stays usable. It also exports `GBRAIN_TEST_KEEP_PROVIDER_KEYS=1` so the unit-lane provider-key strip preload (`test/helpers/provider-keys-preload.ts`) leaves the real keys that live embed/parity e2e tests skip-gate on. Each file runs under a gtimeout/timeout wedge backstop (default signal: SIGTERM — the bun test child installs no JS-level handler for it, so kernel-default termination applies) — 180s default, with a per-file override for known-slow files (`skills.test.ts` gets 420s: the real ingest-skill run replays every migration, so its floor grows as master adds migrations); the cap is a wedge backstop, not a per-test budget, and bare `bun` (no outer cap) is the fallback when neither timeout binary is installed. It activates the PGLite schema snapshot like the other runners: sources `scripts/lib/test-env.sh` + `ensure_pglite_snapshot` after the `--dry-run-list` early exit (list mode stays instant; non-fatal on build failure), re-exports `GBRAIN_PGLITE_SNAPSHOT` as an ABSOLUTE path (e2e tests spawn CLI subprocesses with varying cwd — a relative path silently misses the tar there), and its env keep-list preserves the var; e2e files that assert the path TO post-`initSchema()` state carry per-file `delete process.env.GBRAIN_PGLITE_SNAPSHOT` opt-outs with one-line reasons.
- `scripts/llms-config.ts` + `scripts/build-llms.ts` — Generator for `llms.txt` (llmstxt.org-spec web index) + `llms-full.txt` (inlined single-fetch bundle). Curated config drives both. Run `bun run build:llms` after adding a new doc. `LLMS_REPO_BASE` env lets forks regenerate with their own URL base. `FULL_SIZE_BUDGET` (600KB) caps the inline bundle; generator WARNs if exceeded. Committed output has no runtime consumer; committed for GitHub browsing and fork-safe fetching.
- `AGENTS.md` — Local-clone entry point for non-Claude agents (Codex, Cursor, OpenClaw, Aider). Mirrors `CLAUDE.md` intent via relative links. Claude Code keeps using `CLAUDE.md`.
- `docs/UPGRADING_DOWNSTREAM_AGENTS.md` — Patches for downstream agent skill forks to apply when upgrading. Each release appends a new section; includes diffs for brain-ops, meeting-ingestion, signal-detector, enrich.
diff --git a/docs/eval-bench.md b/docs/eval-bench.md
index 32a3a50bb0..94e3c8499e 100644
--- a/docs/eval-bench.md
+++ b/docs/eval-bench.md
@@ -71,10 +71,13 @@ instead of the gateway, so the gate runs with no API keys and no network.
Correctness-gate-only — it is rejected together with `--baseline` (replay
re-embeds captured queries via the gateway) and requires `--qrels`. Bare
`hybridSearch` never reads or writes the semantic query cache, so a
-deterministic run cannot poison cached production results. This is what CI's
-`check:eval-canary` gate runs via `scripts/run-eval-canary.ts`: a throwaway
+deterministic run cannot poison cached production results. This is what the
+hermetic retrieval canary (`scripts/run-eval-canary.ts`) runs: a throwaway
PGLite brain seeded from the qrels fixture, gating the hybrid ranking
-pipeline (keyword/title/alias arms + RRF) with synthetic vectors. Honest
+pipeline (keyword/title/alias arms + RRF) with synthetic vectors. In CI the
+canary runs via `test/eval-canary.test.ts` in the unit matrix; `bun run
+check:eval-canary` is the on-demand package script (it is deliberately not
+in the `verify` battery — the unit-matrix twin already gates it). Honest
scope: semantic-embedding regressions remain the keyed eval suites' job.
Reproduce locally with `bun run scripts/run-eval-canary.ts` (`--record`
appends to the `.gbrain-evals/eval-results.jsonl` ledger).
diff --git a/docs/eval/FIX_WAVE_BASELINES.md b/docs/eval/FIX_WAVE_BASELINES.md
index 5758ae6c0b..8141b9c9b5 100644
--- a/docs/eval/FIX_WAVE_BASELINES.md
+++ b/docs/eval/FIX_WAVE_BASELINES.md
@@ -101,7 +101,9 @@ recall@10=1.0000 first_relevant=1.0000 expected_top1=0.8333 vs floors
ranking pipeline (keyword/title/alias arms + RRF against gold qrels) with
synthetic basis vectors — no API keys, no production brain, so the live-serve
lock is moot. Semantic-embedding regressions remain the keyed eval suites'
-job. Wired into `bun run verify` as check:eval-canary.
+job. Runs in CI via `test/eval-canary.test.ts` in the unit matrix;
+`check:eval-canary` remains as an on-demand package script (removed from the
+verify battery as pure double work).
Verified-bug status at W0 ship: cycle-lock refresh + fencing (TODO-OPS-2
closed), stall-death parent unblock, started_at ×4, modality carry, import
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index 8e1e5a3000..b1c17c2621 100644
--- a/openclaw.plugin.json
+++ b/openclaw.plugin.json
@@ -1,7 +1,7 @@
{
"id": "gbrain-context-engine",
"name": "gbrain",
- "version": "0.47.6.0",
+ "version": "0.47.7.0",
"description": "Personal knowledge brain with Postgres + pgvector hybrid search",
"family": "bundle-plugin",
"configSchema": {
diff --git a/package.json b/package.json
index 460fdb8e5d..4af84a819c 100644
--- a/package.json
+++ b/package.json
@@ -172,7 +172,7 @@
"bun": ">=1.3.10"
},
"license": "MIT",
- "version": "0.47.6.0",
+ "version": "0.47.7.0",
"overrides": {
"@hono/node-server": "^2.0.5",
"fast-uri": "^3.1.5",
diff --git a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json b/plugin-variants/gbrain-coding/.claude-plugin/plugin.json
index 6973531316..c6b3c8110a 100644
--- a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json
+++ b/plugin-variants/gbrain-coding/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain-coding",
- "version": "0.47.6.0",
+ "version": "0.47.7.0",
"description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 20 skills)",
"author": {
"name": "Garry Tan",
diff --git a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json b/plugin-variants/gbrain-coding/.codex-plugin/plugin.json
index c6f6c8ae7a..afa29c1f75 100644
--- a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json
+++ b/plugin-variants/gbrain-coding/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain-coding",
- "version": "0.47.6.0",
+ "version": "0.47.7.0",
"description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 20 skills)",
"author": {
"name": "Garry Tan",
diff --git a/plugin-variants/gbrain-coding/README.md b/plugin-variants/gbrain-coding/README.md
index b46be6c344..9a8e303db0 100644
--- a/plugin-variants/gbrain-coding/README.md
+++ b/plugin-variants/gbrain-coding/README.md
@@ -1,4 +1,4 @@
-<!-- gbrain-plugin-tree-stamp: 0.47.6.0 -->
+<!-- gbrain-plugin-tree-stamp: 0.47.7.0 -->
# gbrain-coding (generated persona variant — do not hand-edit)
Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant.
diff --git a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json b/plugin-variants/gbrain-daily/.claude-plugin/plugin.json
index 7a506ff9e1..9794c9d895 100644
--- a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json
+++ b/plugin-variants/gbrain-daily/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain-daily",
- "version": "0.47.6.0",
+ "version": "0.47.7.0",
"description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 19 skills)",
"author": {
"name": "Garry Tan",
diff --git a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json b/plugin-variants/gbrain-daily/.codex-plugin/plugin.json
index a23fb81844..4501a4577b 100644
--- a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json
+++ b/plugin-variants/gbrain-daily/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain-daily",
- "version": "0.47.6.0",
+ "version": "0.47.7.0",
"description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 19 skills)",
"author": {
"name": "Garry Tan",
diff --git a/plugin-variants/gbrain-daily/README.md b/plugin-variants/gbrain-daily/README.md
index c583705bdb..9322633e30 100644
--- a/plugin-variants/gbrain-daily/README.md
+++ b/plugin-variants/gbrain-daily/README.md
@@ -1,4 +1,4 @@
-<!-- gbrain-plugin-tree-stamp: 0.47.6.0 -->
+<!-- gbrain-plugin-tree-stamp: 0.47.7.0 -->
# gbrain-daily (generated persona variant — do not hand-edit)
Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant.
diff --git a/plugin/README.md b/plugin/README.md
index acd70bdf03..404b71b4a2 100644
--- a/plugin/README.md
+++ b/plugin/README.md
@@ -1,4 +1,4 @@
-<!-- gbrain-plugin-tree-stamp: 0.47.6.0 -->
+<!-- gbrain-plugin-tree-stamp: 0.47.7.0 -->
# gbrain plugin skill tree (generated — do not hand-edit)
This tree is the curated skill set for the gbrain Codex and Claude Code
diff --git a/scripts/check-synthetic-corpus-privacy.sh b/scripts/check-synthetic-corpus-privacy.sh
index c7e9a724e1..5ef5068175 100755
--- a/scripts/check-synthetic-corpus-privacy.sh
+++ b/scripts/check-synthetic-corpus-privacy.sh
@@ -97,7 +97,7 @@ done < <(find "$CORPUS_DIR" -name '*.md' -type f 2>/dev/null)
# scenario-privacy rule (no real deal shapes / timelines, even anonymized)
# lives in evals/brainbench/README.md and is review-enforced.
# ---------------------------------------------------------------------------
-# Env override exists for the negative-path test (test/eval-brainbench-e2e.test.ts)
+# Env override exists for the negative-path test (test/eval-brainbench-e2e.slow.test.ts)
# — production callers never set it.
BB_DIR="${BRAINBENCH_PRIVACY_DIR:-evals/brainbench}"
if [ -d "$BB_DIR/fixtures" ]; then
diff --git a/scripts/check-test-isolation.allowlist b/scripts/check-test-isolation.allowlist
index f61636b834..5ada197581 100644
--- a/scripts/check-test-isolation.allowlist
+++ b/scripts/check-test-isolation.allowlist
@@ -26,23 +26,17 @@ test/brain-resolver.test.ts
test/check-resolvable-cli.test.ts
test/claw-test-cli.test.ts
test/code-def-refs.test.ts
-test/core/cycle.test.ts
test/destructive-guard.test.ts
-test/doctor-minions-check.test.ts
test/doctor.test.ts
-test/dream.test.ts
-test/embed.test.ts
test/eval-capture.test.ts
test/friction-cli.test.ts
test/friction.test.ts
test/gbrain-home-isolation.test.ts
test/helpers/with-env.test.ts
test/http-transport.test.ts
-test/init-migrate-only.test.ts
test/integrations.test.ts
test/mcp-eval-capture.test.ts
test/migrate.test.ts
-test/migration-orchestrator-v0_31_0.test.ts
test/migration-resume.test.ts
test/migrations-v0_11_0.test.ts
test/migrations-v0_13_1.test.ts
@@ -50,11 +44,9 @@ test/migrations-v0_14_0.test.ts
test/migrations-v0_19_0.test.ts
test/migrations-v0_22_4.test.ts
test/minions-shell.test.ts
-test/minions.test.ts
test/mounts-cli.test.ts
test/multi-source-integration.test.ts
test/orphans.test.ts
-test/pages-soft-delete.test.ts
test/preferences.test.ts
test/reindex-code.test.ts
test/resolve-prepare.test.ts
@@ -62,7 +54,6 @@ test/resolvers.test.ts
test/scenarios.test.ts
test/schema-bootstrap-coverage.test.ts
test/search-limit.test.ts
-test/skillpack-check.test.ts
test/source-resolver.test.ts
test/storage-sync.test.ts
test/subagent-audit.test.ts
diff --git a/scripts/run-e2e.sh b/scripts/run-e2e.sh
index 346b969705..8788b4e451 100755
--- a/scripts/run-e2e.sh
+++ b/scripts/run-e2e.sh
@@ -1,18 +1,19 @@
#!/usr/bin/env bash
-# Run E2E tests ONE FILE AT A TIME.
+# Run E2E tests ONE FILE AT A TIME (within a shard).
#
# Bun's default is to run test files in parallel (each in its own worker).
-# Our E2E suite shares one Postgres database across all 13 files, and
-# `setupDB()` does TRUNCATE CASCADE + fixture import. When files run in
-# parallel, file A's TRUNCATE can race with file B's fixture import,
-# producing observed fails like "expected 16 pages, got 8", missing
-# links, orphaned timeline entries, etc. The flakiness was visible on
-# ~3 of every 5 runs pre-fix.
+# Our E2E suite shares one Postgres database across the whole test/e2e glob
+# (220+ files), and `setupDB()` does TRUNCATE CASCADE + fixture import. When
+# files run in parallel against ONE database, file A's TRUNCATE can race with
+# file B's fixture import, producing observed fails like "expected 16 pages,
+# got 8", missing links, orphaned timeline entries, etc. The flakiness was
+# visible on ~3 of every 5 runs pre-fix.
#
-# Running files sequentially eliminates the race entirely. It also costs
-# some startup overhead (each file spins up a fresh bun process) but for
-# a suite this size that is measured in ~1-2s per file, amortized under
-# the natural per-file test time of 5-10s.
+# Running files sequentially eliminates the race entirely. Parallelism is
+# recovered ACROSS databases instead: the SHARD=N/M env below fans shards out
+# against separate Postgres containers (scripts/ci-local.sh runs 4). Within a
+# shard, per-file bun startup (~1-2s) amortizes under the natural per-file
+# test time of 5-10s.
#
# Exits non-zero on the first failing file so CI fails fast.
#
@@ -186,6 +187,22 @@ if [ "${#files[@]}" -eq 0 ]; then
exit 0
fi
+# PGLite snapshot fast path — ~90 e2e files boot in-memory PGLite; a cold boot
+# replays every migration (~3.5x per booting file). Every other runner already
+# activates this; the env scrub above deliberately keep-lists the var. Placed
+# AFTER --dry-run-list so list mode stays instant. Non-fatal on build failure
+# (tests fall back to cold init; the loader's schema-hash gate is authoritative).
+# Files asserting the path TO post-initSchema state carry their own per-file
+# `delete process.env.GBRAIN_PGLITE_SNAPSHOT` opt-out.
+. scripts/lib/test-env.sh
+ensure_pglite_snapshot "run-e2e"
+# Absolutize: e2e tests spawn CLI subprocesses with varying cwd; a relative
+# path would silently miss the tar there (cold-init fallback, benefit lost).
+# Same reason COVERAGE_DIR is normalized to absolute above.
+if [ -n "${GBRAIN_PGLITE_SNAPSHOT:-}" ] && [ "${GBRAIN_PGLITE_SNAPSHOT#/}" = "$GBRAIN_PGLITE_SNAPSHOT" ]; then
+ export GBRAIN_PGLITE_SNAPSHOT="$PWD/$GBRAIN_PGLITE_SNAPSHOT"
+fi
+
pass_files=0
fail_files=0
fail_list=()
diff --git a/scripts/run-serial-tests.sh b/scripts/run-serial-tests.sh
index 8531f39dae..17f68ceaff 100755
--- a/scripts/run-serial-tests.sh
+++ b/scripts/run-serial-tests.sh
@@ -12,7 +12,7 @@
# `mock.module(...)` in one file leaks into the next file's imports. Per-file
# processes give true isolation — and that isolation is per-PROCESS, not
# per-machine, so separate processes run CONCURRENTLY through the pool below.
-# (The previous runner executed the ~140 processes strictly one-at-a-time:
+# (The previous runner executed the per-file processes strictly one-at-a-time:
# an 8.5-minute CI job whose serialization was never required by the
# quarantine contract.)
#
@@ -116,6 +116,34 @@ for f in "${files[@]}"; do
fi
done
+# LPT dispatch: heaviest-first into the work-stealing pool (descending-weight
+# dispatch into a width-P pool IS longest-processing-time-first). Weights are
+# ADVISORY (scripts/serial-weights.json, seconds, mined from
+# .context/serial-durations.txt below); absent file / corrupt JSON / missing
+# bun keep discovery order (bun, not node: bun-only dev machines are the
+# common case — the script runs `bun test` right after). Absent key → corpus
+# p75 (same doctrine as
+# scripts/sharding.ts). Rank stability is all that matters — a wrong order
+# costs idle tail, never correctness. The --dry-run-list output above stays
+# discovery-ordered on purpose (pinned by test/scripts/run-serial-pool.test.ts).
+if [ "${#pool_files[@]}" -gt 1 ] && [ -f scripts/serial-weights.json ] && command -v bun >/dev/null 2>&1; then
+ lpt_sorted=$(printf '%s\n' "${pool_files[@]}" | bun -e '
+ const fs = require("fs");
+ let w = {};
+ try { w = JSON.parse(fs.readFileSync("scripts/serial-weights.json", "utf8")); } catch {}
+ const files = fs.readFileSync(0, "utf8").split("\n").filter(Boolean);
+ const vals = Object.values(w).filter((v) => typeof v === "number").sort((a, b) => a - b);
+ const p75 = vals.length ? vals[Math.floor(vals.length * 0.75)] : 0;
+ const wt = (f) => (typeof w[f] === "number" ? w[f] : p75);
+ files.sort((a, b) => (wt(b) - wt(a)) || (a < b ? -1 : 1));
+ process.stdout.write(files.join("\n"));
+ ' 2>/dev/null) || lpt_sorted=""
+ if [ -n "$lpt_sorted" ]; then
+ pool_files=()
+ while IFS= read -r f; do pool_files+=("$f"); done <<< "$lpt_sorted"
+ fi
+fi
+
# ──────────────────────────────────────────────────────────────────────────
# Pool sizing: min(detect_cpus, 4) — each pooled bun process can hold a
# PGLite WASM instance (~1.5GB) — then clamped by available memory (same
@@ -192,7 +220,9 @@ idx=0
if [ "${#pool_files[@]}" -gt 0 ]; then
for f in "${pool_files[@]}"; do
while [ "$(jobs -rp | wc -l | tr -d ' ')" -ge "$POOL" ]; do
- sleep 0.2
+ # 0.05s granularity: at 0.2s the dispatch loop idled ~15% of a full
+ # serial run in aggregate poll latency across 200+ dispatches.
+ sleep 0.05
done
(
s=$(date +%s)
@@ -316,6 +346,19 @@ for f in "${ordered_files[@]}"; do
i=$((i + 1))
done | sort -rn | head -10 | sed 's/^/ /'
+# Bank the FULL per-file duration table before the tmpdir EXIT trap destroys
+# it — the mining input for scripts/serial-weights.json (workspace-local,
+# gitignored, overwritten per run).
+if mkdir -p .context 2>/dev/null; then
+ {
+ di=0
+ for f in "${ordered_files[@]}"; do
+ [ -f "$LOG_DIR/$di.dur" ] && echo "$(cat "$LOG_DIR/$di.dur") $f"
+ di=$((di + 1))
+ done
+ } > .context/serial-durations.txt 2>/dev/null || true
+fi
+
total_epoch=$(( $(date +%s) - start_epoch ))
if [ "$fail_count" -gt 0 ]; then
echo "" >&2
diff --git a/scripts/run-unit-parallel.sh b/scripts/run-unit-parallel.sh
index 15c715d294..ba4376eb9b 100755
--- a/scripts/run-unit-parallel.sh
+++ b/scripts/run-unit-parallel.sh
@@ -155,11 +155,16 @@ if [ "${GBRAIN_TEST_NO_MEM_ADAPT:-0}" != "1" ]; then
MAX_TOTAL=$((BUDGET_MB / MEM_PER_FILE_MB))
[ "$MAX_TOTAL" -lt 1 ] && MAX_TOTAL=1
ORIG_N="$N"; ORIG_INTRA="$INTRA_CONC"
- # Shed shards before intra-shard concurrency: fewer bun processes frees
- # more than narrower ones (each process carries its own heap + WASM).
+ # Shed intra-shard concurrency before shards. `bun test --max-concurrency`
+ # only bounds test.concurrent tests (1 file in the corpus) — every other
+ # file runs serially inside its shard process, so INTRA_CONC is nearly
+ # free to shed: dropping it costs no throughput, while dropping a SHARD
+ # removes a whole bun process of real fan-out. The old order (shards
+ # first) collapsed a 16GB box to 1x4 — effectively a serial run behind a
+ # 12000s watchdog (measured 3.25x slower than 4 shards on the same box).
while [ $((N * INTRA_CONC)) -gt "$MAX_TOTAL" ]; do
- if [ "$N" -gt 1 ]; then N=$((N - 1))
- elif [ "$INTRA_CONC" -gt 1 ]; then INTRA_CONC=$((INTRA_CONC - 1))
+ if [ "$INTRA_CONC" -gt 1 ]; then INTRA_CONC=$((INTRA_CONC - 1))
+ elif [ "$N" -gt 1 ]; then N=$((N - 1))
else break
fi
done
@@ -192,7 +197,7 @@ else
mkdir -p "$LOG_DIR" || { echo "ERROR: cannot create log dir" >&2; exit 2; }
fi
# Clear from prior run.
-rm -f "$LOG_DIR"/shard-*.log "$LOG_DIR"/shard-*.exit "$LOG_DIR"/shard-*.wedged "$LOG_DIR"/shard-*.lastkb "$LOG_DIR"/shard-*.lastprogress "$LOG_DIR"/shard-*.start "$LOG_DIR"/shard-*.end 2>/dev/null
+rm -f "$LOG_DIR"/shard-*.log "$LOG_DIR"/shard-*.exit "$LOG_DIR"/shard-*.wedged "$LOG_DIR"/shard-*.lastkb "$LOG_DIR"/shard-*.lastprogress "$LOG_DIR"/shard-*.start "$LOG_DIR"/shard-*.end "$LOG_DIR"/shard-*.watchdog "$LOG_DIR"/shard-*.assigned "$LOG_DIR"/shard-*.hbsum 2>/dev/null
: > "$FAILURES_LOG"
: > "$SUMMARY_FILE"
@@ -237,7 +242,8 @@ for i in $(seq 1 "$N"); do
bash scripts/run-unit-shard.sh --max-concurrency="$INTRA_CONC" \
> "$SHARD_LOG" 2>&1 &
pid=$!
- ( sleep "$SHARD_TIMEOUT" && kill -TERM "$pid" 2>/dev/null && \
+ ( sleep "$SHARD_TIMEOUT" && touch "$LOG_DIR/shard-$i.watchdog" && \
+ kill -TERM "$pid" 2>/dev/null && \
sleep "$SHARD_KILL_AFTER" && kill -KILL "$pid" 2>/dev/null ) &
cap_pid=$!
wait "$pid" 2>/dev/null
@@ -258,6 +264,12 @@ for i in $(seq 1 "$N"); do
date +%s > "$LOG_DIR/shard-$i.end"
echo "$rc" > "$LOG_DIR/shard-$i.exit"
{ [ "$rc" = "124" ] || [ "$rc" = "137" ]; } && echo "WEDGED" > "$LOG_DIR/shard-$i.wedged"
+ # No-timeout-binary fallback: its watchdog TERMs the shard (rc 143), which
+ # the 124/137 line above can't see — the sentinel dropped right before the
+ # TERM marks the wedge, so the EXIT-HANG/WEDGED classifier is reachable on
+ # machines without coreutils timeout instead of a bare rc=143 hard-fail.
+ [ -f "$LOG_DIR/shard-$i.watchdog" ] && { [ "$rc" = "143" ] || [ "$rc" = "137" ]; } \
+ && echo "WEDGED" > "$LOG_DIR/shard-$i.wedged"
) &
SHARD_PIDS+=($!)
done
@@ -363,13 +375,20 @@ heartbeat() {
local hb_elapsed=$((now - hb_start))
for i in $(seq 1 "$N"); do
if [ -f "$LOG_DIR/shard-$i.exit" ]; then
- local rc; rc=$(cat "$LOG_DIR/shard-$i.exit" 2>/dev/null || echo "?")
+ # Finished shards never change: compute the summary once at first
+ # sight of .exit and cache it — re-running strip_ansi+awk over a
+ # multi-MB log twice per shard on every 10s tick was hundreds of
+ # full-file passes per run.
+ local rc p f
+ if [ ! -f "$LOG_DIR/shard-$i.hbsum" ]; then
+ rc=$(cat "$LOG_DIR/shard-$i.exit" 2>/dev/null || echo "?")
+ p=$(bun_summary_count "pass" "$LOG_DIR/shard-$i.log")
+ f=$(bun_summary_count "fail" "$LOG_DIR/shard-$i.log")
+ echo "$rc $p $f" > "$LOG_DIR/shard-$i.hbsum"
+ fi
+ read -r rc p f < "$LOG_DIR/shard-$i.hbsum"
local status="✓"
[ "$rc" != "0" ] && status="✗"
- local f
- f=$(bun_summary_count "fail" "$LOG_DIR/shard-$i.log")
- local p
- p=$(bun_summary_count "pass" "$LOG_DIR/shard-$i.log")
line="$line [s$i: done $status ${p}p ${f}f]"
else
local lf="$LOG_DIR/shard-$i.log"
@@ -498,6 +517,28 @@ failing_files_in_log() {
' | sort -u
}
+# shard_assigned_list: the deterministic per-shard file list, computed once
+# per shard and cached — shard_unstarted_files and the rescue-queue appends
+# used to re-walk `find test` via --dry-run-list up to 3x per wedged shard.
+shard_assigned_list() {
+ local shard_idx="$1" cache="$LOG_DIR/shard-$shard_idx.assigned"
+ if [ ! -f "$cache" ]; then
+ # Cache ONLY on success (tmp + mv): a failed/truncated first attempt —
+ # most likely under the exact fork-pressure conditions this path runs in —
+ # must not be served to the rescue queue as a partial file list.
+ if SHARD="$shard_idx/$N" bash scripts/run-unit-shard.sh --dry-run-list 2>/dev/null > "$cache.tmp"; then
+ mv "$cache.tmp" "$cache"
+ else
+ rm -f "$cache.tmp"
+ # Loud, not silent: an underivable list means a rescue-queue append got
+ # NOTHING while the summary says the shard was queued.
+ echo "⚠️ shard $shard_idx/$N: assigned-file list underivable — rescue queue may be incomplete" >&2
+ return 0
+ fi
+ fi
+ cat "$cache"
+}
+
# shard_unstarted_files: completion evidence for the EXIT-HANG classifier.
# Prints every file assigned to shard $1 (same deterministic split the shard
# itself used, via --dry-run-list) whose started file-header never appeared
@@ -509,7 +550,7 @@ failing_files_in_log() {
shard_unstarted_files() {
local shard_idx="$1" log="$2"
local assigned
- assigned=$(SHARD="$shard_idx/$N" bash scripts/run-unit-shard.sh --dry-run-list 2>/dev/null)
+ assigned=$(shard_assigned_list "$shard_idx")
if [ -z "$assigned" ]; then
echo "(assigned-file-list-underivable)"
return
@@ -618,12 +659,12 @@ for i in $(seq 1 "$N"); do
fi
TOTAL_RC=1
if [ "$shard_external_kill" = "1" ]; then
- SHARD="$i/$N" bash scripts/run-unit-shard.sh --dry-run-list 2>/dev/null >> "$OOM_RESCUE_LIST"
+ shard_assigned_list "$i" >> "$OOM_RESCUE_LIST"
echo "shard $i/$N: KILLED externally after ${s_elapsed}s (rc=$rc, well before ${SHARD_TIMEOUT}s cap — queued for serial rescue)" >> "$SUMMARY_FILE"
elif [ "$shard_oom" = "1" ]; then
# Wedged UNDER memory pressure: we can't attribute failures, so queue
# the shard's entire file list for the serial rescue pass.
- SHARD="$i/$N" bash scripts/run-unit-shard.sh --dry-run-list 2>/dev/null >> "$OOM_RESCUE_LIST"
+ shard_assigned_list "$i" >> "$OOM_RESCUE_LIST"
echo "shard $i/$N: WEDGED after ${SHARD_TIMEOUT}s (rc=$rc, OOM signature — queued for serial rescue)" >> "$SUMMARY_FILE"
else
NON_OOM_FAIL=1
@@ -646,10 +687,10 @@ for i in $(seq 1 "$N"); do
else
# OOM signature but no attributable files (e.g. bun died before any
# file header) → rescue the whole shard.
- SHARD="$i/$N" bash scripts/run-unit-shard.sh --dry-run-list 2>/dev/null >> "$OOM_RESCUE_LIST"
+ shard_assigned_list "$i" >> "$OOM_RESCUE_LIST"
fi
elif [ "$shard_external_kill" = "1" ]; then
- SHARD="$i/$N" bash scripts/run-unit-shard.sh --dry-run-list 2>/dev/null >> "$OOM_RESCUE_LIST"
+ shard_assigned_list "$i" >> "$OOM_RESCUE_LIST"
echo "shard $i/$N: KILLED externally after ${s_elapsed}s (rc=$rc — queued for serial rescue)" >> "$SUMMARY_FILE"
else
NON_OOM_FAIL=1
diff --git a/scripts/run-verify-parallel.sh b/scripts/run-verify-parallel.sh
index 072abcd71a..e8ade0f35b 100755
--- a/scripts/run-verify-parallel.sh
+++ b/scripts/run-verify-parallel.sh
@@ -1,12 +1,14 @@
#!/usr/bin/env bash
# scripts/run-verify-parallel.sh — parallel verify dispatcher.
#
-# Runs the 19+ verify checks (privacy, jsonb, source-id, … + typecheck +
+# Runs the verify checks (privacy, jsonb, source-id, … + typecheck +
# admin-build) as background jobs, waits for all, aggregates exit codes,
-# surfaces failed-check name + tail of its log to stderr.
+# surfaces failed-check name + tail of its log to stderr. The CHECKS array
+# below is the single source of truth for what runs (50+ checks; count it,
+# don't trust prose).
#
# Replaces the sequential `&&`-chain in package.json's `verify` script.
-# Wallclock: 19 sequential checks (~15-25s on CI) → parallel (~3-5s).
+# Wallclock: pool-bounded — the longest check (typecheck) dominates.
#
# Usage:
# bash scripts/run-verify-parallel.sh # run every CHECK below
@@ -63,12 +65,14 @@ CHECKS=(
# Boots its own PGLite — budget ≤60s under a saturated pool; if it breaches
# ~100s under contention, move it into the serial-tests CI job instead.
"check:eval-chronicle"
- # Retrieval canary: $0, hermetic, deterministic-embedder CLI run of the
- # qrels correctness gate. Boots two PGLite processes (seed + real CLI) —
- # budget ≤60s under a saturated pool; if it breaches ~100s under
- # contention, move it into the serial-tests CI job instead (same fallback
- # as eval-chronicle above).
- "check:eval-canary"
+ # check:eval-canary deliberately NOT here: test/eval-canary.test.ts spawns
+ # the identical scripts/run-eval-canary.ts in the unit matrix, and in CI the
+ # verify job and the matrix always run together (same workflow, same cache
+ # gate) — keeping it in verify was pure double work plus this battery's
+ # worst 120s-timeout flake exposure (two extra PGLite boots under a
+ # saturated pool). The package script `check:eval-canary` remains for
+ # on-demand runs; local `verify`-only callers lose the canary, local
+ # `bun run test` keeps it.
"check:bootstrap-templates"
"check:skill-brain-first"
"check:conversation-parser"
diff --git a/scripts/serial-weights.json b/scripts/serial-weights.json
new file mode 100644
index 0000000000..9787f8dbe2
--- /dev/null
+++ b/scripts/serial-weights.json
@@ -0,0 +1,222 @@
+{
+ "test/admin-embed-spawn.serial.test.ts": 30,
+ "test/advisor-backup-coverage.serial.test.ts": 1,
+ "test/agent-register-guards.serial.test.ts": 13,
+ "test/agent-scheduler-contract.serial.test.ts": 26,
+ "test/agent-voice-cors.serial.test.ts": 2,
+ "test/ai/header-transport.serial.test.ts": 0,
+ "test/ai/no-batch-cap-suppression.serial.test.ts": 1,
+ "test/ambient-recall-hooks.serial.test.ts": 1,
+ "test/apply-migrations-list-db-state.serial.test.ts": 1,
+ "test/apply-migrations-pglite-spawn.serial.test.ts": 30,
+ "test/audit-parser-probe.serial.test.ts": 0,
+ "test/audit-slug-fallback.serial.test.ts": 0,
+ "test/audit-synopsis.serial.test.ts": 0,
+ "test/audit/connection-audit.serial.test.ts": 0,
+ "test/autopilot-fanout-clamp.serial.test.ts": 2,
+ "test/backfill-concurrency-clamp.serial.test.ts": 0,
+ "test/backup-cli.serial.test.ts": 0,
+ "test/backup-coverage.serial.test.ts": 1,
+ "test/backup-invalidation.serial.test.ts": 2,
+ "test/backup-status-file.serial.test.ts": 0,
+ "test/binary-self-update-compiled.serial.test.ts": 0,
+ "test/bootstrap-dispatcher.serial.test.ts": 1,
+ "test/bootstrap-harness.serial.test.ts": 0,
+ "test/bootstrap-interview.serial.test.ts": 1,
+ "test/bootstrap-opencode-door.serial.test.ts": 2,
+ "test/bootstrap-plugin-lane.serial.test.ts": 1,
+ "test/bootstrap-status.serial.test.ts": 0,
+ "test/bootstrap-subcommand-help.serial.test.ts": 1,
+ "test/bootstrap-uninstall.serial.test.ts": 0,
+ "test/bootstrap-verify.serial.test.ts": 9,
+ "test/brain-allowlist.serial.test.ts": 2,
+ "test/brain-flag-routing.serial.test.ts": 13,
+ "test/brain-registry.serial.test.ts": 0,
+ "test/brainstorm/checkpoint.serial.test.ts": 1,
+ "test/check-update-refresh.serial.test.ts": 0,
+ "test/checkpoint-harvest.serial.test.ts": 5,
+ "test/cli-help-without-brain.serial.test.ts": 10,
+ "test/cli-util-prompt.serial.test.ts": 2,
+ "test/code-callers-pin.serial.test.ts": 3,
+ "test/config-db-plane.serial.test.ts": 1,
+ "test/config-set-unknown-flag.serial.test.ts": 34,
+ "test/connection-manager.serial.test.ts": 0,
+ "test/connectors-credentials.serial.test.ts": 1,
+ "test/context-engine-checkpoint.serial.test.ts": 0,
+ "test/contextual-retrieval-doctor.serial.test.ts": 2,
+ "test/contextual-synopsis-model.serial.test.ts": 0,
+ "test/core/audit-week-file.serial.test.ts": 0,
+ "test/core/cycle.serial.test.ts": 5,
+ "test/core/remediation-checkpoint.serial.test.ts": 0,
+ "test/creds-vault.serial.test.ts": 1,
+ "test/cross-modal-hybrid-integration.serial.test.ts": 4,
+ "test/cycle-lock-release-diagnostic.serial.test.ts": 1,
+ "test/cycle-lock-steal.serial.test.ts": 3,
+ "test/cycle-patterns-completed-outcome.serial.test.ts": 2,
+ "test/cycle-pglite-lock-ordering.serial.test.ts": 1,
+ "test/cycle-start-recovery-throw.serial.test.ts": 1,
+ "test/cycle/cycle-sync-uncommitted-warn.serial.test.ts": 2,
+ "test/db-repair.serial.test.ts": 0,
+ "test/dispatch-response-meta.serial.test.ts": 1,
+ "test/doctor-autopilot-fanout-concurrency.serial.test.ts": 0,
+ "test/doctor-backup-coverage.serial.test.ts": 0,
+ "test/doctor-cli-smoke.serial.test.ts": 10,
+ "test/doctor-connection-classified.serial.test.ts": 1,
+ "test/doctor-engine-fit.serial.test.ts": 0,
+ "test/doctor-no-migrate.serial.test.ts": 15,
+ "test/doctor-remote.serial.test.ts": 0,
+ "test/doctor-report-remote.serial.test.ts": 4,
+ "test/dream-owner-id-threading.serial.test.ts": 1,
+ "test/dream-postgres.serial.test.ts": 5,
+ "test/embed-backfill-cli-admission.serial.test.ts": 39,
+ "test/embed-exit-code-3037.serial.test.ts": 11,
+ "test/embed-input-type-wire.serial.test.ts": 0,
+ "test/embed-oversize-heal-drain.serial.test.ts": 3,
+ "test/embed-partial-failure-3037.serial.test.ts": 6,
+ "test/embed-quarantine.serial.test.ts": 0,
+ "test/embed-stale-chunkless-pages.serial.test.ts": 5,
+ "test/embed-stale.serial.test.ts": 6,
+ "test/embed.serial.test.ts": 10,
+ "test/embedding-truth-predicates.serial.test.ts": 5,
+ "test/eval-capture-db-plane.serial.test.ts": 1,
+ "test/eval-takes-quality-runner.serial.test.ts": 1,
+ "test/extract-cross-source-links-db.serial.test.ts": 2,
+ "test/extract-facts-embed-unavailable.serial.test.ts": 1,
+ "test/extract-facts-embed-warn.serial.test.ts": 1,
+ "test/facts-backstop-outcome.serial.test.ts": 3,
+ "test/facts-context-injection.serial.test.ts": 2,
+ "test/facts-mcp-allowlist.serial.test.ts": 2,
+ "test/facts-valid-from-context.serial.test.ts": 2,
+ "test/filing-rules-resolution.serial.test.ts": 1,
+ "test/foreground-chat-gateway-init.serial.test.ts": 1,
+ "test/friction-diff.serial.test.ts": 0,
+ "test/fts-language-cache-isolation.serial.test.ts": 1,
+ "test/fts-language-migration.serial.test.ts": 0,
+ "test/fts-language-schema-replay.serial.test.ts": 5,
+ "test/fts-language.serial.test.ts": 1,
+ "test/gateway-reconfigure-clobber.serial.test.ts": 0,
+ "test/git-remote-durable.serial.test.ts": 2,
+ "test/git-remote-pull-file-transport.serial.test.ts": 0,
+ "test/google-connect-cmd.serial.test.ts": 1,
+ "test/hook-backup-notice.serial.test.ts": 0,
+ "test/hook-command.serial.test.ts": 2,
+ "test/hybrid-cache-hit-limit-honors-mode.serial.test.ts": 3,
+ "test/hybrid-cache-scope-poison.serial.test.ts": 2,
+ "test/hybrid-cached-hit-budget-meta.serial.test.ts": 2,
+ "test/hybrid-degraded-cache-meta.serial.test.ts": 3,
+ "test/hybrid-exclude-private-cache-fold.serial.test.ts": 2,
+ "test/hybrid-meta.serial.test.ts": 2,
+ "test/hybrid-pool-floor.serial.test.ts": 2,
+ "test/hybrid-salvage.serial.test.ts": 2,
+ "test/hybrid-search-lite.serial.test.ts": 3,
+ "test/hybrid-since-relative.serial.test.ts": 2,
+ "test/hybrid-types-cache-skip.serial.test.ts": 3,
+ "test/import-configured-root-guard.serial.test.ts": 11,
+ "test/import-json-stdout.serial.test.ts": 11,
+ "test/import-signature-stamp.serial.test.ts": 3,
+ "test/import-source-cr-mode.serial.test.ts": 2,
+ "test/init-picker-pty.serial.test.ts": 9,
+ "test/jobs-autopilot-cycle-braindir.serial.test.ts": 2,
+ "test/jobs-embed-background-dryrun.serial.test.ts": 2,
+ "test/jobs-embed-background-parity.serial.test.ts": 6,
+ "test/jobs-embed-stall-wiring.serial.test.ts": 2,
+ "test/jobs-gateway-refresh.serial.test.ts": 1,
+ "test/jobs-list-get-json.serial.test.ts": 2,
+ "test/jobs-stats-backpressure.serial.test.ts": 1,
+ "test/jobs-stats-divergence.serial.test.ts": 2,
+ "test/jobs-stats-private-queue.serial.test.ts": 2,
+ "test/jobs-subcommand-help.serial.test.ts": 8,
+ "test/llm-intent-hybrid-integration.serial.test.ts": 3,
+ "test/loops-extract-run.serial.test.ts": 2,
+ "test/mcp-backup-nag.serial.test.ts": 1,
+ "test/migrate-embeddings-boundary.serial.test.ts": 6,
+ "test/migrate-embeddings-flow.serial.test.ts": 8,
+ "test/migrate-embeddings-hardening.serial.test.ts": 19,
+ "test/migrate-embeddings-op-contract.serial.test.ts": 7,
+ "test/migrate-engine-completeness.serial.test.ts": 13,
+ "test/migrate-engine-page-copy-failure.serial.test.ts": 17,
+ "test/migrate-quiet-replay.serial.test.ts": 7,
+ "test/migration-in-process.serial.test.ts": 10,
+ "test/migration-orchestrator-v0_46_3.serial.test.ts": 7,
+ "test/migration-v0-29-1.serial.test.ts": 7,
+ "test/model-config.serial.test.ts": 1,
+ "test/models-per-task-extract-atoms.serial.test.ts": 0,
+ "test/models-probe-max-output-tokens.serial.test.ts": 8,
+ "test/native-base-url-fold.serial.test.ts": 0,
+ "test/openai-latest.serial.test.ts": 0,
+ "test/ops-run-onboard-scope-gate.serial.test.ts": 1,
+ "test/page-summary-length.serial.test.ts": 1,
+ "test/pglite-disconnect-watchdog.serial.test.ts": 21,
+ "test/pglite-engine-disconnect.serial.test.ts": 34,
+ "test/pglite-hoisted-install.serial.test.ts": 1,
+ "test/pglite-reconnect.serial.test.ts": 4,
+ "test/pglite-repair-command.serial.test.ts": 4,
+ "test/pglite-snapshot-timezone.serial.test.ts": 6,
+ "test/pglite-wal-repair.serial.test.ts": 14,
+ "test/process-watchdog.serial.test.ts": 4,
+ "test/provider-sunset-doctor.serial.test.ts": 6,
+ "test/put-page-push-reporting.serial.test.ts": 2,
+ "test/query-cache-knobs-hash.serial.test.ts": 2,
+ "test/query-image-flag.serial.test.ts": 2,
+ "test/query-op-limit-mode-4356.serial.test.ts": 0,
+ "test/reconcile-links.serial.test.ts": 1,
+ "test/reindex-code-max-cost.serial.test.ts": 1,
+ "test/reindex-code-model-source.serial.test.ts": 2,
+ "test/reindex-code-nudge.serial.test.ts": 1,
+ "test/reindex-frontmatter-pglite-spawn.serial.test.ts": 12,
+ "test/reindex-search-vector.serial.test.ts": 0,
+ "test/remediation-run-extras.serial.test.ts": 2,
+ "test/remediation-run-loop.serial.test.ts": 1,
+ "test/rerank-sunset-short-circuit.serial.test.ts": 0,
+ "test/schema-cli-database-path.serial.test.ts": 7,
+ "test/schema-pack-find-pack-successors.serial.test.ts": 0,
+ "test/schema-pack-load-active.serial.test.ts": 1,
+ "test/search-multimodal-no-embed.serial.test.ts": 2,
+ "test/search-telemetry-cache-wiring.serial.test.ts": 2,
+ "test/search-telemetry-disconnect-hang.serial.test.ts": 6,
+ "test/search/autocut-integration.serial.test.ts": 3,
+ "test/search/embedding-column.serial.test.ts": 0,
+ "test/search/hybrid-reranker-integration.serial.test.ts": 3,
+ "test/seed-pglite.serial.test.ts": 13,
+ "test/self-upgrade-checkonly.serial.test.ts": 0,
+ "test/serve-source-guard.serial.test.ts": 0,
+ "test/serve-sync-ipc-killswitch.serial.test.ts": 10,
+ "test/serve-sync-runner.serial.test.ts": 6,
+ "test/skillopt/adversarial/concurrent-runs.serial.test.ts": 3,
+ "test/skillopt/cycle-phase-caps.serial.test.ts": 3,
+ "test/skillopt/run-skillopt-op.serial.test.ts": 3,
+ "test/sources-push-cli.serial.test.ts": 2,
+ "test/stdio-stderr-redirect.serial.test.ts": 0,
+ "test/sync-cost-gate.serial.test.ts": 15,
+ "test/sync-deferred-extract-queue.serial.test.ts": 16,
+ "test/sync-delete-trailing-hyphen.serial.test.ts": 6,
+ "test/sync-failure-ledger.serial.test.ts": 0,
+ "test/sync-inline-extract-stamps.serial.test.ts": 4,
+ "test/sync-malformed-path.serial.test.ts": 3,
+ "test/sync-metafile-skip.serial.test.ts": 3,
+ "test/sync-ops-pages.serial.test.ts": 3,
+ "test/sync-pull-failed-anchor.serial.test.ts": 4,
+ "test/sync-reconcile-db-only.serial.test.ts": 2,
+ "test/sync-rename-reconcile.serial.test.ts": 25,
+ "test/sync-resumable-import.serial.test.ts": 6,
+ "test/sync-soft-delete.serial.test.ts": 7,
+ "test/takes-fence-read-ops.serial.test.ts": 1,
+ "test/takes-mcp-allowlist.serial.test.ts": 2,
+ "test/think-cli-source-flag.serial.test.ts": 1,
+ "test/think-extractive.serial.test.ts": 5,
+ "test/think-pipeline.serial.test.ts": 3,
+ "test/think-temporal-window.serial.test.ts": 1,
+ "test/unified-multimodal.serial.test.ts": 2,
+ "test/upgrade-checkpoint.serial.test.ts": 0,
+ "test/upgrade.serial.test.ts": 3,
+ "test/v0_37_fix_wave.serial.test.ts": 0,
+ "test/v0_37_gap_fill.serial.test.ts": 6,
+ "test/watch-sigint.serial.test.ts": 6,
+ "test/worker-lock-renewal-e2e.serial.test.ts": 10,
+ "test/worker-registry.serial.test.ts": 0,
+ "test/workspace-push.serial.test.ts": 5,
+ "test/write-through-commit.serial.test.ts": 2,
+ "test/autopilot-launchd-lifecycle.serial.test.ts": 12,
+ "test/brain-durability-hook.serial.test.ts": 5,
+ "test/brain-repo-durability.serial.test.ts": 4
+}
diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsv
index 79c22c4d2a..c174a000b9 100644
--- a/scripts/structural-suites.tsv
+++ b/scripts/structural-suites.tsv
@@ -124,10 +124,10 @@ test/e2e/openclaw-reference-compat.test.ts OpenClaw reference workspace compat (
test/e2e/skillpack-flow.test.ts skillpack flow (E2E) 17 readFileSync
test/e2e/workspace-generic-compat.test.ts generic agent-workspace compat (INSTALL_FOR_AGENTS.md flow) 6 readFileSync
test/embedding-dim-check-facts.test.ts doctor checkFactsEmbeddingWidthConsistency wiring (T6) 4 doctor-source-helper
-test/eval-brainbench-e2e.test.ts --llm availability gate 1 exec-scan
-test/eval-brainbench-e2e.test.ts privacy guard violation branches (negative path) 1 exec-scan
-test/eval-brainbench-e2e.test.ts render-brainbench-delta.ts (the CI step-summary block) 2 exec-scan
-test/eval-brainbench-e2e.test.ts run-all once-per-sweep semantics (decision 16) 1 exec-scan
+test/eval-brainbench-e2e.slow.test.ts --llm availability gate 1 exec-scan
+test/eval-brainbench-e2e.slow.test.ts privacy guard violation branches (negative path) 1 exec-scan
+test/eval-brainbench-e2e.slow.test.ts render-brainbench-delta.ts (the CI step-summary block) 2 exec-scan
+test/eval-brainbench-e2e.slow.test.ts run-all once-per-sweep semantics (decision 16) 1 exec-scan
test/eval-capture-db-plane.serial.test.ts eval.capture set on the DB plane reaches the runtime gate (#1475) 9 bun-file
test/eval-synthesize-concepts-routing.test.ts dispatch-layer source pins (routing can’t regress silently) 2 readFileSync
test/eval-synthesize-concepts-routing.test.ts subprocess smoke — end-to-end routing 1 readFileSync
diff --git a/scripts/test-shard.sh b/scripts/test-shard.sh
index fb06d0d433..d083fabb21 100755
--- a/scripts/test-shard.sh
+++ b/scripts/test-shard.sh
@@ -73,7 +73,10 @@ cd "$(dirname "$0")/.."
# Removing both heavy atoms from matrix-eligible files keeps the per-shard
# total bounded. With 10 matrix shards the per-shard total drops to ~272s.
# Dedicated jobs run in parallel so total CI wallclock = max(matrix ~4.5min,
-# slow-eval ~3.3min, slow-entity-resolve-perf ~2.6min) ≈ 4.5min.
+# slow-eval ~3.3min, slow-entity-resolve-perf ~2.6min, slow-brainbench ~1.5min)
+# ≈ 4.5min. eval-brainbench-e2e was the matrix's heaviest atom (98s mined —
+# 10% of the whole corpus weight) and capped shard-count scaling; it now rides
+# its own job like the other two outliers.
# evals/ is included: its *.test.ts files (eval-harness unit tests) were
# previously collected by NO runner — 45+ real tests never executed anywhere.
# Every collected evals file must be KEYLESS (no API keys, no network) —
@@ -84,6 +87,7 @@ ALL_FILES=$(find test evals -name '*.test.ts' \
-not -name '*.serial.test.ts' \
-not -name 'eval-longmemeval-e2e.slow.test.ts' \
-not -name 'entity-resolve-perf.slow.test.ts' \
+ -not -name 'eval-brainbench-e2e.slow.test.ts' \
-not -path 'test/e2e/*' | sort)
if [ -z "$ALL_FILES" ]; then
diff --git a/scripts/test-weights.json b/scripts/test-weights.json
index 6815bc4d26..857a1f0cae 100644
--- a/scripts/test-weights.json
+++ b/scripts/test-weights.json
@@ -185,7 +185,7 @@
"test/cli-args.test.ts": 19,
"test/cli-bigint-normalize.test.ts": 16,
"test/cli-concept-nudge.test.ts": 1,
- "test/cli-dispatch-thin-client.test.ts": 11281,
+ "test/cli-dispatch-thin-client.test.ts": 9327,
"test/cli-dream-engine-warn.test.ts": 4153,
"test/cli-empty-retrieval-render.test.ts": 3,
"test/cli-exit-verdict-pin.test.ts": 30,
@@ -194,7 +194,7 @@
"test/cli-force-exit-teardown-arming.test.ts": 2,
"test/cli-format-search-json.test.ts": 9,
"test/cli-format-volunteer.test.ts": 13,
- "test/cli-help-discoverability.test.ts": 7141,
+ "test/cli-help-discoverability.test.ts": 4492,
"test/cli-multimodal-integration.test.ts": 441,
"test/cli-options.test.ts": 2858,
"test/cli-pipe-truncation.test.ts": 1118,
@@ -339,7 +339,7 @@
"test/doctor-home-dir-in-worktree.test.ts": 425,
"test/doctor-image-assets-wsl.test.ts": 1800,
"test/doctor-links-extraction-lag.test.ts": 1717,
- "test/doctor-minions-check.test.ts": 6100,
+ "test/doctor-minions-check.test.ts": 2062,
"test/doctor-orphan-ratio.test.ts": 4731,
"test/doctor-parser-probe-check.test.ts": 6,
"test/doctor-pglite-datadir.test.ts": 13,
@@ -367,7 +367,7 @@
"test/domain-aggregators.test.ts": 1710,
"test/dream-cli-flags.test.ts": 40,
"test/dream-dir-source-stamp.test.ts": 1152,
- "test/dream.test.ts": 11043,
+ "test/dream.test.ts": 4561,
"test/drift-watch.test.ts": 16,
"test/dry-fix.test.ts": 220,
"test/durability-cron.test.ts": 15,
@@ -408,8 +408,7 @@
"test/envelope-to-gbrain.test.ts": 3234,
"test/error-classify.test.ts": 25,
"test/errors.test.ts": 4,
- "test/eval-brainbench-e2e.test.ts": 98338,
- "test/eval-canary.test.ts": 7906,
+ "test/eval-canary.test.ts": 6393,
"test/eval-candidates.test.ts": 379,
"test/eval-capture-drain.test.ts": 153,
"test/eval-capture-scrub.test.ts": 31,
@@ -542,7 +541,7 @@
"test/founder-scorecard.test.ts": 6,
"test/friction-cli.test.ts": 16,
"test/friction.test.ts": 24,
- "test/frontmatter-cli.test.ts": 6340,
+ "test/frontmatter-cli.test.ts": 1388,
"test/frontmatter-inference.test.ts": 7,
"test/frontmatter-install-hook.test.ts": 46,
"test/frontmatter-non-string-fields.test.ts": 5,
@@ -606,7 +605,7 @@
"test/init-embed-check.test.ts": 8,
"test/init-env-detection.test.ts": 19,
"test/init-mcp-only.test.ts": 5864,
- "test/init-migrate-only.test.ts": 10700,
+ "test/init-migrate-only.test.ts": 6014,
"test/init-mode-picker.test.ts": 2058,
"test/init-nudge.test.ts": 5,
"test/init-provider-picker.test.ts": 13,
@@ -671,7 +670,7 @@
"test/migrate-stdout-clean.test.ts": 405,
"test/migrate.test.ts": 6385,
"test/migration-orchestrator-v0_21_0.test.ts": 5,
- "test/migration-orchestrator-v0_31_0.test.ts": 9369,
+ "test/migration-orchestrator-v0_31_0.test.ts": 1117,
"test/migration-resume.test.ts": 18,
"test/migration-v120.test.ts": 338,
"test/migrations-cjk-wave.test.ts": 350,
@@ -700,7 +699,7 @@
"test/minions-shell-redact.test.ts": 2,
"test/minions-shell-validate.test.ts": 34,
"test/minions-shell.test.ts": 477,
- "test/minions.test.ts": 14101,
+ "test/minions.test.ts": 8214,
"test/minions/agent-audit.test.ts": 9,
"test/mode-switch-ux.test.ts": 800,
"test/model-id.test.ts": 5,
@@ -748,7 +747,7 @@
"test/page-lock.test.ts": 262,
"test/page-search-vector-overflow.test.ts": 3152,
"test/page-type-exhaustive.test.ts": 9,
- "test/pages-soft-delete.test.ts": 8483,
+ "test/pages-soft-delete.test.ts": 1209,
"test/parallel.test.ts": 122,
"test/parent-scope.test.ts": 443,
"test/parity.test.ts": 9,
@@ -864,7 +863,7 @@
"test/scenarios.test.ts": 14,
"test/schema-bootstrap-coverage.test.ts": 4794,
"test/schema-cli-contract.test.ts": 4,
- "test/schema-cli.test.ts": 8009,
+ "test/schema-cli.test.ts": 5370,
"test/schema-migrate-link-source-mentions.test.ts": 443,
"test/schema-pack-best-effort.test.ts": 8,
"test/schema-pack-expand-type-filter.test.ts": 3,
@@ -993,7 +992,7 @@
"test/skillpack-bootstrap-display.test.ts": 4,
"test/skillpack-brain-resident-locate.test.ts": 27,
"test/skillpack-changed-since-version.test.ts": 228,
- "test/skillpack-check.test.ts": 8908,
+ "test/skillpack-check.test.ts": 4258,
"test/skillpack-copy.test.ts": 12,
"test/skillpack-endorse.test.ts": 95,
"test/skillpack-frontmatter-sources.test.ts": 8,
@@ -1038,7 +1037,7 @@
"test/sources-archive-idempotent.test.ts": 1872,
"test/sources-load.test.ts": 2785,
"test/sources-mcp.test.ts": 3022,
- "test/sources-ops.test.ts": 7017,
+ "test/sources-ops.test.ts": 7879,
"test/sources-resync-recovery.test.ts": 3664,
"test/sources-set-cr-mode.test.ts": 1632,
"test/sources-webhook.test.ts": 19,
@@ -1198,5 +1197,6 @@
"test/yaml-lite.test.ts": 3,
"test/ze-switch-cli.test.ts": 2793,
"test/ze-switch-env-override.test.ts": 2567,
- "test/zombie-reap.test.ts": 6
-}
\ No newline at end of file
+ "test/zombie-reap.test.ts": 6,
+ "test/eval-brainbench-e2e.slow.test.ts": 57548
+}
diff --git a/templates/bootstrap/template-repo/README.md b/templates/bootstrap/template-repo/README.md
index eeefab6780..36d6dae125 100644
--- a/templates/bootstrap/template-repo/README.md
+++ b/templates/bootstrap/template-repo/README.md
@@ -1,6 +1,6 @@
# gbrain agent workspace — template
-<!-- gbrain-template-stamp: 0.47.6.0 -->
+<!-- gbrain-template-stamp: 0.47.7.0 -->
This repository is the **"Use this template"** distribution artifact for a
[gbrain](https://github.com/garrytan/gbrain) personal-agent workspace — the same
diff --git a/test/ambient-recall.test.ts b/test/ambient-recall.test.ts
index a8bce3113f..af71e050c9 100644
--- a/test/ambient-recall.test.ts
+++ b/test/ambient-recall.test.ts
@@ -16,7 +16,7 @@
*/
import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
-import { configureGateway } from '../src/core/ai/gateway.ts';
+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';
import { operations } from '../src/core/operations.ts';
import { MEMORY_VERBS_VERSION, VERB_NAMES } from '../src/core/verbs.ts';
import {
@@ -79,6 +79,10 @@ beforeAll(async () => {
afterAll(async () => {
await engine.disconnect();
+ // Restore the preload baseline — leaving the keyless config in place
+ // configures every LATER file in this shard's process (the exact
+ // leak-to-neighbor class the beforeAll pin defends against).
+ resetGateway();
});
beforeEach(async () => {
diff --git a/test/bootstrap-atomic-write.test.ts b/test/bootstrap-atomic-write.test.ts
index 9e090df5f4..0733dd4a79 100644
--- a/test/bootstrap-atomic-write.test.ts
+++ b/test/bootstrap-atomic-write.test.ts
@@ -27,6 +27,7 @@ import {
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { atomicWriteTextFile } from '../src/core/bootstrap/atomic-write.ts';
+import { permsEnforced } from './helpers/fs-perms.ts';
let dir: string;
beforeEach(() => {
@@ -123,7 +124,9 @@ describe('atomicWriteTextFile — failure hygiene (no tmp litter)', () => {
expect(lstatSync(target).isDirectory()).toBe(true); // target untouched
});
- test('a failing write in a read-only dir throws without leaving litter behind', () => {
+ // skipIf: asserts a write MUST fail on a 0555 dir — unrunnable on hosts
+ // that don't enforce permission bits (FUSE/overlay sandboxes, root).
+ test.skipIf(!permsEnforced())('a failing write in a read-only dir throws without leaving litter behind', () => {
if (process.getuid?.() === 0) return; // root ignores modes
const ro = join(dir, 'ro');
mkdirSync(ro, { recursive: true });
diff --git a/test/bootstrap-uninstall.serial.test.ts b/test/bootstrap-uninstall.serial.test.ts
index 1c4ab92a6c..1d72aff870 100644
--- a/test/bootstrap-uninstall.serial.test.ts
+++ b/test/bootstrap-uninstall.serial.test.ts
@@ -10,6 +10,7 @@
import { describe, test, expect, beforeEach, afterEach } from 'bun:test';
import { chmodSync, existsSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
+import { permsEnforced } from './helpers/fs-perms.ts';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import {
@@ -162,7 +163,9 @@ describe('uninstallWorkspace', () => {
expect(existsSync(hooksDir)).toBe(false); // created_paths still removed
});
- test('deleteBrain rm FAILURE: brain_deleted false, failure reason surfaced, receipt + telemetry kept (retry possible)', async () => {
+ // skipIf: simulates rm failure via permission bits — unrunnable on hosts
+ // that don't enforce them (FUSE/overlay sandboxes, root).
+ test.skipIf(!permsEnforced())('deleteBrain rm FAILURE: brain_deleted false, failure reason surfaced, receipt + telemetry kept (retry possible)', async () => {
if (typeof process.getuid === 'function' && process.getuid() === 0) return; // root ignores modes
seedHome({ brain_created_by_bootstrap: true });
// A read-only subdir makes rmSync fail mid-removal (EACCES unlinking inside).
diff --git a/test/brain-durability-hook.serial.test.ts b/test/brain-durability-hook.serial.test.ts
index 99ef13feea..17dc187cbc 100644
--- a/test/brain-durability-hook.serial.test.ts
+++ b/test/brain-durability-hook.serial.test.ts
@@ -10,6 +10,7 @@ import { join } from 'path';
import { tmpdir } from 'os';
import { execFileSync } from 'child_process';
import { hardenBrainRepo, unhardenBrainRepo } from '../src/core/brain-repo-durability.ts';
+import { crontabAvailable } from './helpers/fs-perms.ts';
import { runPull } from '../src/commands/sources-harden.ts';
// #2943 root cause: `env: process.env` is REQUIRED here. Bun snapshots
@@ -209,7 +210,10 @@ describe('post-commit hook (D9 local, D7 self-contained)', () => {
// then invokes that exact command to prove it performs a real pull. It always
// unregisters the launchd/cron job afterward so no scheduled job survives.
describe('durability schedule (installCron:true) [D2/D12]', () => {
- test('registers the DB-free pull job with the right command + interval, and the job performs a real pull', async () => {
+ // skipIf: needs a real crontab/launchctl to register against — on hosts
+ // without one (some sandboxes) hardenBrainRepo correctly degrades the cron
+ // step to 'skipped', which is the product working, not this arc.
+ test.skipIf(!crontabAvailable() && process.platform !== 'darwin')('registers the DB-free pull job with the right command + interval, and the job performs a real pull', async () => {
const sourceId = 'wiki';
const report = await hardenBrainRepo({
repoPath: work, sourceId, pat: 'ghp_x', installCron: true, intervalSec: 900, verify: false,
diff --git a/test/cli-dispatch-thin-client.test.ts b/test/cli-dispatch-thin-client.test.ts
index 11d6fef57c..bbf8b9bac8 100644
--- a/test/cli-dispatch-thin-client.test.ts
+++ b/test/cli-dispatch-thin-client.test.ts
@@ -9,33 +9,49 @@
* Doctor is NOT in the refused set — it routes to runRemoteDoctor instead.
*
* Strategy: seed `~/.gbrain/config.json` with remote_mcp set in a tempdir
- * `GBRAIN_HOME`, then spawn `gbrain <cmd>` and assert (a) exit code 1,
- * (b) stderr contains the canonical error message, (c) the local engine
- * was never reached. Async Bun.spawn (NOT execFileSync) so the test event
- * loop stays responsive — see init-mcp-only.test.ts for the rationale.
+ * home, then spawn `gbrain <cmd>` via test/helpers/cli-spawn.ts (async
+ * Bun.spawn — NOT execFileSync — so the test event loop stays responsive;
+ * DATABASE_URL / GBRAIN_DATABASE_URL always stripped, HOME + GBRAIN_HOME
+ * pinned to the temp home) and assert (a) exit code 1, (b) stderr contains
+ * the canonical error message, (c) the local engine was never reached.
+ * GBRAIN_REMOTE_CLIENT_SECRET is stripped per-call — the helper doesn't do
+ * it and an ambient secret would alter thin-client auth routing.
+ *
+ * The 9 refusedCommands spawns run ONCE through runCliBatch (width 2 — the
+ * machine-wide cap, see cli-spawn.ts) in the describe's beforeAll against a
+ * single seeded thin-client home; the loop's tests assert on the cached
+ * results. Sharing the home is safe because refusal happens at the dispatch
+ * guard before any engine/filesystem work (that IS the invariant under
+ * test), the seeded engine is `postgres` with no database_url (no scratch
+ * store possible even under regression), and the loop asserts only on exit
+ * code + stderr. Everything else still spawns its own child against a fresh
+ * per-test home (dispatch wiring coverage).
*
* Includes a regression test that local-config installs still pass through
* to connectEngine normally.
*/
-import { describe, test as testRaw, expect, beforeEach, afterEach } from 'bun:test';
-import { mkdtempSync, rmSync, writeFileSync, mkdirSync } from 'fs';
+import { describe, test as testRaw, expect, beforeAll, afterAll, beforeEach, afterEach } from 'bun:test';
+import { mkdtempSync, rmSync, writeFileSync, mkdirSync, existsSync } from 'fs';
import { join } from 'path';
import { tmpdir } from 'os';
+import { runCli, runCliBatch, type CliResult } from './helpers/cli-spawn.ts';
function test(name: string, fn: () => void | Promise<unknown>): void {
testRaw(name, fn, 30000);
}
-const CLI = join(__dirname, '..', 'src', 'cli.ts');
+// The original hand-rolled spawner stripped this alongside the database
+// URLs; cli-spawn.ts strips only the URLs, so keep stripping it here.
+const HERMETIC_ENV = { GBRAIN_REMOTE_CLIENT_SECRET: undefined } as const;
let tmp: string;
-function configPath(): string { return join(tmp, '.gbrain', 'config.json'); }
+function configPath(home: string): string { return join(home, '.gbrain', 'config.json'); }
-function seedThinClientConfig(extra: Record<string, unknown> = {}) {
- mkdirSync(join(tmp, '.gbrain'), { recursive: true });
- writeFileSync(configPath(), JSON.stringify({
+function seedThinClientConfig(home: string, extra: Record<string, unknown> = {}) {
+ mkdirSync(join(home, '.gbrain'), { recursive: true });
+ writeFileSync(configPath(home), JSON.stringify({
engine: 'postgres',
remote_mcp: {
issuer_url: 'https://brain-host.example',
@@ -47,48 +63,30 @@ function seedThinClientConfig(extra: Record<string, unknown> = {}) {
}, null, 2));
}
-function seedLocalPGLiteConfig() {
- mkdirSync(join(tmp, '.gbrain'), { recursive: true });
- writeFileSync(configPath(), JSON.stringify({
+function seedLocalPGLiteConfig(home: string) {
+ mkdirSync(join(home, '.gbrain'), { recursive: true });
+ writeFileSync(configPath(home), JSON.stringify({
engine: 'pglite',
- database_path: join(tmp, 'brain.pglite'),
+ database_path: join(home, 'brain.pglite'),
}, null, 2));
}
-interface RunResult { exitCode: number; stdout: string; stderr: string; }
+async function run(args: string[]): Promise<CliResult> {
+ return runCli(args, { home: tmp, env: HERMETIC_ENV });
+}
-async function run(args: string[]): Promise<RunResult> {
- const env: Record<string, string> = {};
- for (const [k, v] of Object.entries(process.env)) {
- if (v !== undefined) env[k] = v;
- }
- env.GBRAIN_HOME = tmp;
- delete env.DATABASE_URL;
- delete env.GBRAIN_DATABASE_URL;
- delete env.GBRAIN_REMOTE_CLIENT_SECRET;
- const proc = Bun.spawn({
- cmd: ['bun', 'run', CLI, ...args],
- env,
- stdin: 'ignore',
- stdout: 'pipe',
- stderr: 'pipe',
+// Fresh-home hooks for describes whose tests still spawn their own child.
+// Registered per-describe (not module-level) so the batched refusal tests
+// don't mint homes they never use.
+function useFreshHome(): void {
+ beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), 'gbrain-cli-dispatch-'));
+ });
+ afterEach(() => {
+ try { rmSync(tmp, { recursive: true, force: true }); } catch { /* best-effort */ }
});
- const [stdout, stderr, exitCode] = await Promise.all([
- new Response(proc.stdout).text(),
- new Response(proc.stderr).text(),
- proc.exited,
- ]);
- return { exitCode, stdout, stderr };
}
-beforeEach(() => {
- tmp = mkdtempSync(join(tmpdir(), 'gbrain-cli-dispatch-'));
-});
-
-afterEach(() => {
- try { rmSync(tmp, { recursive: true, force: true }); } catch { /* best-effort */ }
-});
-
describe('thin-client dispatch guard refuses DB-bound commands', () => {
// Each command in the refused set MUST exit 1 with a canonical error and
// MUST NOT attempt to connect to a local engine.
@@ -106,10 +104,32 @@ describe('thin-client dispatch guard refuses DB-bound commands', () => {
['serve'],
];
+ // One shared seeded home for the batch (see file header for why sharing
+ // is safe). Do NOT add anything here that writes to the home or depends
+ // on another row's side effects — batch order is not execution order.
+ let batchHome: string;
+ const refused = new Map<string, CliResult>();
+
+ beforeAll(async () => {
+ batchHome = mkdtempSync(join(tmpdir(), 'gbrain-cli-dispatch-refuse-'));
+ seedThinClientConfig(batchHome);
+ const results = await runCliBatch(refusedCommands, { home: batchHome, env: HERMETIC_ENV });
+ refusedCommands.forEach((argv, i) => refused.set(argv.join(' '), results[i]));
+ }, 120_000);
+
+ afterAll(() => {
+ try { rmSync(batchHome, { recursive: true, force: true }); } catch { /* best-effort */ }
+ });
+
+ function cached(argv: string[]): CliResult {
+ const r = refused.get(argv.join(' '));
+ if (!r) throw new Error(`not in refusedCommands batch: gbrain ${argv.join(' ')}`);
+ return r;
+ }
+
for (const args of refusedCommands) {
- test(`refuses \`gbrain ${args.join(' ')}\` with pinpoint hint`, async () => {
- seedThinClientConfig();
- const r = await run(args);
+ test(`refuses \`gbrain ${args.join(' ')}\` with pinpoint hint`, () => {
+ const r = cached(args);
expect(r.exitCode).toBe(1);
// v0.31.1 (Issue #734): refusal carries an actionable hint via
// THIN_CLIENT_REFUSE_HINTS instead of a generic "run on the remote
@@ -122,11 +142,13 @@ describe('thin-client dispatch guard refuses DB-bound commands', () => {
});
describe('thin-client dispatch guard does NOT refuse safe commands', () => {
+ useFreshHome();
+
// Commands that are still useful in thin-client mode (init, auth, version,
// help) MUST NOT be refused. We assert the canonical thin-client error
// does NOT appear.
test('`gbrain --version` works on thin-client install', async () => {
- seedThinClientConfig();
+ seedThinClientConfig(tmp);
const r = await run(['--version']);
expect(r.exitCode).toBe(0);
expect(r.stdout).toContain('gbrain');
@@ -134,7 +156,7 @@ describe('thin-client dispatch guard does NOT refuse safe commands', () => {
});
test('`gbrain --help` works on thin-client install', async () => {
- seedThinClientConfig();
+ seedThinClientConfig(tmp);
const r = await run(['--help']);
expect(r.exitCode).toBe(0);
expect(r.stderr).not.toContain('requires a local engine');
@@ -142,8 +164,10 @@ describe('thin-client dispatch guard does NOT refuse safe commands', () => {
});
describe('thin-client doctor routes to runRemoteDoctor', () => {
+ useFreshHome();
+
test('`gbrain doctor` runs remote checks (not DB-bound checks) when remote_mcp is set', async () => {
- seedThinClientConfig();
+ seedThinClientConfig(tmp);
const r = await run(['doctor', '--json']);
// Doctor will likely fail because brain-host.example isn't reachable —
// but that's irrelevant. What matters is it ran the THIN-CLIENT doctor,
@@ -156,19 +180,21 @@ describe('thin-client doctor routes to runRemoteDoctor', () => {
});
describe('regression — local config still passes through normally', () => {
+ useFreshHome();
+
test('local PGLite config does NOT trigger thin-client guard for `sync`', async () => {
// Seed a local PGLite config (no remote_mcp). `gbrain sync` shouldn't
// refuse with the thin-client error. It may error for other reasons
// (no brain repo configured, etc.) — what matters is the canonical
// thin-client message MUST NOT appear.
- seedLocalPGLiteConfig();
+ seedLocalPGLiteConfig(tmp);
const r = await run(['sync', '--dry-run']);
expect(r.stderr).not.toContain('thin client');
expect(r.stderr).not.toContain('requires a local engine');
});
test('local PGLite config does NOT trigger guard for `doctor`', async () => {
- seedLocalPGLiteConfig();
+ seedLocalPGLiteConfig(tmp);
const r = await run(['doctor', '--fast', '--json']);
// Local doctor's output has different fingerprint — no `mode: thin-client`.
expect(r.stdout).not.toContain('"mode":"thin-client"');
@@ -176,8 +202,10 @@ describe('regression — local config still passes through normally', () => {
});
describe('thin-client scratch-DB guard — jobs partial dispatch + config refusal', () => {
+ useFreshHome();
+
test('`gbrain config set x y` is refused with pinpoint hint', async () => {
- seedThinClientConfig();
+ seedThinClientConfig(tmp);
const r = await run(['config', 'set', 'search.reranker.enabled', 'false']);
expect(r.exitCode).toBe(1);
expect(r.stderr).toContain('gbrain config');
@@ -186,7 +214,7 @@ describe('thin-client scratch-DB guard — jobs partial dispatch + config refusa
});
test('`gbrain jobs work` is refused with pinpoint hint (host-queue-bound)', async () => {
- seedThinClientConfig();
+ seedThinClientConfig(tmp);
const r = await run(['jobs', 'work']);
expect(r.exitCode).toBe(1);
expect(r.stderr).toContain('gbrain jobs');
@@ -202,9 +230,8 @@ describe('thin-client scratch-DB guard — jobs partial dispatch + config refusa
// ("Schema version 1 → N") on every invocation. The remote call to
// brain-host.example will fail (unreachable) — irrelevant here. What
// matters: no local store is created and no migration replay runs.
- seedThinClientConfig({ engine: 'pglite' });
+ seedThinClientConfig(tmp, { engine: 'pglite' });
const r = await run(['jobs', 'get', '999']);
- const { existsSync } = await import('fs');
expect(existsSync(join(tmp, '.gbrain', 'brain.pglite'))).toBe(false);
expect(r.stdout + r.stderr).not.toContain('Schema version');
expect(r.stdout + r.stderr).not.toContain('migration(s) pending');
@@ -214,9 +241,8 @@ describe('thin-client scratch-DB guard — jobs partial dispatch + config refusa
});
test('`gbrain jobs list` never fabricates a scratch local engine', async () => {
- seedThinClientConfig({ engine: 'pglite' });
+ seedThinClientConfig(tmp, { engine: 'pglite' });
const r = await run(['jobs', 'list']);
- const { existsSync } = await import('fs');
expect(existsSync(join(tmp, '.gbrain', 'brain.pglite'))).toBe(false);
expect(r.stdout + r.stderr).not.toContain('Schema version');
expect(r.stdout + r.stderr).not.toContain('Setting up brain schema');
@@ -225,9 +251,8 @@ describe('thin-client scratch-DB guard — jobs partial dispatch + config refusa
test('`gbrain think` never fabricates a scratch local engine', async () => {
// Same class as jobs get: pglite-keyed thin client must not open a
// scratch store / replay migrations before the remote think call.
- seedThinClientConfig({ engine: 'pglite' });
+ seedThinClientConfig(tmp, { engine: 'pglite' });
const r = await run(['think', 'What do we know?']);
- const { existsSync } = await import('fs');
expect(existsSync(join(tmp, '.gbrain', 'brain.pglite'))).toBe(false);
expect(r.stdout + r.stderr).not.toContain('Schema version');
expect(r.stdout + r.stderr).not.toContain('Setting up brain schema');
@@ -239,7 +264,7 @@ describe('thin-client scratch-DB guard — jobs partial dispatch + config refusa
// Today's connectEngine() throws `database_url is missing` before
// runThinkCli's isThinClient branch. Remote call to brain-host.example
// will fail (unreachable) — irrelevant. Pin that connectEngine did not run.
- seedThinClientConfig({ engine: 'postgres' });
+ seedThinClientConfig(tmp, { engine: 'postgres' });
const r = await run(['think', 'What do we know?']);
expect(r.stdout + r.stderr).not.toContain('database_url is missing');
expect(r.stdout + r.stderr).not.toContain('No brain configured');
diff --git a/test/cli-help-discoverability.test.ts b/test/cli-help-discoverability.test.ts
index 75cdcd9cbb..d3ef0de9ee 100644
--- a/test/cli-help-discoverability.test.ts
+++ b/test/cli-help-discoverability.test.ts
@@ -10,52 +10,40 @@
* WARN-6: `capture`, `brainstorm`, `lsd` were missing from the main
* `gbrain --help` text. Added a BRAIN section to printHelp.
*
- * These tests spawn `bun run src/cli.ts` as a subprocess so they
- * exercise the real dispatcher flow end-to-end (no mocking of
- * cli.ts internals).
+ * These tests spawn `bun src/cli.ts` as a subprocess so they exercise
+ * the real dispatcher flow end-to-end (no mocking of cli.ts internals).
+ * Help output is read-only, so calls route through runCliMemo
+ * (test/helpers/cli-spawn.ts) — one spawn per unique argv (`--help`
+ * repeats 8x, `takes --help` 3x, ...). The lone un-memoized call is
+ * `sources detach --help`: it depends on cwd and asserts a filesystem
+ * non-side-effect, both outside the memo's argv+home key.
*/
import { describe, test, expect } from 'bun:test';
-import { spawnSync } from 'node:child_process';
import { mkdtempSync, writeFileSync, existsSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
-
-// Absolute path to the CLI entrypoint so `cwd` can be overridden (needed for
-// the `sources detach --help` regression test below, which must run with the
-// spawned process's cwd pointed at a scratch directory).
-const CLI_ENTRY = join(process.cwd(), 'src/cli.ts');
-
-function runCli(args: string[], opts: { cwd?: string } = {}): { stdout: string; stderr: string; status: number } {
- // Hermetic no-brain environment, matching cli-help-without-brain.serial.test.ts:
- // GBRAIN_HOME alone is not enough — loadConfig also honours GBRAIN_DATABASE_URL
- // and DATABASE_URL, so a developer or CI runner exporting either would let the
- // CLI connect anyway and these assertions would go inert.
- const env: Record<string, string | undefined> = {
- ...process.env,
- GBRAIN_HOME: '/tmp/gbrain-test-help-nonexistent',
- };
- delete env.GBRAIN_DATABASE_URL;
- delete env.DATABASE_URL;
- // --no-env-file: bun auto-loads .env from cwd, and GBRAIN_DATABASE_URL is
- // honored unconditionally, so a local .env would put back exactly what the
- // deletes above removed.
- const result = spawnSync('bun', ['--no-env-file', 'run', CLI_ENTRY, ...args], {
- cwd: opts.cwd ?? process.cwd(),
- encoding: 'utf8',
- env,
- });
- return {
- stdout: result.stdout ?? '',
- stderr: result.stderr ?? '',
- status: result.status ?? -1,
- };
+import { runCli, runCliMemo } from './helpers/cli-spawn.ts';
+
+// Hermetic no-brain environment, matching cli-help-without-brain.serial.test.ts:
+// GBRAIN_HOME alone is not enough — loadConfig also honours GBRAIN_DATABASE_URL
+// and DATABASE_URL, so a developer or CI runner exporting either would let the
+// CLI connect anyway and these assertions would go inert. cli-spawn strips both
+// from every child env; opts.home points HOME + GBRAIN_HOME at a nonexistent
+// dir. The helper also spawns with `bun --no-env-file` (as the old local
+// wrapper did) so a repo-root .env cannot re-add the stripped vars.
+const NO_BRAIN_HOME = '/tmp/gbrain-test-help-nonexistent';
+
+// Memoized: identical argv returns the cached CliResult without respawning.
+// Safe here because every invocation is a pure --help/-h read.
+function help(args: string[]) {
+ return runCliMemo(args, { home: NO_BRAIN_HOME });
}
describe('WARN-5 — `gbrain capture --help` reaches the detailed HELP constant', () => {
- test('output contains every documented flag', () => {
- const { stdout, status } = runCli(['capture', '--help']);
- expect(status).toBe(0);
+ test('output contains every documented flag', async () => {
+ const { stdout, exitCode } = await help(['capture', '--help']);
+ expect(exitCode).toBe(0);
expect(stdout).toContain('--slug');
expect(stdout).toContain('--type');
expect(stdout).toContain('--file');
@@ -65,8 +53,8 @@ describe('WARN-5 — `gbrain capture --help` reaches the detailed HELP constant'
expect(stdout).toContain('--json');
});
- test('output is NOT the generic short-circuit fallback', () => {
- const { stdout } = runCli(['capture', '--help']);
+ test('output is NOT the generic short-circuit fallback', async () => {
+ const { stdout } = await help(['capture', '--help']);
// Pre-fix output was: "Usage: gbrain capture\n\ngbrain capture - run gbrain --help ..."
// Post-fix HELP is much longer and includes Examples.
expect(stdout).toContain('Examples:');
@@ -74,25 +62,25 @@ describe('WARN-5 — `gbrain capture --help` reaches the detailed HELP constant'
expect(stdout).not.toMatch(/^Usage: gbrain capture\s*$/m);
});
- test('-h short flag also works', () => {
- const { stdout, status } = runCli(['capture', '-h']);
- expect(status).toBe(0);
+ test('-h short flag also works', async () => {
+ const { stdout, exitCode } = await help(['capture', '-h']);
+ expect(exitCode).toBe(0);
expect(stdout).toContain('--file PATH');
});
});
describe('WARN-6 — main `gbrain --help` lists capture/brainstorm/lsd', () => {
- test('output mentions all three commands by name', () => {
- const { stdout, status } = runCli(['--help']);
- expect(status).toBe(0);
+ test('output mentions all three commands by name', async () => {
+ const { stdout, exitCode } = await help(['--help']);
+ expect(exitCode).toBe(0);
// Must appear as command names (not just words in prose somewhere)
expect(stdout).toMatch(/^\s*capture\s/m);
expect(stdout).toMatch(/^\s*brainstorm\s/m);
expect(stdout).toMatch(/^\s*lsd\s/m);
});
- test('BRAIN section heading is present and groups the three commands', () => {
- const { stdout } = runCli(['--help']);
+ test('BRAIN section heading is present and groups the three commands', async () => {
+ const { stdout } = await help(['--help']);
expect(stdout).toContain('BRAIN');
// The 3 commands should appear AFTER the BRAIN heading in textual order.
const brainIdx = stdout.indexOf('BRAIN');
@@ -102,11 +90,11 @@ describe('WARN-6 — main `gbrain --help` lists capture/brainstorm/lsd', () => {
expect(stdout.indexOf('lsd', brainIdx)).toBeGreaterThan(brainIdx);
});
- test('regression: existing top-level commands still listed', () => {
+ test('regression: existing top-level commands still listed', async () => {
// Snapshot guard against accidentally deleting other groups when we
// added the BRAIN section. Spot-check a few commands from different
// groups (SETUP, PAGES, SEARCH, IMPORT/EXPORT).
- const { stdout } = runCli(['--help']);
+ const { stdout } = await help(['--help']);
expect(stdout).toContain('init');
expect(stdout).toContain('doctor');
expect(stdout).toContain('get');
@@ -120,36 +108,36 @@ describe('WARN-6 — main `gbrain --help` lists capture/brainstorm/lsd', () => {
});
describe('#2795 — `sync --install-cron` help line no longer promises an unbuilt feature', () => {
- test('main `gbrain --help` does not advertise install-cron', () => {
+ test('main `gbrain --help` does not advertise install-cron', async () => {
// Pre-fix: `sync --install-cron Install persistent sync daemon` was
// listed in the top-level help with no flag parsing or handler behind
// it anywhere in src/commands/sync.ts — `gbrain sync --install-cron`
// silently ran an ordinary sync instead of installing anything.
- const { stdout, status } = runCli(['--help']);
- expect(status).toBe(0);
+ const { stdout, exitCode } = await help(['--help']);
+ expect(exitCode).toBe(0);
expect(stdout).not.toContain('install-cron');
expect(stdout).not.toContain('Install persistent sync daemon');
});
- test('main `gbrain --help` points sync users at the real continuous-daemon command', () => {
- const { stdout } = runCli(['--help']);
+ test('main `gbrain --help` points sync users at the real continuous-daemon command', async () => {
+ const { stdout } = await help(['--help']);
// autopilot --install already runs sync+extract+embed on a schedule
// (docs/architecture/KEY_FILES.md); point discoverability there instead
// of promising a separate sync-only cron installer that never existed.
expect(stdout).toMatch(/sync --watch \[--interval N\][^\n]*\n\s*See also: autopilot --install/);
});
- test('`gbrain sync --help` never listed install-cron either', () => {
- const { stdout, status } = runCli(['sync', '--help']);
- expect(status).toBe(0);
+ test('`gbrain sync --help` never listed install-cron either', async () => {
+ const { stdout, exitCode } = await help(['sync', '--help']);
+ expect(exitCode).toBe(0);
expect(stdout).not.toContain('install-cron');
});
});
describe('#1175 — main `gbrain --help` SOURCES block matches the real subcommand set', () => {
- test('archive and its lifecycle siblings are listed', () => {
- const { stdout, status } = runCli(['--help']);
- expect(status).toBe(0);
+ test('archive and its lifecycle siblings are listed', async () => {
+ const { stdout, exitCode } = await help(['--help']);
+ expect(exitCode).toBe(0);
// Pre-fix the SOURCES block listed only list/add/remove; the soft-delete
// alternative that `sources remove` itself recommends was undiscoverable.
expect(stdout).toMatch(/^\s*sources archive <id>\s/m);
@@ -163,9 +151,9 @@ describe('#1175 — main `gbrain --help` SOURCES block matches the real subcomma
});
describe('#4003 — `gbrain auth --help` reaches the detailed usage block', () => {
- test('output contains the real auth subcommand usage, not the generic stub', () => {
- const { stdout, status } = runCli(['auth', '--help']);
- expect(status).toBe(0);
+ test('output contains the real auth subcommand usage, not the generic stub', async () => {
+ const { stdout, exitCode } = await help(['auth', '--help']);
+ expect(exitCode).toBe(0);
// Pre-fix: `auth` was missing from CLI_ONLY_SELF_HELP, so this printed
// only "gbrain auth - run gbrain --help for the full command list."
expect(stdout).toContain('GBrain Token Management');
@@ -174,15 +162,15 @@ describe('#4003 — `gbrain auth --help` reaches the detailed usage block', () =
expect(stdout).not.toContain('run gbrain --help for the full command list');
});
- test('-h short flag also works', () => {
- const { stdout, status } = runCli(['auth', '-h']);
- expect(status).toBe(0);
+ test('-h short flag also works', async () => {
+ const { stdout, exitCode } = await help(['auth', '-h']);
+ expect(exitCode).toBe(0);
expect(stdout).toContain('GBrain Token Management');
});
- test('main `gbrain --help` lists auth', () => {
- const { stdout, status } = runCli(['--help']);
- expect(status).toBe(0);
+ test('main `gbrain --help` lists auth', async () => {
+ const { stdout, exitCode } = await help(['--help']);
+ expect(exitCode).toBe(0);
expect(stdout).toMatch(/^\s*auth </m);
expect(stdout).toMatch(/^\s*auth --help\s/m);
});
@@ -196,28 +184,28 @@ describe('#4083 follow-up — auth subcommand + --help shows usage, never execut
// trailing --help on a real subcommand fell through to that
// subcommand's real handler instead of showing help — e.g. `gbrain auth
// create foo --help` would mint a real token named "foo".
- test('`gbrain auth create <name> --help` shows usage, does not create a token', () => {
- const { stdout, status } = runCli(['auth', 'create', 'definitely-not-a-real-token-name', '--help']);
- expect(status).toBe(0);
+ test('`gbrain auth create <name> --help` shows usage, does not create a token', async () => {
+ const { stdout, exitCode } = await help(['auth', 'create', 'definitely-not-a-real-token-name', '--help']);
+ expect(exitCode).toBe(0);
expect(stdout).toContain('GBrain Token Management');
expect(stdout).not.toContain('Token created for');
});
- test('`gbrain auth revoke <name> --help` shows usage, does not attempt a revoke', () => {
- const { stdout, status } = runCli(['auth', 'revoke', 'definitely-not-a-real-token-name', '--help']);
- expect(status).toBe(0);
+ test('`gbrain auth revoke <name> --help` shows usage, does not attempt a revoke', async () => {
+ const { stdout, exitCode } = await help(['auth', 'revoke', 'definitely-not-a-real-token-name', '--help']);
+ expect(exitCode).toBe(0);
expect(stdout).toContain('GBrain Token Management');
});
- test('`gbrain auth register-client <name> --help` shows usage, does not register a client', () => {
- const { stdout, status } = runCli(['auth', 'register-client', 'definitely-not-a-real-client', '--help']);
- expect(status).toBe(0);
+ test('`gbrain auth register-client <name> --help` shows usage, does not register a client', async () => {
+ const { stdout, exitCode } = await help(['auth', 'register-client', 'definitely-not-a-real-client', '--help']);
+ expect(exitCode).toBe(0);
expect(stdout).toContain('GBrain Token Management');
});
- test('-h works the same way as --help on a subcommand', () => {
- const { stdout, status } = runCli(['auth', 'create', 'definitely-not-a-real-token-name', '-h']);
- expect(status).toBe(0);
+ test('-h works the same way as --help on a subcommand', async () => {
+ const { stdout, exitCode } = await help(['auth', 'create', 'definitely-not-a-real-token-name', '-h']);
+ expect(exitCode).toBe(0);
expect(stdout).toContain('GBrain Token Management');
expect(stdout).not.toContain('Token created for');
});
@@ -238,25 +226,25 @@ describe('#3834 — extract flags are discoverable from both help surfaces', ()
'--workers',
];
- test('`gbrain extract --help` reaches detailed command help without a configured brain', () => {
- const { stdout, stderr, status } = runCli(['extract', '--help']);
- expect(status).toBe(0);
+ test('`gbrain extract --help` reaches detailed command help without a configured brain', async () => {
+ const { stdout, stderr, exitCode } = await help(['extract', '--help']);
+ expect(exitCode).toBe(0);
expect(stderr).toBe('');
expect(stdout).toContain('Usage: gbrain extract');
expect(stdout).not.toContain('run gbrain --help for the full command list');
for (const flag of implementedFlags) expect(stdout).toContain(flag);
});
- test('`gbrain extract -h` reaches the same detailed command help', () => {
- const { stdout, status } = runCli(['extract', '-h']);
- expect(status).toBe(0);
+ test('`gbrain extract -h` reaches the same detailed command help', async () => {
+ const { stdout, exitCode } = await help(['extract', '-h']);
+ expect(exitCode).toBe(0);
expect(stdout).toContain('--stale');
expect(stdout).toContain('--include-frontmatter');
});
- test('main `gbrain --help` documents every implemented extract flag', () => {
- const { stdout, status } = runCli(['--help']);
- expect(status).toBe(0);
+ test('main `gbrain --help` documents every implemented extract flag', async () => {
+ const { stdout, exitCode } = await help(['--help']);
+ expect(exitCode).toBe(0);
const extractStart = stdout.indexOf(' extract <links|timeline|all>');
const publishStart = stdout.indexOf(' publish <page.md>', extractStart);
expect(extractStart).toBeGreaterThan(-1);
@@ -267,9 +255,9 @@ describe('#3834 — extract flags are discoverable from both help surfaces', ()
});
describe('sources --help reaches its own usage block instead of the circular generic stub', () => {
- test('`gbrain sources --help` reaches detailed command help without a configured brain', () => {
- const { stdout, stderr, status } = runCli(['sources', '--help']);
- expect(status).toBe(0);
+ test('`gbrain sources --help` reaches detailed command help without a configured brain', async () => {
+ const { stdout, stderr, exitCode } = await help(['sources', '--help']);
+ expect(exitCode).toBe(0);
expect(stderr).toBe('');
expect(stdout).toContain('Subcommands:');
// Pre-fix output was the generic short-circuit, which itself points back
@@ -286,9 +274,9 @@ describe('sources --help reaches its own usage block instead of the circular gen
expect(stdout).toContain('harden');
});
- test('`gbrain sources -h` reaches the same detailed command help', () => {
- const { stdout, status } = runCli(['sources', '-h']);
- expect(status).toBe(0);
+ test('`gbrain sources -h` reaches the same detailed command help', async () => {
+ const { stdout, exitCode } = await help(['sources', '-h']);
+ expect(exitCode).toBe(0);
expect(stdout).toContain('set-cr-mode');
expect(stdout).not.toContain('run gbrain --help for the full command list');
});
@@ -303,9 +291,9 @@ describe('regression: nested `sources <sub> --help` must print help, not dispatc
// — crashing on the placeholder engine. Some subcommands (`detach`) don't
// even touch the engine and would perform their real, destructive action
// instead of crashing.
- test('`sources list --help` prints help and does not dispatch into runList (no null-engine crash)', () => {
- const { stdout, stderr, status } = runCli(['sources', 'list', '--help']);
- expect(status).toBe(0);
+ test('`sources list --help` prints help and does not dispatch into runList (no null-engine crash)', async () => {
+ const { stdout, stderr, exitCode } = await help(['sources', 'list', '--help']);
+ expect(exitCode).toBe(0);
expect(stdout).toContain('Subcommands:');
expect(stdout).not.toContain('run gbrain --help for the full command list');
// Pre-fix this crashed inside runList with something like
@@ -314,13 +302,19 @@ describe('regression: nested `sources <sub> --help` must print help, not dispatc
expect(stderr).not.toContain('TypeError');
});
- test('`sources detach --help` prints help and does NOT delete .gbrain-source', () => {
+ test('`sources detach --help` prints help and does NOT delete .gbrain-source', async () => {
const dir = mkdtempSync(join(tmpdir(), 'gbrain-sources-detach-help-'));
const dotfile = join(dir, '.gbrain-source');
writeFileSync(dotfile, 'example-source\n');
try {
- const { stdout, status } = runCli(['sources', 'detach', '--help'], { cwd: dir });
- expect(status).toBe(0);
+ // Un-memoized on purpose: the spawned process's cwd must point at the
+ // scratch directory, and the assertion is a filesystem non-side-effect
+ // — neither is part of runCliMemo's argv+home cache key.
+ const { stdout, exitCode } = await runCli(['sources', 'detach', '--help'], {
+ home: NO_BRAIN_HOME,
+ cwd: dir,
+ });
+ expect(exitCode).toBe(0);
expect(stdout).toContain('Subcommands:');
// The regression: runDetach() takes no engine and unconditionally
// unlinks .gbrain-source — with no guard, `detach --help` silently
@@ -333,9 +327,9 @@ describe('regression: nested `sources <sub> --help` must print help, not dispatc
});
describe('`sources webhook --help` reaches its own detailed help, not the general block or runWebhook*', () => {
- test('`sources webhook --help` prints the webhook-specific usage (set/show/rotate/clear), not the general SOURCES block', () => {
- const { stdout, status } = runCli(['sources', 'webhook', '--help']);
- expect(status).toBe(0);
+ test('`sources webhook --help` prints the webhook-specific usage (set/show/rotate/clear), not the general SOURCES block', async () => {
+ const { stdout, exitCode } = await help(['sources', 'webhook', '--help']);
+ expect(exitCode).toBe(0);
expect(stdout).toContain('Usage: gbrain sources webhook');
expect(stdout).toContain('rotate <id>');
expect(stdout).toContain('clear <id>');
@@ -347,9 +341,9 @@ describe('`sources webhook --help` reaches its own detailed help, not the genera
expect(stdout).not.toContain('add <id> --path');
});
- test('`sources webhook set x --help` prints webhook help and does NOT reach runWebhookSet', () => {
- const { stdout, stderr, status } = runCli(['sources', 'webhook', 'set', 'x', '--help']);
- expect(status).toBe(0);
+ test('`sources webhook set x --help` prints webhook help and does NOT reach runWebhookSet', async () => {
+ const { stdout, stderr, exitCode } = await help(['sources', 'webhook', 'set', 'x', '--help']);
+ expect(exitCode).toBe(0);
expect(stdout).toContain('Usage: gbrain sources webhook');
// runWebhookSet's own usage-error / not-found text must never appear —
// its presence would mean the guard let dispatch fall through to it.
@@ -361,9 +355,9 @@ describe('`sources webhook --help` reaches its own detailed help, not the genera
});
describe('`gbrain takes --help` reaches the detailed subcommand block', () => {
- test('every mutate + read subcommand is listed', () => {
- const { stdout, status } = runCli(['takes', '--help']);
- expect(status).toBe(0);
+ test('every mutate + read subcommand is listed', async () => {
+ const { stdout, exitCode } = await help(['takes', '--help']);
+ expect(exitCode).toBe(0);
// Pre-fix these were undiscoverable from the CLI: `takes` was in CLI_ONLY
// but not CLI_ONLY_SELF_HELP, so the generic stub fired before runTakes.
expect(stdout).toContain('takes add');
@@ -375,8 +369,8 @@ describe('`gbrain takes --help` reaches the detailed subcommand block', () => {
expect(stdout).toContain('takes search');
});
- test('output is NOT the generic short-circuit fallback', () => {
- const { stdout } = runCli(['takes', '--help']);
+ test('output is NOT the generic short-circuit fallback', async () => {
+ const { stdout } = await help(['takes', '--help']);
// Pre-fix output was exactly: "Usage: gbrain takes\n\ngbrain takes - run
// gbrain --help for the full command list."
expect(stdout).not.toContain('run gbrain --help for the full command list');
@@ -384,11 +378,11 @@ describe('`gbrain takes --help` reaches the detailed subcommand block', () => {
expect(stdout.split('\n').length).toBeGreaterThan(10);
});
- test('help works with no brain configured (pre-engine-bind branch)', () => {
- // runCli points GBRAIN_HOME at a nonexistent dir. Without the pre-engine
+ test('help works with no brain configured (pre-engine-bind branch)', async () => {
+ // `help` points GBRAIN_HOME at a nonexistent dir. Without the pre-engine
// branch this printed "No brain configured. Run: gbrain init".
- const { stdout, status } = runCli(['takes', '--help']);
- expect(status).toBe(0);
+ const { stdout, exitCode } = await help(['takes', '--help']);
+ expect(exitCode).toBe(0);
expect(stdout).not.toContain('No brain configured');
expect(stdout).toContain('--dir <path>');
});
diff --git a/test/doctor-minions-check.test.ts b/test/doctor-minions-check.test.ts
index 92c2099ee1..cfd72012e3 100644
--- a/test/doctor-minions-check.test.ts
+++ b/test/doctor-minions-check.test.ts
@@ -9,66 +9,65 @@
* - DB-path (check #6a): schema is v7+ but `preferences.json` is missing.
* Catches installs that never ran the stopgap at all.
*
- * Invokes the CLI via subprocess against a temp $HOME so the checks see
- * clean fixture state per test.
+ * JSON-shape assertions drive the exported `buildChecks()` seam in-process
+ * (the same seam test/doctor-behavioral.test.ts uses) under a withEnv-scoped
+ * temp GBRAIN_HOME — the check reads completed.jsonl at call time through
+ * gbrainPath(), so no subprocess is needed. Exit-code parity is exact:
+ * runDoctor's verdict is computeDoctorReport(checks).status === 'unhealthy'
+ * ? 1 : 0 (doctor.ts:outputResults) and buildChecks receives the same args
+ * the --fast CLI dispatch passes. Two real CLI spawns remain, each pinning a
+ * path the seam can't reach:
+ * - the human-output banner render + real process exit code (wiring smoke)
+ * - the dead-DB fallback note + credential redaction, which live in
+ * src/cli.ts's doctor dispatch, not in buildChecks
*/
import { describe, test, expect, beforeEach, afterEach } from 'bun:test';
import { mkdtempSync, rmSync, writeFileSync, mkdirSync } from 'fs';
import { join } from 'path';
import { tmpdir } from 'os';
-import { execFileSync } from 'child_process';
-
-const CLI = join(__dirname, '..', 'src', 'cli.ts');
+import { withEnv } from './helpers/with-env.ts';
+import { runCli } from './helpers/cli-spawn.ts';
+import { buildChecks, computeDoctorReport, type Check } from '../src/commands/doctor.ts';
+import { getDbUrlSource } from '../src/core/config.ts';
let tmp: string;
-let origHome: string | undefined;
-function run(args: string[]): { exitCode: number; stdout: string; stderr: string } {
- // Strip DATABASE_URL so doctor runs filesystem-only for these tests.
- // Half-migrated checks run in the filesystem section; no DB needed.
- // Both HOME and GBRAIN_HOME must point at the fixture dir: config/path
- // resolution prefers GBRAIN_HOME (which the test preload sets to its own
- // scratch), so HOME alone leaves the child reading the wrong .gbrain.
- const env = { ...process.env, HOME: tmp, GBRAIN_HOME: tmp } as Record<string, string | undefined>;
- delete env.DATABASE_URL;
- delete env.GBRAIN_DATABASE_URL;
- // Cross-file poisoning guard: sibling test files in the same bun process
- // set process.env.GBRAIN_HOME (preferences, friction, bootstrap-* et al),
- // and doctor resolves ~/.gbrain via resolveGbrainHome — which prefers
- // GBRAIN_HOME over HOME. A leaked value makes the seeded
- // $HOME/.gbrain/migrations fixture invisible and doctor exits 0 where the
- // test expects the FAIL exit. Scrub it like the DB URLs above.
- delete env.GBRAIN_HOME;
- try {
- const stdout = execFileSync('bun', ['run', CLI, ...args], {
- env: env as Record<string, string>,
- encoding: 'utf-8',
- stdio: ['ignore', 'pipe', 'pipe'],
- });
- return { exitCode: 0, stdout, stderr: '' };
- } catch (err: any) {
- return {
- exitCode: err.status ?? 1,
- stdout: err.stdout?.toString?.() ?? '',
- stderr: err.stderr?.toString?.() ?? '',
- };
- }
+/**
+ * In-process equivalent of the old `bun run src/cli.ts doctor --fast --json`
+ * child. Both HOME and GBRAIN_HOME are scoped to the fixture dir — gbrainPath
+ * prefers GBRAIN_HOME and appends '.gbrain', so either root resolves to the
+ * same `<tmp>/.gbrain` the fixtures seed — and the DB URLs are stripped so
+ * doctor runs filesystem-only (half-migrated checks need no DB). Sibling test
+ * files' env mutations can't poison this: withEnv overrides GBRAIN_HOME for
+ * the duration of the call instead of inheriting a leaked value. exitCode is
+ * derived exactly the way runDoctor derives it (unhealthy → 1), and
+ * getDbUrlSource() is computed inside the env scope, matching the --fast
+ * dispatch in src/cli.ts.
+ */
+async function runFastChecks(): Promise<{ exitCode: number; checks: Check[] }> {
+ return withEnv(
+ { HOME: tmp, GBRAIN_HOME: tmp, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined },
+ async () => {
+ const checks = await buildChecks(null, ['--fast', '--json'], getDbUrlSource());
+ return {
+ exitCode: computeDoctorReport(checks).status === 'unhealthy' ? 1 : 0,
+ checks,
+ };
+ },
+ );
}
beforeEach(() => {
- origHome = process.env.HOME;
tmp = mkdtempSync(join(tmpdir(), 'gbrain-doctor-minions-test-'));
});
afterEach(() => {
- if (origHome === undefined) delete process.env.HOME;
- else process.env.HOME = origHome;
try { rmSync(tmp, { recursive: true, force: true }); } catch { /* best-effort */ }
});
describe('gbrain doctor — half-migrated Minions detection', () => {
- test('filesystem: partial completed.jsonl entry with no matching complete → FAIL', () => {
+ test('filesystem: partial completed.jsonl entry with no matching complete → FAIL', async () => {
// Seed ~/.gbrain/migrations/completed.jsonl with a single status:"partial"
// entry — the classic signal the stopgap ran but apply-migrations didn't.
const migrationsDir = join(tmp, '.gbrain', 'migrations');
@@ -85,11 +84,11 @@ describe('gbrain doctor — half-migrated Minions detection', () => {
}) + '\n',
);
- // Use --fast so we skip the DB section entirely (no engine configured).
- const result = run(['doctor', '--fast', '--json']);
+ // --fast skips the DB section entirely (no engine configured).
+ const result = await runFastChecks();
// doctor exits 1 on any FAIL; that's expected here.
expect(result.exitCode).toBe(1);
- const checks = JSON.parse(result.stdout).checks as Array<{ name: string; status: string; message: string }>;
+ const checks = result.checks;
const minions = checks.find(c => c.name === 'minions_migration');
expect(minions).toBeDefined();
expect(minions!.status).toBe('fail');
@@ -98,7 +97,7 @@ describe('gbrain doctor — half-migrated Minions detection', () => {
expect(minions!.message).toContain('0.11.0');
});
- test('filesystem: partial followed by complete → NO warning', () => {
+ test('filesystem: partial followed by complete → NO warning', async () => {
// The stopgap wrote partial, then v0.11.1 apply-migrations wrote
// complete. Doctor should stay quiet.
const migrationsDir = join(tmp, '.gbrain', 'migrations');
@@ -111,8 +110,8 @@ describe('gbrain doctor — half-migrated Minions detection', () => {
].join('\n') + '\n',
);
- const result = run(['doctor', '--fast', '--json']);
- const checks = JSON.parse(result.stdout).checks as Array<{ name: string; status: string }>;
+ const result = await runFastChecks();
+ const checks = result.checks;
const minions = checks.find(c => c.name === 'minions_migration');
// No warn/fail — either the check isn't emitted at all (no issues) or
// it emits an ok entry. Either is acceptable for a quiet state.
@@ -121,19 +120,19 @@ describe('gbrain doctor — half-migrated Minions detection', () => {
}
});
- test('filesystem: no completed.jsonl at all → NO warning (fresh install path)', () => {
+ test('filesystem: no completed.jsonl at all → NO warning (fresh install path)', async () => {
// Doctor must NOT warn about half-migrated Minions just because a user
// hasn't run any migration yet. The FS check only fires when there's
// genuine partial-without-complete evidence.
- const result = run(['doctor', '--fast', '--json']);
- const checks = JSON.parse(result.stdout).checks as Array<{ name: string; status: string }>;
+ const result = await runFastChecks();
+ const checks = result.checks;
const minions = checks.find(c => c.name === 'minions_migration');
if (minions) {
expect(['ok']).toContain(minions.status);
}
});
- test('regression: fresh install with schema-applied DB but no prefs must NOT fail', () => {
+ test('regression: fresh install with schema-applied DB but no prefs must NOT fail', async () => {
// CI regression. `gbrain init` against Postgres applies schema v7 but
// doesn't write preferences.json (the migration orchestrator does that
// via apply-migrations). For that brief window, schema is v7 with no
@@ -144,8 +143,8 @@ describe('gbrain doctor — half-migrated Minions detection', () => {
// preferences.json → FAIL" rule was too aggressive. Only a concrete
// "partial without complete" entry in completed.jsonl counts as
// half-migrated.
- const result = run(['doctor', '--fast', '--json']);
- const checks = JSON.parse(result.stdout).checks as Array<{ name: string; status: string }>;
+ const result = await runFastChecks();
+ const checks = result.checks;
// No check with `minions_config` or `minions_migration` should be in FAIL
for (const check of checks) {
if (check.name === 'minions_config' || check.name === 'minions_migration') {
@@ -154,7 +153,7 @@ describe('gbrain doctor — half-migrated Minions detection', () => {
}
});
- test('filesystem: multiple versions each need their own complete entry', () => {
+ test('filesystem: multiple versions each need their own complete entry', async () => {
// v0.10 is fully migrated but v0.11 is only partial. Doctor should
// flag v0.11 by name. The forward-progress override only kicks in
// when a NEWER version completed; v0.10 is older than v0.11 so the
@@ -169,16 +168,16 @@ describe('gbrain doctor — half-migrated Minions detection', () => {
].join('\n') + '\n',
);
- const result = run(['doctor', '--fast', '--json']);
+ const result = await runFastChecks();
expect(result.exitCode).toBe(1);
- const checks = JSON.parse(result.stdout).checks as Array<{ name: string; status: string; message: string }>;
+ const checks = result.checks;
const minions = checks.find(c => c.name === 'minions_migration');
expect(minions!.status).toBe('fail');
expect(minions!.message).toContain('0.11.0');
expect(minions!.message).not.toContain('0.10.0');
});
- test('filesystem: stale partial superseded by newer complete → NO warning (forward-progress override)', () => {
+ test('filesystem: stale partial superseded by newer complete → NO warning (forward-progress override)', async () => {
// v0.16.0 completed AFTER v0.11.0 went partial. The schema clearly
// advanced past v0.11.0, so the partial record is stale historical
// noise — not a real "MINIONS HALF-INSTALLED" condition.
@@ -201,10 +200,10 @@ describe('gbrain doctor — half-migrated Minions detection', () => {
].join('\n') + '\n',
);
- const result = run(['doctor', '--fast', '--json']);
+ const result = await runFastChecks();
// No FAIL on minions_migration — the v0.11.0 partials are stale
// because v0.16.0 (a newer release) completed.
- const checks = JSON.parse(result.stdout).checks as Array<{ name: string; status: string }>;
+ const checks = result.checks;
const minions = checks.find(c => c.name === 'minions_migration');
if (minions) {
expect(minions.status).not.toBe('fail');
@@ -215,7 +214,7 @@ describe('gbrain doctor — half-migrated Minions detection', () => {
expect(result.exitCode).toBe(0);
});
- test('filesystem: stale partial NOT superseded → still flagged', () => {
+ test('filesystem: stale partial NOT superseded → still flagged', async () => {
// The override only fires when a >= partial version has completed.
// Older completes (e.g. v0.10 complete + v0.16 partial) do NOT
// supersede the partial; the partial still indicates a real problem.
@@ -229,18 +228,19 @@ describe('gbrain doctor — half-migrated Minions detection', () => {
].join('\n') + '\n',
);
- const result = run(['doctor', '--fast', '--json']);
+ const result = await runFastChecks();
expect(result.exitCode).toBe(1);
- const checks = JSON.parse(result.stdout).checks as Array<{ name: string; status: string; message: string }>;
+ const checks = result.checks;
const minions = checks.find(c => c.name === 'minions_migration');
expect(minions!.status).toBe('fail');
expect(minions!.message).toContain('0.16.0');
});
- test('human output: prints MINIONS HALF-INSTALLED loud banner', () => {
+ test('human output: prints MINIONS HALF-INSTALLED loud banner', async () => {
// Same fixture as the first test, but check the human-readable output
// includes the exact banner phrase an OpenClaw host's cron script
- // can grep for.
+ // can grep for. This is the file's real-CLI wiring smoke: render +
+ // process exit code go through src/cli.ts, which buildChecks can't reach.
const migrationsDir = join(tmp, '.gbrain', 'migrations');
mkdirSync(migrationsDir, { recursive: true });
writeFileSync(
@@ -248,17 +248,19 @@ describe('gbrain doctor — half-migrated Minions detection', () => {
JSON.stringify({ version: '0.11.0', status: 'partial' }) + '\n',
);
- const result = run(['doctor', '--fast']);
+ const result = await runCli(['doctor', '--fast'], { home: tmp });
expect(result.exitCode).toBe(1);
expect(result.stdout).toContain('MINIONS HALF-INSTALLED');
expect(result.stdout).toContain('gbrain apply-migrations --yes');
- });
+ }, 60_000);
- test('DB-connect failure announces the filesystem-only fallback on stderr, credentials redacted', () => {
+ test('DB-connect failure announces the filesystem-only fallback on stderr, credentials redacted', async () => {
// The fallback used to be silent — indistinguishable from a healthy
// DB-backed run minus the DB checks. Pin the stderr note AND that a
// credential-bearing connect error never leaks the password (doctor
- // output is what users paste into issues and CI logs).
+ // output is what users paste into issues and CI logs). Must be a real
+ // spawn: the note + redaction live in src/cli.ts's doctor dispatch,
+ // not in buildChecks.
const gbrainDir = join(tmp, '.gbrain');
mkdirSync(gbrainDir, { recursive: true });
// Assembled at runtime so the source never contains a scannable
@@ -269,17 +271,10 @@ describe('gbrain doctor — half-migrated Minions detection', () => {
JSON.stringify({ engine: 'postgres', database_url: fakeUrl }) + '\n',
);
- // The shared run() helper discards stderr on exit 0; this pin needs it
- // regardless of exit code, so spawn directly.
- const env = { ...process.env, HOME: tmp, GBRAIN_HOME: tmp } as Record<string, string | undefined>;
- delete env.DATABASE_URL;
- delete env.GBRAIN_DATABASE_URL;
- const { spawnSync } = require('child_process') as typeof import('child_process');
- const res = spawnSync('bun', ['run', CLI, 'doctor', '--json'], {
- env: env as NodeJS.ProcessEnv,
- encoding: 'utf-8',
- timeout: 60_000,
- });
+ // runCli strips DATABASE_URL/GBRAIN_DATABASE_URL and points HOME +
+ // GBRAIN_HOME at the fixture dir; it captures stderr regardless of the
+ // exit code, which this pin needs.
+ const res = await runCli(['doctor', '--json'], { home: tmp });
expect(res.stderr).toContain('[doctor] DB-backed doctor run failed');
expect(res.stderr).toContain('filesystem-only checks');
expect(res.stderr).not.toContain('sekrit-hunter2');
diff --git a/test/dream.test.ts b/test/dream.test.ts
index d0c96e59d9..c6b768754f 100644
--- a/test/dream.test.ts
+++ b/test/dream.test.ts
@@ -11,57 +11,56 @@
* every test that imports shouldExclude/deriveDomain/formatOrphansText).
* Testing against real calls is honest and mock-leak-free.
*
+ * Cost model: ONE engine per file (beforeAll + afterAll disconnect,
+ * resetPgliteState per test) and ONE build-once git fixture
+ * (fixture.reset() per test = git clean -fdx + reset --hard). No test
+ * here commits to the repo and runCycle never auto-commits, so reset()
+ * needs no commit rewind; untracked artifacts a phase drops into the
+ * repo are cleaned per test. The fixture's empty initial commit keeps
+ * rev-parse HEAD working; the tree stays empty so lint/backlinks have
+ * nothing to scan → status=clean.
+ *
* What this test file does NOT cover: the exhaustive dryRun-×-phases-×-
* lock matrix, which test/core/cycle.test.ts handles (in isolation).
* Here we only verify that dream.ts routes args correctly.
*/
-import { describe, test, expect, beforeEach, afterEach, spyOn } from 'bun:test';
+import { describe, test, expect, beforeAll, afterAll, beforeEach, spyOn } from 'bun:test';
import { mkdtempSync, rmSync } from 'fs';
import { join } from 'path';
import { tmpdir } from 'os';
-import { execSync } from 'child_process';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { makeGitFixture, type GitFixture } from './helpers/git-fixture.ts';
import { runDream } from '../src/commands/dream.ts';
-// ─── Helpers ───────────────────────────────────────────────────────
+// ─── Shared fixtures (built once; reset per test) ──────────────────
+
+let engine: PGLiteEngine;
+let fixture: GitFixture;
+let repo: string;
-/** Make an empty, engine-backed PGLite brain. */
-async function makePGLite() {
- const engine = new PGLiteEngine();
+beforeAll(async () => {
+ engine = new PGLiteEngine();
await engine.connect({});
await engine.initSchema();
- return engine;
-}
-
-/** Make an empty git repo. Lint/backlinks have nothing to scan → status=clean. */
-function makeGitRepo(): string {
- const dir = mkdtempSync(join(tmpdir(), 'gbrain-dream-repo-'));
- execSync('git init', { cwd: dir, stdio: 'pipe' });
- execSync('git config user.email [email protected]', { cwd: dir, stdio: 'pipe' });
- execSync('git config user.name t', { cwd: dir, stdio: 'pipe' });
- // Commit an empty .gitkeep so rev-parse HEAD succeeds.
- require('fs').writeFileSync(join(dir, '.gitkeep'), '');
- execSync('git add -A && git commit -m init', { cwd: dir, stdio: 'pipe' });
- return dir;
-}
+ repo = mkdtempSync(join(tmpdir(), 'gbrain-dream-repo-'));
+ fixture = await makeGitFixture(repo);
+}, 300_000); // OAuth v25 + git init; needs breathing room under full-suite + parallel-agent load
-// ─── brainDir resolution ───────────────────────────────────────────
-
-describe('runDream — brainDir resolution', () => {
- let repo: string;
- let engine: InstanceType<typeof PGLiteEngine>;
+afterAll(async () => {
+ await engine.disconnect();
+ rmSync(repo, { recursive: true, force: true });
+}, 300_000);
- beforeEach(async () => {
- repo = makeGitRepo();
- engine = await makePGLite();
- }, 300_000); // OAuth v25 + git init; needs breathing room under full-suite + parallel-agent load
+beforeEach(async () => {
+ await resetPgliteState(engine);
+ fixture.reset();
+}, 300_000);
- afterEach(async () => {
- if (engine) await engine.disconnect();
- rmSync(repo, { recursive: true, force: true });
- }, 300_000);
+// ─── brainDir resolution ───────────────────────────────────────────
+describe('runDream — brainDir resolution', () => {
test('explicit --dir takes precedence over engine config', async () => {
await engine.setConfig('sync.repo_path', '/configured/dir');
const report = await runDream(engine, ['--dir', repo, '--json']);
@@ -106,19 +105,6 @@ describe('runDream — brainDir resolution', () => {
// ─── Phase selection (single-phase runs stay fast) ─────────────────
describe('runDream — --phase <name> restricts the cycle', () => {
- let repo: string;
- let engine: InstanceType<typeof PGLiteEngine>;
-
- beforeEach(async () => {
- repo = makeGitRepo();
- engine = await makePGLite();
- }, 300_000); // OAuth v25 + git init; needs breathing room under full-suite + parallel-agent load
-
- afterEach(async () => {
- if (engine) await engine.disconnect();
- rmSync(repo, { recursive: true, force: true });
- }, 300_000);
-
test('--phase lint produces a report with exactly one phase = lint', async () => {
const report = await runDream(engine, ['--dir', repo, '--phase', 'lint', '--json']);
expect(report).toBeTruthy();
@@ -218,19 +204,6 @@ describe('runDream — --phase <name> restricts the cycle', () => {
// ─── --once (issue #2860) ───────────────────────────────────────────
describe('runDream — --once (issue #2860)', () => {
- let repo: string;
- let engine: InstanceType<typeof PGLiteEngine>;
-
- beforeEach(async () => {
- repo = makeGitRepo();
- engine = await makePGLite();
- }, 300_000);
-
- afterEach(async () => {
- if (engine) await engine.disconnect();
- rmSync(repo, { recursive: true, force: true });
- }, 300_000);
-
test('bare --once (no --phase) exits 2 with a usage hint', async () => {
const exitSpy = spyOn(process, 'exit').mockImplementation(() => { throw new Error('EXIT'); });
const errSpy = spyOn(console, 'error').mockImplementation(() => {});
@@ -331,19 +304,6 @@ describe('runDream — --once (issue #2860)', () => {
// ─── Output format ─────────────────────────────────────────────────
describe('runDream — output format', () => {
- let repo: string;
- let engine: InstanceType<typeof PGLiteEngine>;
-
- beforeEach(async () => {
- repo = makeGitRepo();
- engine = await makePGLite();
- }, 300_000); // OAuth v25 + git init; needs breathing room under full-suite + parallel-agent load
-
- afterEach(async () => {
- if (engine) await engine.disconnect();
- rmSync(repo, { recursive: true, force: true });
- }, 300_000);
-
test('--json emits parsable CycleReport JSON with schema_version', async () => {
const lines: string[] = [];
const logSpy = spyOn(console, 'log').mockImplementation((msg: string) => { lines.push(String(msg)); });
@@ -396,19 +356,6 @@ describe('runDream — output format', () => {
// ─── Dry-run propagation ───────────────────────────────────────────
describe('runDream — dry-run propagates through to runCycle', () => {
- let repo: string;
- let engine: InstanceType<typeof PGLiteEngine>;
-
- beforeEach(async () => {
- repo = makeGitRepo();
- engine = await makePGLite();
- }, 300_000); // OAuth v25 + git init; needs breathing room under full-suite + parallel-agent load
-
- afterEach(async () => {
- if (engine) await engine.disconnect();
- rmSync(repo, { recursive: true, force: true });
- }, 300_000);
-
test('--dry-run produces a report where no DB-mutating work happened', async () => {
// Before: empty pages table.
const { rows: before } = await (engine as any).db.query('SELECT COUNT(*)::int AS n FROM pages');
@@ -425,19 +372,6 @@ describe('runDream — dry-run propagates through to runCycle', () => {
// ─── Exit-code semantics ───────────────────────────────────────────
describe('runDream — exit-code semantics', () => {
- let repo: string;
- let engine: InstanceType<typeof PGLiteEngine>;
-
- beforeEach(async () => {
- repo = makeGitRepo();
- engine = await makePGLite();
- }, 300_000); // OAuth v25 + git init; needs breathing room under full-suite + parallel-agent load
-
- afterEach(async () => {
- if (engine) await engine.disconnect();
- rmSync(repo, { recursive: true, force: true });
- }, 300_000);
-
test('clean/ok/partial statuses do not call process.exit', async () => {
const spy = spyOn(process, 'exit').mockImplementation(() => { throw new Error('UNEXPECTED_EXIT'); });
await runDream(engine, ['--dir', repo, '--phase', 'lint', '--json']);
@@ -460,9 +394,6 @@ describe('runDream — exit-code semantics', () => {
// - back-compat regression: bare `gbrain dream` writes no per-source stamp
describe('runDream — --source / --source-id (v0.41.13)', () => {
- let repo: string;
- let engine: InstanceType<typeof PGLiteEngine>;
-
async function seedSource(id: string, archived: boolean = false): Promise<void> {
await engine.executeRaw(
`INSERT INTO sources (id, name, local_path, config, archived, created_at)
@@ -480,16 +411,6 @@ describe('runDream — --source / --source-id (v0.41.13)', () => {
return typeof raw === 'string' ? raw : null;
}
- beforeEach(async () => {
- repo = makeGitRepo();
- engine = await makePGLite();
- }, 300_000);
-
- afterEach(async () => {
- if (engine) await engine.disconnect();
- rmSync(repo, { recursive: true, force: true });
- }, 300_000);
-
// ─── parseArgs: --source missing / conflict / repetition ────────────
test('--source with no value exits 2 with usage hint', async () => {
@@ -699,7 +620,9 @@ describe('runDream — --source / --source-id (v0.41.13)', () => {
// matches resolver-user-error message shapes; a TypeError thrown
// from any source-resolution path must bubble up with its original
// stack trace (proving real programmer bugs are NOT hidden behind
- // operator-error UX).
+ // operator-error UX). The patch MUST restore in finally — the engine
+ // is shared file-wide; a leaked patch breaks every later test's
+ // resetPgliteState.
await seedSource('gamma');
const original = (engine as any).executeRaw.bind(engine);
let restored = false;
@@ -732,19 +655,6 @@ describe('runDream — --source / --source-id (v0.41.13)', () => {
// chain through the exact seam both sides consume.
describe('runDream → checkCycleFreshness end-to-end (D5)', () => {
- let repo: string;
- let engine: InstanceType<typeof PGLiteEngine>;
-
- beforeEach(async () => {
- repo = makeGitRepo();
- engine = await makePGLite();
- }, 300_000);
-
- afterEach(async () => {
- if (engine) await engine.disconnect();
- rmSync(repo, { recursive: true, force: true });
- }, 300_000);
-
test('stale source becomes fresh after dream --source (column-name drift guard)', async () => {
// Seed source with last_full_cycle_at backdated 25h (above warn floor).
const stale = new Date(Date.now() - 25 * 60 * 60 * 1000).toISOString();
diff --git a/test/e2e/bootstrap-attach.serial.test.ts b/test/e2e/bootstrap-attach.serial.test.ts
index 9798f8c95c..71193399e6 100644
--- a/test/e2e/bootstrap-attach.serial.test.ts
+++ b/test/e2e/bootstrap-attach.serial.test.ts
@@ -30,6 +30,7 @@ import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { runBootstrap } from '../../src/commands/bootstrap.ts';
+
import type { ExecRunner } from '../../src/core/bootstrap/repo.ts';
import { attachWorkspace } from '../../src/core/bootstrap/attach.ts';
import { readManifest, readReceipt } from '../../src/core/bootstrap/format.ts';
@@ -43,6 +44,10 @@ import { operations, type OperationContext } from '../../src/core/operations.ts'
import type { CapabilityReport } from '../../src/core/capability.ts';
import { CORPUS_DIR } from '../helpers/bootstrap-corpus.ts';
+// Cold-path opt-out (conservative): bootstrap-arc file — attach semantics on
+// a brain whose init path should stay the genuine cold build.
+delete process.env.GBRAIN_PGLITE_SNAPSHOT;
+
/** Keyless capability report — machine 2 re-ingests + verifies with ZERO keys. */
const KEYLESS: CapabilityReport = {
embeddings: { available: false },
diff --git a/test/e2e/bootstrap-keyed-postgres.serial.test.ts b/test/e2e/bootstrap-keyed-postgres.serial.test.ts
index 4218eb24ae..93c395f569 100644
--- a/test/e2e/bootstrap-keyed-postgres.serial.test.ts
+++ b/test/e2e/bootstrap-keyed-postgres.serial.test.ts
@@ -20,6 +20,7 @@ import { join } from 'node:path';
import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
import { PostgresEngine } from '../../src/core/postgres-engine.ts';
+
import { addSource } from '../../src/core/sources-ops.ts';
import { loadCorpusPages } from '../helpers/bootstrap-corpus.ts';
import { runEmbedCore } from '../../src/commands/embed.ts';
@@ -40,6 +41,10 @@ import {
} from '../../src/core/bootstrap/verify.ts';
import type { CapabilityReport } from '../../src/core/capability.ts';
+// Cold-path opt-out (conservative): runs runSchemaTransition (embedding-width
+// schema migration) on top of a fresh engine — the base must be cold-built.
+delete process.env.GBRAIN_PGLITE_SNAPSHOT;
+
const OPENAI = process.env.OPENAI_API_KEY;
const VOYAGE = process.env.VOYAGE_API_KEY;
const ANTHROPIC = process.env.ANTHROPIC_API_KEY;
diff --git a/test/e2e/frontmatter-migration.test.ts b/test/e2e/frontmatter-migration.test.ts
index ef3628434d..7be99ea12b 100644
--- a/test/e2e/frontmatter-migration.test.ts
+++ b/test/e2e/frontmatter-migration.test.ts
@@ -30,6 +30,10 @@ import { tmpdir } from 'os';
import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
import { v0_22_4, __setTestEngineOverride } from '../../src/commands/migrations/v0_22_4.ts';
+// Cold-path opt-out: drives the real v0_22_4 migration orchestrator — the
+// engine under migration must be a cold build, not a snapshot restore.
+delete process.env.GBRAIN_PGLITE_SNAPSHOT;
+
const fence = '---';
let workdir: string;
diff --git a/test/e2e/schema-cathedral.test.ts b/test/e2e/schema-cathedral.test.ts
index 6ad384c341..c5c5feda4b 100644
--- a/test/e2e/schema-cathedral.test.ts
+++ b/test/e2e/schema-cathedral.test.ts
@@ -9,6 +9,7 @@
import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+
import { resetPgliteState } from '../helpers/reset-pglite.ts';
import { parseMarkdown } from '../../src/core/markdown.ts';
import { runDetect } from '../../src/core/schema-pack/detect.ts';
@@ -16,6 +17,11 @@ import { runReviewCandidates, runReviewOrphans } from '../../src/core/schema-pac
import { knobsHash } from '../../src/core/search/mode.ts';
import { detectArtifactKind, validateManifestByKind } from '../../src/core/artifact/index.ts';
+// Cold-path opt-out (conservative): umbrella schema-invariant suite whose
+// point is proving the cathedral end-to-end through a genuinely cold-built
+// schema — keep it off the snapshot fast path.
+delete process.env.GBRAIN_PGLITE_SNAPSHOT;
+
let engine: PGLiteEngine;
beforeAll(async () => {
diff --git a/test/e2e/v030_1-integration-pglite.test.ts b/test/e2e/v030_1-integration-pglite.test.ts
index eb2b4158af..8e7d4fa4ff 100644
--- a/test/e2e/v030_1-integration-pglite.test.ts
+++ b/test/e2e/v030_1-integration-pglite.test.ts
@@ -29,6 +29,7 @@ import { join } from 'node:path';
import { tmpdir } from 'node:os';
import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
import { listBackfills, getBackfill } from '../../src/core/backfill-registry.ts';
+
import { runBackfill } from '../../src/core/backfill-base.ts';
import { dropZombieIndexes, checkActiveBuild } from '../../src/core/vector-index.ts';
import {
@@ -41,6 +42,11 @@ import {
} from '../../src/core/upgrade-checkpoint.ts';
import { LATEST_VERSION } from '../../src/core/migrate.ts';
+// Cold-path opt-out: asserts config.version === LATEST_VERSION *because of*
+// initSchema's migration chain — under a snapshot the version comes from the
+// fixture and the assertion proves nothing.
+delete process.env.GBRAIN_PGLITE_SNAPSHOT;
+
let tmpHome: string;
let originalHome: string | undefined;
let engine: PGLiteEngine;
diff --git a/test/e2e/v0_28_5-fix-wave.test.ts b/test/e2e/v0_28_5-fix-wave.test.ts
index e7e0fa5235..a57945837d 100644
--- a/test/e2e/v0_28_5-fix-wave.test.ts
+++ b/test/e2e/v0_28_5-fix-wave.test.ts
@@ -37,6 +37,12 @@
import { describe, test, expect } from 'bun:test';
import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
import { LATEST_VERSION } from '../../src/core/migrate.ts';
+
+// Cold-path opt-out: asserts hasPendingMigrations === true on a FRESH brain
+// before initSchema — a restored snapshot already carries the config.version
+// row, which would flip that to false. The migration-replay arc must start cold.
+delete process.env.GBRAIN_PGLITE_SNAPSHOT;
+
import {
readContentChunksEmbeddingDim,
embeddingMismatchMessage,
diff --git a/test/e2e/v0_30_3-fix-wave.test.ts b/test/e2e/v0_30_3-fix-wave.test.ts
index ee44c02812..4a37b42b86 100644
--- a/test/e2e/v0_30_3-fix-wave.test.ts
+++ b/test/e2e/v0_30_3-fix-wave.test.ts
@@ -28,6 +28,10 @@ import { describe, test, expect } from 'bun:test';
import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
import { LATEST_VERSION } from '../../src/core/migrate.ts';
+// Cold-path opt-out: the rewind-to-v38 → re-initSchema → LATEST arc needs its
+// seeding initSchema to be a genuine cold build, not a snapshot restore.
+delete process.env.GBRAIN_PGLITE_SNAPSHOT;
+
describe('v0.30.3 wave — pre-v39/v40/v41 forward-reference bootstrap (#741)', () => {
test('pre-v39 brain (missing modality + embedding_image) re-runs initSchema cleanly', async () => {
const engine = new PGLiteEngine();
diff --git a/test/eval-brainbench-e2e.test.ts b/test/eval-brainbench-e2e.slow.test.ts
similarity index 64%
rename from test/eval-brainbench-e2e.test.ts
rename to test/eval-brainbench-e2e.slow.test.ts
index 0fb8348bff..4844970bbf 100644
--- a/test/eval-brainbench-e2e.test.ts
+++ b/test/eval-brainbench-e2e.slow.test.ts
@@ -3,11 +3,23 @@
* literal exit codes (the CI product, decision 9) are asserted end-to-end:
* 0 pass · 1 regression · 2 error/inconclusive. Also pins: the --out artifact
* is complete valid JSON with the _meta.metric_glossary block, --update-baseline
- * is byte-deterministic across runs, anti-vacuous-pass, and the run-all wiring
- * (full corpus, in-process).
+ * is byte-deterministic across runs, anti-vacuous-pass, and the run-all
+ * once-per-sweep record semantics.
+ *
+ * Spawn budget: every independent CLI run executes ONCE in beforeAll through a
+ * width-2 pool (each child boots its own PGLite; wider would multiply across
+ * shards); tests assert on the cached results. The runs were order-independent
+ * by construction already (each depends only on the beforeAll artifacts).
+ *
+ * The former "run-all wiring — full corpus, in-process" describe was deleted:
+ * CI's dedicated brainbench job (scripts/ci-brainbench-gate.sh) runs the same
+ * committed corpus fresh on every PR and its --compare against the committed
+ * baseline is the authoritative completion + fixtures-hash drift gate; the
+ * once-per-sweep test below still runs the full corpus once for the ledger
+ * contract.
*/
import { beforeAll, describe, expect, test } from 'bun:test';
-import { cpSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync, existsSync } from 'node:fs';
+import { cpSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
@@ -17,14 +29,19 @@ let root: string;
let fixtures: string;
let gold: string;
-function run(args: string[], cwd = REPO): { exitCode: number; stdout: string; stderr: string } {
+type RunResult = { exitCode: number; stdout: string; stderr: string };
+
+function withDefaultCommittedBaseline(args: string[]): string[] {
// Foreign-corpus runs opt OUT of the repo's committed baseline: the
// poisoning defense requires any committed-vs-main divergence to match the
// current run, and the repo's main.json never matches a tmp-corpus run.
- const full = args.includes('--committed-baseline')
+ return args.includes('--committed-baseline')
? args
: [...args, '--committed-baseline', join(root, 'no-committed-baseline.json')];
- const proc = Bun.spawnSync(['bun', CLI, 'eval', 'brainbench', ...full], {
+}
+
+function run(args: string[], cwd = REPO): RunResult {
+ const proc = Bun.spawnSync(['bun', CLI, 'eval', 'brainbench', ...withDefaultCommittedBaseline(args)], {
cwd,
env: { ...process.env, GBRAIN_QUIET: '1' },
stdout: 'pipe',
@@ -37,7 +54,55 @@ function run(args: string[], cwd = REPO): { exitCode: number; stdout: string; st
};
}
-beforeAll(() => {
+async function runAsync(args: string[], cwd = REPO): Promise<RunResult> {
+ const proc = Bun.spawn(['bun', CLI, 'eval', 'brainbench', ...withDefaultCommittedBaseline(args)], {
+ cwd,
+ env: { ...process.env, GBRAIN_QUIET: '1' },
+ stdout: 'pipe',
+ stderr: 'pipe',
+ });
+ // A wedged child (the synchronous PGLite-WASM block class) would otherwise
+ // hang beforeAll to its 300s cap and orphan a ~1.5GB process behind the CI
+ // job timeout. SIGTERM at 120s (healthy runs finish in ~5-15s), SIGKILL +2s.
+ const term = setTimeout(() => { try { proc.kill(); } catch { /* exited */ } }, 120_000);
+ const hardKill = setTimeout(() => { try { proc.kill(9); } catch { /* exited */ } }, 122_000);
+ try {
+ const [stdout, stderr, exitCode] = await Promise.all([
+ new Response(proc.stdout).text(),
+ new Response(proc.stderr).text(),
+ proc.exited,
+ ]);
+ return { exitCode: exitCode ?? -1, stdout, stderr };
+ } finally {
+ clearTimeout(term);
+ clearTimeout(hardKill);
+ }
+}
+
+/**
+ * The independent CLI runs, executed once through a width-2 pool.
+ *
+ * Local pool rather than test/helpers/cli-spawn.ts#runCliBatch: that helper
+ * takes ONE shared opts for the whole batch, and this batch needs a per-job
+ * cwd (the outside-cwd case) plus this file's own argv wrapper (the
+ * --committed-baseline default). If runCliBatch grows per-argv opts, fold
+ * this into it.
+ */
+const batch: Record<string, RunResult> = {};
+
+async function runBatch(jobs: Array<[string, string[], string?]>, width = 2): Promise<void> {
+ let next = 0;
+ async function worker(): Promise<void> {
+ while (next < jobs.length) {
+ const idx = next++;
+ const [key, args, cwd] = jobs[idx];
+ batch[key] = await runAsync(args, cwd);
+ }
+ }
+ await Promise.all(Array.from({ length: Math.min(width, jobs.length) }, () => worker()));
+}
+
+beforeAll(async () => {
root = mkdtempSync(join(tmpdir(), 'bb-e2e-'));
fixtures = join(root, 'fixtures');
gold = join(root, 'gold');
@@ -56,14 +121,63 @@ beforeAll(() => {
const cellKey = Object.keys(doctored.counts).find((k) => doctored.counts[k].gold_total > 0)!;
doctored.counts[cellKey].gold_failed = -1; // pretends fewer failures than any run can match
writeFileSync(join(root, 'doctored.json'), JSON.stringify(doctored, null, 2));
- // The baseline build spawns a full brainbench run (~10-15s); bun's default
- // 5s hook timeout would SIGTERM it on a loaded shard. Explicit generous cap.
-}, 120_000);
+
+ const foreign = JSON.parse(readFileSync(join(root, 'base1.json'), 'utf-8'));
+ foreign.fixtures_hash = 'f'.repeat(64);
+ writeFileSync(join(root, 'foreign.json'), JSON.stringify(foreign, null, 2));
+
+ // Error-path corpora (independent tmp trees, built up front for the batch).
+ const empty = join(root, 'empty-fixtures');
+ const emptyGold = join(root, 'empty-gold');
+ mkdirSync(empty, { recursive: true });
+ mkdirSync(emptyGold, { recursive: true });
+ const badRoot = mkdtempSync(join(tmpdir(), 'bb-bad-'));
+ mkdirSync(join(badRoot, 'fixtures'));
+ mkdirSync(join(badRoot, 'gold'));
+ writeFileSync(join(badRoot, 'fixtures', 'bad.fixture.json'), '{ not json');
+ const dupRoot = mkdtempSync(join(tmpdir(), 'bb-dup-'));
+ mkdirSync(join(dupRoot, 'fixtures'));
+ mkdirSync(join(dupRoot, 'gold'));
+ // A page whose content exceeds importFromContent's size cap → status 'skipped' → SeedError.
+ const huge = 'x'.repeat(5_000_001);
+ writeFileSync(
+ join(dupRoot, 'fixtures', 'seedfail-001.fixture.json'),
+ JSON.stringify({
+ schema_version: 1,
+ fixture_id: 'seedfail-001',
+ suites: ['know-to-ask'],
+ seed_pages: [{ slug: 'people/too-big', content: `---\ntitle: Too Big\n---\n${huge}` }],
+ turns: [{ turn_id: 1, role: 'user', text: 'Hello Too Big' }],
+ }),
+ );
+ writeFileSync(
+ join(dupRoot, 'gold', 'seedfail-001.gold.json'),
+ JSON.stringify({ fixture_id: 'seedfail-001', turns: { '1': { should_retrieve: false } } }),
+ );
+ const outsideCwd = mkdtempSync(join(tmpdir(), 'bb-outside-cwd-'));
+
+ await runBatch([
+ ['outside-cwd', ['--harness', 'openclaw', '--suite', 'know-to-ask', '--json'], outsideCwd],
+ ['clean-out', ['--fixtures', fixtures, '--gold', gold, '--harness', 'openclaw', '--out', join(root, 'r1.json')]],
+ ['base2', ['--fixtures', fixtures, '--gold', gold, '--update-baseline', join(root, 'base2.json')]],
+ ['compare-own', ['--fixtures', fixtures, '--gold', gold, '--compare', join(root, 'base1.json')]],
+ ['compare-doctored', ['--fixtures', fixtures, '--gold', gold, '--compare', join(root, 'doctored.json')]],
+ ['allow-regression', ['--fixtures', fixtures, '--gold', gold, '--compare', join(root, 'doctored.json'), '--allow-regression', 'e2e test bless']],
+ ['foreign-hash', ['--fixtures', fixtures, '--gold', gold, '--compare', join(root, 'foreign.json'), '--committed-baseline', join(root, 'nonexistent.json')]],
+ ['json-complete', ['--fixtures', fixtures, '--gold', gold, '--json', '--compare', join(root, 'base1.json')]],
+ ['empty-fixtures', ['--fixtures', empty, '--gold', emptyGold]],
+ ['suite-zero', ['--fixtures', fixtures, '--gold', gold, '--suite', 'continuity']],
+ ['malformed', ['--fixtures', join(badRoot, 'fixtures'), '--gold', join(badRoot, 'gold')]],
+ ['usage-error', ['--frobnicate']],
+ ['seed-failure', ['--fixtures', join(dupRoot, 'fixtures'), '--gold', join(dupRoot, 'gold')]],
+ ]);
+ // The baseline build + 13 pooled runs each spawn a full brainbench child;
+ // bun's default 5s hook timeout would SIGTERM them on a loaded shard.
+}, 300_000);
describe('exit contract over a multi-brain run (PGLite exitCode-hijack guard)', () => {
test('bundled defaults resolve outside the package working directory', () => {
- const outside = mkdtempSync(join(tmpdir(), 'bb-outside-cwd-'));
- const r = run(['--harness', 'openclaw', '--suite', 'know-to-ask', '--json'], outside);
+ const r = batch['outside-cwd'];
expect(r.exitCode).toBe(0);
const doc = JSON.parse(r.stdout);
expect(doc.cells.length).toBeGreaterThan(0);
@@ -72,10 +186,9 @@ describe('exit contract over a multi-brain run (PGLite exitCode-hijack guard)',
}, 60_000);
test('clean run: exit 0, --out is complete valid JSON with the glossary block', () => {
- const out = join(root, 'r1.json');
- const r = run(['--fixtures', fixtures, '--gold', gold, '--harness', 'openclaw', '--out', out]);
+ const r = batch['clean-out'];
expect(r.exitCode).toBe(0);
- const doc = JSON.parse(readFileSync(out, 'utf-8'));
+ const doc = JSON.parse(readFileSync(join(root, 'r1.json'), 'utf-8'));
expect(doc.receipt.result_schema_version).toBe(1);
expect(doc.cells.length).toBeGreaterThan(0);
expect(doc._meta.metric_glossary.know_to_ask_failure_rate).toContain('thesis failure mode');
@@ -84,46 +197,32 @@ describe('exit contract over a multi-brain run (PGLite exitCode-hijack guard)',
}, 30_000);
test('--update-baseline is byte-deterministic across two runs (decision 10)', () => {
- const b2 = join(root, 'base2.json');
- expect(run(['--fixtures', fixtures, '--gold', gold, '--update-baseline', b2]).exitCode).toBe(0);
+ expect(batch['base2'].exitCode).toBe(0);
// base1.json was produced by an entirely separate run in beforeAll.
- expect(readFileSync(b2, 'utf-8')).toBe(readFileSync(join(root, 'base1.json'), 'utf-8'));
+ expect(readFileSync(join(root, 'base2.json'), 'utf-8')).toBe(readFileSync(join(root, 'base1.json'), 'utf-8'));
}, 60_000);
test('--compare against own baseline: exit 0 PASS', () => {
- const b = join(root, 'base1.json');
- const r = run(['--fixtures', fixtures, '--gold', gold, '--compare', b]);
+ const r = batch['compare-own'];
expect(r.exitCode).toBe(0);
expect(r.stdout).toContain('## Gate: PASS (same-hash)');
}, 30_000);
test('doctored main baseline (pretends fewer failures): exit 1 REGRESSION with named breach', () => {
- const r = run(['--fixtures', fixtures, '--gold', gold, '--compare', join(root, 'doctored.json')]);
+ const r = batch['compare-doctored'];
expect(r.exitCode).toBe(1);
expect(r.stdout).toContain('## Gate: REGRESSION');
expect(r.stdout).toContain('newly-failed');
}, 30_000);
test('--allow-regression flips the same comparison to exit 0 and records the reason', () => {
- const r = run([
- '--fixtures', fixtures, '--gold', gold,
- '--compare', join(root, 'doctored.json'),
- '--allow-regression', 'e2e test bless',
- ]);
+ const r = batch['allow-regression'];
expect(r.exitCode).toBe(0);
expect(r.stdout).toContain('regression allowed: e2e test bless');
}, 30_000);
test('fixtures_hash mismatch without a committed baseline: exit 2 INCONCLUSIVE', () => {
- const foreign = JSON.parse(readFileSync(join(root, 'base1.json'), 'utf-8'));
- foreign.fixtures_hash = 'f'.repeat(64);
- const path = join(root, 'foreign.json');
- writeFileSync(path, JSON.stringify(foreign, null, 2));
- const r = run([
- '--fixtures', fixtures, '--gold', gold,
- '--compare', path,
- '--committed-baseline', join(root, 'nonexistent.json'),
- ]);
+ const r = batch['foreign-hash'];
expect(r.exitCode).toBe(2);
expect(r.stdout).toContain('corpus-bless');
}, 30_000);
@@ -131,62 +230,31 @@ describe('exit contract over a multi-brain run (PGLite exitCode-hijack guard)',
describe('anti-vacuous-pass + error paths (always exit 2, never 0)', () => {
test('empty fixtures dir: exit 2', () => {
- const empty = join(root, 'empty-fixtures');
- const emptyGold = join(root, 'empty-gold');
- mkdirSync(empty, { recursive: true });
- mkdirSync(emptyGold, { recursive: true });
- const r = run(['--fixtures', empty, '--gold', emptyGold]);
+ const r = batch['empty-fixtures'];
expect(r.exitCode).toBe(2);
expect(r.stderr).toContain('vacuous');
}, 30_000);
test('suite filter matching zero fixtures: exit 2', () => {
- const r = run(['--fixtures', fixtures, '--gold', gold, '--suite', 'continuity']);
+ const r = batch['suite-zero'];
expect(r.exitCode).toBe(2);
expect(r.stderr).toContain('vacuous');
}, 30_000);
test('malformed fixture JSON: exit 2 with the validation error named', () => {
- const badRoot = mkdtempSync(join(tmpdir(), 'bb-bad-'));
- const badF = join(badRoot, 'fixtures');
- const badG = join(badRoot, 'gold');
- mkdirSync(badF);
- mkdirSync(badG);
- writeFileSync(join(badF, 'bad.fixture.json'), '{ not json');
- const r = run(['--fixtures', badF, '--gold', badG]);
+ const r = batch['malformed'];
expect(r.exitCode).toBe(2);
expect(r.stderr).toContain('invalid JSON');
}, 30_000);
test('usage error (unknown flag): exit 2 with usage', () => {
- const r = run(['--frobnicate']);
+ const r = batch['usage-error'];
expect(r.exitCode).toBe(2);
expect(r.stderr).toContain('Usage: gbrain eval brainbench');
}, 30_000);
test('seed failure (duplicate slug across seed pages in one source): exit 2, fixture named', () => {
- const dupRoot = mkdtempSync(join(tmpdir(), 'bb-dup-'));
- const dupF = join(dupRoot, 'fixtures');
- const dupG = join(dupRoot, 'gold');
- mkdirSync(dupF);
- mkdirSync(dupG);
- // A page whose content exceeds importFromContent's size cap → status 'skipped' → SeedError.
- const huge = 'x'.repeat(5_000_001);
- writeFileSync(
- join(dupF, 'seedfail-001.fixture.json'),
- JSON.stringify({
- schema_version: 1,
- fixture_id: 'seedfail-001',
- suites: ['know-to-ask'],
- seed_pages: [{ slug: 'people/too-big', content: `---\ntitle: Too Big\n---\n${huge}` }],
- turns: [{ turn_id: 1, role: 'user', text: 'Hello Too Big' }],
- }),
- );
- writeFileSync(
- join(dupG, 'seedfail-001.gold.json'),
- JSON.stringify({ fixture_id: 'seedfail-001', turns: { '1': { should_retrieve: false } } }),
- );
- const r = run(['--fixtures', dupF, '--gold', dupG]);
+ const r = batch['seed-failure'];
expect(r.exitCode).toBe(2);
expect(r.stderr).toContain('SEED FAILURES');
expect(r.stderr).toContain('seedfail-001');
@@ -242,11 +310,7 @@ describe('--json stdout completeness', () => {
test('stdout parses as a full result doc with compare embedded', () => {
// All harnesses: base1.json carries cells for all three seams, and a
// narrower run would (correctly) trip the disappeared-coverage breach.
- const r = run([
- '--fixtures', fixtures, '--gold', gold,
- '--json',
- '--compare', join(root, 'base1.json'),
- ]);
+ const r = batch['json-complete'];
expect(r.exitCode).toBe(0);
const doc = JSON.parse(r.stdout);
expect(doc.receipt.result_schema_version).toBe(1);
@@ -338,19 +402,3 @@ describe('run-all once-per-sweep semantics (decision 16)', () => {
expect(Object.keys(record.params.cells).length).toBe(12);
}, 120_000);
});
-
-describe('run-all wiring (decision 16) — full corpus, in-process', () => {
- test('runBrainBenchCore completes over the committed corpus with 12 cells', async () => {
- const { runBrainBenchCore } = await import('../src/commands/eval-brainbench.ts');
- const core = await runBrainBenchCore();
- expect(core.status).toBe('completed');
- expect(Object.keys(core.cells ?? {}).length).toBe(12);
- expect(core.fixtures_hash).toBeDefined();
- // Committed baseline matches the committed corpus hash (drift guard).
- // UNCONDITIONAL (review finding): a conditional existsSync would turn a
- // deleted baseline into a silent no-op instead of a failure.
- expect(existsSync('evals/brainbench/baselines/main.json')).toBe(true);
- const baseline = JSON.parse(readFileSync('evals/brainbench/baselines/main.json', 'utf-8'));
- expect(baseline.fixtures_hash).toBe(core.fixtures_hash);
- }, 120_000);
-});
diff --git a/test/eval-canary.test.ts b/test/eval-canary.test.ts
index a669e920b4..08d0bc81b9 100644
--- a/test/eval-canary.test.ts
+++ b/test/eval-canary.test.ts
@@ -12,7 +12,10 @@
* queryEmbedFn seam produce identical metrics.
* 5. Check mode writes nothing to tracked files (git status unchanged).
*
- * Fully hermetic: no API keys, no network, no DATABASE_URL.
+ * Fully hermetic: no API keys, no network, no DATABASE_URL. The PGLite
+ * engine is scoped to the one describe that needs it (the queryEmbedFn-seam
+ * determinism test) so the pure-function and subprocess tests don't pay
+ * engine init/reset.
*/
import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
@@ -30,26 +33,6 @@ import { hybridSearch } from '../src/core/search/hybrid.ts';
const ROOT = resolve(import.meta.dir, '..');
const QRELS_PATH = join(ROOT, 'test', 'fixtures', 'eval-baselines', 'qrels-search.json');
-// ---------------------------------------------------------------------------
-// Canonical PGLite block (CLAUDE.md R3+R4)
-// ---------------------------------------------------------------------------
-
-let engine: PGLiteEngine;
-
-beforeAll(async () => {
- engine = new PGLiteEngine();
- await engine.connect({});
- await engine.initSchema();
-});
-
-afterAll(async () => {
- await engine.disconnect();
-});
-
-beforeEach(async () => {
- await resetPgliteState(engine);
-});
-
// ---------------------------------------------------------------------------
// 1. basisEmbedding
// ---------------------------------------------------------------------------
@@ -114,6 +97,25 @@ describe('buildQrelsQueryEmbedFn', () => {
// ---------------------------------------------------------------------------
describe('correctness gate through the queryEmbedFn seam', () => {
+ // Canonical PGLite block (CLAUDE.md R3+R4), scoped to this describe: the
+ // seam test is the ONLY engine consumer in the file — the pure-function
+ // and subprocess describes must not pay PGLite init/reset.
+ let engine: PGLiteEngine;
+
+ beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ });
+
+ afterAll(async () => {
+ await engine.disconnect();
+ });
+
+ beforeEach(async () => {
+ await resetPgliteState(engine);
+ });
+
test('two in-process runs produce identical metrics, at/above the default floors', async () => {
const raw = readFileSync(QRELS_PATH, 'utf-8');
await seedCanaryCorpus(engine, parseLegacyQrels(raw));
diff --git a/test/extract-atoms-chunk-embed.test.ts b/test/extract-atoms-chunk-embed.test.ts
index 90984ec836..43387990fe 100644
--- a/test/extract-atoms-chunk-embed.test.ts
+++ b/test/extract-atoms-chunk-embed.test.ts
@@ -20,6 +20,7 @@ import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
import { serializeMarkdown, parseMarkdown } from '../src/core/markdown.ts';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { runPhaseExtractAtoms } from '../src/core/cycle/extract-atoms.ts';
+import { configureGateway, resetGateway, isAvailable } from '../src/core/ai/gateway.ts';
import type { ChatResult, ChatOpts } from '../src/core/ai/gateway.ts';
/** Mirrors the write site in extract-atoms.ts. */
@@ -157,14 +158,34 @@ describe('extracted atoms reach content_chunks (PGLite round-trip)', () => {
// src file and re-running.
let engine: PGLiteEngine;
beforeAll(async () => {
+ // Hermetic embedding (TODOS "deflake extract-atoms chunk-embed"): pin the
+ // gateway to a KEYLESS config so importFromContent's
+ // `noEmbed: !isAvailable('embedding')` (extract-atoms.ts write site) is
+ // deterministically true. A shard-neighbor's leaked provider key otherwise
+ // reaches the gateway singleton via the preload's `env: {...process.env}`
+ // snapshot (surviving the neighbor's own env restore), the atom import
+ // fires a real embed inside withBudgetTracker, reserve() throws
+ // BudgetExhausted(no_pricing), and every work item is skipped → status
+ // 'warn' with 0 processed. Same pin as test/ambient-recall.test.ts.
+ // Dimensions stay 1536 to match the preload's schema width; configure
+ // BEFORE initSchema (the vector column width tracks gateway dims).
+ configureGateway({
+ embedding_model: 'openai:text-embedding-3-large',
+ embedding_dimensions: 1536,
+ env: {},
+ });
engine = new PGLiteEngine();
await engine.connect({});
await engine.initSchema();
});
afterAll(async () => {
await engine.disconnect();
+ resetGateway(); // back to the preload baseline; don't leak env:{} onward
});
test('runPhaseExtractAtoms writes content_chunks rows for atom pages', async () => {
+ // Self-asserting hermeticity pin: if a neighbor's key ever reaches the
+ // gateway again, fail loudly here instead of flaking downstream.
+ expect(isAvailable('embedding')).toBe(false);
{
const chat = async (_o: ChatOpts): Promise<ChatResult> => ({
text: `[{"title":"Chunked atom","atom_type":"insight","body":"Enterprise buyers want tangible prototypes, not renders."}]`,
diff --git a/test/frontmatter-cli.test.ts b/test/frontmatter-cli.test.ts
index 598f4aab7b..0484d99448 100644
--- a/test/frontmatter-cli.test.ts
+++ b/test/frontmatter-cli.test.ts
@@ -1,23 +1,93 @@
+/**
+ * gbrain frontmatter CLI (src/commands/frontmatter.ts) — validate + generate
+ * on real tmp-dir fixtures, no DB.
+ *
+ * runFrontmatter is driven IN-PROCESS for the pure-filesystem paths:
+ * frontmatter.ts writes through console.log/console.error (never
+ * process.stdout.write), so the harness swaps the console methods and reads
+ * exit codes through currentExitCode() — the gbrain-owned verdict channel the
+ * real CLI exit seam reads (same harness family as test/loops-cli.test.ts;
+ * console capture per test/cache-cli.test.ts). GBRAIN_HOME is resolved lazily
+ * per call (configDir()), so withEnv scopes the backup root per test.
+ *
+ * Two invocations stay REAL spawns as CLI wiring smokes so
+ * `bun src/cli.ts frontmatter ...` exit codes stay pinned end-to-end:
+ * one validate (exit 1 on errors) and one --fix (exit 0 + centralized backup
+ * under GBRAIN_HOME).
+ */
+
import { describe, expect, test, beforeEach, afterEach } from 'bun:test';
-import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, rmSync } from 'fs';
+import {
+ mkdtempSync,
+ mkdirSync,
+ writeFileSync,
+ readFileSync,
+ existsSync,
+ rmSync,
+ readdirSync,
+} from 'fs';
import { join } from 'path';
import { tmpdir } from 'os';
-import { spawnSync } from 'child_process';
+
+import { runFrontmatter } from '../src/commands/frontmatter.ts';
+import {
+ currentExitCode,
+ _resetCliExitVerdictForTests,
+} from '../src/core/cli-force-exit.ts';
+import { runCli } from './helpers/cli-spawn.ts';
+import { withEnv } from './helpers/with-env.ts';
const fence = '---';
-const CLI = ['run', 'src/cli.ts', 'frontmatter'];
-function runCli(args: string[], env: Record<string, string> = {}): { stdout: string; stderr: string; code: number } {
- const result = spawnSync(process.execPath, [...CLI, ...args], {
- encoding: 'utf8',
- cwd: process.cwd(),
- env: { ...process.env, ...env },
- });
- return {
- stdout: result.stdout ?? '',
- stderr: result.stderr ?? '',
- code: result.status ?? -1,
- };
+interface Captured {
+ out: string;
+ err: string;
+ /** gbrain's owned exit verdict after the run (0 when none was set). */
+ verdict: number;
+}
+
+/**
+ * Drive `gbrain frontmatter <args>` in-process. Frontmatter output goes
+ * exclusively through console.log/console.error; the verdict channel is reset
+ * before the run and read (then cleared, mirror included) after so no verdict
+ * leaks into other tests in the shard.
+ */
+async function runFm(args: string[]): Promise<Captured> {
+ const logOrig = console.log;
+ const errOrig = console.error;
+ const prevExitCode = process.exitCode;
+ const out: string[] = [];
+ const err: string[] = [];
+ _resetCliExitVerdictForTests();
+ console.log = (...a: unknown[]) => { out.push(a.map(String).join(' ') + '\n'); };
+ console.error = (...a: unknown[]) => { err.push(a.map(String).join(' ') + '\n'); };
+ try {
+ await runFrontmatter(args);
+ } finally {
+ console.log = logOrig;
+ console.error = errOrig;
+ }
+ const verdict = currentExitCode();
+ // Never leak a verdict (or its process.exitCode mirror) into other tests.
+ _resetCliExitVerdictForTests();
+ process.exitCode = prevExitCode ?? 0;
+ return { out: out.join(''), err: err.join(''), verdict };
+}
+
+/** In-process replacement for the old `find <dir> -name <name>` child. */
+function findFilesNamed(dir: string, name: string): string[] {
+ if (!existsSync(dir)) return [];
+ const hits: string[] = [];
+ const stack = [dir];
+ while (stack.length > 0) {
+ const d = stack.pop()!;
+ for (const entry of readdirSync(d, { withFileTypes: true })) {
+ const full = join(d, entry.name);
+ if (entry.isDirectory()) stack.push(full);
+ else if (entry.isFile() && entry.name === name) hits.push(full);
+ }
+ }
+ return hits;
}
describe('gbrain frontmatter CLI (B4)', () => {
@@ -31,115 +101,126 @@ describe('gbrain frontmatter CLI (B4)', () => {
rmSync(tmp, { recursive: true, force: true });
});
- test('--help works without a DB', () => {
- const { stdout, code } = runCli(['--help']);
- expect(code).toBe(0);
- expect(stdout).toContain('frontmatter validation');
+ test('--help works without a DB', async () => {
+ const { out, verdict } = await runFm(['--help']);
+ expect(verdict).toBe(0);
+ expect(out).toContain('frontmatter validation');
});
- test('validate clean file: exit 0, OK message', () => {
+ test('validate clean file: exit 0, OK message', async () => {
const f = join(tmp, 'clean.md');
writeFileSync(f, `${fence}\ntype: concept\ntitle: ok\n${fence}\n\nbody`);
- const { stdout, code } = runCli(['validate', f]);
- expect(code).toBe(0);
- expect(stdout).toContain('OK');
+ const { out, verdict } = await runFm(['validate', f]);
+ expect(verdict).toBe(0);
+ expect(out).toContain('OK');
});
- test('validate broken file: exit 1, codes listed', () => {
+ // CLI wiring smoke #1 (kept as a real spawn): the validate error path's
+ // exit code must survive cli.ts dispatch + the exit seam, not just the
+ // in-process verdict channel.
+ test('validate broken file: exit 1, codes listed', async () => {
const f = join(tmp, 'broken.md');
writeFileSync(f, `${fence}\ntype: concept\ntitle: "P "I" L"\n${fence}\n\nbody`);
- const { stdout, code } = runCli(['validate', f]);
- expect(code).toBe(1);
+ const { stdout, exitCode } = await runCli(['frontmatter', 'validate', f]);
+ expect(exitCode).toBe(1);
expect(stdout).toContain('NESTED_QUOTES');
- });
+ }, 60_000);
- test('validate --json envelope shape', () => {
+ test('validate --json envelope shape', async () => {
const f = join(tmp, 'broken.md');
writeFileSync(f, `${fence}\ntype: concept\ntitle: "P "I" L"\n${fence}\n\nbody`);
- const { stdout } = runCli(['validate', f, '--json']);
- const env = JSON.parse(stdout);
+ const { out } = await runFm(['validate', f, '--json']);
+ const env = JSON.parse(out);
expect(env.ok).toBe(false);
expect(env.total_files).toBe(1);
expect(env.results[0].errors.length).toBeGreaterThan(0);
expect(env.results[0].errors[0]).toHaveProperty('code');
});
- test('validate --fix --dry-run does not write', () => {
+ test('validate --fix --dry-run does not write', async () => {
const f = join(tmp, 'broken.md');
const original = `${fence}\ntype: concept\ntitle: "P "I" L"\n${fence}\n\nbody`;
writeFileSync(f, original);
- const { stdout, code } = runCli(['validate', f, '--fix', '--dry-run']);
- expect(stdout).toContain('would fix');
+ const { out, verdict } = await runFm(['validate', f, '--fix', '--dry-run']);
+ expect(out).toContain('would fix');
expect(readFileSync(f, 'utf8')).toBe(original);
expect(existsSync(f + '.bak')).toBe(false);
// exit 0 with --fix even when issues remain (the fix path is the success path)
- expect(code).toBe(0);
+ expect(verdict).toBe(0);
});
- test('validate --fix writes centralized backup and rewrites in place', () => {
+ // CLI wiring smoke #2 (kept as a real spawn): --fix through the real CLI,
+ // pinning exit 0 + the GBRAIN_HOME-routed centralized backup end-to-end.
+ test('validate --fix writes centralized backup and rewrites in place', async () => {
const f = join(tmp, 'broken.md');
const gbrainHome = join(tmp, 'home');
const original = `${fence}\ntype: concept\ntitle: "P "I" L"\n${fence}\n\nbody`;
writeFileSync(f, original);
- const { stdout, code } = runCli(['validate', f, '--fix'], { GBRAIN_HOME: gbrainHome });
- expect(code).toBe(0);
+ const { stdout, exitCode } = await runCli(
+ ['frontmatter', 'validate', f, '--fix'],
+ { env: { GBRAIN_HOME: gbrainHome } },
+ );
+ expect(exitCode).toBe(0);
expect(existsSync(f + '.bak')).toBe(false);
expect(stdout).toContain('centralized backups');
const backupDir = join(gbrainHome, '.gbrain', 'backups', 'frontmatter');
- const backup = spawnSync('find', [backupDir, '-type', 'f', '-name', 'broken.md.bak'], { encoding: 'utf8' });
- const backupPath = backup.stdout.trim().split('\n').filter(Boolean)[0];
+ const backupPath = findFilesNamed(backupDir, 'broken.md.bak')[0];
expect(backupPath).toBeTruthy();
expect(readFileSync(backupPath, 'utf8')).toBe(original);
expect(readFileSync(f, 'utf8')).toMatch(/^title: '.*'\s*$/m);
- });
+ }, 60_000);
- test('validate --fix succeeds on a non-git path (no dirty-tree guard)', () => {
+ test('validate --fix succeeds on a non-git path (no dirty-tree guard)', async () => {
// tmp is not a git repo; --fix must still work.
const f = join(tmp, 'broken.md');
const gbrainHome = join(tmp, 'home');
writeFileSync(f, `${fence}\ntype: concept\ntitle: "A "B" C"\n${fence}\n\nbody`);
- const { code } = runCli(['validate', f, '--fix'], { GBRAIN_HOME: gbrainHome });
- expect(code).toBe(0);
+ const { verdict } = await withEnv({ GBRAIN_HOME: gbrainHome }, () =>
+ runFm(['validate', f, '--fix']),
+ );
+ expect(verdict).toBe(0);
expect(existsSync(f + '.bak')).toBe(false);
expect(existsSync(join(gbrainHome, '.gbrain', 'backups', 'frontmatter'))).toBe(true);
});
- test('validate scans a directory recursively, skips non-.md files', () => {
+ test('validate scans a directory recursively, skips non-.md files', async () => {
mkdirSync(join(tmp, 'subdir'), { recursive: true });
writeFileSync(join(tmp, 'a.md'), `${fence}\ntype: concept\ntitle: A\n${fence}\n\nbody`);
writeFileSync(join(tmp, 'subdir', 'b.md'), `${fence}\ntype: concept\ntitle: B\n${fence}\n\nbody`);
writeFileSync(join(tmp, 'README.md'), 'meta'); // skipped by isSyncable
writeFileSync(join(tmp, 'image.png'), 'not markdown');
- const { stdout } = runCli(['validate', tmp, '--json']);
- const env = JSON.parse(stdout);
+ const { out } = await runFm(['validate', tmp, '--json']);
+ const env = JSON.parse(out);
// Two .md files: a.md, subdir/b.md. README.md is filtered by isSyncable.
expect(env.total_files).toBe(2);
});
- test('generate --fix skips catch-all note writes unless explicitly included', () => {
+ test('generate --fix skips catch-all note writes unless explicitly included', async () => {
const gbrainHome = join(tmp, 'home');
writeFileSync(join(tmp, 'random.md'), '# Random\n\nbody');
writeFileSync(join(tmp, 'notes.md'), '# Also Random\n\nbody');
- const skipped = runCli(['generate', tmp, '--fix', '--json'], { GBRAIN_HOME: gbrainHome });
- expect(skipped.code).toBe(0);
- const skippedEnv = JSON.parse(skipped.stdout);
- expect(skippedEnv.generated).toBe(0);
- expect(skippedEnv.skippedCatchAll).toBe(2);
- expect(readFileSync(join(tmp, 'random.md'), 'utf8')).toBe('# Random\n\nbody');
-
- const included = runCli(['generate', tmp, '--fix', '--json', '--include-catch-all'], { GBRAIN_HOME: gbrainHome });
- expect(included.code).toBe(0);
- const includedEnv = JSON.parse(included.stdout);
- expect(includedEnv.generated).toBe(2);
- expect(readFileSync(join(tmp, 'random.md'), 'utf8')).toContain('type: note');
- expect(existsSync(join(gbrainHome, '.gbrain', 'backups', 'frontmatter'))).toBe(true);
- expect(existsSync(join(tmp, 'random.md.bak'))).toBe(false);
+ await withEnv({ GBRAIN_HOME: gbrainHome }, async () => {
+ const skipped = await runFm(['generate', tmp, '--fix', '--json']);
+ expect(skipped.verdict).toBe(0);
+ const skippedEnv = JSON.parse(skipped.out);
+ expect(skippedEnv.generated).toBe(0);
+ expect(skippedEnv.skippedCatchAll).toBe(2);
+ expect(readFileSync(join(tmp, 'random.md'), 'utf8')).toBe('# Random\n\nbody');
+
+ const included = await runFm(['generate', tmp, '--fix', '--json', '--include-catch-all']);
+ expect(included.verdict).toBe(0);
+ const includedEnv = JSON.parse(included.out);
+ expect(includedEnv.generated).toBe(2);
+ expect(readFileSync(join(tmp, 'random.md'), 'utf8')).toContain('type: note');
+ expect(existsSync(join(gbrainHome, '.gbrain', 'backups', 'frontmatter'))).toBe(true);
+ expect(existsSync(join(tmp, 'random.md.bak'))).toBe(false);
+ });
});
- test('validate missing path errors clearly', () => {
- const { stderr, code } = runCli(['validate', join(tmp, 'does-not-exist.md')]);
- expect(code).toBe(1);
- expect(stderr).toContain('not found');
+ test('validate missing path errors clearly', async () => {
+ const { err, verdict } = await runFm(['validate', join(tmp, 'does-not-exist.md')]);
+ expect(verdict).toBe(1);
+ expect(err).toContain('not found');
});
});
diff --git a/test/git-remote.test.ts b/test/git-remote.test.ts
index c565227b04..df5487dd2e 100644
--- a/test/git-remote.test.ts
+++ b/test/git-remote.test.ts
@@ -17,6 +17,7 @@ import {
} from '../src/core/git-remote.ts';
import { execFileSync } from 'child_process';
import { withEnv } from './helpers/with-env.ts';
+import { gitStderrLeads } from './helpers/git-stderr-probe.ts';
// ---------------------------------------------------------------------------
// Fake-git harness: write a shell script that records its argv to a log file,
@@ -488,7 +489,10 @@ describe('#1315 — stderr-first GitOperationError (real git, file-origin repo)'
return mirror;
}
- test('pullRepo message leads with the real git stderr, not the Command-failed envelope', () => {
+ // skipIf: pins "git's own fatal: appears within the first 200 chars" —
+ // unrunnable behind an ambient git PATH shim that prints its own stderr
+ // first (e.g. Conductor's auth-broker wrapper). See helpers/git-stderr-probe.
+ test.skipIf(!gitStderrLeads())('pullRepo message leads with the real git stderr, not the Command-failed envelope', () => {
const mirror = mkFileOriginMirror();
let threw: GitOperationError | undefined;
try {
@@ -507,7 +511,7 @@ describe('#1315 — stderr-first GitOperationError (real git, file-origin repo)'
expect(threw!.cause).toBeDefined();
});
- test('fetchRemote message is stderr-first too', () => {
+ test.skipIf(!gitStderrLeads())('fetchRemote message is stderr-first too', () => {
const mirror = mkFileOriginMirror();
let threw: GitOperationError | undefined;
try {
diff --git a/test/helpers/cli-spawn.test.ts b/test/helpers/cli-spawn.test.ts
new file mode 100644
index 0000000000..2ccc3ce40c
--- /dev/null
+++ b/test/helpers/cli-spawn.test.ts
@@ -0,0 +1,168 @@
+/**
+ * Unit tests for cli-spawn.ts via the `_setSpawnTarget` seam: children are
+ * `bun -e <script>` fixtures (~50ms each), never the real CLI, so the whole
+ * file stays under ~5s. Pins: batch width cap, input-order results, memo
+ * identity, timeout reaping, env hermeticity.
+ */
+import { describe, test, expect, beforeEach, afterEach } from 'bun:test';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { withEnv } from './with-env.ts';
+import {
+ runCli,
+ runCliBatch,
+ runCliMemo,
+ clearCliMemo,
+ _setSpawnTarget,
+} from './cli-spawn.ts';
+
+beforeEach(() => {
+ // Children become `bun -e <argv[0]>` — process.execPath is bun under bun test.
+ _setSpawnTarget([process.execPath, '-e']);
+});
+
+afterEach(() => {
+ _setSpawnTarget(null);
+ clearCliMemo();
+});
+
+describe('runCli', () => {
+ test('captures stdout, stderr, and exit code', async () => {
+ // exitCode (not process.exit) so pipe output can't be truncated mid-flush.
+ const r = await runCli([
+ `console.log('out'); console.error('err'); process.exitCode = 3;`,
+ ]);
+ expect(r.stdout.trim()).toBe('out');
+ expect(r.stderr.trim()).toBe('err');
+ expect(r.exitCode).toBe(3);
+ });
+
+ test('timeout kills the child and still resolves', async () => {
+ const t0 = Date.now();
+ const r = await runCli(
+ [`setTimeout(() => console.log('late'), 8000);`],
+ { timeoutMs: 300 },
+ );
+ expect(Date.now() - t0).toBeLessThan(5000);
+ expect(r.exitCode).not.toBe(0);
+ expect(r.stdout).not.toContain('late');
+ });
+
+ test('hermetic env: DATABASE_URL / GBRAIN_DATABASE_URL stripped, startup hooks skipped', async () => {
+ await withEnv(
+ { DATABASE_URL: 'postgres://leak', GBRAIN_DATABASE_URL: 'postgres://leak2' },
+ async () => {
+ const r = await runCli([
+ `console.log([process.env.DATABASE_URL, process.env.GBRAIN_DATABASE_URL, process.env.GBRAIN_SKIP_STARTUP_HOOKS].map(v => v ?? 'unset').join('|'));`,
+ ]);
+ expect(r.exitCode).toBe(0);
+ expect(r.stdout.trim()).toBe('unset|unset|1');
+ },
+ );
+ });
+
+ test('opts.home sets HOME and GBRAIN_HOME; opts.env undefined deletes a key', async () => {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-cli-spawn-home-'));
+ try {
+ const r = await runCli(
+ [`console.log([process.env.HOME, process.env.GBRAIN_HOME].join('|'));`],
+ { home },
+ );
+ expect(r.stdout.trim()).toBe(`${home}|${home}`);
+ } finally {
+ rmSync(home, { recursive: true, force: true });
+ }
+
+ await withEnv({ GBRAIN_CLI_SPAWN_TEST_VAR: 'ambient' }, async () => {
+ const r = await runCli(
+ [`console.log(process.env.GBRAIN_CLI_SPAWN_TEST_VAR ?? 'unset');`],
+ { env: { GBRAIN_CLI_SPAWN_TEST_VAR: undefined } },
+ );
+ expect(r.stdout.trim()).toBe('unset');
+ });
+ });
+});
+
+describe('runCliBatch', () => {
+ test('results preserve input order even when completion order inverts', async () => {
+ const script = (idx: number, ms: number) =>
+ `setTimeout(() => console.log('idx-${idx}'), ${ms});`;
+ const results = await runCliBatch(
+ [[script(0, 120)], [script(1, 10)], [script(2, 10)]],
+ { width: 3 },
+ );
+ expect(results.map(r => r.stdout.trim())).toEqual(['idx-0', 'idx-1', 'idx-2']);
+ });
+
+ test('width cap: never more than `width` children in flight', async () => {
+ // Each child reports its own start/end wall-clock (one clock domain);
+ // peak interval overlap is the true simultaneity, immune to pool timing.
+ const argvs = [0, 1, 2, 3].map(i => [
+ `const s = Date.now(); setTimeout(() => console.log('${i}|' + s + '|' + Date.now()), 120);`,
+ ]);
+ const results = await runCliBatch(argvs, { width: 2 });
+ const spans = results.map((r, i) => {
+ const parts = r.stdout.trim().split('|');
+ expect(parts[0]).toBe(String(i)); // order preserved too
+ return { start: Number(parts[1]), end: Number(parts[2]) };
+ });
+ const events = spans
+ .flatMap(s => [{ t: s.start, d: 1 }, { t: s.end, d: -1 }])
+ .sort((a, b) => a.t - b.t || a.d - b.d); // tie: end before start
+ let running = 0;
+ let peak = 0;
+ for (const e of events) {
+ running += e.d;
+ peak = Math.max(peak, running);
+ }
+ expect(peak).toBeGreaterThanOrEqual(1);
+ expect(peak).toBeLessThanOrEqual(2);
+ });
+
+ test('empty input resolves to empty results', async () => {
+ expect(await runCliBatch([])).toEqual([]);
+ });
+
+ test('spawn failure rejects the batch', async () => {
+ // Relies on Bun.spawn throwing for a nonexistent executable
+ // (it does in current Bun; if a future Bun returns an exited-with-error
+ // subprocess instead, this becomes a resolved nonzero-exit batch and the
+ // assertion needs revisiting). Reap-of-siblings is exercised implicitly:
+ // both argvs share the broken target, and the catch path awaits them.
+ _setSpawnTarget(['/nonexistent-gbrain-cli-spawn-fixture']);
+ await expect(runCliBatch([[], []], { width: 2 })).rejects.toThrow();
+ });
+});
+
+describe('runCliMemo', () => {
+ test('memo hit returns the identical object without respawning', async () => {
+ // Child output is unique per spawn; identical stdout proves no respawn.
+ const argv = [`console.log(Date.now() + '-' + Math.random());`];
+ const [a, b] = await Promise.all([runCliMemo(argv), runCliMemo(argv)]);
+ expect(a).toBe(b);
+
+ // Key is argv content + home, not array identity.
+ const c = await runCliMemo([...argv]);
+ expect(c).toBe(a);
+
+ clearCliMemo();
+ const d = await runCliMemo(argv);
+ expect(d).not.toBe(a);
+ expect(d.stdout).not.toBe(a.stdout);
+ });
+
+ test('different argv or home misses the memo', async () => {
+ const argv = [`console.log('memo-fixture');`];
+ const a = await runCliMemo(argv);
+ const b = await runCliMemo([`console.log('memo-fixture');/*v2*/`]);
+ expect(b).not.toBe(a);
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-cli-memo-home-'));
+ try {
+ const c = await runCliMemo(argv, { home });
+ expect(c).not.toBe(a);
+ } finally {
+ rmSync(home, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/test/helpers/cli-spawn.ts b/test/helpers/cli-spawn.ts
new file mode 100644
index 0000000000..299bd22423
--- /dev/null
+++ b/test/helpers/cli-spawn.ts
@@ -0,0 +1,252 @@
+/**
+ * Hermetic async CLI spawn wrappers for subprocess tests against the real
+ * `src/cli.ts` entrypoint. Consolidates the hand-rolled `run()` helpers in
+ * ambient-recall-cli.test.ts / cli-dispatch-thin-client.test.ts.
+ *
+ * Constraints:
+ * - Async Bun.spawn (NOT spawnSync/execFileSync) — the test event loop
+ * stays responsive; see init-mcp-only.test.ts for the rationale.
+ * - Hermetic env: DATABASE_URL / GBRAIN_DATABASE_URL /
+ * GBRAIN_REMOTE_CLIENT_SECRET are ALWAYS stripped (a dev shell's ambient
+ * Postgres URL or remote secret must never reach a test child), the real
+ * CLI is spawned with `--no-env-file` so a repo-root .env cannot
+ * re-inject what the strip removed, and GBRAIN_SKIP_STARTUP_HOOKS=1 so no
+ * detached check-update child leaks past the test (override via opts.env
+ * if a test needs the hooks). Provider keys (OPENAI_/ANTHROPIC_API_KEY)
+ * are NOT stripped here — the bunfig provider-keys preload already scrubs
+ * them from the test process, so children inherit the scrubbed set;
+ * strip per-call via opts.env when a test re-injects them.
+ * - `opts.home` sets BOTH HOME and GBRAIN_HOME so the child cannot read or
+ * clobber the operator's real ~/.gbrain.
+ * - The DIRECT child is reaped: timeout sends SIGTERM, escalates to SIGKILL
+ * +2s later, and the result always awaits `exited`. Grandchildren the CLI
+ * forks are NOT swept — a caller whose CLI spawns heavy subprocesses
+ * should assert on their completion, not rely on the timeout kill.
+ */
+import { existsSync } from 'node:fs';
+import { dirname, join } from 'node:path';
+
+export interface CliResult {
+ stdout: string;
+ stderr: string;
+ exitCode: number;
+}
+
+export interface CliSpawnOpts {
+ /** Merged over the hermetic base env; `undefined` value deletes the key. */
+ env?: Record<string, string | undefined>;
+ /** Child working directory. Default: repo root. */
+ cwd?: string;
+ /** Sets HOME and GBRAIN_HOME in the child. */
+ home?: string;
+ /** SIGTERM the child after this long (SIGKILL +2s later). Default 60000. */
+ timeoutMs?: number;
+}
+
+/**
+ * Locate the repo root by walking up until `src/cli.ts` exists — never
+ * hardcode a `../..` depth (survives this helper moving directories).
+ */
+function findRepoRoot(from: string): string {
+ let dir = from;
+ for (;;) {
+ if (existsSync(join(dir, 'src', 'cli.ts'))) return dir;
+ const parent = dirname(dir);
+ if (parent === dir) {
+ throw new Error(`cli-spawn: no src/cli.ts found in any ancestor of ${from}`);
+ }
+ dir = parent;
+ }
+}
+
+const REPO_ROOT = findRepoRoot(import.meta.dir);
+const CLI_PATH = join(REPO_ROOT, 'src', 'cli.ts');
+
+/**
+ * Test seam: replaces the `[process.execPath, CLI_PATH]` command prefix so
+ * cli-spawn's own unit tests can exercise pool/timeout/env behavior against a
+ * tiny `bun -e` fixture instead of booting the real CLI (~1.5GB PGLite).
+ * Pass null to restore the real CLI. Reset in afterEach — module-global.
+ */
+let spawnTargetOverride: readonly string[] | null = null;
+
+export function _setSpawnTarget(cmd: readonly string[] | null): void {
+ spawnTargetOverride = cmd;
+}
+
+function buildEnv(opts?: CliSpawnOpts): Record<string, string> {
+ const env: Record<string, string> = {};
+ for (const [k, v] of Object.entries(process.env)) {
+ if (v !== undefined) env[k] = v;
+ }
+ delete env.DATABASE_URL;
+ delete env.GBRAIN_DATABASE_URL;
+ delete env.GBRAIN_REMOTE_CLIENT_SECRET;
+ env.GBRAIN_SKIP_STARTUP_HOOKS = '1';
+ if (opts?.home !== undefined) {
+ env.HOME = opts.home;
+ env.GBRAIN_HOME = opts.home;
+ }
+ if (opts?.env) {
+ for (const [k, v] of Object.entries(opts.env)) {
+ if (v === undefined) delete env[k];
+ else env[k] = v;
+ }
+ }
+ return env;
+}
+
+// Wrapper exists so `Child` is the exact inferred Subprocess specialization
+// (stdout/stderr typed as ReadableStream) without naming Bun generics.
+function spawnChild(cmd: string[], env: Record<string, string>, cwd: string) {
+ return Bun.spawn({ cmd, env, cwd, stdin: 'ignore', stdout: 'pipe', stderr: 'pipe' });
+}
+type Child = ReturnType<typeof spawnChild>;
+
+async function spawnOnce(
+ args: string[],
+ opts: CliSpawnOpts | undefined,
+ onSpawn?: (proc: Child) => void,
+ onSettle?: (proc: Child) => void,
+): Promise<CliResult> {
+ // --no-env-file: bun auto-loads a repo-root .env into the child, which
+ // would re-inject the exact vars buildEnv() strips (a dev .env defining
+ // GBRAIN_DATABASE_URL un-hermeticizes every consumer). The wrapper this
+ // helper replaced passed the flag for the same reason.
+ const prefix = spawnTargetOverride ?? [process.execPath, '--no-env-file', CLI_PATH];
+ const proc = spawnChild([...prefix, ...args], buildEnv(opts), opts?.cwd ?? REPO_ROOT);
+ onSpawn?.(proc);
+ const timeoutMs = opts?.timeoutMs ?? 60_000;
+ const term = setTimeout(() => {
+ try { proc.kill(); } catch { /* already exited */ }
+ }, timeoutMs);
+ // A child that ignores SIGTERM would hang the suite; escalate.
+ const hardKill = setTimeout(() => {
+ try { proc.kill(9); } catch { /* already exited */ }
+ }, timeoutMs + 2_000);
+ try {
+ const [stdout, stderr, exitCode] = await Promise.all([
+ new Response(proc.stdout).text(),
+ new Response(proc.stderr).text(),
+ proc.exited,
+ ]);
+ // Bun types `exited` as Promise<number>, but a signal-killed child's
+ // code is runtime-defined; coerce a hypothetical null to -1 so
+ // CliResult.exitCode is always a number (and never 0 on timeout).
+ return { stdout, stderr, exitCode: exitCode ?? -1 };
+ } catch (err) {
+ // A rejected pipe read exits Promise.all BEFORE proc.exited — without
+ // this, the finally below would clear both kill timers on a still-running
+ // child and break the reap guarantee.
+ try { proc.kill(9); } catch { /* already exited */ }
+ await proc.exited.catch(() => {});
+ throw err;
+ } finally {
+ clearTimeout(term);
+ clearTimeout(hardKill);
+ onSettle?.(proc);
+ }
+}
+
+/**
+ * Spawn `bun src/cli.ts <args>` once. Never throws on nonzero exit — the
+ * exit code is data (assert on it). Throws only when the spawn itself fails
+ * (missing executable) — see runCliBatch for the reap guarantee there.
+ */
+export async function runCli(args: string[], opts?: CliSpawnOpts): Promise<CliResult> {
+ return spawnOnce(args, opts);
+}
+
+/**
+ * Run many CLI invocations through a bounded-concurrency pool, results in
+ * INPUT order regardless of completion order.
+ *
+ * DEFAULT WIDTH 2 — do not raise casually. The cap is per-invocation: the
+ * parallel runner puts 4 shards on one machine, so 4 shards x width
+ * multiplies CLI children machine-wide, and each child can boot a ~1.5GB
+ * PGLite. Keep 2 unless the file is alone in a lane.
+ *
+ * If any spawn throws, all still-running children are killed and awaited
+ * (reaped — no orphans) before the error propagates.
+ */
+export async function runCliBatch(
+ argvs: string[][],
+ opts?: CliSpawnOpts & { width?: number },
+): Promise<CliResult[]> {
+ const width = Math.max(1, Math.floor(opts?.width ?? 2));
+ const results: CliResult[] = new Array(argvs.length);
+ const live = new Set<Child>();
+ let aborted = false;
+ let next = 0;
+
+ async function worker(): Promise<void> {
+ for (;;) {
+ if (aborted) return;
+ const i = next;
+ next += 1;
+ if (i >= argvs.length) return;
+ results[i] = await spawnOnce(
+ argvs[i],
+ opts,
+ p => live.add(p),
+ p => live.delete(p),
+ );
+ }
+ }
+
+ const workers = Array.from({ length: Math.min(width, argvs.length) }, () => worker());
+ try {
+ await Promise.all(workers);
+ } catch (err) {
+ aborted = true;
+ for (const p of live) {
+ try { p.kill(); } catch { /* already exited */ }
+ }
+ // Wait for every worker to settle (a sibling may have spawned between
+ // the sweep above and its abort check), then sweep + reap once more.
+ await Promise.allSettled(workers);
+ for (const p of live) {
+ try { p.kill(); } catch { /* already exited */ }
+ }
+ await Promise.allSettled([...live].map(p => p.exited));
+ throw err;
+ }
+ return results;
+}
+
+// Keyed on (argv, home) ONLY — env/cwd/timeout differences do NOT miss.
+const memo = new Map<string, Promise<CliResult>>();
+
+/**
+ * Memoized runCli for PURE READ-ONLY invocations (`--help`, `--tools-json`,
+ * `--version`) that many tests repeat verbatim. A hit returns the identical
+ * CliResult object without respawning. Never use for anything that touches
+ * the brain or depends on opts.env — the key is argv + home only. Failed
+ * spawns are evicted so an error isn't cached.
+ */
+export function runCliMemo(args: string[], opts?: CliSpawnOpts): Promise<CliResult> {
+ if (opts?.env !== undefined || opts?.cwd !== undefined) {
+ // The memo key is argv+home+timeout ONLY — an env/cwd-varying call served
+ // from cache would silently return a result produced under different inputs.
+ throw new Error('runCliMemo: opts.env/opts.cwd are not part of the memo key — use runCli');
+ }
+ const key = JSON.stringify([args, opts?.home ?? null, opts?.timeoutMs ?? null]);
+ const hit = memo.get(key);
+ if (hit) return hit;
+ // Freeze the settled result: hits share ONE object across test files in the
+ // same shard process — a caller mutating it would poison later consumers.
+ // Nonzero exits (including timeout kills, exitCode -1/143) are EVICTED after
+ // being returned to the caller that triggered them — one overloaded-machine
+ // timeout must not poison every later identical assertion in the shard.
+ const p = runCli(args, opts).then(r => {
+ if (r.exitCode !== 0) memo.delete(key);
+ return Object.freeze(r) as CliResult;
+ });
+ memo.set(key, p);
+ p.catch(() => memo.delete(key));
+ return p;
+}
+
+export function clearCliMemo(): void {
+ memo.clear();
+}
diff --git a/test/helpers/fs-perms.ts b/test/helpers/fs-perms.ts
new file mode 100644
index 0000000000..f99aa5456d
--- /dev/null
+++ b/test/helpers/fs-perms.ts
@@ -0,0 +1,50 @@
+/**
+ * Environment probes for tests that depend on OS behavior the host may not
+ * provide. Some sandboxes (Vercel sandboxes, certain container/FUSE overlay
+ * filesystems, root shells) do not enforce file permission bits: writes into
+ * a 0555 directory and reads of a 0000 file both succeed. Tests that assert
+ * "this write MUST fail" are unrunnable there — skip them visibly instead of
+ * failing red. CI (ubuntu runners, non-root) enforces permissions, so the
+ * skips never fire where the coverage matters.
+ *
+ * Probes are cached: one filesystem round-trip per process.
+ */
+import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+let _permsEnforced: boolean | undefined;
+
+/** True when the host actually refuses writes into a read-only directory. */
+export function permsEnforced(): boolean {
+ if (_permsEnforced !== undefined) return _permsEnforced;
+ const root = mkdtempSync(join(tmpdir(), 'gbrain-perm-probe-'));
+ try {
+ const ro = join(root, 'ro');
+ mkdirSync(ro);
+ chmodSync(ro, 0o555);
+ try {
+ writeFileSync(join(ro, 'probe'), 'x');
+ _permsEnforced = false; // write into 0555 dir succeeded → not enforced
+ } catch {
+ _permsEnforced = true;
+ }
+ } finally {
+ try {
+ chmodSync(join(root, 'ro'), 0o755);
+ } catch {
+ /* probe dir may not exist */
+ }
+ rmSync(root, { recursive: true, force: true });
+ }
+ return _permsEnforced;
+}
+
+let _crontab: boolean | undefined;
+
+/** True when a `crontab` binary is on PATH (absent in some sandboxes). */
+export function crontabAvailable(): boolean {
+ if (_crontab !== undefined) return _crontab;
+ _crontab = Bun.which('crontab') !== null;
+ return _crontab;
+}
diff --git a/test/helpers/git-fixture.test.ts b/test/helpers/git-fixture.test.ts
new file mode 100644
index 0000000000..1fccafb052
--- /dev/null
+++ b/test/helpers/git-fixture.test.ts
@@ -0,0 +1,85 @@
+import { describe, test, expect, afterEach } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { makeGitFixture, type GitFixture } from './git-fixture.ts';
+
+const dirs: string[] = [];
+
+async function makeFixture(): Promise<GitFixture> {
+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-git-fixture-'));
+ dirs.push(dir);
+ return makeGitFixture(dir);
+}
+
+function head(dir: string): string {
+ return execFileSync('git', ['-C', dir, 'rev-parse', 'HEAD'], {
+ encoding: 'utf8',
+ stdio: ['ignore', 'pipe', 'pipe'],
+ }).trim();
+}
+
+function status(dir: string): string {
+ return execFileSync('git', ['-C', dir, 'status', '--porcelain'], {
+ encoding: 'utf8',
+ stdio: ['ignore', 'pipe', 'pipe'],
+ }).trim();
+}
+
+afterEach(() => {
+ for (const dir of dirs.splice(0)) {
+ try { rmSync(dir, { recursive: true, force: true }); } catch { /* best-effort */ }
+ }
+});
+
+describe('makeGitFixture', () => {
+ test('creates a repo with an initial commit and a clean tree', async () => {
+ const fixture = await makeFixture();
+ expect(existsSync(join(fixture.dir, '.git'))).toBe(true);
+ expect(head(fixture.dir)).toMatch(/^[0-9a-f]{40}$/);
+ expect(status(fixture.dir)).toBe('');
+ });
+
+ test('reset removes untracked files and restores tracked content', async () => {
+ const fixture = await makeFixture();
+ writeFileSync(join(fixture.dir, 'a.txt'), 'v1\n');
+ fixture.commitAll('add a.txt');
+
+ writeFileSync(join(fixture.dir, 'a.txt'), 'v2-dirty\n'); // tracked, modified
+ writeFileSync(join(fixture.dir, 'untracked.txt'), 'junk\n'); // untracked
+
+ fixture.reset();
+
+ expect(readFileSync(join(fixture.dir, 'a.txt'), 'utf8')).toBe('v1\n');
+ expect(existsSync(join(fixture.dir, 'untracked.txt'))).toBe(false);
+ expect(status(fixture.dir)).toBe('');
+ });
+
+ test('reset does not rewind commits: HEAD stays where commitAll left it', async () => {
+ const fixture = await makeFixture();
+ writeFileSync(join(fixture.dir, 'a.txt'), 'v1\n');
+ fixture.commitAll('add a.txt');
+ const after = head(fixture.dir);
+
+ fixture.reset();
+
+ expect(head(fixture.dir)).toBe(after);
+ expect(readFileSync(join(fixture.dir, 'a.txt'), 'utf8')).toBe('v1\n');
+ });
+
+ test('commitAll advances HEAD and leaves a clean tree', async () => {
+ const fixture = await makeFixture();
+ const before = head(fixture.dir);
+ writeFileSync(join(fixture.dir, 'b.txt'), 'content\n');
+ fixture.commitAll('add b.txt');
+ const after = head(fixture.dir);
+ expect(after).not.toBe(before);
+ expect(status(fixture.dir)).toBe('');
+ });
+
+ test('commitAll throws when there is nothing to commit', async () => {
+ const fixture = await makeFixture();
+ expect(() => fixture.commitAll('empty')).toThrow();
+ });
+});
diff --git a/test/helpers/git-fixture.ts b/test/helpers/git-fixture.ts
new file mode 100644
index 0000000000..2852e537c5
--- /dev/null
+++ b/test/helpers/git-fixture.ts
@@ -0,0 +1,54 @@
+/**
+ * Build-once git repo fixture. Model: dream.test.ts's makeGitRepo, but the
+ * expensive part (init + config + initial commit) runs ONCE; tests call
+ * `reset()` between cases instead of re-initializing — the same
+ * pay-cold-start-once shape as reset-pglite.ts.
+ *
+ * Constraints:
+ * - Caller owns `dir` (mkdtempSync it, rmSync it after) — the fixture never
+ * creates or deletes the directory itself.
+ * - reset() = `git clean -ffdx` + `git reset --hard`: removes untracked
+ * files/dirs (ignored ones too) and restores tracked content to HEAD. It
+ * does NOT rewind commits — HEAD stays wherever commitAll left it.
+ * - execFileSync (no shell) so commit messages and paths need no quoting;
+ * stdio piped so output stays quiet, git errors still throw with stderr.
+ * - Signing is not disabled here: under bun test the git-hermetic-preload
+ * already injects commit.gpgsign=false via GIT_CONFIG_COUNT.
+ */
+import { execFileSync } from 'node:child_process';
+
+export interface GitFixture {
+ dir: string;
+ /** Remove untracked files and restore tracked files to HEAD. */
+ reset(): void;
+ /** Stage everything and commit. Throws if there is nothing to commit. */
+ commitAll(msg: string): void;
+}
+
+function git(dir: string, args: string[]): string {
+ return execFileSync('git', ['-C', dir, ...args], {
+ encoding: 'utf8',
+ stdio: ['ignore', 'pipe', 'pipe'],
+ });
+}
+
+export async function makeGitFixture(dir: string): Promise<GitFixture> {
+ git(dir, ['init', '-q']);
+ git(dir, ['config', 'user.email', '[email protected]']);
+ git(dir, ['config', 'user.name', 't']);
+ // Empty initial commit so rev-parse HEAD and reset --hard work immediately.
+ git(dir, ['commit', '--allow-empty', '-q', '-m', 'init']);
+ return {
+ dir,
+ reset(): void {
+ // -ff (double force): a single -f skips untracked NESTED git repos,
+ // which would then contaminate later cases.
+ git(dir, ['clean', '-ffdx', '-q']);
+ git(dir, ['reset', '--hard', '-q']);
+ },
+ commitAll(msg: string): void {
+ git(dir, ['add', '-A']);
+ git(dir, ['commit', '-q', '-m', msg]);
+ },
+ };
+}
diff --git a/test/helpers/git-stderr-probe.ts b/test/helpers/git-stderr-probe.ts
new file mode 100644
index 0000000000..3fb1bdacf1
--- /dev/null
+++ b/test/helpers/git-stderr-probe.ts
@@ -0,0 +1,54 @@
+/**
+ * Probe: does a failing SSRF-flagged `git fetch`'s stderr begin with git's
+ * OWN error? Some environments PATH-shim git with a wrapper that prints its
+ * own diagnostics before delegating (e.g. Conductor workspaces' auth-broker
+ * shim warns "could not reach the GitHub auth broker socket" ahead of git's
+ * `fatal:` when its socket env was scrubbed by the test preloads). Tests
+ * that pin "the real git stderr leads within the first N chars" are
+ * unrunnable behind such a wrapper — skip them visibly there. CI runners
+ * exec real git, so the skip never fires where the coverage matters.
+ *
+ * The probe replicates git-remote.ts's exact failing shape (SSRF `-c` config
+ * flags + blocked file transport + GIT_ENV overrides): wrapper shims can
+ * behave differently per subcommand/argv shape, and only a failing
+ * invocation surfaces the pollution the guarded tests slice into.
+ *
+ * Cached: one subprocess per test process.
+ */
+import { execFileSync } from 'node:child_process';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+let _gitStderrLeads: boolean | undefined;
+
+/** True when a failing git command's stderr begins with git's own output. */
+export function gitStderrLeads(): boolean {
+ if (_gitStderrLeads !== undefined) return _gitStderrLeads;
+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-git-probe-'));
+ try {
+ execFileSync('git', ['init', '-q', dir], { stdio: ['ignore', 'pipe', 'pipe'] });
+ let stderr = '';
+ try {
+ execFileSync(
+ 'git',
+ ['-C', dir, '-c', 'protocol.file.allow=never', 'fetch', 'file:///nonexistent-gbrain-stderr-probe'],
+ {
+ stdio: ['ignore', 'pipe', 'pipe'],
+ env: { ...process.env, GIT_TERMINAL_PROMPT: '0', GIT_ASKPASS: '/bin/false' },
+ timeout: 15_000,
+ },
+ );
+ // A fetch of a nonexistent blocked-transport URL succeeding means the
+ // host's git is too strange to certify — treat as not-leading.
+ _gitStderrLeads = false;
+ } catch (e) {
+ const err = e as { stderr?: Buffer | string };
+ stderr = (err.stderr?.toString() ?? '').trimStart();
+ _gitStderrLeads = stderr.startsWith('fatal:') || stderr.startsWith('error:');
+ }
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ return _gitStderrLeads;
+}
diff --git a/test/helpers/reset-pglite-narrow.test.ts b/test/helpers/reset-pglite-narrow.test.ts
new file mode 100644
index 0000000000..30dca0ec90
--- /dev/null
+++ b/test/helpers/reset-pglite-narrow.test.ts
@@ -0,0 +1,118 @@
+/**
+ * resetPgliteStateNarrow: truncates ONLY the named tables, validates names,
+ * re-seeds the default source only when 'sources' is listed.
+ *
+ * Uses the canonical PGLite block from docs/TESTING.md (one engine per file
+ * in beforeAll, resetPgliteState in beforeEach, disconnect in afterAll) —
+ * import depths adjusted for this file living in test/helpers/ rather than
+ * test/. Scratch tables (narrow_a / narrow_b) keep the assertions independent
+ * of the gbrain schema; the full reset wipes their rows between tests.
+ */
+import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import { resetPgliteState, resetPgliteStateNarrow } from './reset-pglite.ts';
+
+let engine: PGLiteEngine;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ await engine.executeRaw(
+ `CREATE TABLE IF NOT EXISTS narrow_a (id serial PRIMARY KEY, v text)`,
+ );
+ await engine.executeRaw(
+ `CREATE TABLE IF NOT EXISTS narrow_b (id serial PRIMARY KEY, v text)`,
+ );
+});
+
+afterAll(async () => {
+ await engine.disconnect();
+});
+
+beforeEach(async () => {
+ await resetPgliteState(engine);
+});
+
+async function count(table: 'narrow_a' | 'narrow_b' | 'sources'): Promise<number> {
+ const rows = await engine.executeRaw<{ n: number }>(
+ `SELECT count(*)::int AS n FROM ${table}`,
+ );
+ return rows[0].n;
+}
+
+describe('resetPgliteStateNarrow', () => {
+ test('truncates only the named tables; unlisted tables survive', async () => {
+ await engine.executeRaw(`INSERT INTO narrow_a (v) VALUES ('a1')`);
+ await engine.executeRaw(`INSERT INTO narrow_b (v) VALUES ('b1')`);
+ await engine.executeRaw(
+ `INSERT INTO sources (id, name, config) VALUES ('extra', 'extra', '{}'::jsonb)`,
+ );
+
+ await resetPgliteStateNarrow(engine, ['narrow_a']);
+
+ expect(await count('narrow_a')).toBe(0);
+ expect(await count('narrow_b')).toBe(1); // unlisted: survives
+ expect(await count('sources')).toBe(2); // default + extra: untouched
+ });
+
+ test('RESTART IDENTITY: serial restarts for listed tables only', async () => {
+ await engine.executeRaw(`INSERT INTO narrow_a (v) VALUES ('a1'), ('a2')`);
+ await resetPgliteStateNarrow(engine, ['narrow_a']);
+ await engine.executeRaw(`INSERT INTO narrow_a (v) VALUES ('fresh')`);
+ const rows = await engine.executeRaw<{ id: number }>(
+ `SELECT id FROM narrow_a`,
+ );
+ expect(rows.map(r => r.id)).toEqual([1]);
+ });
+
+ test("re-seeds the default source row when 'sources' is listed", async () => {
+ await engine.executeRaw(
+ `INSERT INTO sources (id, name, config) VALUES ('extra', 'extra', '{}'::jsonb)`,
+ );
+ await resetPgliteStateNarrow(engine, ['sources']);
+ const rows = await engine.executeRaw<{ id: string }>(
+ `SELECT id FROM sources ORDER BY id`,
+ );
+ expect(rows.map(r => r.id)).toEqual(['default']);
+ });
+
+ test("does not touch sources when 'sources' is not listed", async () => {
+ await engine.executeRaw(
+ `INSERT INTO sources (id, name, config) VALUES ('extra', 'extra', '{}'::jsonb)`,
+ );
+ await resetPgliteStateNarrow(engine, ['narrow_a']);
+ expect(await count('sources')).toBe(2);
+ });
+
+ test('rejects invalid table names before any SQL runs', async () => {
+ await engine.executeRaw(`INSERT INTO narrow_a (v) VALUES ('survivor')`);
+ const bad = [
+ 'Pages', // uppercase
+ 'pages"; DROP TABLE pages;--', // injection shape
+ 'narrow-a', // hyphen
+ '', // empty
+ '1pages', // leading digit
+ ];
+ for (const name of bad) {
+ await expect(resetPgliteStateNarrow(engine, ['narrow_a', name])).rejects.toThrow(
+ 'invalid table name',
+ );
+ }
+ // A rejected list truncates nothing, including its valid entries.
+ expect(await count('narrow_a')).toBe(1);
+ });
+
+ test('rejects preserved infrastructure tables', async () => {
+ await expect(resetPgliteStateNarrow(engine, ['schema_version'])).rejects.toThrow(
+ 'preserved infrastructure table',
+ );
+ await expect(
+ resetPgliteStateNarrow(engine, ['page_generation_clock']),
+ ).rejects.toThrow('preserved infrastructure table');
+ });
+
+ test('rejects an empty table list (no default)', async () => {
+ await expect(resetPgliteStateNarrow(engine, [])).rejects.toThrow('non-empty');
+ });
+});
diff --git a/test/helpers/reset-pglite.ts b/test/helpers/reset-pglite.ts
index d15e863431..7558aa25c9 100644
--- a/test/helpers/reset-pglite.ts
+++ b/test/helpers/reset-pglite.ts
@@ -75,3 +75,61 @@ export async function resetPgliteState(engine: PGLiteEngine): Promise<void> {
ON CONFLICT (id) DO NOTHING`,
);
}
+
+/** Structural engine slice so the narrow reset works on either engine. */
+export interface NarrowResetEngine {
+ executeRaw(sql: string): Promise<unknown>;
+}
+
+const TABLE_NAME_RE = /^[a-z_][a-z0-9_]*$/;
+
+/**
+ * Truncate ONLY the named tables (one TRUNCATE ... RESTART IDENTITY CASCADE
+ * statement) — for hot loops where the full-catalog reset is overkill.
+ *
+ * The table list is EXPLICIT and REQUIRED — there is deliberately no default.
+ * A default silently under-truncates the moment a migration adds a table the
+ * test writes to; writer.test.ts's 7-table set (pages, links, content_chunks,
+ * timeline_entries, tags, raw_data, page_versions) is a reference example,
+ * not a default.
+ *
+ * Constraints:
+ * - Every name must match /^[a-z_][a-z0-9_]*$/ (throws otherwise — names
+ * reach the SQL text; validated names are additionally identifier-quoted).
+ * - Refuses PRESERVE_TABLES (schema_version, page_generation_clock): the
+ * narrow variant preserves everything resetPgliteState preserves.
+ * - CASCADE follows FKs — truncating `sources` also empties pages etc.
+ * - Re-seeds the default source row ONLY when 'sources' is in the list
+ * (mirrors resetPgliteState).
+ */
+export async function resetPgliteStateNarrow(
+ engine: NarrowResetEngine,
+ tables: string[],
+): Promise<void> {
+ if (tables.length === 0) {
+ throw new Error(
+ 'resetPgliteStateNarrow: table list is required and must be non-empty (no default; see doc comment)',
+ );
+ }
+ for (const t of tables) {
+ if (!TABLE_NAME_RE.test(t)) {
+ throw new Error(
+ `resetPgliteStateNarrow: invalid table name ${JSON.stringify(t)} (must match ${TABLE_NAME_RE})`,
+ );
+ }
+ if (PRESERVE_TABLES.has(t)) {
+ throw new Error(
+ `resetPgliteStateNarrow: refusing to truncate preserved infrastructure table "${t}"`,
+ );
+ }
+ }
+ const quoted = tables.map(t => `"${t}"`).join(', ');
+ await engine.executeRaw(`TRUNCATE ${quoted} RESTART IDENTITY CASCADE`);
+ if (tables.includes('sources')) {
+ await engine.executeRaw(
+ `INSERT INTO sources (id, name, config)
+ VALUES ('default', 'default', '{"federated": true}'::jsonb)
+ ON CONFLICT (id) DO NOTHING`,
+ );
+ }
+}
diff --git a/test/helpers/wait-for.test.ts b/test/helpers/wait-for.test.ts
new file mode 100644
index 0000000000..cb7ecfdfa9
--- /dev/null
+++ b/test/helpers/wait-for.test.ts
@@ -0,0 +1,101 @@
+import { describe, test, expect } from 'bun:test';
+import { waitFor, waitForValue } from './wait-for.ts';
+
+describe('waitFor', () => {
+ test('immediate-true fast path: single check, no interval sleep', async () => {
+ let calls = 0;
+ const t0 = Date.now();
+ await waitFor(() => {
+ calls += 1;
+ return true;
+ });
+ expect(calls).toBe(1);
+ expect(Date.now() - t0).toBeLessThan(1000);
+ });
+
+ test('eventually-true: polls until the predicate flips', async () => {
+ let calls = 0;
+ await waitFor(
+ () => {
+ calls += 1;
+ return calls >= 3;
+ },
+ { intervalMs: 5 },
+ );
+ expect(calls).toBe(3);
+ });
+
+ test('deadline throw carries label and elapsed', async () => {
+ let caught: unknown = null;
+ try {
+ await waitFor(() => false, { timeoutMs: 50, intervalMs: 5, label: 'row-appears' });
+ } catch (e) {
+ caught = e;
+ }
+ expect(caught).toBeInstanceOf(Error);
+ const msg = (caught as Error).message;
+ expect(msg).toContain('row-appears');
+ expect(msg).toMatch(/after \d+ms/);
+ expect(msg).toContain('timeout 50ms');
+ });
+
+ test('checks at least once even with timeoutMs 0', async () => {
+ let calls = 0;
+ await waitFor(() => {
+ calls += 1;
+ return true;
+ }, { timeoutMs: 0 });
+ expect(calls).toBe(1);
+ });
+
+ test('async predicate is awaited', async () => {
+ let calls = 0;
+ await waitFor(
+ async () => {
+ calls += 1;
+ await new Promise(r => setTimeout(r, 2));
+ return calls >= 2;
+ },
+ { intervalMs: 5 },
+ );
+ expect(calls).toBe(2);
+ });
+});
+
+describe('waitForValue', () => {
+ test('returns the first non-null value', async () => {
+ let calls = 0;
+ const value = await waitForValue(
+ () => {
+ calls += 1;
+ return calls >= 3 ? { hit: calls } : undefined;
+ },
+ { intervalMs: 5 },
+ );
+ expect(value).toEqual({ hit: 3 });
+ });
+
+ test('null is "keep polling", not a value', async () => {
+ let calls = 0;
+ const value = await waitForValue(
+ () => {
+ calls += 1;
+ return calls >= 2 ? 'ready' : null;
+ },
+ { intervalMs: 5 },
+ );
+ expect(value).toBe('ready');
+ expect(calls).toBe(2);
+ });
+
+ test('async fn: resolved value is returned', async () => {
+ const value = await waitForValue(async () => 42);
+ expect(value).toBe(42);
+ });
+
+ test('deadline throw when the value never appears', async () => {
+ await expect(
+ waitForValue(() => undefined, { timeoutMs: 40, intervalMs: 5, label: 'never-value' }),
+ ).rejects.toThrow('never-value');
+ });
+});
diff --git a/test/helpers/wait-for.ts b/test/helpers/wait-for.ts
new file mode 100644
index 0000000000..9f3a64a28f
--- /dev/null
+++ b/test/helpers/wait-for.ts
@@ -0,0 +1,55 @@
+/**
+ * Deadline-bounded polling for tests that await an async condition (a file
+ * appearing, a child writing a row, a heartbeat firing). Replaces bare
+ * `await sleep(N)` guesses — the poll returns as soon as the condition holds
+ * and fails loudly (label + elapsed) instead of flaking on slow machines.
+ *
+ * The predicate is checked at least once even with timeoutMs <= 0.
+ */
+export interface WaitForOpts {
+ /** Deadline. Default 5000ms. */
+ timeoutMs?: number;
+ /** Poll interval. Default 10ms. */
+ intervalMs?: number;
+ /** Names the condition in the timeout error. */
+ label?: string;
+}
+
+export async function waitFor(
+ predicate: () => boolean | Promise<boolean>,
+ opts: WaitForOpts = {},
+): Promise<void> {
+ const timeoutMs = opts.timeoutMs ?? 5000;
+ const intervalMs = opts.intervalMs ?? 10;
+ const start = Date.now();
+ for (;;) {
+ if (await predicate()) return;
+ const elapsed = Date.now() - start;
+ if (elapsed >= timeoutMs) {
+ const label = opts.label ? `${opts.label}: ` : '';
+ throw new Error(
+ `waitFor: ${label}condition still false after ${elapsed}ms (timeout ${timeoutMs}ms)`,
+ );
+ }
+ // Clamp the final sleep to the remaining deadline so a coarse interval
+ // can't overshoot the timeout by a full interval. (A predicate that HANGS
+ // is out of scope by design — bun's per-test --timeout is that backstop.)
+ await new Promise<void>(resolve => setTimeout(resolve, Math.min(intervalMs, timeoutMs - elapsed)));
+ }
+}
+
+/**
+ * Poll `fn` until it yields a non-null, non-undefined value; return it.
+ * Same deadline/label semantics as waitFor.
+ */
+export async function waitForValue<T>(
+ fn: () => T | undefined | null | Promise<T | undefined | null>,
+ opts: WaitForOpts = {},
+): Promise<T> {
+ let value: T | undefined | null;
+ await waitFor(async () => {
+ value = await fn();
+ return value !== undefined && value !== null;
+ }, opts);
+ return value as T;
+}
diff --git a/test/helpers/with-snapshot.test.ts b/test/helpers/with-snapshot.test.ts
new file mode 100644
index 0000000000..4ffae2d080
--- /dev/null
+++ b/test/helpers/with-snapshot.test.ts
@@ -0,0 +1,69 @@
+// Prior env state is established through withEnv (R1: no direct process.env
+// assignment in non-serial files); the helpers under test run inside it.
+import { describe, test, expect } from 'bun:test';
+import { withEnv } from './with-env.ts';
+import { withColdPglite, withSnapshotValue } from './with-snapshot.ts';
+
+const KEY = 'GBRAIN_PGLITE_SNAPSHOT';
+
+describe('withColdPglite', () => {
+ test('restore-on-success: snapshot cleared during fn, prior value back after', async () => {
+ await withEnv({ [KEY]: '/tmp/snap.tar' }, async () => {
+ const result = await withColdPglite(async () => {
+ expect(process.env[KEY]).toBeUndefined();
+ return 7;
+ });
+ expect(result).toBe(7);
+ expect(process.env[KEY]).toBe('/tmp/snap.tar');
+ });
+ });
+
+ test('restore-on-throw: fn throws, prior value still restored', async () => {
+ await withEnv({ [KEY]: '/tmp/snap.tar' }, async () => {
+ let caught: unknown = null;
+ try {
+ await withColdPglite(async () => {
+ expect(process.env[KEY]).toBeUndefined();
+ throw new Error('boom');
+ });
+ } catch (e) {
+ caught = e;
+ }
+ expect((caught as Error).message).toBe('boom');
+ expect(process.env[KEY]).toBe('/tmp/snap.tar');
+ });
+ });
+
+ test('was-undefined restore: stays unset after fn, never becomes ""', async () => {
+ await withEnv({ [KEY]: undefined }, async () => {
+ await withColdPglite(async () => {
+ expect(process.env[KEY]).toBeUndefined();
+ });
+ expect(process.env[KEY]).toBeUndefined();
+ });
+ });
+});
+
+describe('withSnapshotValue', () => {
+ test('sets the given value for the duration of fn', async () => {
+ await withEnv({ [KEY]: undefined }, async () => {
+ await withSnapshotValue('/tmp/other.tar', async () => {
+ expect(process.env[KEY]).toBe('/tmp/other.tar');
+ });
+ expect(process.env[KEY]).toBeUndefined();
+ });
+ });
+
+ test('nesting: inner restores to outer value, not the original', async () => {
+ await withEnv({ [KEY]: '/tmp/original.tar' }, async () => {
+ await withSnapshotValue('/tmp/outer.tar', async () => {
+ expect(process.env[KEY]).toBe('/tmp/outer.tar');
+ await withColdPglite(async () => {
+ expect(process.env[KEY]).toBeUndefined();
+ });
+ expect(process.env[KEY]).toBe('/tmp/outer.tar');
+ });
+ expect(process.env[KEY]).toBe('/tmp/original.tar');
+ });
+ });
+});
diff --git a/test/helpers/with-snapshot.ts b/test/helpers/with-snapshot.ts
new file mode 100644
index 0000000000..26d7b9d285
--- /dev/null
+++ b/test/helpers/with-snapshot.ts
@@ -0,0 +1,37 @@
+/**
+ * Scoped GBRAIN_PGLITE_SNAPSHOT overrides. Extracts the inline W0 pattern
+ * from test/migrate.test.ts (save → delete → restore-exact-prior, including
+ * was-undefined → delete) into a composable helper.
+ *
+ * Why: PGLiteEngine.connect() reads GBRAIN_PGLITE_SNAPSHOT to warm-start from
+ * a schema snapshot. Tests whose premise is an EMPTY PGLite (no config table,
+ * pre-migration state) must opt out for the connect they own — and restore
+ * the exact prior value so later engines in the same shard process still get
+ * the fast path.
+ *
+ * Scope note: unlike migrate.test.ts's micro-optimization (restore
+ * immediately after connect()), these helpers restore in `finally` AFTER fn
+ * completes — the generic helper can't know when fn's connect happens. Any
+ * engine fn itself connects runs snapshot-less; don't nest an unrelated
+ * cold-start-sensitive connect inside.
+ *
+ * Same caveat as withEnv: process.env is process-global — cross-test safe,
+ * NOT intra-file concurrent-safe.
+ */
+import { withEnv } from './with-env.ts';
+
+/**
+ * Run fn with GBRAIN_PGLITE_SNAPSHOT set to `value` (undefined = deleted),
+ * restoring the exact prior state via try/finally.
+ */
+export async function withSnapshotValue<T>(
+ value: string | undefined,
+ fn: () => T | Promise<T>,
+): Promise<T> {
+ return withEnv({ GBRAIN_PGLITE_SNAPSHOT: value }, fn);
+}
+
+/** Run fn with the PGLite snapshot fast path disabled (true cold start). */
+export async function withColdPglite<T>(fn: () => Promise<T>): Promise<T> {
+ return withSnapshotValue(undefined, fn);
+}
diff --git a/test/import-resume.test.ts b/test/import-resume.test.ts
index e3e0e28522..bd1bf08080 100644
--- a/test/import-resume.test.ts
+++ b/test/import-resume.test.ts
@@ -26,6 +26,7 @@ import { join } from 'path';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { resetPgliteState } from './helpers/reset-pglite.ts';
import { withEnv } from './helpers/with-env.ts';
+import { permsEnforced } from './helpers/fs-perms.ts';
import { runImport } from '../src/commands/import.ts';
let engine: PGLiteEngine;
@@ -149,7 +150,10 @@ describe('runImport checkpoint resume — v0.33.2 path-based', () => {
});
}, 30_000);
- test('interrupted run preserves its tail below the 100-file boundary', async () => {
+ // skipIf: forces the error path via a chmod-000 file — unrunnable on hosts
+ // that don't enforce permission bits (the read succeeds, errors stays 0,
+ // and the checkpoint is legitimately cleared).
+ test.skipIf(!permsEnforced())('interrupted run preserves its tail below the 100-file boundary', async () => {
// The periodic checkpoint save fires on `completed.size % 100 === 0`. With
// fewer than 100 successful files there is no boundary to hit, so before
// the final save every completed file in a run that ends with errors was
diff --git a/test/init-migrate-only.test.ts b/test/init-migrate-only.test.ts
index c3df2c47a5..0e4faa127d 100644
--- a/test/init-migrate-only.test.ts
+++ b/test/init-migrate-only.test.ts
@@ -6,71 +6,72 @@
* existing Postgres install must not flip it to PGLite. Running it against a
* missing config must fail loudly with a clear "run gbrain init first" error.
*
- * Uses child_process subprocess invocations (not in-proc) because runInit
- * calls process.exit(1) on error paths, which breaks test isolation.
+ * Uses subprocess invocations (not in-proc) because runInit calls
+ * process.exit(1) on error paths, which breaks test isolation. Spawns route
+ * through test/helpers/cli-spawn.ts (async Bun.spawn; DATABASE_URL /
+ * GBRAIN_DATABASE_URL always stripped — the "no config" error paths need
+ * loadConfig() to return null, which any env-var fallback would defeat, see
+ * src/core/config.ts:30; opts.home pins BOTH HOME and GBRAIN_HOME so the
+ * child never reads the operator's real ~/.gbrain). The four error paths are
+ * flag/config validation that exits before any write, so they share one
+ * empty home and run once through runCliBatch (width 2 — the machine-wide
+ * cap, see cli-spawn.ts) in the describe's beforeAll; each test asserts on
+ * its cached result, exit code included. The happy-path tests share one
+ * home: the idempotence rerun reuses the brain the config-preservation test
+ * already built (bun runs in-file tests in declaration order) instead of
+ * cold-building a second PGLite schema from scratch.
*/
-import { describe, test, expect, beforeEach, afterEach } from 'bun:test';
+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
import { mkdtempSync, rmSync, writeFileSync, readFileSync, existsSync, statSync, mkdirSync } from 'fs';
import { join } from 'path';
import { tmpdir } from 'os';
-import { execFileSync } from 'child_process';
-
-const CLI = join(__dirname, '..', 'src', 'cli.ts');
-
-let tmp: string;
-let origHome: string | undefined;
-
-function run(args: string[]): { exitCode: number; stdout: string; stderr: string } {
- // Strip DATABASE_URL / GBRAIN_DATABASE_URL from the subprocess env. The
- // "no config" error-path tests need loadConfig() to return null, which it
- // won't if any env var fallback is set (src/core/config.ts:30). Tests
- // that seed their own config use freshHomeWithConfig() below.
- // Both HOME and GBRAIN_HOME must point at the fixture dir: config/path
- // resolution prefers GBRAIN_HOME (which the test preload sets to its own
- // scratch), so HOME alone leaves the child reading the wrong .gbrain.
- const env = { ...process.env, HOME: tmp, GBRAIN_HOME: tmp } as Record<string, string | undefined>;
- delete env.DATABASE_URL;
- delete env.GBRAIN_DATABASE_URL;
- try {
- const stdout = execFileSync('bun', ['run', CLI, ...args], {
- env: env as Record<string, string>,
- encoding: 'utf-8',
- stdio: ['ignore', 'pipe', 'pipe'],
- });
- return { exitCode: 0, stdout, stderr: '' };
- } catch (err: any) {
- return {
- exitCode: err.status ?? 1,
- stdout: err.stdout?.toString?.() ?? '',
- stderr: err.stderr?.toString?.() ?? '',
- };
- }
-}
+import { runCli, runCliBatch, type CliResult } from './helpers/cli-spawn.ts';
-beforeEach(() => {
- origHome = process.env.HOME;
- tmp = mkdtempSync(join(tmpdir(), 'gbrain-init-migrate-only-test-'));
-});
+describe('gbrain init --migrate-only — error paths', () => {
+ // Every argv here is a validation-failure path verified to exit before any
+ // migrate-only side effects (no config write, no DB touch), so all four
+ // share one empty home. That makes the config.json absence checks below
+ // strictly stronger than the per-test homes they replaced: if ANY of the
+ // four runs wrote a config, they fail. Do NOT add anything here that
+ // writes config or state — batch order is not execution order.
+ const ERROR_ARGVS: string[][] = [
+ ['init', '--migrate-only', '--dry-run'],
+ ['init', '--migrate-only', '--dry-run', '--json'],
+ ['init', '--migrate-only'],
+ ['init', '--migrate-only', '--json'],
+ ];
+
+ let errHome: string;
+ const batched = new Map<string, CliResult>();
+
+ beforeAll(async () => {
+ errHome = mkdtempSync(join(tmpdir(), 'gbrain-init-migrate-only-test-'));
+ const results = await runCliBatch(ERROR_ARGVS, { home: errHome });
+ ERROR_ARGVS.forEach((argv, i) => batched.set(argv.join(' '), results[i]));
+ }, 60_000);
-afterEach(() => {
- if (origHome === undefined) delete process.env.HOME;
- else process.env.HOME = origHome;
- try { rmSync(tmp, { recursive: true, force: true }); } catch { /* best-effort */ }
-});
+ afterAll(() => {
+ try { rmSync(errHome, { recursive: true, force: true }); } catch { /* best-effort */ }
+ });
+
+ function cached(...argv: string[]): CliResult {
+ const r = batched.get(argv.join(' '));
+ if (!r) throw new Error(`not in ERROR_ARGVS batch: gbrain ${argv.join(' ')}`);
+ return r;
+ }
-describe('gbrain init --migrate-only — error paths', () => {
test('rejects unknown flags before any migrate-only side effects', () => {
- const result = run(['init', '--migrate-only', '--dry-run']);
+ const result = cached('init', '--migrate-only', '--dry-run');
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain('unknown flag --dry-run');
// Unknown safety flags must not fall through to the migration path.
expect(result.stderr).not.toContain('No brain configured');
- expect(existsSync(join(tmp, '.gbrain', 'config.json'))).toBe(false);
+ expect(existsSync(join(errHome, '.gbrain', 'config.json'))).toBe(false);
});
test('unknown flags respect --json output', () => {
- const result = run(['init', '--migrate-only', '--dry-run', '--json']);
+ const result = cached('init', '--migrate-only', '--dry-run', '--json');
expect(result.exitCode).toBe(1);
const lines = result.stdout.split('\n').filter((l: string) => l.trim().startsWith('{'));
const parsed = JSON.parse(lines[lines.length - 1]);
@@ -80,15 +81,15 @@ describe('gbrain init --migrate-only — error paths', () => {
});
test('errors with clear message when no config exists', () => {
- const result = run(['init', '--migrate-only']);
+ const result = cached('init', '--migrate-only');
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain('No brain configured');
// Config file must not have been created (no saveConfig silently)
- expect(existsSync(join(tmp, '.gbrain', 'config.json'))).toBe(false);
+ expect(existsSync(join(errHome, '.gbrain', 'config.json'))).toBe(false);
});
test('JSON output flag emits a structured error', () => {
- const result = run(['init', '--migrate-only', '--json']);
+ const result = cached('init', '--migrate-only', '--json');
expect(result.exitCode).toBe(1);
// --json writes the structured error to stdout per the pattern in init.ts
const lines = result.stdout.split('\n').filter((l: string) => l.trim().startsWith('{'));
@@ -100,9 +101,24 @@ describe('gbrain init --migrate-only — error paths', () => {
});
describe('gbrain init --migrate-only — happy path with PGLite config', () => {
- test('applies schema against existing PGLite config; does NOT modify config.json', () => {
+ // One home for both tests: the config-preservation test builds the brain,
+ // the idempotence test reruns against it. Declaration order IS execution
+ // order within a bun test file, so the reuse never observes an unbuilt
+ // brain in a full-file run.
+ let home: string;
+ let firstRun: CliResult | null = null;
+
+ beforeAll(() => {
+ home = mkdtempSync(join(tmpdir(), 'gbrain-init-migrate-only-test-'));
+ });
+
+ afterAll(() => {
+ try { rmSync(home, { recursive: true, force: true }); } catch { /* best-effort */ }
+ });
+
+ test('applies schema against existing PGLite config; does NOT modify config.json', async () => {
// Seed an existing PGLite config + brain file.
- const gbrainDir = join(tmp, '.gbrain');
+ const gbrainDir = join(home, '.gbrain');
mkdirSync(gbrainDir, { recursive: true });
const dbPath = join(gbrainDir, 'brain.pglite');
const configPath = join(gbrainDir, 'config.json');
@@ -114,7 +130,8 @@ describe('gbrain init --migrate-only — happy path with PGLite config', () => {
const contentBefore = readFileSync(configPath, 'utf-8');
// First run: should apply schema.
- const result = run(['init', '--migrate-only', '--json']);
+ const result = await runCli(['init', '--migrate-only', '--json'], { home });
+ firstRun = result; // stash before asserting so the rerun test reuses it even on failure
expect(result.exitCode).toBe(0);
const jsonLines = result.stdout.split('\n').filter((l: string) => l.trim().startsWith('{'));
const parsed = JSON.parse(jsonLines[jsonLines.length - 1]);
@@ -133,17 +150,22 @@ describe('gbrain init --migrate-only — happy path with PGLite config', () => {
expect(existsSync(dbPath)).toBe(true);
}, 30_000);
- test('idempotent on rerun — second call succeeds without error', () => {
- const gbrainDir = join(tmp, '.gbrain');
- mkdirSync(gbrainDir, { recursive: true });
- const dbPath = join(gbrainDir, 'brain.pglite');
- const configPath = join(gbrainDir, 'config.json');
- writeFileSync(configPath, JSON.stringify({ engine: 'pglite', database_path: dbPath }) + '\n');
-
- const first = run(['init', '--migrate-only', '--json']);
+ test('idempotent on rerun — second call succeeds without error', async () => {
+ // Normal path: `first` is the previous test's run against this home —
+ // the second call below is the true rerun on an existing brain. Under a
+ // `-t` filter that skipped the previous test, seed + run the first call
+ // here (the original two-spawn shape).
+ let first = firstRun;
+ if (first === null) {
+ const gbrainDir = join(home, '.gbrain');
+ mkdirSync(gbrainDir, { recursive: true });
+ const dbPath = join(gbrainDir, 'brain.pglite');
+ writeFileSync(join(gbrainDir, 'config.json'), JSON.stringify({ engine: 'pglite', database_path: dbPath }) + '\n');
+ first = await runCli(['init', '--migrate-only', '--json'], { home });
+ }
expect(first.exitCode).toBe(0);
- const second = run(['init', '--migrate-only', '--json']);
+ const second = await runCli(['init', '--migrate-only', '--json'], { home });
expect(second.exitCode).toBe(0);
}, 60_000);
});
diff --git a/test/migrate.test.ts b/test/migrate.test.ts
index 02e4524a03..b5b925ca0a 100644
--- a/test/migrate.test.ts
+++ b/test/migrate.test.ts
@@ -3,6 +3,7 @@ import { LATEST_VERSION, runMigrations, MIGRATIONS, getIdleBlockers, hasPendingM
import type { IdleBlocker } from '../src/core/migrate.ts';
import type { BrainEngine } from '../src/core/engine.ts';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { withColdPglite } from './helpers/with-snapshot.ts';
import { readFileSync } from 'fs';
import { resolve } from 'path';
@@ -52,19 +53,18 @@ describe('hasPendingMigrations', () => {
test('returns true when version config is missing entirely (defensive default)', async () => {
// W0: opt out of the default-on snapshot — this test's premise is an
// empty PGlite with no config table at all.
- const priorSnapshot = process.env.GBRAIN_PGLITE_SNAPSHOT;
- delete process.env.GBRAIN_PGLITE_SNAPSHOT;
- const engine = new PGLiteEngine();
- await engine.connect({});
- if (priorSnapshot !== undefined) process.env.GBRAIN_PGLITE_SNAPSHOT = priorSnapshot;
- try {
- // Don't call initSchema. Probe against an empty PGlite — getConfig should
- // either return null (treated as version=1) or throw on missing config
- // table; either way the probe must say "yes pending."
- expect(await hasPendingMigrations(engine)).toBe(true);
- } finally {
- await engine.disconnect();
- }
+ await withColdPglite(async () => {
+ const engine = new PGLiteEngine();
+ await engine.connect({});
+ try {
+ // Don't call initSchema. Probe against an empty PGlite — getConfig
+ // should either return null (treated as version=1) or throw on missing
+ // config table; either way the probe must say "yes pending."
+ expect(await hasPendingMigrations(engine)).toBe(true);
+ } finally {
+ await engine.disconnect();
+ }
+ });
}, 30000);
});
diff --git a/test/migration-orchestrator-v0_31_0.test.ts b/test/migration-orchestrator-v0_31_0.test.ts
index b3f9fd5cfb..7971d6b223 100644
--- a/test/migration-orchestrator-v0_31_0.test.ts
+++ b/test/migration-orchestrator-v0_31_0.test.ts
@@ -13,89 +13,91 @@
* having the facts table, then crashed on the post-condition check
* three lines later. Restored here to `v < 45` (table-existence
* precondition); column shape is enforced by migration v46 alone.
+ *
+ * Lifecycle: one shared PGLite engine (beforeAll, in-memory) replaces the
+ * prior fresh-engine-per-test boot. phaseASchema takes the engine argument
+ * directly and never calls loadConfig(), so no GBRAIN_HOME / config.json
+ * fixture is required; the engine override stays set as the orchestrator-path
+ * backstop. resetPgliteState truncates `config`, wiping the `version` stamp
+ * initSchema wrote — the DB-backed describe's beforeEach re-stamps it to
+ * LATEST_VERSION so each test starts at the post-initSchema state. The two
+ * engine-free short-circuit tests run hook-less (no reset).
*/
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
-import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';
-import { join } from 'node:path';
-import { tmpdir } from 'node:os';
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
-import { createEngine } from '../src/core/engine-factory.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { LATEST_VERSION } from '../src/core/migrate.ts';
import { __testing, __setTestEngineOverride } from '../src/commands/migrations/v0_31_0.ts';
-import { runMigrationsUpTo } from './e2e/helpers.ts';
-import type { BrainEngine } from '../src/core/engine.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
describe('v0.31.0 orchestrator — phaseASchema gate', () => {
- let tmp: string;
- let oldGbrainHome: string | undefined;
- let engine: BrainEngine;
-
- beforeEach(async () => {
- oldGbrainHome = process.env.GBRAIN_HOME;
- tmp = mkdtempSync(join(tmpdir(), 'gbrain-v0310-gate-'));
- process.env.GBRAIN_HOME = tmp;
-
- const gbrainHome = join(tmp, '.gbrain');
- const dbPath = join(tmp, 'brain-db');
- mkdirSync(gbrainHome, { recursive: true });
- writeFileSync(
- join(gbrainHome, 'config.json'),
- JSON.stringify({ engine: 'pglite', database_path: dbPath }, null, 2) + '\n',
- );
+ let engine: PGLiteEngine;
- engine = await createEngine({ engine: 'pglite', database_path: dbPath });
- await engine.connect({ engine: 'pglite', database_path: dbPath });
+ beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
await engine.initSchema();
__setTestEngineOverride(engine);
});
- afterEach(async () => {
+ afterAll(async () => {
__setTestEngineOverride(null);
await engine.disconnect();
- if (oldGbrainHome === undefined) delete process.env.GBRAIN_HOME;
- else process.env.GBRAIN_HOME = oldGbrainHome;
- rmSync(tmp, { recursive: true, force: true });
- });
-
- test('schema_version < 45 fails with operator-facing message naming v45 + recovery command', async () => {
- // Roll the version backwards to simulate a brain stuck at pre-v45.
- await engine.setConfig('version', '40');
-
- const result = await __testing.phaseASchema(engine, { yes: true, dryRun: false, noAutopilotInstall: true });
-
- expect(result.name).toBe('schema');
- expect(result.status).toBe('failed');
- expect(result.detail).toContain('version >= 45');
- expect(result.detail).toContain('apply-migrations');
- // Negative: must NOT mention 'v40' as the gate version (the prior bug).
- expect(result.detail).not.toContain('version >= 40');
- // Negative: must NOT carry the misleading "+ notability" claim from
- // the prior gate text — column shape is enforced by v46, not gated here.
- expect(result.detail).not.toContain('notability');
});
- test('schema_version >= 45 with facts table present → status complete', async () => {
- // Advance the brain to LATEST so v45 + v46 land and the facts table exists.
- const { LATEST_VERSION } = await import('../src/core/migrate.ts');
- await runMigrationsUpTo(engine as never, LATEST_VERSION);
-
- const result = await __testing.phaseASchema(engine, { yes: true, dryRun: false, noAutopilotInstall: true });
-
- expect(result.status).toBe('complete');
- expect(result.detail).toContain('facts table present');
+ describe('DB-backed', () => {
+ beforeEach(async () => {
+ await resetPgliteState(engine);
+ // resetPgliteState truncates `config`; restore the `version` stamp
+ // initSchema left (getConfig('version') must read LATEST, not null).
+ await engine.setConfig('version', String(LATEST_VERSION));
+ });
+
+ test('schema_version < 45 fails with operator-facing message naming v45 + recovery command', async () => {
+ // Roll the version backwards to simulate a brain stuck at pre-v45.
+ await engine.setConfig('version', '40');
+
+ const result = await __testing.phaseASchema(engine, { yes: true, dryRun: false, noAutopilotInstall: true });
+
+ expect(result.name).toBe('schema');
+ expect(result.status).toBe('failed');
+ expect(result.detail).toContain('version >= 45');
+ expect(result.detail).toContain('apply-migrations');
+ // Negative: must NOT mention 'v40' as the gate version (the prior bug).
+ expect(result.detail).not.toContain('version >= 40');
+ // Negative: must NOT carry the misleading "+ notability" claim from
+ // the prior gate text — column shape is enforced by v46, not gated here.
+ expect(result.detail).not.toContain('notability');
+ });
+
+ test('schema_version >= 45 with facts table present → status complete', async () => {
+ // Brain is at LATEST: initSchema (beforeAll) applied every migration —
+ // v45 + v46 landed and the facts table exists — and the beforeEach
+ // re-stamped `version` to LATEST_VERSION. The prior
+ // runMigrationsUpTo(engine, LATEST_VERSION) was a provable no-op after
+ // initSchema (current = LATEST → pending = []); deleted.
+ const result = await __testing.phaseASchema(engine, { yes: true, dryRun: false, noAutopilotInstall: true });
+
+ expect(result.status).toBe('complete');
+ expect(result.detail).toContain('facts table present');
+ });
});
- test('dryRun short-circuits before any DB read', async () => {
- const result = await __testing.phaseASchema(engine, { yes: true, dryRun: true, noAutopilotInstall: true });
+ // Short-circuits return before any DB read — no per-test reset needed.
+ describe('engine-free short-circuits', () => {
+ test('dryRun short-circuits before any DB read', async () => {
+ const result = await __testing.phaseASchema(engine, { yes: true, dryRun: true, noAutopilotInstall: true });
- expect(result.status).toBe('skipped');
- expect(result.detail).toBe('dry-run');
- });
+ expect(result.status).toBe('skipped');
+ expect(result.detail).toBe('dry-run');
+ });
- test('null engine short-circuits with no_brain_configured', async () => {
- const result = await __testing.phaseASchema(null, { yes: true, dryRun: false, noAutopilotInstall: true });
+ test('null engine short-circuits with no_brain_configured', async () => {
+ const result = await __testing.phaseASchema(null, { yes: true, dryRun: false, noAutopilotInstall: true });
- expect(result.status).toBe('skipped');
- expect(result.detail).toBe('no_brain_configured');
+ expect(result.status).toBe('skipped');
+ expect(result.detail).toBe('no_brain_configured');
+ });
});
});
diff --git a/test/minions.test.ts b/test/minions.test.ts
index d354148cd5..0a8c8d618d 100644
--- a/test/minions.test.ts
+++ b/test/minions.test.ts
@@ -1,3 +1,9 @@
+// Wait discipline: no fixed sleep-waits for async conditions — poll with
+// waitFor/waitForValue (helpers/wait-for.ts) against the condition the wait
+// exists for (job terminal, handler entered, event emitted). Fixed sleeps
+// remain only where the window itself is the contract (negative assertions,
+// timestamp separation) and carry an inline justification. Env mutation goes
+// through withEnv (helpers/with-env.ts) — never bare process.env writes.
import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
import { PGlite } from '@electric-sql/pglite';
import type { BrainEngine } from '../src/core/engine.ts';
@@ -7,11 +13,36 @@ import { MinionWorker } from '../src/core/minions/worker.ts';
import { calculateBackoff } from '../src/core/minions/backoff.ts';
import { UnrecoverableError } from '../src/core/minions/types.ts';
import type { MinionJob } from '../src/core/minions/types.ts';
+import { waitFor, waitForValue } from './helpers/wait-for.ts';
+import { withEnv } from './helpers/with-env.ts';
let engine: PGLiteEngine;
let queue: MinionQueue;
let workerBackedQueue: MinionQueue;
+const TERMINAL_STATUSES = new Set(['completed', 'failed', 'dead', 'cancelled']);
+
+/** Poll the shared table until job `id` reaches `status` (or any terminal status). */
+async function waitForJobStatus(
+ id: number,
+ status: string | Set<string> = TERMINAL_STATUSES,
+ timeoutMs = 5_000,
+): Promise<void> {
+ const want = typeof status === 'string' ? new Set([status]) : status;
+ await waitFor(async () => {
+ const j = await queue.getJob(id);
+ return j !== null && want.has(j.status);
+ }, { timeoutMs, label: `job ${id} → ${[...want].join('|')}` });
+}
+
+/** Poll promoteDelayed until it promotes something; returns that batch. */
+async function promoteDelayedEventually(): Promise<MinionJob[]> {
+ return waitForValue(async () => {
+ const promoted = await queue.promoteDelayed();
+ return promoted.length > 0 ? promoted : null;
+ }, { timeoutMs: 5_000, label: 'promoteDelayed picked up the expired delay' });
+}
+
beforeAll(async () => {
engine = new PGLiteEngine();
await engine.connect({ database_url: '' }); // in-memory
@@ -149,8 +180,7 @@ describe('MinionQueue: State Machine', () => {
test('delayed → waiting (promote)', async () => {
const job = await queue.add('sync', {}, { delay: 1 }); // 1ms delay
expect(job.status).toBe('delayed');
- await new Promise(r => setTimeout(r, 10));
- const promoted = await queue.promoteDelayed();
+ const promoted = await promoteDelayedEventually();
expect(promoted.length).toBe(1);
expect(promoted[0].status).toBe('waiting');
expect(promoted[0].delay_until).toBeNull();
@@ -635,9 +665,9 @@ describe('MinionWorker', () => {
return { processed: true };
});
- // Start worker in background, stop after a short delay
+ // Start worker in background, stop once the job lands terminal
const workerPromise = worker.start();
- await new Promise(r => setTimeout(r, 200));
+ await waitForJobStatus(job.id);
worker.stop();
await workerPromise;
@@ -656,7 +686,7 @@ describe('MinionWorker', () => {
});
const workerPromise = worker.start();
- await new Promise(r => setTimeout(r, 200));
+ await waitForJobStatus(job.id);
worker.stop();
await workerPromise;
@@ -674,7 +704,7 @@ describe('MinionWorker', () => {
});
const workerPromise = worker.start();
- await new Promise(r => setTimeout(r, 200));
+ await waitForJobStatus(job.id);
worker.stop();
await workerPromise;
@@ -758,8 +788,7 @@ describe('MinionQueue: Claim Mechanics', () => {
await queue.add('past', {}, { delay: 1 }); // 1ms delay, will expire quickly
await queue.add('future', {}, { delay: 999999 }); // way in the future
- await new Promise(r => setTimeout(r, 10));
- const promoted = await queue.promoteDelayed();
+ const promoted = await promoteDelayedEventually();
expect(promoted.length).toBe(1);
expect(promoted[0].name).toBe('past');
});
@@ -1134,7 +1163,7 @@ describe('MinionWorker: Concurrent', () => {
});
const p = worker.start();
- await new Promise(r => setTimeout(r, 500));
+ await waitForJobStatus(job.id);
worker.stop();
await p;
@@ -1153,7 +1182,7 @@ describe('MinionWorker: Concurrent', () => {
});
const p = worker.start();
- await new Promise(r => setTimeout(r, 500));
+ await waitForJobStatus(job.id);
worker.stop();
await p;
@@ -1171,7 +1200,7 @@ describe('MinionWorker: Concurrent', () => {
});
const p = worker.start();
- await new Promise(r => setTimeout(r, 500));
+ await waitForJobStatus(job.id);
worker.stop();
await p;
@@ -1186,6 +1215,7 @@ describe('MinionWorker: v7 Behavior', () => {
const job = await queue.add('pause-test', {});
let signalSeenAborted = false;
let handlerEntered = false;
+ let handlerExited = false;
const worker = new MinionWorker(engine, {
concurrency: 1,
@@ -1200,17 +1230,19 @@ describe('MinionWorker: v7 Behavior', () => {
await new Promise(r => setTimeout(r, 25));
}
signalSeenAborted = ctx.signal.aborted;
+ handlerExited = true;
throw new Error('aborted');
});
const p = worker.start();
// Wait for handler to enter
- await new Promise(r => setTimeout(r, 200));
+ await waitFor(() => handlerEntered, { timeoutMs: 5_000, label: 'pause-test handler entry' });
expect(handlerEntered).toBe(true);
// Pause clears the lock token; next renewLock fails → abort fires
await queue.pauseJob(job.id);
- // Give renewLock time to fire (lockDuration / 2 = 100ms)
- await new Promise(r => setTimeout(r, 500));
+ // renewLock cadence is lockDuration / 2 = 100ms; wait for the handler to
+ // observe the abort (or give up at its internal 2s budget) and exit.
+ await waitFor(() => handlerExited, { timeoutMs: 5_000, label: 'pause-test handler exit' });
worker.stop();
await p;
@@ -1219,6 +1251,8 @@ describe('MinionWorker: v7 Behavior', () => {
test('catch block skips failJob when ctx.signal.aborted', async () => {
const job = await queue.add('skip-fail', {}, { max_attempts: 5 });
+ let handlerEntered = false;
+ let handlerExited = false;
const worker = new MinionWorker(engine, {
concurrency: 1,
@@ -1226,18 +1260,22 @@ describe('MinionWorker: v7 Behavior', () => {
lockDuration: 200,
});
worker.register('skip-fail', async (ctx) => {
+ handlerEntered = true;
// Wait for abort, then throw — failJob should NOT be called
const start = Date.now();
while (!ctx.signal.aborted && Date.now() - start < 2000) {
await new Promise(r => setTimeout(r, 25));
}
+ handlerExited = true;
throw new Error('after-abort');
});
const p = worker.start();
- await new Promise(r => setTimeout(r, 200));
+ // Pause only after the handler holds the job — pausing a still-waiting
+ // row would skip the catch path entirely.
+ await waitFor(() => handlerEntered, { timeoutMs: 5_000, label: 'skip-fail handler entry' });
await queue.pauseJob(job.id);
- await new Promise(r => setTimeout(r, 500));
+ await waitFor(() => handlerExited, { timeoutMs: 5_000, label: 'skip-fail handler exit' });
worker.stop();
await p;
@@ -1272,10 +1310,7 @@ describe('MinionWorker: v7 Behavior', () => {
const p = worker.start();
// Wait for all 3 handlers to enter
- const t0 = Date.now();
- while (entered < 3 && Date.now() - t0 < 3000) {
- await new Promise(r => setTimeout(r, 25));
- }
+ await waitFor(() => entered >= 3, { timeoutMs: 15_000, label: 'barrier handlers entered' });
expect(entered).toBe(3);
// While blocked, all 3 jobs should be active in DB
@@ -1284,7 +1319,9 @@ describe('MinionWorker: v7 Behavior', () => {
// Release all handlers, let worker complete them
release();
- await new Promise(r => setTimeout(r, 300));
+ await waitFor(async () => (await queue.getJobs({ status: 'completed' })).length >= 3, {
+ timeoutMs: 5_000, label: 'barrier jobs completed',
+ });
worker.stop();
await p;
@@ -1305,13 +1342,15 @@ describe('MinionWorker: v7 Behavior', () => {
});
const p = worker.start();
- await new Promise(r => setTimeout(r, 300));
+ await waitForJobStatus(job.id);
worker.stop();
await p;
const completed = await queue.getJob(job.id);
expect(completed!.status).toBe('completed');
- // Wait beyond the timeout window to confirm the timer was cleared
+ // Wait beyond the timeout window to confirm the timer was cleared.
+ // Genuinely time-based negative check (a leaked timer fires on wall
+ // clock; there is nothing to poll) — the fixed window stays.
await new Promise(r => setTimeout(r, 200));
expect(abortFired).toBe(false);
});
@@ -1330,15 +1369,16 @@ describe('MinionWorker: v7 Behavior', () => {
});
worker.register('slow', async (ctx) => {
ctx.signal.addEventListener('abort', () => { abortFired = true; });
- // Stall longer than timeout_ms
- await new Promise(r => setTimeout(r, 800));
+ // Stall past timeout_ms: hold until the safety-net timer aborts us
+ // (deadline-bounded poll instead of a fixed oversleep).
+ await waitFor(() => ctx.signal.aborted, { timeoutMs: 5_000, label: 'safety-net abort' });
// After abort fires, throwing here goes through the catch — but
// catch sees signal.aborted and skips failJob.
throw new Error('should-be-aborted');
});
const p = worker.start();
- await new Promise(r => setTimeout(r, 1200));
+ await waitFor(() => abortFired, { timeoutMs: 6_000, label: 'safety-net abort observed' });
worker.stop();
await p;
@@ -1479,9 +1519,11 @@ describe('MinionQueue: handleTimeouts', () => {
test('handleTimeouts dead-letters expired active jobs', async () => {
const job = await queue.add('slow', {}, { timeout_ms: 50 });
await queue.claim('tok1', 30000, 'default', ['slow']);
- // Wait past the timeout
- await new Promise(r => setTimeout(r, 100));
- const timedOut = await queue.handleTimeouts();
+ // Sweep until the 50ms timeout_at lapses and the eviction lands
+ const timedOut = await waitForValue(async () => {
+ const killed = await queue.handleTimeouts();
+ return killed.length > 0 ? killed : null;
+ }, { timeoutMs: 5_000, label: 'handleTimeouts eviction' });
expect(timedOut.length).toBe(1);
expect(timedOut[0].id).toBe(job.id);
@@ -1499,8 +1541,12 @@ describe('MinionQueue: handleTimeouts', () => {
test('handleTimeouts ignores stalled jobs (lock_until > now guard)', async () => {
// Force a stalled job: timeout_at expired AND lock_until expired
await queue.add('slow', {}, { timeout_ms: 50 });
- await queue.claim('tok1', 1, 'default', ['slow']); // 1ms lock duration → expires immediately
- await new Promise(r => setTimeout(r, 100));
+ const claimed = await queue.claim('tok1', 1, 'default', ['slow']); // 1ms lock duration → expires immediately
+ // Both deadlines must lapse before the negative sweep check is meaningful
+ await waitFor(async () => {
+ const j = await queue.getJob(claimed!.id);
+ return j!.timeout_at!.getTime() <= Date.now() && j!.lock_until!.getTime() <= Date.now();
+ }, { timeoutMs: 5_000, label: 'timeout_at + lock_until lapsed' });
// handleTimeouts should NOT touch it (lock_until < now → stalled, not timed out)
const timedOut = await queue.handleTimeouts();
@@ -1510,6 +1556,8 @@ describe('MinionQueue: handleTimeouts', () => {
test('jobs without timeout_ms never timeout', async () => {
await queue.add('forever', {});
await queue.claim('tok1', 30000, 'default', ['forever']);
+ // Negative assertion with no expiring deadline to poll — a small fixed
+ // grace window is the whole check.
await new Promise(r => setTimeout(r, 50));
const timedOut = await queue.handleTimeouts();
expect(timedOut.length).toBe(0);
@@ -1839,7 +1887,9 @@ describe('MinionQueue: child_done', () => {
await queue.claim('tok-a', 30000, 'default', ['a']);
await queue.completeJob(c1.id, 'tok-a');
- // Capture a cursor between the two completions
+ // Capture a cursor between the two completions. Genuinely time-based:
+ // the cursor must sit strictly between the two child_done DB timestamps,
+ // so a small separation sleep on each side IS the condition.
await new Promise(r => setTimeout(r, 50));
const cursor = new Date();
await new Promise(r => setTimeout(r, 50));
@@ -2378,27 +2428,25 @@ describe('backpressure-audit (v0.19.1 Q1): JSONL on coalesce', () => {
const os = await import('node:os');
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'gbrain-audit-'));
- const prev = process.env.GBRAIN_AUDIT_DIR;
- process.env.GBRAIN_AUDIT_DIR = tmp;
try {
- expect(resolveAuditDir()).toBe(tmp);
- logBackpressureCoalesce({
- queue: 'default',
- name: 'poll',
- waiting_count: 2,
- max_waiting: 2,
- returned_job_id: 42,
+ await withEnv({ GBRAIN_AUDIT_DIR: tmp }, async () => {
+ expect(resolveAuditDir()).toBe(tmp);
+ logBackpressureCoalesce({
+ queue: 'default',
+ name: 'poll',
+ waiting_count: 2,
+ max_waiting: 2,
+ returned_job_id: 42,
+ });
+ const file = path.join(tmp, computeAuditFilename());
+ const text = fs.readFileSync(file, 'utf8');
+ const line = JSON.parse(text.trim());
+ expect(line.decision).toBe('coalesced');
+ expect(line.name).toBe('poll');
+ expect(line.returned_job_id).toBe(42);
+ expect(typeof line.ts).toBe('string');
});
- const file = path.join(tmp, computeAuditFilename());
- const text = fs.readFileSync(file, 'utf8');
- const line = JSON.parse(text.trim());
- expect(line.decision).toBe('coalesced');
- expect(line.name).toBe('poll');
- expect(line.returned_job_id).toBe(42);
- expect(typeof line.ts).toBe('string');
} finally {
- if (prev === undefined) delete process.env.GBRAIN_AUDIT_DIR;
- else process.env.GBRAIN_AUDIT_DIR = prev;
fs.rmSync(tmp, { recursive: true, force: true });
}
});
@@ -2565,9 +2613,11 @@ describe('MinionWorker: --max-rss watchdog', () => {
await queue.add('noop', {});
await queue.add('noop', {});
- // Run for a moment, then stop manually
+ // Run until all 3 jobs drain (and each post-job RSS check ran), then stop
const startPromise = worker.start();
- await new Promise(r => setTimeout(r, 500));
+ await waitFor(async () =>
+ postJobCount >= 3 && (await queue.getJobs({ status: 'completed' })).length >= 3,
+ { timeoutMs: 5_000, label: '3 noop jobs completed + RSS checks' });
worker.stop();
await startPromise;
@@ -2589,10 +2639,10 @@ describe('MinionWorker: --max-rss watchdog', () => {
});
worker.register('noop', async () => {});
- await queue.add('noop', {});
+ const job = await queue.add('noop', {});
const startPromise = worker.start();
- await new Promise(r => setTimeout(r, 500));
+ await waitForJobStatus(job.id);
worker.stop();
await startPromise;
@@ -2704,8 +2754,8 @@ describe('MinionWorker: abort signal propagation (v0.20.5)', () => {
});
const workerPromise = worker.start();
- // Wait for timeout (150ms) + handler to notice + margin
- await new Promise(r => setTimeout(r, 500));
+ // Wait for timeout (150ms) + handler to notice + dead-letter to land
+ await waitForJobStatus(job.id);
worker.stop();
await workerPromise;
@@ -2730,7 +2780,8 @@ describe('MinionWorker: abort signal propagation (v0.20.5)', () => {
const worker = new MinionWorker(engine, { pollInterval: 50 });
worker.register('abort-ignorer', async (ctx) => {
handlerStarted = true;
- // Wait a bit, then check if signal was aborted
+ // Deliberately ignore the signal past timeout_ms (100), then check —
+ // the fixed sleep IS the "handler that doesn't poll its signal".
await new Promise(r => setTimeout(r, 200));
signalWasAborted = ctx.signal.aborted;
// Now exit (a well-behaved handler would do this)
@@ -2741,7 +2792,7 @@ describe('MinionWorker: abort signal propagation (v0.20.5)', () => {
});
const workerPromise = worker.start();
- await new Promise(r => setTimeout(r, 500));
+ await waitForJobStatus(job.id);
expect(handlerStarted).toBe(true);
expect(signalWasAborted).toBe(true);
@@ -2778,11 +2829,15 @@ describe('MinionWorker: abort signal propagation (v0.20.5)', () => {
const workerPromise = worker.start();
// Wait for slow job to start and timeout
- await new Promise(r => setTimeout(r, 300));
+ await waitFor(() => slowAborted, { timeoutMs: 5_000, label: 'slow-timeout abort observed' });
// Now submit the fast job — it should get claimed
const fastJob = await queue.add('fast-after', {});
- await new Promise(r => setTimeout(r, 300));
+ await waitFor(async () => {
+ const fast = await queue.getJob(fastJob.id);
+ const slow = await queue.getJob(slowJob.id);
+ return fast?.status === 'completed' && slow?.status === 'dead';
+ }, { timeoutMs: 5_000, label: 'fast completed + slow dead' });
worker.stop();
await workerPromise;
@@ -2842,11 +2897,7 @@ describe('checkAborted (v0.20.5 cycle signal)', () => {
describe('MinionWorker: self-health-check', () => {
test('health check is active when GBRAIN_SUPERVISED is not set', async () => {
- // Save and clear the env var
- const saved = process.env.GBRAIN_SUPERVISED;
- delete process.env.GBRAIN_SUPERVISED;
-
- try {
+ await withEnv({ GBRAIN_SUPERVISED: undefined }, async () => {
const worker = new MinionWorker(engine, {
queue: 'default',
concurrency: 1,
@@ -2857,28 +2908,25 @@ describe('MinionWorker: self-health-check', () => {
});
worker.register('noop', async () => {});
- await queue.add('noop', {});
+ const job = await queue.add('noop', {});
const startPromise = worker.start();
- // Let the health check fire at least once (100ms interval)
- await new Promise(r => setTimeout(r, 300));
+ // Let the health check fire at least once (100ms interval) — the
+ // premise under test is that a live tick coexists with processing,
+ // so this floor is genuinely time-based; then poll for the drain.
+ await new Promise(r => setTimeout(r, 150));
+ await waitForJobStatus(job.id);
worker.stop();
await startPromise;
// Worker should have processed the job despite health check running
const completed = await queue.getJobs({ status: 'completed' });
expect(completed.length).toBeGreaterThanOrEqual(1);
- } finally {
- if (saved !== undefined) process.env.GBRAIN_SUPERVISED = saved;
- else delete process.env.GBRAIN_SUPERVISED;
- }
+ });
}, 10_000);
test('health check is skipped when GBRAIN_SUPERVISED=1', async () => {
- const saved = process.env.GBRAIN_SUPERVISED;
- process.env.GBRAIN_SUPERVISED = '1';
-
- try {
+ await withEnv({ GBRAIN_SUPERVISED: '1' }, async () => {
const worker = new MinionWorker(engine, {
queue: 'default',
concurrency: 1,
@@ -2889,44 +2937,41 @@ describe('MinionWorker: self-health-check', () => {
});
worker.register('noop', async () => {});
- await queue.add('noop', {});
+ const job = await queue.add('noop', {});
const startPromise = worker.start();
- await new Promise(r => setTimeout(r, 300));
+ await waitForJobStatus(job.id);
worker.stop();
await startPromise;
// Worker should still process jobs fine
const completed = await queue.getJobs({ status: 'completed' });
expect(completed.length).toBeGreaterThanOrEqual(1);
- } finally {
- if (saved !== undefined) process.env.GBRAIN_SUPERVISED = saved;
- else delete process.env.GBRAIN_SUPERVISED;
- }
+ });
}, 10_000);
test('healthCheckInterval=0 disables health check', async () => {
- delete process.env.GBRAIN_SUPERVISED;
-
- const worker = new MinionWorker(engine, {
- queue: 'default',
- concurrency: 1,
- healthCheckInterval: 0,
- pollInterval: 50,
- stalledInterval: 10_000,
- maxRssMb: 0,
- });
+ await withEnv({ GBRAIN_SUPERVISED: undefined }, async () => {
+ const worker = new MinionWorker(engine, {
+ queue: 'default',
+ concurrency: 1,
+ healthCheckInterval: 0,
+ pollInterval: 50,
+ stalledInterval: 10_000,
+ maxRssMb: 0,
+ });
- worker.register('noop', async () => {});
- await queue.add('noop', {});
+ worker.register('noop', async () => {});
+ const job = await queue.add('noop', {});
- const startPromise = worker.start();
- await new Promise(r => setTimeout(r, 300));
- worker.stop();
- await startPromise;
+ const startPromise = worker.start();
+ await waitForJobStatus(job.id);
+ worker.stop();
+ await startPromise;
- const completed = await queue.getJobs({ status: 'completed' });
- expect(completed.length).toBeGreaterThanOrEqual(1);
+ const completed = await queue.getJobs({ status: 'completed' });
+ expect(completed.length).toBeGreaterThanOrEqual(1);
+ });
}, 10_000);
});
@@ -2973,224 +3018,237 @@ function makeProbeEngine(overrides: ProbeOverrides) {
describe('MinionWorker: self-health-check behavior (v0.22.14)', () => {
test('emits unhealthy{db_dead} after dbFailExitAfter consecutive DB probe failures', async () => {
- delete process.env.GBRAIN_SUPERVISED;
-
- let probeCount = 0;
- const probeEngine = makeProbeEngine({
- selectOne: async () => {
- probeCount++;
- throw new Error('connection terminated unexpectedly');
- },
- });
+ await withEnv({ GBRAIN_SUPERVISED: undefined }, async () => {
+ let probeCount = 0;
+ const probeEngine = makeProbeEngine({
+ selectOne: async () => {
+ probeCount++;
+ throw new Error('connection terminated unexpectedly');
+ },
+ });
- const worker = new MinionWorker(probeEngine, {
- queue: 'default',
- concurrency: 1,
- healthCheckInterval: 30,
- dbFailExitAfter: 3,
- pollInterval: 50,
- stalledInterval: 10_000,
- maxRssMb: 0,
- });
+ const worker = new MinionWorker(probeEngine, {
+ queue: 'default',
+ concurrency: 1,
+ healthCheckInterval: 30,
+ dbFailExitAfter: 3,
+ pollInterval: 50,
+ stalledInterval: 10_000,
+ maxRssMb: 0,
+ });
- worker.register('noop', async () => {});
+ worker.register('noop', async () => {});
- const events: Array<{ reason: string }> = [];
- worker.on('unhealthy', (info) => { events.push(info); });
+ const events: Array<{ reason: string }> = [];
+ worker.on('unhealthy', (info) => { events.push(info); });
- const startPromise = worker.start();
- // 3 ticks at 30ms = 90ms; give extra slack.
- await new Promise(r => setTimeout(r, 250));
- worker.stop();
- await startPromise;
+ const startPromise = worker.start();
+ // 3 ticks at 30ms trip the counter; poll for the event itself.
+ await waitFor(() => probeCount >= 3 && events.length >= 1, {
+ timeoutMs: 5_000, label: 'db_dead unhealthy event',
+ });
+ worker.stop();
+ await startPromise;
- expect(probeCount).toBeGreaterThanOrEqual(3);
- expect(events.length).toBeGreaterThanOrEqual(1);
- expect(events[0].reason).toBe('db_dead');
+ expect(probeCount).toBeGreaterThanOrEqual(3);
+ expect(events.length).toBeGreaterThanOrEqual(1);
+ expect(events[0].reason).toBe('db_dead');
+ });
}, 10_000);
test('DB recovery resets the failure counter (no exit after intermittent failures)', async () => {
- delete process.env.GBRAIN_SUPERVISED;
-
- let probeCount = 0;
- // Pattern: fail, fail, succeed (resets), fail, fail, then permanently succeed.
- // No 3 consecutive failures, so dbFailExitAfter=3 must NOT trip.
- const probeEngine = makeProbeEngine({
- selectOne: async () => {
- const idx = probeCount++;
- if (idx === 0 || idx === 1 || idx === 3 || idx === 4) {
- throw new Error('transient blip');
- }
- return [{ ok: 1 }];
- },
- });
+ await withEnv({ GBRAIN_SUPERVISED: undefined }, async () => {
+ let probeCount = 0;
+ // Pattern: fail, fail, succeed (resets), fail, fail, then permanently succeed.
+ // No 3 consecutive failures, so dbFailExitAfter=3 must NOT trip.
+ const probeEngine = makeProbeEngine({
+ selectOne: async () => {
+ const idx = probeCount++;
+ if (idx === 0 || idx === 1 || idx === 3 || idx === 4) {
+ throw new Error('transient blip');
+ }
+ return [{ ok: 1 }];
+ },
+ });
- const worker = new MinionWorker(probeEngine, {
- queue: 'default',
- concurrency: 1,
- healthCheckInterval: 30,
- dbFailExitAfter: 3,
- pollInterval: 50,
- stalledInterval: 10_000,
- maxRssMb: 0,
- });
+ const worker = new MinionWorker(probeEngine, {
+ queue: 'default',
+ concurrency: 1,
+ healthCheckInterval: 30,
+ dbFailExitAfter: 3,
+ pollInterval: 50,
+ stalledInterval: 10_000,
+ maxRssMb: 0,
+ });
- worker.register('noop', async () => {});
+ worker.register('noop', async () => {});
- const events: Array<{ reason: string }> = [];
- worker.on('unhealthy', (info) => { events.push(info); });
+ const events: Array<{ reason: string }> = [];
+ worker.on('unhealthy', (info) => { events.push(info); });
- const startPromise = worker.start();
- await new Promise(r => setTimeout(r, 250));
- worker.stop();
- await startPromise;
+ const startPromise = worker.start();
+ // Run until the fail/ok/fail pattern is fully exercised (6 probes).
+ await waitFor(() => probeCount >= 6, { timeoutMs: 5_000, label: 'probe pattern exercised' });
+ worker.stop();
+ await startPromise;
- // Counter should never have hit 3 consecutive — success at index 2 resets it.
- const dbDeadEvents = events.filter(e => e.reason === 'db_dead');
- expect(dbDeadEvents.length).toBe(0);
+ // Counter should never have hit 3 consecutive — success at index 2 resets it.
+ const dbDeadEvents = events.filter(e => e.reason === 'db_dead');
+ expect(dbDeadEvents.length).toBe(0);
+ });
}, 10_000);
test('emits unhealthy{stalled} after stallExitAfterMs of continuous idle with waiting jobs', async () => {
- delete process.env.GBRAIN_SUPERVISED;
-
- const probeEngine = makeProbeEngine({
- selectOne: async () => [{ ok: 1 }],
- countWaiting: () => 5, // pretend 5 jobs are waiting for our handler names
- });
+ await withEnv({ GBRAIN_SUPERVISED: undefined }, async () => {
+ const probeEngine = makeProbeEngine({
+ selectOne: async () => [{ ok: 1 }],
+ countWaiting: () => 5, // pretend 5 jobs are waiting for our handler names
+ });
- const worker = new MinionWorker(probeEngine, {
- queue: 'default',
- concurrency: 1,
- healthCheckInterval: 30,
- stallWarnAfterMs: 50,
- stallExitAfterMs: 100,
- pollInterval: 50,
- stalledInterval: 10_000,
- maxRssMb: 0,
- });
+ const worker = new MinionWorker(probeEngine, {
+ queue: 'default',
+ concurrency: 1,
+ healthCheckInterval: 30,
+ stallWarnAfterMs: 50,
+ stallExitAfterMs: 100,
+ pollInterval: 50,
+ stalledInterval: 10_000,
+ maxRssMb: 0,
+ });
- worker.register('noop', async () => {});
- // Don't queue any real jobs — claim returns null, inFlight stays 0,
- // jobsCompleted stays 0, idle clock advances.
+ worker.register('noop', async () => {});
+ // Don't queue any real jobs — claim returns null, inFlight stays 0,
+ // jobsCompleted stays 0, idle clock advances.
- const events: Array<{ reason: string; waitingCount?: number }> = [];
- worker.on('unhealthy', (info) => { events.push(info); });
+ const events: Array<{ reason: string; waitingCount?: number }> = [];
+ worker.on('unhealthy', (info) => { events.push(info); });
- const startPromise = worker.start();
- // Both thresholds measured from lastCompletionTime (corrected per codex r2):
- // - tick @ +30ms: idle=30ms, < stallWarnAfterMs(50), no warn
- // - tick @ +60ms: idle=60ms, > 50, warn fires (stallWarningSince set)
- // - tick @ +90ms: idle=90ms, < stallExitAfterMs(100), no exit yet
- // - tick @ +120ms: idle=120ms, > 100 → exit fires (unhealthy event)
- // Wait 350ms which leaves comfortable slack for setTimeout drift.
- await new Promise(r => setTimeout(r, 350));
- worker.stop();
- await startPromise;
+ const startPromise = worker.start();
+ // Both thresholds measured from lastCompletionTime (corrected per codex r2):
+ // - tick @ +30ms: idle=30ms, < stallWarnAfterMs(50), no warn
+ // - tick @ +60ms: idle=60ms, > 50, warn fires (stallWarningSince set)
+ // - tick @ +90ms: idle=90ms, < stallExitAfterMs(100), no exit yet
+ // - tick @ +120ms: idle=120ms, > 100 → exit fires (unhealthy event)
+ // Poll for the event instead of guessing setTimeout drift.
+ await waitFor(() => events.some(e => e.reason === 'stalled'), {
+ timeoutMs: 5_000, label: 'stalled unhealthy event',
+ });
+ worker.stop();
+ await startPromise;
- const stalledEvents = events.filter(e => e.reason === 'stalled');
- expect(stalledEvents.length).toBeGreaterThanOrEqual(1);
- expect(stalledEvents[0].waitingCount).toBe(5);
- // The idleMinutes payload should reflect total idle, not warn-since.
- // With idle ~120ms at exit time, idleMinutes rounds to 0 — that's
- // expected; the value is informative, not load-bearing.
+ const stalledEvents = events.filter(e => e.reason === 'stalled');
+ expect(stalledEvents.length).toBeGreaterThanOrEqual(1);
+ expect(stalledEvents[0].waitingCount).toBe(5);
+ // The idleMinutes payload should reflect total idle, not warn-since.
+ // With idle ~120ms at exit time, idleMinutes rounds to 0 — that's
+ // expected; the value is informative, not load-bearing.
+ });
}, 10_000);
test('inFlight > 0 blocks stall detection (long-running legitimate job)', async () => {
- delete process.env.GBRAIN_SUPERVISED;
-
- const probeEngine = makeProbeEngine({
- selectOne: async () => [{ ok: 1 }],
- countWaiting: () => 5,
- });
+ await withEnv({ GBRAIN_SUPERVISED: undefined }, async () => {
+ const probeEngine = makeProbeEngine({
+ selectOne: async () => [{ ok: 1 }],
+ countWaiting: () => 5,
+ });
- const worker = new MinionWorker(probeEngine, {
- queue: 'default',
- concurrency: 1,
- healthCheckInterval: 30,
- stallWarnAfterMs: 50,
- stallExitAfterMs: 100,
- pollInterval: 50,
- stalledInterval: 10_000,
- maxRssMb: 0,
- });
+ const worker = new MinionWorker(probeEngine, {
+ queue: 'default',
+ concurrency: 1,
+ healthCheckInterval: 30,
+ stallWarnAfterMs: 50,
+ stallExitAfterMs: 100,
+ pollInterval: 50,
+ stalledInterval: 10_000,
+ maxRssMb: 0,
+ });
- worker.register('noop', async () => {});
+ worker.register('noop', async () => {});
- const events: Array<{ reason: string }> = [];
- worker.on('unhealthy', (info) => { events.push(info); });
-
- // Inject a fake in-flight entry directly. This bypasses the claim path
- // (which goes through the proxy and complicates the cleanup race) and
- // tests exactly what we want: the stall check's `inFlight.size === 0`
- // gate when there's legitimate ongoing work.
- const fakeInFlight = (worker as unknown as {
- inFlight: Map<number, { lockTimer: NodeJS.Timeout; abort: AbortController; promise: Promise<void> }>
- }).inFlight;
- const fakeAbort = new AbortController();
- const fakePromise = new Promise<void>(() => { /* never resolves */ });
- const fakeTimer = setInterval(() => {}, 60_000); // dummy lock timer
- fakeInFlight.set(99999, { lockTimer: fakeTimer, abort: fakeAbort, promise: fakePromise });
+ const events: Array<{ reason: string }> = [];
+ worker.on('unhealthy', (info) => { events.push(info); });
+
+ // Inject a fake in-flight entry directly. This bypasses the claim path
+ // (which goes through the proxy and complicates the cleanup race) and
+ // tests exactly what we want: the stall check's `inFlight.size === 0`
+ // gate when there's legitimate ongoing work.
+ const fakeInFlight = (worker as unknown as {
+ inFlight: Map<number, { lockTimer: NodeJS.Timeout; abort: AbortController; promise: Promise<void> }>
+ }).inFlight;
+ const fakeAbort = new AbortController();
+ const fakePromise = new Promise<void>(() => { /* never resolves */ });
+ const fakeTimer = setInterval(() => {}, 60_000); // dummy lock timer
+ fakeInFlight.set(99999, { lockTimer: fakeTimer, abort: fakeAbort, promise: fakePromise });
- const startPromise = worker.start();
- await new Promise(r => setTimeout(r, 350));
- // Remove our fake entry before stop so the worker doesn't wait 30s for it.
- clearInterval(fakeTimer);
- fakeInFlight.delete(99999);
- worker.stop();
- await startPromise;
+ const startPromise = worker.start();
+ // Negative-assertion window: must comfortably exceed stallExitAfterMs
+ // (100ms) plus several 30ms health ticks; there is no positive event to
+ // poll (the point is that none fires), so the fixed window stays.
+ await new Promise(r => setTimeout(r, 350));
+ // Remove our fake entry before stop so the worker doesn't wait 30s for it.
+ clearInterval(fakeTimer);
+ fakeInFlight.delete(99999);
+ worker.stop();
+ await startPromise;
- // No stall event should fire — inFlight.size > 0 gates the stall check.
- const stalledEvents = events.filter(e => e.reason === 'stalled');
- expect(stalledEvents.length).toBe(0);
+ // No stall event should fire — inFlight.size > 0 gates the stall check.
+ const stalledEvents = events.filter(e => e.reason === 'stalled');
+ expect(stalledEvents.length).toBe(0);
+ });
}, 10_000);
test('regression (D1): waiting jobs of unregistered handler names do NOT trigger stall exit', async () => {
- delete process.env.GBRAIN_SUPERVISED;
-
- // The count(*) query is filtered by registered handler names. If handlers=['noop']
- // and the queue has 5 'widget-fn' jobs, the SQL `name = ANY($2)` filter returns 0.
- // The probe engine simulates this by checking handlers before returning a count;
- // we ALSO capture the SQL to assert the predicate text is actually present (so a
- // future refactor that silently drops `AND name = ANY(...)` is caught).
- const capturedStallSql = { sql: null as string | null };
- const probeEngine = makeProbeEngine({
- selectOne: async () => [{ ok: 1 }],
- countWaiting: (handlers) => handlers.includes('widget-fn') ? 5 : 0,
- capturedStallSql,
- });
+ await withEnv({ GBRAIN_SUPERVISED: undefined }, async () => {
+ // The count(*) query is filtered by registered handler names. If handlers=['noop']
+ // and the queue has 5 'widget-fn' jobs, the SQL `name = ANY($2)` filter returns 0.
+ // The probe engine simulates this by checking handlers before returning a count;
+ // we ALSO capture the SQL to assert the predicate text is actually present (so a
+ // future refactor that silently drops `AND name = ANY(...)` is caught).
+ const capturedStallSql = { sql: null as string | null };
+ const probeEngine = makeProbeEngine({
+ selectOne: async () => [{ ok: 1 }],
+ countWaiting: (handlers) => handlers.includes('widget-fn') ? 5 : 0,
+ capturedStallSql,
+ });
- const worker = new MinionWorker(probeEngine, {
- queue: 'default',
- concurrency: 1,
- healthCheckInterval: 50,
- stallWarnAfterMs: 100,
- stallExitAfterMs: 200,
- pollInterval: 50,
- stalledInterval: 10_000,
- maxRssMb: 0,
- });
+ const worker = new MinionWorker(probeEngine, {
+ queue: 'default',
+ concurrency: 1,
+ healthCheckInterval: 50,
+ stallWarnAfterMs: 100,
+ stallExitAfterMs: 200,
+ pollInterval: 50,
+ stalledInterval: 10_000,
+ maxRssMb: 0,
+ });
- // Register 'noop' but pretend the queue is full of 'widget-fn' (unhandled).
- worker.register('noop', async () => {});
+ // Register 'noop' but pretend the queue is full of 'widget-fn' (unhandled).
+ worker.register('noop', async () => {});
- const events: Array<{ reason: string }> = [];
- worker.on('unhealthy', (info) => { events.push(info); });
+ const events: Array<{ reason: string }> = [];
+ worker.on('unhealthy', (info) => { events.push(info); });
- const startPromise = worker.start();
- // Window > stallExitAfterMs; if D1 fix wasn't applied, stall would fire.
- await new Promise(r => setTimeout(r, 500));
- worker.stop();
- await startPromise;
+ const startPromise = worker.start();
+ // Anchor on the first stall-count probe, then hold a negative window
+ // past stallExitAfterMs (200ms); if the D1 fix regressed, stall fires
+ // inside it. No positive event exists to poll — the window stays.
+ await waitFor(() => capturedStallSql.sql !== null, {
+ timeoutMs: 5_000, label: 'stall-count probe ran',
+ });
+ await new Promise(r => setTimeout(r, 300));
+ worker.stop();
+ await startPromise;
- // No stall event — the count for 'noop' handlers is 0, so worker is correctly idle.
- const stalledEvents = events.filter(e => e.reason === 'stalled');
- expect(stalledEvents.length).toBe(0);
- // SQL shape assertion: the production query MUST filter by handler names.
- // Without this assertion, a future change that drops the predicate would
- // pass the no-event check above (the handler array would be irrelevant
- // to the underlying DB but our probe just needs to return 0).
- expect(capturedStallSql.sql).not.toBeNull();
- expect(capturedStallSql.sql).toMatch(/name\s*=\s*ANY/i);
+ // No stall event — the count for 'noop' handlers is 0, so worker is correctly idle.
+ const stalledEvents = events.filter(e => e.reason === 'stalled');
+ expect(stalledEvents.length).toBe(0);
+ // SQL shape assertion: the production query MUST filter by handler names.
+ // Without this assertion, a future change that drops the predicate would
+ // pass the no-event check above (the handler array would be irrelevant
+ // to the underlying DB but our probe just needs to return 0).
+ expect(capturedStallSql.sql).not.toBeNull();
+ expect(capturedStallSql.sql).toMatch(/name\s*=\s*ANY/i);
+ });
}, 10_000);
test('regression (R3): constructor throws when stallExitAfterMs <= stallWarnAfterMs', () => {
@@ -3256,14 +3314,16 @@ describe('MinionWorker: inFlight generation-safety (#4145 R2-1)', () => {
// Release stale execution A: its completeJob is fenced-false ("completion
// dropped") and its finally fires. Pre-fix, that finally deleted B's
- // entry by bare job.id — the R2-1 generation race.
+ // entry by bare job.id — the R2-1 generation race. A's pipeline has no
+ // external observable when the fix holds (a negative assertion), so a
+ // fixed grace window is the check.
gates[0]();
await new Promise(r => setTimeout(r, 150));
expect(inFlight.get(row.id)?.lockToken).toBe('tok-B'); // B survived A's finally
// Release B: its OWN finally removes its own entry and completes the row.
gates[1]();
- await new Promise(r => setTimeout(r, 150));
+ await waitFor(() => !inFlight.has(row.id), { timeoutMs: 5_000, label: 'execution B drained' });
expect(inFlight.has(row.id)).toBe(false);
const final = await queue.getJob(row.id);
expect(final!.status).toBe('completed');
@@ -3417,12 +3477,13 @@ describe('MinionQueue: per-job lock lease (#4145)', () => {
(worker as unknown as { launchJob(j: MinionJob, t: string): void }).launchJob(claimed!, 'tok-lease-renew');
// Cadence = min(5000/2, 60000) = 2500ms; wait for at least one tick.
- const started = Date.now();
- while (durs.length === 0 && Date.now() - started < 8_000) {
- await new Promise(r => setTimeout(r, 100));
+ // release() runs in finally so a timeout can't leak the gated handler.
+ try {
+ await waitFor(() => durs.length > 0, { timeoutMs: 8_000, label: 'per-job lease renewal tick' });
+ } finally {
+ release();
}
- release();
- await new Promise(r => setTimeout(r, 150));
+ await waitForJobStatus(claimed!.id, 'completed');
expect(durs.length).toBeGreaterThanOrEqual(1);
// Every renewal used the per-job 5s lease — NOT the worker's 60s default.
expect(new Set(durs)).toEqual(new Set([5_000]));
diff --git a/test/opencode-json.test.ts b/test/opencode-json.test.ts
index cc110abd72..478c5d0420 100644
--- a/test/opencode-json.test.ts
+++ b/test/opencode-json.test.ts
@@ -12,6 +12,7 @@
import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
+import { permsEnforced } from './helpers/fs-perms.ts';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { withEnv } from './helpers/with-env.ts';
@@ -132,7 +133,9 @@ describe('read-failure classes are distinct', () => {
expect((parsed.mcp as Record<string, unknown>).gbrain).toBeDefined();
});
- test('unreadable file → refuse loudly, never clobber', () => {
+ // skipIf: asserts a chmod-000 read MUST fail — unrunnable on hosts that
+ // don't enforce permission bits (FUSE/overlay sandboxes, root).
+ test.skipIf(!permsEnforced())('unreadable file → refuse loudly, never clobber', () => {
if (process.getuid?.() === 0) return; // root ignores modes
writeFileSync(cfg(), '{"mcp":{}}');
chmodSync(cfg(), 0o000);
diff --git a/test/pages-soft-delete.test.ts b/test/pages-soft-delete.test.ts
index 759f86150f..7394b8c70b 100644
--- a/test/pages-soft-delete.test.ts
+++ b/test/pages-soft-delete.test.ts
@@ -12,19 +12,30 @@
* Runs against PGLite — same SQL contract as Postgres but DATABASE_URL-free.
* Postgres-specific paths (CONCURRENTLY index, two-stage CTE) covered by
* separate Postgres E2E tests.
+ *
+ * One shared engine for the whole file (schema init paid once, snapshot
+ * allowed — nothing here asserts bootstrap behavior); each describe gets a
+ * clean slate via a describe-scoped resetPgliteState beforeAll. Reset is
+ * per-DESCRIBE, not per-test: tests within a describe deliberately share
+ * state (the purge/dry-run describes assert against leftover rows from
+ * earlier tests), matching the original one-engine-per-describe semantics.
*/
import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
-delete process.env.GBRAIN_PGLITE_SNAPSHOT;
+let engine: PGLiteEngine;
-async function setupBrain(): Promise<PGLiteEngine> {
- const engine = new PGLiteEngine();
+beforeAll(async () => {
+ engine = new PGLiteEngine();
await engine.connect({});
await engine.initSchema();
- return engine;
-}
+}, 30000);
+
+afterAll(async () => {
+ await engine.disconnect();
+});
async function seedPage(engine: PGLiteEngine, slug: string): Promise<void> {
await engine.putPage(slug, {
@@ -37,14 +48,8 @@ async function seedPage(engine: PGLiteEngine, slug: string): Promise<void> {
}
describe('softDeletePage', () => {
- let engine: PGLiteEngine;
-
beforeAll(async () => {
- engine = await setupBrain();
- }, 30000);
-
- afterAll(async () => {
- await engine.disconnect();
+ await resetPgliteState(engine);
});
test('happy path: sets deleted_at and returns slug', async () => {
@@ -75,14 +80,8 @@ describe('softDeletePage', () => {
});
describe('restorePage', () => {
- let engine: PGLiteEngine;
-
beforeAll(async () => {
- engine = await setupBrain();
- }, 30000);
-
- afterAll(async () => {
- await engine.disconnect();
+ await resetPgliteState(engine);
});
test('clears deleted_at on a soft-deleted page', async () => {
@@ -107,14 +106,8 @@ describe('restorePage', () => {
});
describe('purgeDeletedPages (TTL boundary)', () => {
- let engine: PGLiteEngine;
-
beforeAll(async () => {
- engine = await setupBrain();
- }, 30000);
-
- afterAll(async () => {
- await engine.disconnect();
+ await resetPgliteState(engine);
});
test('purges pages whose deleted_at is older than the cutoff', async () => {
@@ -194,14 +187,8 @@ describe('purgeDeletedPages (TTL boundary)', () => {
});
describe('purgeDeletedPages dry-run (shares the delete predicate)', () => {
- let engine: PGLiteEngine;
-
beforeAll(async () => {
- engine = await setupBrain();
- }, 30000);
-
- afterAll(async () => {
- await engine.disconnect();
+ await resetPgliteState(engine);
});
async function pageCount(): Promise<number> {
@@ -311,14 +298,8 @@ describe('purgeDeletedPages dry-run (shares the delete predicate)', () => {
});
describe('getPage / listPages includeDeleted contract (Q3 IRON RULE)', () => {
- let engine: PGLiteEngine;
-
beforeAll(async () => {
- engine = await setupBrain();
- }, 30000);
-
- afterAll(async () => {
- await engine.disconnect();
+ await resetPgliteState(engine);
});
test('Q3 round-trip: delete → get returns null → get(include_deleted) returns row → restore → get returns row again', async () => {
@@ -368,14 +349,8 @@ describe('getPage / listPages includeDeleted contract (Q3 IRON RULE)', () => {
});
describe('search visibility (soft-deleted pages hidden from searchKeyword)', () => {
- let engine: PGLiteEngine;
-
beforeAll(async () => {
- engine = await setupBrain();
- }, 30000);
-
- afterAll(async () => {
- await engine.disconnect();
+ await resetPgliteState(engine);
});
test('searchKeyword hides soft-deleted pages', async () => {
diff --git a/test/pglite-leftovers-check.test.ts b/test/pglite-leftovers-check.test.ts
index 0a38dbaede..88f8c1a54b 100644
--- a/test/pglite-leftovers-check.test.ts
+++ b/test/pglite-leftovers-check.test.ts
@@ -6,6 +6,7 @@
*/
import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
import { chmodSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, utimesSync, writeFileSync } from 'node:fs';
+import { permsEnforced } from './helpers/fs-perms.ts';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import {
@@ -165,7 +166,9 @@ describe('assessPgliteLeftovers', () => {
expect(a.leftovers[0]?.approx_bytes).toBe(1024); // the symlink target's 8 KB is NOT counted
});
- test('an unreadable subdirectory marks the size incomplete, never exactly 0 B', () => {
+ // skipIf: needs a directory whose listing MUST fail (chmod 000) —
+ // unrunnable on hosts that don't enforce permission bits.
+ test.skipIf(!permsEnforced())('an unreadable subdirectory marks the size incomplete, never exactly 0 B', () => {
const home = makeHome('unreadable');
const dir = makeStore(home, 'brain.pglite', [1024]);
const locked = join(dir, 'locked');
diff --git a/test/schema-cli.test.ts b/test/schema-cli.test.ts
index 55a992a1bd..e4a06e9d7a 100644
--- a/test/schema-cli.test.ts
+++ b/test/schema-cli.test.ts
@@ -1,18 +1,24 @@
// v0.38 Phase C: gbrain schema CLI smoke tests.
//
// Tests the runSchema dispatch + each subcommand's output shape via
-// the public CLI entrypoint. Hermetic — uses Bun's subprocess to run
-// the CLI like a user would.
+// the public CLI entrypoint. Hermetic — spawns the real CLI through
+// test/helpers/cli-spawn.ts (async Bun.spawn; DATABASE_URL /
+// GBRAIN_DATABASE_URL always stripped; opts.home pins BOTH HOME and
+// GBRAIN_HOME in the child). The bundled-pack reads and the error
+// paths that exit before touching config are independent of each
+// other, so they run once through runCliBatch (width 2 — the
+// machine-wide cap, see cli-spawn.ts) in the describe's beforeAll and
+// each test asserts on its cached result. Anything that writes config
+// (`schema use <pack>`) or needs a pre-seeded home stays a sequential
+// await against a per-test home.
import { describe, expect, test, beforeAll, afterAll, beforeEach, afterEach } from 'bun:test';
-import { spawnSync } from 'node:child_process';
import { mkdtempSync, rmSync, existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { runCli, runCliBatch, type CliResult } from './helpers/cli-spawn.ts';
-const REPO_ROOT = join(import.meta.dir, '..');
-
-// Default-isolated GBRAIN_HOME for every gbrain() call. Without this,
+// Default-isolated GBRAIN_HOME for every batched call. Without this,
// tests that read `~/.gbrain/config.json` inherit the developer's real
// brain config — and sibling Conductor worktrees writing to the same
// config (e.g. via `schema use` or `config set` during their own tests)
@@ -29,44 +35,51 @@ afterAll(() => {
rmSync(DEFAULT_GBRAIN_HOME, { recursive: true, force: true });
});
-function gbrain(
- args: string[],
- extraEnv: Record<string, string> = {},
-): { stdout: string; stderr: string; code: number } {
- // bun's spawnSync does NOT inherit env mutations done via process.env = ...,
- // so pass env explicitly. CLAUDE.md flags this pattern as load-bearing for
- // any subprocess test that needs GBRAIN_HOME isolation.
- const env = {
- ...process.env,
- GBRAIN_DATABASE_URL: '',
- DATABASE_URL: '',
- GBRAIN_HOME: DEFAULT_GBRAIN_HOME,
- ...extraEnv,
- };
- const result = spawnSync('bun', ['run', 'src/cli.ts', ...args], {
- cwd: REPO_ROOT,
- encoding: 'utf-8',
- env,
- });
- return {
- stdout: result.stdout ?? '',
- stderr: result.stderr ?? '',
- code: result.status ?? -1,
- };
-}
-
describe('gbrain schema CLI (Phase C)', () => {
+ // Every argv here is read-only against the shared DEFAULT_GBRAIN_HOME:
+ // bundled-pack reads, the default-resolution `active`, and error paths
+ // verified to exit before any config write (no-arg `use` exits 2 at the
+ // usage check in runUse; unknown subcommands exit 2 in the dispatch
+ // switch). Do NOT add anything that writes config or depends on another
+ // row's side effects — batch order is not execution order.
+ const READ_ONLY_ARGVS: string[][] = [
+ ['schema'],
+ ['schema', 'list'],
+ ['schema', 'show', 'gbrain-base'],
+ ['schema', 'validate', 'gbrain-base'],
+ ['schema', 'show', 'gbrain-recommended'],
+ ['schema', 'validate', 'gbrain-recommended'],
+ ['schema', 'show', 'gbrain-base-v2'],
+ ['schema', 'active'],
+ ['schema', 'show', 'nonexistent-pack'],
+ ['schema', 'frobnicate'],
+ ['schema', 'use'],
+ ];
+
+ const batched = new Map<string, CliResult>();
+
+ beforeAll(async () => {
+ const results = await runCliBatch(READ_ONLY_ARGVS, { home: DEFAULT_GBRAIN_HOME });
+ READ_ONLY_ARGVS.forEach((argv, i) => batched.set(argv.join(' '), results[i]));
+ }, 120_000);
+
+ function cached(...argv: string[]): CliResult {
+ const r = batched.get(argv.join(' '));
+ if (!r) throw new Error(`not in READ_ONLY_ARGVS batch: gbrain ${argv.join(' ')}`);
+ return r;
+ }
+
test('schema with no subcommand shows help text', () => {
// Note: `schema --help` is intercepted by the CLI's parent help system
// and prints generic help (`gbrain --help` for full command list). The
// schema-specific help fires when no subcommand is provided.
- const r = gbrain(['schema']);
+ const r = cached('schema');
expect(r.stdout + r.stderr).toMatch(/schema|active|list|show|validate|use/i);
});
test('schema list shows all bundled packs', () => {
- const r = gbrain(['schema', 'list']);
- expect(r.code).toBe(0);
+ const r = cached('schema', 'list');
+ expect(r.exitCode).toBe(0);
expect(r.stdout).toContain('Bundled packs:');
expect(r.stdout).toContain('gbrain-base');
expect(r.stdout).toContain('gbrain-recommended');
@@ -75,8 +88,8 @@ describe('gbrain schema CLI (Phase C)', () => {
});
test('schema show gbrain-base prints manifest details', () => {
- const r = gbrain(['schema', 'show', 'gbrain-base']);
- expect(r.code).toBe(0);
+ const r = cached('schema', 'show', 'gbrain-base');
+ expect(r.exitCode).toBe(0);
expect(r.stdout).toContain('gbrain-base v1.0.0');
// v0.41.11.0: page types extended from 22 to 24 by promoting
// `conversation` and `atom` into gbrain-base.
@@ -94,27 +107,27 @@ describe('gbrain schema CLI (Phase C)', () => {
});
test('schema validate gbrain-base passes', () => {
- const r = gbrain(['schema', 'validate', 'gbrain-base']);
- expect(r.code).toBe(0);
+ const r = cached('schema', 'validate', 'gbrain-base');
+ expect(r.exitCode).toBe(0);
expect(r.stdout).toContain('✓');
expect(r.stdout).toContain('valid manifest');
});
test('schema show/validate exposes bundled gbrain-recommended', () => {
- const show = gbrain(['schema', 'show', 'gbrain-recommended']);
- expect(show.code).toBe(0);
+ const show = cached('schema', 'show', 'gbrain-recommended');
+ expect(show.exitCode).toBe(0);
expect(show.stdout).toContain('gbrain-recommended v1.0.0');
expect(show.stdout).toContain('Page types (');
expect(show.stdout).toContain('meeting :: temporal');
- const validate = gbrain(['schema', 'validate', 'gbrain-recommended']);
- expect(validate.code).toBe(0);
+ const validate = cached('schema', 'validate', 'gbrain-recommended');
+ expect(validate.exitCode).toBe(0);
expect(validate.stdout).toContain('valid manifest');
});
test('schema show exposes bundled gbrain-base-v2 successor pack', () => {
- const r = gbrain(['schema', 'show', 'gbrain-base-v2']);
- expect(r.code).toBe(0);
+ const r = cached('schema', 'show', 'gbrain-base-v2');
+ expect(r.exitCode).toBe(0);
// v1.2.0 (v0.47 open-loop engine): +owes_to +awaiting_reply_from — 15
// link verbs became 17. (#2117 history: 14 became 15 with `advises`.)
expect(r.stdout).toContain('gbrain-base-v2 v1.2.0');
@@ -122,43 +135,45 @@ describe('gbrain schema CLI (Phase C)', () => {
expect(r.stdout).toContain('Link verbs (17)');
});
- test('schema active loads configured gbrain-recommended with real types', () => {
+ test('schema active loads configured gbrain-recommended with real types', async () => {
+ // Needs a pre-seeded config.json, so it gets its own home + spawn
+ // (never the shared read-only batch).
const home = mkdtempSync(join(tmpdir(), 'gbrain-schema-active-recommended-'));
try {
mkdirSync(join(home, '.gbrain'), { recursive: true });
writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({ schema_pack: 'gbrain-recommended' }), 'utf-8');
- const r = gbrain(['schema', 'active'], { GBRAIN_HOME: home });
- expect(r.code).toBe(0);
+ const r = await runCli(['schema', 'active'], { home });
+ expect(r.exitCode).toBe(0);
expect(r.stdout).toContain('Active pack: gbrain-recommended');
expect(r.stdout).not.toContain('Page types: 0');
} finally {
rmSync(home, { recursive: true, force: true });
}
- });
+ }, 60_000);
test('schema active reports default resolution', () => {
- const r = gbrain(['schema', 'active']);
- expect(r.code).toBe(0);
+ const r = cached('schema', 'active');
+ expect(r.exitCode).toBe(0);
expect(r.stdout).toContain('Active pack:');
expect(r.stdout).toContain('Pack identity:');
});
test('schema show unknown-pack errors with hint', () => {
- const r = gbrain(['schema', 'show', 'nonexistent-pack']);
- expect(r.code).not.toBe(0);
+ const r = cached('schema', 'show', 'nonexistent-pack');
+ expect(r.exitCode).not.toBe(0);
expect(r.stderr).toContain('Unknown pack');
expect(r.stderr).toContain('schema list');
});
test('unknown subcommand exits with hint', () => {
- const r = gbrain(['schema', 'frobnicate']);
- expect(r.code).toBe(2);
+ const r = cached('schema', 'frobnicate');
+ expect(r.exitCode).toBe(2);
expect(r.stderr).toContain('Unknown schema subcommand');
});
test('schema use without arg shows usage hint', () => {
- const r = gbrain(['schema', 'use']);
- expect(r.code).toBe(2);
+ const r = cached('schema', 'use');
+ expect(r.exitCode).toBe(2);
expect(r.stderr).toContain('Usage:');
});
});
@@ -174,48 +189,48 @@ describe('gbrain schema use (Phase C, gap-fill T3)', () => {
rmSync(home, { recursive: true, force: true });
});
- test('writes schema_pack to ~/.gbrain/config.json on happy path', () => {
- const r = gbrain(['schema', 'use', 'gbrain-base'], { GBRAIN_HOME: home });
- expect(r.code).toBe(0);
+ test('writes schema_pack to ~/.gbrain/config.json on happy path', async () => {
+ const r = await runCli(['schema', 'use', 'gbrain-base'], { home });
+ expect(r.exitCode).toBe(0);
expect(r.stdout).toContain('Active schema pack set to: gbrain-base');
expect(r.stdout).toContain('schema active');
const cfgPath = join(home, '.gbrain', 'config.json');
expect(existsSync(cfgPath)).toBe(true);
const cfg = JSON.parse(readFileSync(cfgPath, 'utf-8'));
expect(cfg.schema_pack).toBe('gbrain-base');
- });
+ }, 60_000);
- test('preserves pre-existing config fields when writing schema_pack', () => {
+ test('preserves pre-existing config fields when writing schema_pack', async () => {
// Pre-seed a config with engine + a custom key so the merge preserves them.
mkdirSync(join(home, '.gbrain'), { recursive: true });
const cfgPath = join(home, '.gbrain', 'config.json');
writeFileSync(cfgPath, JSON.stringify({ engine: 'pglite', openai_key: 'sk-fake' }, null, 2), 'utf-8');
- const r = gbrain(['schema', 'use', 'gbrain-base'], { GBRAIN_HOME: home });
- expect(r.code).toBe(0);
+ const r = await runCli(['schema', 'use', 'gbrain-base'], { home });
+ expect(r.exitCode).toBe(0);
const cfg = JSON.parse(readFileSync(cfgPath, 'utf-8'));
expect(cfg.engine).toBe('pglite');
expect(cfg.openai_key).toBe('sk-fake');
expect(cfg.schema_pack).toBe('gbrain-base');
- });
+ }, 60_000);
- test('overwrites prior schema_pack value on re-run', () => {
+ test('overwrites prior schema_pack value on re-run', async () => {
// First set a placeholder, then overwrite via the CLI.
mkdirSync(join(home, '.gbrain'), { recursive: true });
const cfgPath = join(home, '.gbrain', 'config.json');
writeFileSync(cfgPath, JSON.stringify({ engine: 'pglite', schema_pack: 'something-else' }, null, 2), 'utf-8');
- const r = gbrain(['schema', 'use', 'gbrain-base'], { GBRAIN_HOME: home });
- expect(r.code).toBe(0);
+ const r = await runCli(['schema', 'use', 'gbrain-base'], { home });
+ expect(r.exitCode).toBe(0);
const cfg = JSON.parse(readFileSync(cfgPath, 'utf-8'));
expect(cfg.schema_pack).toBe('gbrain-base');
- });
+ }, 60_000);
- test('unknown pack rejected with exit 1 + paste-ready hint', () => {
- const r = gbrain(['schema', 'use', 'no-such-pack-xyz'], { GBRAIN_HOME: home });
- expect(r.code).toBe(1);
+ test('unknown pack rejected with exit 1 + paste-ready hint', async () => {
+ const r = await runCli(['schema', 'use', 'no-such-pack-xyz'], { home });
+ expect(r.exitCode).toBe(1);
expect(r.stderr).toContain('Unknown pack');
expect(r.stderr).toContain('schema list');
// Importantly: a failed `use` must NOT have written a config.
const cfgPath = join(home, '.gbrain', 'config.json');
expect(existsSync(cfgPath)).toBe(false);
- });
+ }, 60_000);
});
diff --git a/test/scripts/run-serial-pool.test.ts b/test/scripts/run-serial-pool.test.ts
index bf0891f026..b1555b9fcc 100644
--- a/test/scripts/run-serial-pool.test.ts
+++ b/test/scripts/run-serial-pool.test.ts
@@ -172,4 +172,68 @@ it('passes after one external SIGTERM', () => {
expect(r.out).toContain('test/h-hang.serial.test.ts');
rmSync(join(ROOT, 'test', 'h-hang.serial.test.ts'));
}, 60000);
+
+ it('dispatches heaviest-first from serial-weights.json (LPT); --dry-run-list stays discovery-ordered', () => {
+ // The aggregation loop prints PASS lines in pool_files order, so stdout
+ // order IS dispatch order regardless of pool width. Weights are advisory:
+ // the sort must reorder dispatch without touching the discovery list.
+ writeFileSync(join(ROOT, 'test', 'a-light.serial.test.ts'), PASSING);
+ writeFileSync(join(ROOT, 'test', 'm-mid.serial.test.ts'), PASSING);
+ writeFileSync(join(ROOT, 'test', 'z-heavy.serial.test.ts'), PASSING);
+ writeFileSync(join(ROOT, 'scripts', 'serial-weights.json'), JSON.stringify({
+ 'test/a-light.serial.test.ts': 1,
+ 'test/m-mid.serial.test.ts': 10,
+ 'test/z-heavy.serial.test.ts': 30,
+ }));
+ try {
+ const dry = execFileSync(
+ 'bash',
+ [join(ROOT, 'scripts', 'run-serial-tests.sh'), '--dry-run-list'],
+ { cwd: ROOT, encoding: 'utf-8', env: ENV },
+ );
+ expect(dry.trim().split('\n')).toEqual([
+ 'test/a-light.serial.test.ts',
+ 'test/m-mid.serial.test.ts',
+ 'test/z-heavy.serial.test.ts',
+ ]);
+ const r = runScript();
+ expect(r.code).toBe(0);
+ const passOrder = [...r.out.matchAll(/\] PASS \d+s (\S+)/g)].map((m) => m[1]);
+ expect(passOrder).toEqual([
+ 'test/z-heavy.serial.test.ts',
+ 'test/m-mid.serial.test.ts',
+ 'test/a-light.serial.test.ts',
+ ]);
+ } finally {
+ rmSync(join(ROOT, 'test', 'a-light.serial.test.ts'), { force: true });
+ rmSync(join(ROOT, 'test', 'm-mid.serial.test.ts'), { force: true });
+ rmSync(join(ROOT, 'test', 'z-heavy.serial.test.ts'), { force: true });
+ rmSync(join(ROOT, 'scripts', 'serial-weights.json'), { force: true });
+ }
+ }, 60000);
+
+ it('a corrupt serial-weights.json falls back to discovery order (fail-soft)', () => {
+ writeFileSync(join(ROOT, 'test', 'a-first.serial.test.ts'), PASSING);
+ writeFileSync(join(ROOT, 'test', 'b-second.serial.test.ts'), PASSING);
+ // Truncated JSON that, if a lenient parser ever "recovered" it, would put
+ // b-second FIRST (weight 99) — so this test distinguishes the fail-soft
+ // branch from an accidentally-parsed sort, not just from a crash.
+ writeFileSync(
+ join(ROOT, 'scripts', 'serial-weights.json'),
+ '{"test/b-second.serial.test.ts": 99, "test/a-first.serial.test.ts": 1',
+ );
+ try {
+ const r = runScript();
+ expect(r.code).toBe(0);
+ const passOrder = [...r.out.matchAll(/\] PASS \d+s (\S+)/g)].map((m) => m[1]);
+ expect(passOrder).toEqual([
+ 'test/a-first.serial.test.ts',
+ 'test/b-second.serial.test.ts',
+ ]);
+ } finally {
+ rmSync(join(ROOT, 'test', 'a-first.serial.test.ts'), { force: true });
+ rmSync(join(ROOT, 'test', 'b-second.serial.test.ts'), { force: true });
+ rmSync(join(ROOT, 'scripts', 'serial-weights.json'), { force: true });
+ }
+ }, 60000);
});
diff --git a/test/scripts/run-unit-parallel.test.ts b/test/scripts/run-unit-parallel.test.ts
index ffefbd0aa1..3f17c66f02 100644
--- a/test/scripts/run-unit-parallel.test.ts
+++ b/test/scripts/run-unit-parallel.test.ts
@@ -406,3 +406,105 @@ describe('run-unit-parallel.sh external-kill rescue contract', () => {
expect(source).toContain('date +%s > "$LOG_DIR/shard-$i.end"');
});
});
+
+describe('run-unit-parallel.sh mem-adapt shed order (intra before shards)', () => {
+ // `bun test --max-concurrency` only bounds test.concurrent tests (1 file in
+ // the corpus), so intra-shard width is nearly free to shed while every
+ // dropped SHARD removes a whole bun process of real fan-out. The old order
+ // (shards first) collapsed a 16GB box to 1x4 — a serial run behind a 12000s
+ // watchdog, measured 3.25x slower than 4 shards on the same machine.
+ it('sheds intra-shard concurrency to 1 before dropping any shard', () => {
+ // Stub detect_available_mem_mb by appending a redefinition to the
+ // sandbox's test-env.sh copy (last definition wins in bash). --dry-run
+ // prints the banner and exits before spawning anything.
+ const stubEnv = join(TMPROOT, 'scripts', 'lib', 'test-env.sh');
+ const orig = readFileSync(stubEnv, 'utf-8');
+ writeFileSync(stubEnv, orig + '\ndetect_available_mem_mb() { echo "${FAKE_AVAIL_MB:-0}"; }\n');
+ try {
+ const r = spawnSync(
+ 'bash',
+ [join(TMPROOT, 'scripts', 'run-unit-parallel.sh'), '--shards', '4', '--dry-run'],
+ {
+ cwd: TMPROOT,
+ encoding: 'utf-8',
+ // budget = 8704 - 4096 = 4608MB → MAX_TOTAL 3 at 1536MB/file.
+ // Old policy landed at 1x3; the fix must land at 3x1.
+ env: {
+ ...process.env,
+ GBRAIN_TEST_NO_MEM_ADAPT: '0',
+ GBRAIN_TEST_MAX_CONCURRENCY: '4',
+ FAKE_AVAIL_MB: '8704',
+ },
+ },
+ );
+ expect(r.stderr).toContain('mem-adapted 4x4→3x1');
+ expect(r.stderr).not.toContain('→1x');
+ } finally {
+ writeFileSync(stubEnv, orig);
+ }
+ });
+});
+
+describe('run-unit-parallel.sh no-timeout-binary wedge sentinel (rc 143 at cap → WEDGED)', () => {
+ // Regression pin: the fallback watchdog TERMs a hung shard (rc 143), which
+ // the pinned 124/137 wedge line cannot see. Before the .watchdog sentinel,
+ // that run died as a bare NON_OOM_FAIL with an rc=143 summary — the
+ // EXIT-HANG/WEDGED classifier was unreachable on machines without coreutils
+ // timeout, turning the known exit-hang leak into a false hard-red there.
+ let WROOT: string;
+
+ beforeAll(() => {
+ WROOT = mkdtempSync(join(tmpdir(), 'gbrain-parallel-wedge-'));
+ mkdirSync(join(WROOT, 'scripts'), { recursive: true });
+ mkdirSync(join(WROOT, 'test'), { recursive: true });
+ for (const s of ['run-unit-parallel.sh', 'run-unit-shard.sh', 'run-serial-tests.sh', 'lib/test-env.sh']) {
+ mkdirSync(dirname(join(WROOT, 'scripts', s)), { recursive: true });
+ copyFileSync(resolve(REPO_ROOT, 'scripts', s), join(WROOT, 'scripts', s));
+ chmodSync(join(WROOT, 'scripts', s), 0o755);
+ }
+ // A test still mid-sleep at the shard cap — the fallback watchdog TERMs
+ // the bun process (rc 143). What this pins is the CLASSIFICATION of that
+ // kill (sentinel → WEDGED), not bun's exit-hang leak itself: a plain
+ // module-level ref'd timer no longer holds bun 1.3 open after the run,
+ // so a sleeping test is the reliable way to be alive at the cap.
+ const hanging = `import { describe, it } from 'bun:test';
+describe('hanging', () => { it('sleeps past the shard cap', async () => { await Bun.sleep(30_000); }, 55_000); });`;
+ writeFileSync(join(WROOT, 'test', 'a-hang-at-exit.test.ts'), hanging);
+
+ // Curated PATH with every tool the scripts call EXCEPT timeout binaries,
+ // so the fallback branch executes even on hosts with coreutils.
+ const bin = join(WROOT, 'bin');
+ mkdirSync(bin);
+ for (const tool of ['bash', 'sh', 'env', 'dirname', 'basename', 'mktemp', 'date', 'sleep', 'cat', 'tail', 'head', 'rm', 'mkdir', 'pkill', 'grep', 'sed', 'awk', 'wc', 'tr', 'seq', 'find', 'sort', 'touch', 'stat', 'bun']) {
+ const p = Bun.which(tool);
+ if (p) symlinkSync(p, join(bin, tool));
+ }
+ });
+
+ afterAll(() => {
+ if (WROOT) rmSync(WROOT, { recursive: true, force: true });
+ });
+
+ it('classifies a watchdog-TERMed shard as WEDGED via the sentinel, not a bare rc=143 fail', () => {
+ const r = spawnSync(
+ 'bash',
+ [join(WROOT, 'scripts', 'run-unit-parallel.sh'), '--shards', '1'],
+ {
+ cwd: WROOT,
+ encoding: 'utf-8',
+ env: {
+ PATH: join(WROOT, 'bin'),
+ HOME: process.env.HOME ?? WROOT,
+ TMPDIR: process.env.TMPDIR ?? '/tmp',
+ GBRAIN_TEST_SHARD_TIMEOUT: '6',
+ GBRAIN_TEST_SHARD_KILL_AFTER: '2',
+ GBRAIN_TEST_NO_MEM_ADAPT: '1',
+ },
+ },
+ );
+ expect(r.status).not.toBe(0);
+ expect(existsSync(join(WROOT, '.context', 'test-shards', 'shard-1.watchdog'))).toBe(true);
+ const summary = readFileSync(join(WROOT, '.context', 'test-summary.txt'), 'utf-8');
+ expect(summary).toContain('WEDGED');
+ }, 120_000);
+});
diff --git a/test/skillpack-check.test.ts b/test/skillpack-check.test.ts
index 9784e363a2..bd52a14b57 100644
--- a/test/skillpack-check.test.ts
+++ b/test/skillpack-check.test.ts
@@ -9,62 +9,67 @@
* - --quiet → no stdout, same exit code.
* - --help → prints usage, exits 0.
*
- * Subprocess invocation against temp $HOME so each test sees clean fixture
- * state. DATABASE_URL / GBRAIN_DATABASE_URL stripped so the report runs
- * filesystem-only (the checks we care about live there).
+ * Subprocess invocation via runCliBatch against two fixture $HOMEs (healthy
+ * and half-migrated), spawned once in beforeAll; tests assert on the cached
+ * results. Sharing a home within a batch is safe: skillpack-check is
+ * read-only against $HOME (doctor --fast reads filesystem state;
+ * apply-migrations --list early-returns when no brain is configured).
+ * DATABASE_URL / GBRAIN_DATABASE_URL are stripped by the helper so the
+ * report runs filesystem-only (the checks we care about live there).
*/
-import { describe, test, expect, beforeEach, afterEach } from 'bun:test';
+import { describe, test, expect, beforeAll, afterAll, afterEach } from 'bun:test';
import { mkdtempSync, rmSync, mkdirSync, writeFileSync } from 'fs';
import { join } from 'path';
import { tmpdir } from 'os';
-import { execFileSync } from 'child_process';
+import { runCliBatch, type CliResult } from './helpers/cli-spawn.ts';
import { __testing } from '../src/commands/skillpack-check.ts';
-const CLI = join(__dirname, '..', 'src', 'cli.ts');
-
-let tmp: string;
-let origHome: string | undefined;
-
-function run(args: string[]): { exitCode: number; stdout: string; stderr: string } {
- // Both HOME and GBRAIN_HOME must point at the fixture dir: config/path
- // resolution prefers GBRAIN_HOME (which the test preload sets to its own
- // scratch), so HOME alone leaves the child reading the wrong .gbrain.
- const env = { ...process.env, HOME: tmp, GBRAIN_HOME: tmp } as Record<string, string | undefined>;
- delete env.DATABASE_URL;
- delete env.GBRAIN_DATABASE_URL;
- try {
- const stdout = execFileSync('bun', ['run', CLI, ...args], {
- env: env as Record<string, string>,
- encoding: 'utf-8',
- stdio: ['ignore', 'pipe', 'pipe'],
- });
- return { exitCode: 0, stdout, stderr: '' };
- } catch (err: any) {
- return {
- exitCode: err.status ?? 1,
- stdout: err.stdout?.toString?.() ?? '',
- stderr: err.stderr?.toString?.() ?? '',
- };
+let healthyHome: string;
+let brokenHome: string;
+
+// Cached batch results — spawned once in beforeAll, asserted per-test.
+let healthy: CliResult; // skillpack-check (healthy home)
+let healthyQuiet: CliResult; // skillpack-check --quiet (healthy home)
+let help: CliResult; // skillpack-check --help (healthy home)
+let broken: CliResult; // skillpack-check (half-migrated home)
+let brokenQuiet: CliResult; // skillpack-check --quiet (half-migrated home)
+
+beforeAll(async () => {
+ healthyHome = mkdtempSync(join(tmpdir(), 'gbrain-skillpack-check-test-'));
+ brokenHome = mkdtempSync(join(tmpdir(), 'gbrain-skillpack-check-test-'));
+
+ // Half-migrated fixture: a partial record in completed.jsonl trips the
+ // minions_migration doctor check → apply-migrations action.
+ const migrationsDir = join(brokenHome, '.gbrain', 'migrations');
+ mkdirSync(migrationsDir, { recursive: true });
+ writeFileSync(
+ join(migrationsDir, 'completed.jsonl'),
+ JSON.stringify({ version: '0.11.0', status: 'partial' }) + '\n',
+ );
+
+ // Two sequential batches at the default width 2 — each run spawns doctor +
+ // apply-migrations grandchildren, so machine-wide CLI children stay bounded.
+ [healthy, healthyQuiet, help] = await runCliBatch(
+ [['skillpack-check'], ['skillpack-check', '--quiet'], ['skillpack-check', '--help']],
+ { home: healthyHome },
+ );
+ [broken, brokenQuiet] = await runCliBatch(
+ [['skillpack-check'], ['skillpack-check', '--quiet']],
+ { home: brokenHome },
+ );
+}, 120_000);
+
+afterAll(() => {
+ for (const dir of [healthyHome, brokenHome]) {
+ try { rmSync(dir, { recursive: true, force: true }); } catch { /* best-effort */ }
}
-}
-
-beforeEach(() => {
- origHome = process.env.HOME;
- tmp = mkdtempSync(join(tmpdir(), 'gbrain-skillpack-check-test-'));
-});
-
-afterEach(() => {
- if (origHome === undefined) delete process.env.HOME;
- else process.env.HOME = origHome;
- try { rmSync(tmp, { recursive: true, force: true }); } catch { /* best-effort */ }
});
describe('gbrain skillpack-check', () => {
test('healthy fresh install → exit 0, healthy:true, empty actions', () => {
- const result = run(['skillpack-check']);
- expect(result.exitCode).toBe(0);
- const report = JSON.parse(result.stdout);
+ expect(healthy.exitCode).toBe(0);
+ const report = JSON.parse(healthy.stdout);
expect(report.healthy).toBe(true);
expect(report.actions).toEqual([]);
expect(report.summary).toBe('gbrain skillpack healthy');
@@ -73,16 +78,8 @@ describe('gbrain skillpack-check', () => {
});
test('half-migrated (partial completed.jsonl) → exit 1, apply-migrations in actions', () => {
- const migrationsDir = join(tmp, '.gbrain', 'migrations');
- mkdirSync(migrationsDir, { recursive: true });
- writeFileSync(
- join(migrationsDir, 'completed.jsonl'),
- JSON.stringify({ version: '0.11.0', status: 'partial' }) + '\n',
- );
-
- const result = run(['skillpack-check']);
- expect(result.exitCode).toBe(1);
- const report = JSON.parse(result.stdout);
+ expect(broken.exitCode).toBe(1);
+ const report = JSON.parse(broken.stdout);
expect(report.healthy).toBe(false);
expect(report.actions).toContain('gbrain apply-migrations --yes');
expect(report.summary).toContain('gbrain apply-migrations --yes');
@@ -96,42 +93,27 @@ describe('gbrain skillpack-check', () => {
test('--quiet → no stdout, same exit code', () => {
// Healthy path quiet
- const healthy = run(['skillpack-check', '--quiet']);
- expect(healthy.exitCode).toBe(0);
- expect(healthy.stdout).toBe('');
-
- // Broken path quiet — need new tmp with fixture
- const migrationsDir = join(tmp, '.gbrain', 'migrations');
- mkdirSync(migrationsDir, { recursive: true });
- writeFileSync(
- join(migrationsDir, 'completed.jsonl'),
- JSON.stringify({ version: '0.11.0', status: 'partial' }) + '\n',
- );
- const broken = run(['skillpack-check', '--quiet']);
- expect(broken.exitCode).toBe(1);
- expect(broken.stdout).toBe('');
+ expect(healthyQuiet.exitCode).toBe(0);
+ expect(healthyQuiet.stdout).toBe('');
+
+ // Broken path quiet — the half-migrated fixture home
+ expect(brokenQuiet.exitCode).toBe(1);
+ expect(brokenQuiet.stdout).toBe('');
});
test('--help → exit 0, prints usage', () => {
- const result = run(['skillpack-check', '--help']);
- expect(result.exitCode).toBe(0);
- expect(result.stdout).toContain('skillpack-check');
- expect(result.stdout).toContain('healthy');
- expect(result.stdout).toContain('Exit codes');
+ expect(help.exitCode).toBe(0);
+ expect(help.stdout).toContain('skillpack-check');
+ expect(help.stdout).toContain('healthy');
+ expect(help.stdout).toContain('Exit codes');
});
test('summary includes top action when multiple present', () => {
// Partial record creates apply-migrations action + the migrations count
// action. Summary should reference the first (highest-priority) action.
- const migrationsDir = join(tmp, '.gbrain', 'migrations');
- mkdirSync(migrationsDir, { recursive: true });
- writeFileSync(
- join(migrationsDir, 'completed.jsonl'),
- JSON.stringify({ version: '0.11.0', status: 'partial' }) + '\n',
- );
- const result = run(['skillpack-check']);
- expect(result.exitCode).toBe(1);
- const report = JSON.parse(result.stdout);
+ // Identical fixture + argv as the half-migrated test → shares its run.
+ expect(broken.exitCode).toBe(1);
+ const report = JSON.parse(broken.stdout);
expect(report.summary).toMatch(/\d+ action\(s\)/);
expect(report.summary).toContain(report.actions[0]);
});
diff --git a/test/sources-ops.test.ts b/test/sources-ops.test.ts
index c4c3ae52d6..05640a1714 100644
--- a/test/sources-ops.test.ts
+++ b/test/sources-ops.test.ts
@@ -112,11 +112,10 @@ afterAll(async () => {
});
beforeEach(async () => {
+ // resetPgliteState re-seeds the default source row (tests that rely on the
+ // v0.17 row get it from there; a second ON CONFLICT DO NOTHING insert here
+ // was always a no-op).
await resetPgliteState(engine);
- // Make sure the default source exists for tests that rely on the v0.17 row.
- await engine.executeRaw(
- `INSERT INTO sources (id, name, local_path, config) VALUES ('default', 'default', NULL, '{}'::jsonb) ON CONFLICT (id) DO NOTHING`,
- );
// Reset GBRAIN_HOME fixtures between tests
rmSync(GBRAIN_HOME, { recursive: true, force: true });
mkdirSync(GBRAIN_HOME, { recursive: true });
diff --git a/test/stats-health-source-scope.test.ts b/test/stats-health-source-scope.test.ts
index b8a5fd0bd3..2ccd3654e6 100644
--- a/test/stats-health-source-scope.test.ts
+++ b/test/stats-health-source-scope.test.ts
@@ -265,6 +265,10 @@ describe.skipIf(!DATABASE_URL)('#4592 source-scoped stats/health (REAL Postgres
}, 120_000);
afterAll(async () => {
+ // Guard: when beforeAll dies before assigning (e.g. a shard-neighbor
+ // leaked a DATABASE_URL that flips the skipIf but fails the db-guard),
+ // this hook still runs — a bare TypeError here buries the real error.
+ if (!engine) return;
await engine.executeRaw(`DELETE FROM pages WHERE source_id IN ('${SRCA}', '${SRCB}')`);
await engine.executeRaw(`DELETE FROM sources WHERE id IN ('${SRCA}', '${SRCB}')`);
await (engine as { disconnect(): Promise<void> }).disconnect();
diff --git a/test/writer.test.ts b/test/writer.test.ts
index c84c3a92df..8dc143fdee 100644
--- a/test/writer.test.ts
+++ b/test/writer.test.ts
@@ -11,6 +11,7 @@ import { mkdtempSync, rmSync } from 'fs';
import { join } from 'path';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { resetPgliteStateNarrow } from './helpers/reset-pglite.ts';
import type { BrainEngine } from '../src/core/engine.ts';
import type { ResolverContext } from '../src/core/resolvers/index.ts';
@@ -63,9 +64,12 @@ afterAll(async () => {
rmSync(dbDir, { recursive: true, force: true });
});
-// Reset DB between tests by truncating — cheaper than tearing down PGLite.
+// Reset DB between tests by truncating ONLY the tables this file writes —
+// cheaper than tearing down PGLite or the full-catalog reset.
async function reset(): Promise<void> {
- await engine.executeRaw('TRUNCATE pages, links, content_chunks, timeline_entries, tags, raw_data, page_versions RESTART IDENTITY CASCADE');
+ await resetPgliteStateNarrow(engine, [
+ 'pages', 'links', 'content_chunks', 'timeline_entries', 'tags', 'raw_data', 'page_versions',
+ ]);
}
function makeCtx(overrides: Partial<ResolverContext> = {}): ResolverContext {