Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
v0.46.5.0 perf(test,ci,eval): CI in half — pooled serial lane, snapshot-in-CI, hermetic retrieval canary (#4154)
Garry Tan11ad23e34655
diff --git a/.gbrain-evals/eval-results.jsonl b/.gbrain-evals/eval-results.jsonlnew file mode 100644index 0000000000..70b784bb06--- /dev/null+++ b/.gbrain-evals/eval-results.jsonl@@ -0,0 +1 @@+{"schema_version":3,"run_id":"f2b40f7ef-retrieval-canary-na-0","ran_at":"2026-08-15T15:37:16.659Z","suite":"retrieval-canary","mode":"n/a","commit":"f2b40f7ef","seed":0,"params":{"qrels":"test/fixtures/eval-baselines/qrels-search.json","embedder":"deterministic","k":10,"metrics":{"mean_recall_at_k":1,"first_relevant_hit_rate":1,"expected_top1_hit_rate":0.8333333333333334,"expected_top1_denominator":12,"queries_run":12,"queries_total":12},"floors":{"recall_at_k":0.7,"first_relevant_hit":0.6,"expected_top1":0.5}},"status":"completed","duration_ms":2290}diff --git a/.gitattributes b/.gitattributesindex 0f1c53fab3..34fb3a8050 100644--- a/.gitattributes+++ b/.gitattributes@@ -27,3 +27,4 @@# Markdown it does not own), but pinning this repo's own .md checkout to LF# removes the whole class for anyone working here.*.md text eol=lf+/.gbrain-evals/eval-results.jsonl merge=uniondiff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.ymlindex bb8abe6039..ce7020d052 100644--- a/.github/workflows/e2e.yml+++ b/.github/workflows/e2e.yml@@ -20,6 +20,44 @@ concurrency:cancel-in-progress: truejobs:+ # ──────────────────────────────────────────────────────────────────────+ # e2e-cache-check: same content-hash skip as test.yml's cache-check, in+ # its own key namespace (e2e-pass-<hash>). Doc-only pushes previously+ # provisioned 3 pgvector services and spent real OpenAI/Anthropic/+ # ZeroEntropy tokens in tier2; now they skip. SCHEDULED runs are exempt+ # below — the nightly is a drift check against live providers and must+ # run even when the tree is unchanged.+ # ──────────────────────────────────────────────────────────────────────+ e2e-cache-check:+ runs-on: ubuntu-latest+ timeout-minutes: 10+ outputs:+ hit: ${{ steps.lookup.outputs.cache-hit }}+ hash: ${{ steps.compute.outputs.hash }}+ steps:+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4+ - name: Compute content hash+ id: compute+ run: |+ HASH=$(bash scripts/ci-cache-hash.sh --verbose 2>/tmp/cache-diag)+ cat /tmp/cache-diag+ echo "Computed cache hash: $HASH"+ echo "hash=$HASH" >> "$GITHUB_OUTPUT"+ - name: Lookup actions/cache for e2e-pass-<hash>+ id: lookup+ uses: actions/cache/restore@5a3ec84eff668545956fd18022155c47e93e2684 # v4.2.3+ with:+ key: e2e-pass-${{ steps.compute.outputs.hash }}+ path: .e2e-cache-marker+ lookup-only: true+ - name: Cache status+ run: |+ if [ "${{ steps.lookup.outputs.cache-hit }}" = "true" ]; then+ echo "✓ e2e cache HIT for hash ${{ steps.compute.outputs.hash }} — e2e jobs will skip (unless scheduled)"+ else+ echo "✗ e2e cache MISS for hash ${{ steps.compute.outputs.hash }} — e2e suite will run"+ fi+jsonb-parity:# Dedicated required guard for the JSONB double-encode bug-class (#2339).# PGLite parses a double-encoded jsonb string silently, so this assertion can@@ -28,6 +66,8 @@ jobs:# Postgres and HARD-FAILS if DATABASE_URL is missing, so the guard can never# silently skip.name: JSONB parity (#2339 regression guard)+ needs: e2e-cache-check+ if: needs.e2e-cache-check.outputs.hit != 'true' || github.event_name == 'schedule' || github.event_name == 'workflow_dispatch'runs-on: ubuntu-latesttimeout-minutes: 15services:@@ -49,7 +89,12 @@ jobs:- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2with:bun-version: 1.3.13- - run: bun install+ - 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 }}-+ - run: bun install --frozen-lockfile- name: Require DATABASE_URL (no silent skip)env:DATABASE_URL: postgresql://postgres:postgres@localhost:5432/gbrain_test@@ -73,6 +118,8 @@ jobs:tier1:name: Tier 1 (Mechanical)+ needs: e2e-cache-check+ if: needs.e2e-cache-check.outputs.hit != 'true' || github.event_name == 'schedule' || github.event_name == 'workflow_dispatch'runs-on: ubuntu-latesttimeout-minutes: 20services:@@ -94,7 +141,12 @@ jobs:- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2with:bun-version: 1.3.13- - run: bun install+ - 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 }}-+ - run: bun install --frozen-lockfile- 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.@@ -106,12 +158,15 @@ jobs:tier2:name: Tier 2 (LLM Skills)+ # Runs on every push/PR (promoted from schedule-only in v0.19.0), in+ # PARALLEL with tier1 (own postgres service — the old `needs: tier1`+ # serialized ~2min for no shared state). The jsonb-parity gate (~40s)+ # stays in front as the broken-build SPEND gate: this job burns real+ # OpenAI/Anthropic/ZeroEntropy tokens and must not fire when the build+ # can't even pass the cheapest DB guard.+ needs: [e2e-cache-check, jsonb-parity]+ if: needs.e2e-cache-check.outputs.hit != 'true' || github.event_name == 'schedule' || github.event_name == 'workflow_dispatch'runs-on: ubuntu-latest- # Runs on every push/PR now (promoted from schedule-only in v0.19.0).- # Tier 1 must pass first; Tier 2 uses OPENAI_API_KEY + ANTHROPIC_API_KEY- # from repo/org secrets. Nightly + manual triggers still supported via- # the workflow-level `on:` list.- needs: tier1timeout-minutes: 30services:postgres:@@ -132,7 +187,12 @@ jobs:- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2with:bun-version: 1.3.13- - run: bun install+ - 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 }}-+ - run: bun install --frozen-lockfile- 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@@ -179,3 +239,61 @@ jobs:# zeroEntropyCompatFetch response-rewriter + URL rewrite + flexible# dim handling + gateway.rerank against the real provider.ZEROENTROPY_API_KEY: ${{ secrets.ZEROENTROPY_API_KEY }}++ # ──────────────────────────────────────────────────────────────────────+ # e2e-cache-write: seals e2e-pass-<hash> only when every gated job+ # succeeded (writing earlier would bless states the suite never proved).+ # Scheduled runs may also write: a nightly green at an unchanged hash is+ # the same proof a push green is.+ # ──────────────────────────────────────────────────────────────────────+ e2e-cache-write:+ needs: [e2e-cache-check, jsonb-parity, tier1, tier2]+ if: success() && needs.e2e-cache-check.outputs.hit != 'true'+ runs-on: ubuntu-latest+ timeout-minutes: 5+ steps:+ - name: Create cache marker+ run: |+ mkdir -p .e2e-cache-marker+ echo "${{ needs.e2e-cache-check.outputs.hash }}" > .e2e-cache-marker/hash+ echo "$GITHUB_SHA" > .e2e-cache-marker/sha+ echo "$GITHUB_REF" > .e2e-cache-marker/ref+ - uses: actions/cache/save@5a3ec84eff668545956fd18022155c47e93e2684 # v4.2.3+ with:+ key: e2e-pass-${{ needs.e2e-cache-check.outputs.hash }}+ path: .e2e-cache-marker++ # ──────────────────────────────────────────────────────────────────────+ # e2e-status: the single stable "did E2E pass?" name (mirror of+ # test.yml's test-status). Succeeds when the cache hit on a non-scheduled+ # run, or when every gated job succeeded.+ # ──────────────────────────────────────────────────────────────────────+ e2e-status:+ needs: [e2e-cache-check, jsonb-parity, tier1, tier2]+ if: always()+ runs-on: ubuntu-latest+ timeout-minutes: 5+ steps:+ - name: Aggregate result+ run: |+ HIT="${{ needs.e2e-cache-check.outputs.hit }}"+ JSONB="${{ needs.jsonb-parity.result }}"+ TIER1="${{ needs.tier1.result }}"+ TIER2="${{ needs.tier2.result }}"+ EVENT="${{ github.event_name }}"+ echo "e2e-cache-check.hit=$HIT event=$EVENT"+ echo "jsonb-parity=$JSONB tier1=$TIER1 tier2=$TIER2"+ # schedule AND workflow_dispatch always run the real suite — a+ # manual dispatch is an explicit ask for a live run, so a cache+ # hit must not report green-without-running for either.+ if [ "$HIT" = "true" ] && [ "$EVENT" != "schedule" ] && [ "$EVENT" != "workflow_dispatch" ]; then+ echo "✓ e2e cache HIT for hash ${{ needs.e2e-cache-check.outputs.hash }} — E2E green"+ exit 0+ fi+ for r in "$JSONB" "$TIER1" "$TIER2"; do+ if [ "$r" != "success" ]; then+ echo "✗ gated e2e job did not succeed (got $r) — E2E fail"+ exit 1+ fi+ done+ echo "✓ all e2e jobs succeeded — E2E green"diff --git a/.github/workflows/heavy-tests.yml b/.github/workflows/heavy-tests.ymlindex 5b04ac2157..2f65f838f9 100644--- a/.github/workflows/heavy-tests.yml+++ b/.github/workflows/heavy-tests.yml@@ -64,7 +64,12 @@ jobs:- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2with:bun-version: 1.3.13- - run: bun install+ - 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 }}-+ - run: bun install --frozen-lockfile- name: Run heavy testsenv:@@ -148,7 +153,12 @@ jobs:- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2with:bun-version: 1.3.13- - run: bun install+ - 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 }}-+ - run: bun install --frozen-lockfile# Reference the door tests; run only the ones present (a door may land# in a sibling PR). Missing binary/auth → the file self-skips, so a@@ -209,7 +219,12 @@ jobs:- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2with:bun-version: 1.3.13- - run: bun install+ - 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 }}-+ - run: bun install --frozen-lockfile# `runner.temp` is not an allowed context in job-level env, so the# evidence dir is derived here and exported for every later step (the@@ -411,7 +426,12 @@ jobs:- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2with:bun-version: 1.3.13- - run: bun install+ - 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 }}-+ - run: bun install --frozen-lockfile- name: Prepare evidence dirrun: |diff --git a/.github/workflows/osv-scanner.yml b/.github/workflows/osv-scanner.ymlindex 8c8b4f9b13..1e242873b8 100644--- a/.github/workflows/osv-scanner.yml+++ b/.github/workflows/osv-scanner.yml@@ -19,6 +19,11 @@ on:permissions:contents: read+# Rapid pushes to the same PR previously queued duplicate scans.+concurrency:+ group: osv-${{ github.event.pull_request.number || github.ref }}+ cancel-in-progress: true+jobs:osv-scan:permissions:diff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex 3d98e35d7c..0f7a24681d 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -35,6 +35,7 @@ concurrency:jobs:version:runs-on: ubuntu-latest+ timeout-minutes: 10outputs:version: ${{ steps.v.outputs.version }}exists: ${{ steps.v.outputs.exists }}@@ -80,6 +81,7 @@ jobs:target: bun-linux-x64artifact: gbrain-linux-x64runs-on: ${{ matrix.os }}+ timeout-minutes: 30permissions:contents: readid-token: write # for attest-build-provenance (Sigstore OIDC)@@ -89,7 +91,12 @@ jobs:- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2with:bun-version: 1.3.13- - run: bun install+ - 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 }}-+ - run: bun install --frozen-lockfile# No test re-run here: the Test workflow already gated this exact SHA at# merge (10 shards + E2E). Re-running the whole suite serially on the# release runner is a flakier duplicate gate — it blocked the first@@ -116,6 +123,7 @@ jobs:needs: [version, build]if: needs.version.outputs.exists == 'false'runs-on: ubuntu-latest+ timeout-minutes: 15permissions:contents: write # create the tag + release (scoped to this job only)steps:@@ -182,6 +190,7 @@ jobs:needs: [version, release]if: needs.version.outputs.exists == 'false'runs-on: ubuntu-latest+ timeout-minutes: 15permissions:contents: readenv:@@ -207,7 +216,13 @@ jobs:with:bun-version: 1.3.13- if: steps.gate.outputs.publish == 'true'- run: bun install+ 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 }}-+ - if: steps.gate.outputs.publish == 'true'+ run: bun install --frozen-lockfile- if: steps.gate.outputs.publish == 'true'name: Generate template tree and byte-diff against the vendored copyrun: |diff --git a/.github/workflows/test.yml b/.github/workflows/test.ymlindex 6c32596d12..ad11c4a9f9 100644--- a/.github/workflows/test.yml+++ b/.github/workflows/test.yml@@ -91,16 +91,24 @@ jobs:# now enforces a paid GITLEAKS_LICENSE (fails the job with "missing# gitleaks license" for accounts it can't validate). The CLI is free, uses# the committed .gitleaks.toml allowlist, and scans the same commit range.+ - name: Cache gitleaks tarball+ uses: actions/cache@5a3ec84eff668545956fd18022155c47e93e2684 # v4.2.3+ with:+ path: /tmp/gitleaks-dl+ key: gitleaks-8.30.1-linux-x64- name: Install gitleaks (pinned + checksum-verified)run: |set -euo pipefailVER=8.30.1BASE="gitleaks_${VER}_linux_x64.tar.gz"URL="https://github.com/gitleaks/gitleaks/releases/download/v${VER}"- curl -fsSL -o "/tmp/${BASE}" "${URL}/${BASE}"+ mkdir -p /tmp/gitleaks-dl+ [ -f "/tmp/gitleaks-dl/${BASE}" ] || curl -fsSL -o "/tmp/gitleaks-dl/${BASE}" "${URL}/${BASE}"+ # Checksums fetched fresh EVERY run: a cache-restored tarball is+ # re-verified against the published digest, never trusted.curl -fsSL -o /tmp/gitleaks_checksums.txt "${URL}/gitleaks_${VER}_checksums.txt"- ( cd /tmp && grep " ${BASE}\$" gitleaks_checksums.txt | sha256sum -c - )- tar -xzf "/tmp/${BASE}" -C /tmp gitleaks+ ( cd /tmp/gitleaks-dl && grep " ${BASE}\$" /tmp/gitleaks_checksums.txt | sha256sum -c - )+ tar -xzf "/tmp/gitleaks-dl/${BASE}" -C /tmp gitleaksinstall /tmp/gitleaks /usr/local/bin/gitleaksgitleaks version- name: Scan for secrets (gitleaks CLI, .gitleaks.toml)@@ -134,11 +142,25 @@ jobs:- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2with:bun-version: 1.3.13+ # This job is the ONE designated saver of the bun cache (the others+ # restore-only, so 5 redundant post-job save attempts disappear).+ # admin/bun.lock is in the key because verify's check:admin-build+ # installs from it.- uses: actions/cache@5a3ec84eff668545956fd18022155c47e93e2684 # v4.2.3with:path: ~/.bun/install/cache- key: bun-cache-${{ runner.os }}-${{ hashFiles('bun.lock') }}- - run: bun install+ key: bun-cache-${{ runner.os }}-${{ hashFiles('bun.lock', 'admin/bun.lock') }}+ restore-keys: bun-cache-${{ runner.os }}-+ # verify's runner sources test-env.sh and builds the snapshot for its+ # PGLite-booting eval checks — restore the cache so it's the ~40ms+ # freshness check, not a cold build ahead of all ~47 checks.+ - 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- run: bun run verify# Guard: no bare `bun test` in workflows/scripts — bun ignores# bunfig.toml's timeout, and hooks (beforeAll/afterAll) get the 5s@@ -147,10 +169,11 @@ jobs:- run: bash scripts/check-bun-test-timeout.shserial-tests:- # *.serial.test.ts at --max-concurrency=1. Lives in its own runner so- # the matrix shards aren't carrying the serial-pass tail (the old shape- # stuffed this into `test (1)` after the matrix work, which compounded- # shard 1's overload).+ # *.serial.test.ts — one bun process per file (module-registry isolation),+ # POOLED across files by scripts/run-serial-tests.sh (was strictly+ # sequential: an 8.5-minute job whose serialization the quarantine+ # contract never required). Lives in its own runner so the matrix shards+ # aren't carrying the serial tail.needs: cache-checkif: needs.cache-check.outputs.hit != 'true'runs-on: ubuntu-latest@@ -160,11 +183,27 @@ jobs:- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2with:bun-version: 1.3.13- - uses: actions/cache@5a3ec84eff668545956fd18022155c47e93e2684 # v4.2.3+ - uses: actions/cache/restore@5a3ec84eff668545956fd18022155c47e93e2684 # v4.2.3with:path: ~/.bun/install/cachekey: bun-cache-${{ runner.os }}-${{ hashFiles('bun.lock') }}- - run: bun install+ restore-keys: bun-cache-${{ runner.os }}-+ # PGLite schema snapshot (~42MB): the runner builds it when absent or+ # stale (its runtime hash is authoritative — a stale restore is rebuilt,+ # never trusted). Cached so the build is paid once per schema change,+ # 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.+ - uses: actions/cache@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- run: bun run test:serialslow-eval-longmemeval:@@ -185,11 +224,20 @@ jobs:- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2with:bun-version: 1.3.13- - uses: actions/cache@5a3ec84eff668545956fd18022155c47e93e2684 # v4.2.3+ - uses: actions/cache/restore@5a3ec84eff668545956fd18022155c47e93e2684 # v4.2.3with:path: ~/.bun/install/cachekey: bun-cache-${{ runner.os }}-${{ hashFiles('bun.lock') }}- - run: bun install+ 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)+ run: bash -c '. scripts/lib/test-env.sh && ensure_pglite_snapshot slow-eval && echo "GBRAIN_PGLITE_SNAPSHOT=${GBRAIN_PGLITE_SNAPSHOT:-}" >> "$GITHUB_ENV"'- run: bun test test/eval-longmemeval-e2e.slow.test.ts --timeout=60000brainbench:@@ -206,16 +254,19 @@ jobs:timeout-minutes: 10 # ~15s hermetic run; matches the per-job-timeout hardening (#2254)steps:- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4- with:- fetch-depth: 0 # the gate needs origin/master's baseline+ - name: Fetch origin/master baseline ref (shallow)+ # The gate reads ONE file via `git show origin/master:...` — a depth-1+ # fetch of the master ref replaces the previous full 3700-commit clone.+ run: git fetch --no-tags --depth=1 origin +refs/heads/master:refs/remotes/origin/master- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2with:bun-version: 1.3.13- - uses: actions/cache@5a3ec84eff668545956fd18022155c47e93e2684 # v4.2.3+ - uses: actions/cache/restore@5a3ec84eff668545956fd18022155c47e93e2684 # v4.2.3with:path: ~/.bun/install/cachekey: bun-cache-${{ runner.os }}-${{ hashFiles('bun.lock') }}- - run: bun install+ restore-keys: bun-cache-${{ runner.os }}-+ - run: bun install --frozen-lockfile- run: bash scripts/ci-brainbench-gate.shenv:BRAINBENCH_OUT: ${{ runner.temp }}/brainbench-result.json@@ -242,11 +293,20 @@ jobs:- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2with:bun-version: 1.3.13- - uses: actions/cache@5a3ec84eff668545956fd18022155c47e93e2684 # v4.2.3+ - uses: actions/cache/restore@5a3ec84eff668545956fd18022155c47e93e2684 # v4.2.3with:path: ~/.bun/install/cachekey: bun-cache-${{ runner.os }}-${{ hashFiles('bun.lock') }}- - run: bun install+ 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)+ run: bash -c '. scripts/lib/test-env.sh && ensure_pglite_snapshot slow-perf && echo "GBRAIN_PGLITE_SNAPSHOT=${GBRAIN_PGLITE_SNAPSHOT:-}" >> "$GITHUB_ENV"'- run: bun test test/entity-resolve-perf.slow.test.ts --timeout=300000# MEMORY_VERBS v1 (Cathedral 1): the entity() p99 < 100ms contract gate# (20K-page corpus + ratio guard) shares this runner — same perf-job@@ -299,11 +359,20 @@ jobs:- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2with:bun-version: 1.3.13- - uses: actions/cache@5a3ec84eff668545956fd18022155c47e93e2684 # v4.2.3+ - uses: actions/cache/restore@5a3ec84eff668545956fd18022155c47e93e2684 # v4.2.3with:path: ~/.bun/install/cachekey: bun-cache-${{ runner.os }}-${{ hashFiles('bun.lock') }}- - run: bun install+ restore-keys: bun-cache-${{ runner.os }}-+ # Restore-only: test-shard.sh validates the snapshot's runtime hash and+ # rebuilds when stale (the serial-tests job is the designated saver).+ - 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: Run test shard ${{ matrix.shard }}/10run: scripts/test-shard.sh ${{ matrix.shard }} 10diff --git a/BOOTSTRAP_FOR_AGENTS.md b/BOOTSTRAP_FOR_AGENTS.mdindex e11ba3b28d..6fc513ae90 100644--- a/BOOTSTRAP_FOR_AGENTS.md+++ b/BOOTSTRAP_FOR_AGENTS.md@@ -1,4 +1,4 @@-<!-- gbrain-runbook-stamp: 0.46.4.0 -->+<!-- gbrain-runbook-stamp: 0.46.5.0 --><!-- This stamp must equal the VERSION file at every release; CI enforces it(scripts/check-bootstrap-tag.sh). `gbrain bootstrap status` compares it tothe installed binary and warns on skew. -->diff --git a/CHANGELOG.md b/CHANGELOG.mdindex f3b0b0d480..c0c1c8eb15 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,40 @@All notable changes to GBrain will be documented in this file.+## [0.46.5.0] - 2026-08-15++**CI in half, evals actually gating.** The Test workflow ran 8–9.5 minutes on+every push; its long pole was a serial-test job that executed ~140 per-file bun+processes strictly one-at-a-time even though the quarantine only ever required+per-process isolation. This release pools that lane (8.5 min → ~4 min in CI,+~2.5 min locally), wires the PGLite schema-snapshot fast-path into the CI test+runners (it previously existed but only the local loop used it), and rebalances+the 10-shard matrix on freshly mined weights (new files without a mined weight+now fall back to the p75 file weight instead of the median) — a measured branch+run landed the whole workflow at 255s. E2E stops spending real provider tokens on doc-only+pushes (content-hash skip with nightly + manual-dispatch exemptions) and runs+its tiers in parallel behind a fast broken-build spend gate.++Retrieval quality now has a hermetic CLI canary: `gbrain eval gate` accepts a+deterministic embedder option that drives the full hybrid/RRF pipeline with+zero API keys, gated in CI on every run (`check:eval-canary`, alongside the new+`check:eval-chronicle` gate) with its run ledger committed to+`.gbrain-evals/eval-results.jsonl`. Two registered-but-never-executed guards+came alive, a registration⇒execution coverage test closes that class for good,+and 47 orphaned eval-harness tests joined the CI matrix behind a keyless+allowlist. Test reliability hardening rounds it out: externally-killed serial+files get a sequential rescue re-run (never a silent pass), machine-global+files live on a growth-guarded exclusive lane, and the shard-balance test now+asserts the matrix CI actually runs instead of recomputing its own inputs.++**To take advantage of v0.46.5.0:** nothing to configure — CI and the local+loops (`bun run test`, `bun run test:serial`, `bun run verify`) are just+faster. New knobs if you need them: `GBRAIN_SERIAL_POOL=1` restores the old+fully-sequential serial lane, `GBRAIN_VERIFY_MAX_PARALLEL` bounds verify's+worker pool, `GBRAIN_NO_SNAPSHOT=1` opts any runner out of the snapshot+fast-path. Run the retrieval canary yourself with+`bun run scripts/run-eval-canary.ts` (add `--record` to append the committed+ledger).## [0.46.4.0] - 2026-08-15**opencode joins the supported-client roster — at full parity from day one.**diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 976b14c36e..87aa7441a8 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -127,8 +127,6 @@ the database name must carry "test" as a word segment (like `gbrain_test`above) or destructive tests refuse to run — opt a differently-named databasein one-shot with `GBRAIN_E2E_ALLOW_DB=<name>`.-Use `bun run verify` before pushing. It runs 19+ guard checks in parallel-Use `bun run verify` before pushing. It runs 40+ guard checks in parallel(`scripts/run-verify-parallel.sh`), including: banned fork-name leaks(`scripts/check-privacy.sh`), `JSON.stringify(x)::jsonb` interpolationdiff --git a/TODOS.md b/TODOS.mdindex 06bde420ec..e26229313c 100644--- a/TODOS.md+++ b/TODOS.md@@ -177,14 +177,77 @@ fix-wave plan; the wave series (W0.5–W9, 3.4, 3.6) tracks its own scope there.- [ ] **Legacy Anthropic-SDK subagent loop deletion.** **Priority: P2.** Onerelease after W8 flips `agent.use_gateway_loop` default ON (flag stays asthe revert path for that release).-- [ ] **Deeper test-suite speedup** beyond the W0 snapshot default-on (which- already cut the full parallel suite ~4,900s → ~490s). **Priority: P3.**- Revisit with post-W0 timing data; diminishing returns until measured.+- [x] **Deeper test-suite speedup** beyond the W0 snapshot default-on —+ LANDED in the test/eval/CI speedup pass (serial pool 8.5min → ~2.5min,+ snapshot in every CI runner + memoized loader, verify worker pool,+ perf-gate row shrink, chunk-grain engine consolidation). Remaining+ long-tail items are filed in "Test/eval/CI speedup pass deferrals" below.- [ ] **PGLite schema build-time derivation** from SCHEMA_SQL via a namedtransform list. **Priority: P3.** Only if W3's schema drift TEST provesannoying in practice — the test alone kills the drift bug class (CodexD4.8/D5.23: fresh-schema equivalence ≠ upgrade correctness; old-shapebootstrap fixtures + replay coverage stay regardless).+## Test/eval/CI speedup pass deferrals (filed with the pass; plan: ~/.claude/plans/system-instruction-you-are-working-iterative-hopcroft.md)++Each was explicitly deferred in the pass's CEO/eng/outside-voice reviews.++- [ ] **Sleep-to-poll conversions.** **What:** replace ~49.5s of hard-coded+ `setTimeout` waits with event/poll-based waits; no fake timers exist in the+ suite. Worst offenders: test/minions.test.ts (12.2s across 43 sites),+ test/process-cleanup.test.ts (5.0s), test/worker-lock-renewal-e2e.serial.test.ts+ (4.0s), test/e2e/worker-abort-recovery.test.ts (3.6s), test/e2e/zombie-reaping.test.ts+ (3.3s). **Why deferred:** careful per-site work against flake-hardened timings;+ ~50s ceiling. **Effort:** M. **Priority:** P3.+- [ ] **E2E: PGLite-only parallel lane + default SHARD.** **What:** run-e2e.sh runs+ 181 files sequentially (one bun cold start each); ~42 PGLite-only files need no+ Postgres and no TRUNCATE-race protection — run them in a parallel lane; default+ the existing SHARD support (only ci-local uses it). Fold into the Postgres+ template-database entry below in this file (CREATE DATABASE … TEMPLATE, ~50ms).+ **Why deferred:** e2e is off the CI critical path after the workflow restructure;+ ci-local + nightly benefit only. **Effort:** M. **Priority:** P2.+- [ ] **Second PGLite snapshot keyed by dims/model.** **What:** ~34 test files+ configure zembed/1280 and always cold-init (the snapshot's shape gate correctly+ refuses the 1536 fixture). Bake a second snapshot per shape; the version-file+ format already carries dims/model. **Why deferred:** moderate effort, small win,+ and it interacts with the shape gate the memoized loader deliberately keeps hot.+ **Effort:** M. **Priority:** P3.+- [ ] **Persistent-engine snapshot.** **What:** the snapshot fast-path only covers+ in-memory engines (`!dataDir` gate at pglite-engine.ts). ~58 files pass+ database_path and pay full cold init (~121s weighted). Needs tar-extract-into-+ dataDir (or PGlite loadDataDir with a dataDir) design. **Effort:** M. **Priority:** P3.+- [ ] **Engine consolidation audit: doctor/bootstrap/migrations-v0_19_0.** **What:**+ 33 files construct 95 engines; chunk-grain-fts was consolidated in-pass, but+ doctor.test.ts (9 engines), bootstrap.test.ts (9), migrations-v0_19_0.test.ts (7)+ need a per-file audit — migration-from-old-schema tests structurally cannot share+ a current-schema engine or use the snapshot. **Effort:** M. **Priority:** P3.+- [ ] **Verify per-check double-spawn removal.** **What:** each CHECKS entry costs a+ `bun run <key>` startup before its bash script; invoking scripts directly from a+ manifest would drop ~47 bun startups. **Why deferred:** micro-win; touches the+ package.json-scripts-as-API convention. **Effort:** S. **Priority:** P3.+- [ ] **Snapshot-tar digest verification (defense-in-depth).** **What:** the CI+ actions/cache for `test/fixtures/pglite-snapshot.tar` validates only the+ schema-hash/dims lines in the sidecar `.version` — which travels in the SAME+ cache entry, so both are forgeable together by anyone with cache write access.+ Record a sha256 of the tar bytes in the version file at build time and have+ `tryLoadSnapshot` verify it (mirror of the gitleaks fetch-fresh-digest+ pattern). **Why deferred:** exploitability bounded by GitHub cache scoping+ (fork caches isolated; poisoning needs push access) and impact is test-DB+ contents only. **Effort:** S. **Priority:** P3.+- [ ] **Redact provider/DB strings in eval ledger writes.** **What:**+ `EvalRunRecord.error` (free text) is persisted unredacted by+ `persistRunRecord` (eval-run-all) and the canary's record mode into the now-+ TRACKED `.gbrain-evals/eval-results.jsonl` — a failed keyed run whose error+ embeds a connection string would ride a later commit into the public repo.+ Route `record.error` + provider-derived params through+ `redactConnectionInfo`/`redactPgUrl` before append; optionally add+ `.gbrain-evals/` to the fixture-privacy scan surface. **Effort:** S.+ **Priority:** P2.+- [ ] **check-image-decoders-embedded.sh into verify CHECKS.** **What:** the guard+ runs its own `bun build --compile` (~60s) — too heavy per-verify. Revisit if the+ binary-embed bug class recurs; guards-manifest.tsv carries the exemption note,+ and the registration⇒execution coverage test allowlists it explicitly.+ **Effort:** S. **Priority:** P3.+## Jobs fix-wave follow-ups (filed v0.45.15.0 — upstream issues #2/#3/#4)- [ ] **P2 — `jobs submit --max-pending` public flag.** maxPending stays an@@ -3011,8 +3074,13 @@ outside-voice triage on the reshaped plan.- [ ] **v0.42+: ship the coordinated `gbrain-evals/baselines/v0.41-launch.baseline.ndjson`+ `gbrain-evals/qrels/v0.41-launch.qrels.json` (hermetic-synthetic per D9).**Generate locally via `gbrain bench publish --from <hermetic-test-corpus>` then- commit to the sibling gbrain-evals repo. Gives `gbrain eval gate` a canonical- baseline target so users don't have to bootstrap their own immediately.+ commit to the sibling gbrain-evals repo. PARTIALLY SUPERSEDED by the test/eval/CI+ 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+ here is only the sibling-repo REGRESSION baseline (.baseline.ndjson for the+ jaccard/top1 gate) — the correctness-gate half is done.## v0.40.7.0 Schema Cathedral v3 follow-ups (v0.40.7+)@@ -4088,7 +4156,12 @@ verify Voyage adapter integration in `src/core/ai/recipes/voyage.ts`).## test infra (v0.26.4 follow-up — intra-file parallelism)### Sweep cross-file shared-state contention; enable `bun test --concurrent` for another 2-3x speedup-**Priority:** P0+**Priority:** P3 (downgraded from P0 in the test/eval/CI speedup pass — premises stale:+the entry says "~58 PGLiteEngine instantiations", the suite now has 600+; the serial+quarantine grew from 4 files to ~140, and the pass's pooled serial runner + CI snapshot++ verify pool delivered a comparable multiple for hours of work instead of the 1-2+weeks this sweep estimates. Re-scope against post-pass timing data before spending+anything here; `test.concurrent` adoption remains at zero.)**Status:** v0.26.7 shipped foundation slice (helpers + lint + mock.module quarantine). v0.26.8 (env sweep) and v0.26.9 (PGLite sweep + codemod + measurement) carry the rest.**What:** v0.26.4 shipped file-level parallel fan-out (8 shards) and got `bun run test` from 18 minutes to ~85s — a 12x speedup. The next layer is **intra-file** parallelism via Bun's `--concurrent` flag (or per-test `test.concurrent()` markers). This requires every test file to be safe under concurrent execution within the same `bun test` process.diff --git a/VERSION b/VERSIONindex 4befb2654f..fdc55ee32c 100644--- a/VERSION+++ b/VERSION@@ -1 +1 @@-0.46.4.0\ No newline at end of file+0.46.5.0diff --git a/docs/TESTING.md b/docs/TESTING.mdindex e462db3d50..1a761fb754 100644--- a/docs/TESTING.md+++ b/docs/TESTING.md@@ -11,11 +11,11 @@ Six 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 (~10x wallclock on a full run; 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 in parallel by `scripts/run-verify-parallel.sh`: the full `check:*` battery (privacy, jsonb, progress, source-id, test-isolation, wasm, …) plus `bun run typecheck`. The `CHECKS` array in that script is the single source of truth — CI literally calls `bun run verify` in a dedicated job. | ~16s (parallel; typecheck 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 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: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). | ~1s per quarantined file | Debugging a specific quarantined file. |+| `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. |There is no `check:all` script anymore — it was a second, hand-synced guard@@ -32,11 +32,17 @@ self-test" below).post-`initSchema()` PGLite data dir into `test/fixtures/pglite-snapshot.tar`plus a version file; `PGLiteEngine.initSchema()` restores the tar instead ofreplaying the embedded schema + all migrations when the env var-`GBRAIN_PGLITE_SNAPSHOT` points at it. Both `bun run test`-(`scripts/run-unit-parallel.sh`, before the shard fan-out) and-`scripts/ci-local.sh` call the builder unconditionally and export the env var.-Measured effect: a full parallel suite run drops ~10x (PGLite-booting files go-~1.63s → ~0.91s each). Properties:+`GBRAIN_PGLITE_SNAPSHOT` points at it. Runners activate it through the shared+`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+exports the env var, no-ops on `GBRAIN_NO_SNAPSHOT=1` or an already-inherited+path, and is non-fatal on build failure — tests fall back to cold init, with+a one-line "active" echo so a silent fallback stays visible in CI logs.+Measured effect: ~3.5x per PGLite-booting file (a cold boot replays every+migration, ~3.1s each on a CI shard). Properties:- **Idempotent.** A hash short-circuit exits in ~40ms when the snapshot isfresh, and REBUILDS a stale one. The hash covers `PGLITE_SCHEMA_SQL`, every@@ -106,7 +112,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`) and INCLUDES `*.slow.test.ts` (the two outlier slow files run as dedicated jobs alongside the matrix). CI EXCLUDES `*.serial.test.ts` from the shards and runs them in a dedicated job via `bun run test:serial`, one bun process per file — keeping serial files out of the shard processes is what preserves the `mock.module` quarantine (a top-level mock in one file leaks into every other file sharing its process). `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. 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 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."- **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.@@ -131,7 +137,7 @@ Triage rule: a `warn-pass` EXIT-HANG line in `.context/test-summary.txt` is NOT- `*.test.ts` → fast loop (parallel up-to-4-shard fan-out, memory-adaptive).- `*.slow.test.ts` → run via `bun run test:slow` only (intentional cold-path tests; would dominate the fast loop's wallclock).-- `*.serial.test.ts` → run via `bun run test:serial` after the parallel pass completes; one bun process per file (`--max-concurrency=1` within a shared process is not enough — the module registry still leaks `mock.module`). Quarantine for tests that share file-wide state and race when run alongside other files in the same `bun test` process. Several dozen files, discovered by the `*.serial.test.ts` glob — no list to maintain. Typical residents: `mock.module(...)` users (top-level mocks leak across files in a shard process, e.g. `test/embed.serial.test.ts`), env-coupled files (e.g. `test/brain-registry.serial.test.ts`), and process-lifecycle suites that assert on `process.exitCode` (e.g. `test/pglite-engine-disconnect.serial.test.ts`). **Do not put the parallelism back on a serial file unless you've fixed the contention root cause** (it just re-introduces the flake).+- `*.serial.test.ts` → run via `bun run test:serial` after the parallel pass completes; one bun process per file (`--max-concurrency=1` within a shared process is not enough — the module registry still leaks `mock.module`), with those per-file processes POOLED (per-process isolation never required one-at-a-time execution). Files touching machine-global state (launchd/cron) live on the sequential `EXCLUSIVE_FILES` lane inside `scripts/run-serial-tests.sh` — growth-guarded to ≤3 entries with justification comments. Quarantine for tests that share file-wide state and race when run alongside other files in the same `bun test` process. Several dozen files, discovered by the `*.serial.test.ts` glob — no list to maintain. Typical residents: `mock.module(...)` users (top-level mocks leak across files in a shard process, e.g. `test/embed.serial.test.ts`), env-coupled files (e.g. `test/brain-registry.serial.test.ts`), and process-lifecycle suites that assert on `process.exitCode` (e.g. `test/pglite-engine-disconnect.serial.test.ts`). **Do not put the parallelism back on a serial file unless you've fixed the contention root cause** (it just re-introduces the flake).- `test/e2e/*.test.ts` → real-Postgres E2E. Skipped when `DATABASE_URL` is unset. One out-of-directory file rides this lane: `test/phantom-redirect-engine-parity.test.ts` (lives in `test/` for its PGLite arm, but its Postgres arm is only reachable through a DATABASE_URL-bearing lane — the unit wrappers strip the URL per #3485, so `run-e2e.sh`'s no-args list and CI's parity job carry it).- `tests/heavy/*.sh` → ops-shape shell scripts. Cost minutes per run; NOT in default `bun test`. Run via `bun run test:heavy` or scheduled nightly via `.github/workflows/heavy-tests.yml`. Examples: pg_upgrade matrix (boot legacy brain → walk to head), RSS budget gate (measure peak worker RSS vs committed baseline), read-latency-under-sync (p50/p95/p99 under concurrent writer load), sync lock regression (N concurrent syncs assert 1 winner + N-1 lock-busy + zero leaked `gbrain_cycle_locks` rows). See `tests/heavy/README.md` for when to add a script here vs `*.slow.test.ts`. Files prefixed with `_` (e.g. `tests/heavy/_build_legacy_fixtures.sh`) are helpers/libs invoked by sibling tests — the runner skips them.- `test/fuzz/*.test.ts` → property-based fuzz harness. Pure-validator targets in `pure-validators.test.ts` are guarded by `scripts/check-fuzz-purity.sh` (in `bun run verify`), which `bun build --target=bun` bundles each target and greps the resulting bundle for banned transitive imports (`node:fs`, `node:child_process`, engine modules). Anything that fails the guard moves to `mixed-validators.test.ts` (still property-tested, but no purity guarantee) or `filesystem-validators.test.ts` (fs-backed, uses temp dirs). Fuzz tests run in the default `bun test` loop because they're fast (~3s for ~12 properties × 1000 runs each).diff --git a/docs/architecture/KEY_FILES.md b/docs/architecture/KEY_FILES.mdindex 4e43ca872e..f492e3319e 100644--- a/docs/architecture/KEY_FILES.md+++ b/docs/architecture/KEY_FILES.md@@ -105,7 +105,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`. 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-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`, 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/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`.@@ -118,7 +118,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this- `docs/eval-bench.md` — contributor guide for using captured data to benchmark retrieval changes before merging. Linked from CONTRIBUTING.md under "Running real-world eval benchmarks (touching retrieval code)".- `src/core/eval-capture.ts` — op-layer capture wrapper called from `src/core/operations.ts` `query` + `search` handlers (catches MCP + CLI + subagent tool-bridge from one site). Fire-and-forget; failures route to `engine.logEvalCaptureFailure` so `gbrain doctor` sees drops cross-process. Capture is off by default — `isEvalCaptureEnabled` resolution: explicit `config.eval.capture` (true/false) wins, else `process.env.GBRAIN_CONTRIBUTOR_MODE === '1'`, else off. Contributors set `export GBRAIN_CONTRIBUTOR_MODE=1`. PII scrubber gate is independent and defaults to true regardless of CONTRIBUTOR_MODE.- `src/core/eval-capture-scrub.ts` — zero-deps PII scrubber: emails, phones, SSN, Luhn-verified credit cards, JWT-shaped tokens, bearer tokens.-- `src/core/search/hybrid.ts` — Cathedral II `Promise<SearchResult[]>` return shape. `onMeta?: (m: HybridSearchMeta) => void` callback so op-layer capture records what hybridSearch actually did; existing callers leave it undefined. `HybridSearchOpts.types?: PageType[]` (on `SearchOpts`) threads a multi-type filter into per-engine `searchKeyword` + `searchVector` + `searchKeywordChunks` as `AND p.type = ANY($N::text[])` (primary consumer `gbrain whoknows`, filters to `['person','company']`); AND-applies alongside the single-value `type` filter. `hybridSearch` resolves the embedding column at the boundary via `resolveColumn(loadRegistry(cfg), opts.embedding_column, cfg)` from `src/core/search/embedding-column.ts`, threads the `ResolvedColumn` descriptor (not a raw string) into per-engine `searchVector`, and uses `isCacheSafe(resolved, cfg)` for the cache-skip decision so a repointed `embedding` builtin doesn't leak across vector spaces. `cosineReScore` calls `engine.getEmbeddingsByChunkIds(ids, resolved.name)` so rerank uses vectors from the active column, not the hardcoded OpenAI `embedding`. The `query` MCP op accepts `embedding_column` for per-call A/B; `search` (keyword-only) rejects it. Two post-fusion stages + evidence stamp: `applyTitleBoost(results, query, titleBoost, floorThreshold)` multiplies a result's score by the resolved `title_boost` when `isTitlePhraseMatch` fires, stamps `title_match_boost`, inherits the floor-ratio gate so a title match can't shove a much-stronger page below it; `applyAliasHop(engine, results, query, opts)` normalizes the query, calls `engine.resolveAliases`, and on exact normalized-alias match surfaces that page at top-of-organic + epsilon with `alias_hit=true`; `stampEvidence(...)` runs LAST (after the alias hop, before slice) on every path — keyword-only, no-embed, and full hybrid — so MCP callers and `--explain` read the same `evidence` + `create_safety` contract. `title_boost` resolved from the mode bundle and threaded in. `runPostFusionStages` has a 4th stage (`graphSignalsEnabled`, `onGraphMeta`, `onScoreDistribution`). `base_score` stamped at function entry idempotently (captured ONCE before any boost stage mutates `score`). Each post-fusion stage stamps its multiplier: `applyBacklinkBoost`→`backlink_boost`, `applySalienceBoost`→`salience_boost`, `applyRecencyBoost`→`recency_boost`. `applyReranker` (earlier in the pipeline) stamps `reranker_delta` as a rank delta (positive = improved). `applyExactMatchBoost` in `src/core/search/intent-weights.ts` stamps `exact_match_boost` when fired. Per-stage attribution powers `gbrain search --explain` — every boost surface carries its own field so `formatResultsExplain` reads them all without coupling to internal stage ordering. with `src/core/search/sql-ranking.ts` + `src/core/operations.ts` + `src/core/types.ts`: agent-warning channel. `SearchResult.content_flag?: {reason, detail}` (new optional field in `types.ts`) is stamped post-fusion by `stampContentFlags` (the `stampEvidence` precedent) in `hybridSearch` AND in the keyword-only `search` MCP op so both retrieval paths surface the marker. `get_page` returns a top-level `content_flag` parallel field via `getContentFlag(page.frontmatter)`. `buildVisibilityClause` (sql-ranking.ts) ANDs in `QUARANTINE_FILTER_FRAGMENT` so quarantined pages are excluded from all six search call sites (alongside soft-delete + archived-source filters). Pinned by `test/sql-ranking.test.ts` + `test/e2e/quarantine-search-exclusion.test.ts`. Cross-modal routing at the embed step: `effectiveModality` resolves per-call `opts.crossModal` (literal `'auto'` → undefined) → `suggestions.suggestedModality` → `'text'`. Image route: `embedQueryMultimodal` + `searchVector({embeddingColumn: 'embedding_image'})`, skipping expansion + keyword. `'both'` route: parallel text + image vector searches merged via `rrfFusionWeighted` with `effectiveRrfK(baseRrfK, weight)` from the configured cross-modal weights. Unified routing fires when `search.unified_multimodal` is true — bypasses dual-column branching, runs `embedQueryMultimodal` + `searchVector({embeddingColumn: 'embedding_multimodal'})`, fail-open on zero rows (non-strict falls through to dual-column). LLM modality escalation fires only when no explicit per-call opt is set AND the regex returned `'text'` AND `search.cross_modal.llm_intent` is on AND `isAmbiguousModalityQuery` fires; fail-open on every error.+- `src/core/search/hybrid.ts` — Cathedral II `Promise<SearchResult[]>` return shape. `onMeta?: (m: HybridSearchMeta) => void` callback so op-layer capture records what hybridSearch actually did; existing callers leave it undefined. `HybridSearchOpts.queryEmbedFn?: (text) => Float32Array | Promise<Float32Array>` is the hermetic eval seam: when set, the TEXT vector arm's query embedding comes from this function instead of the gateway's query-embed path AND the no-embedding-provider keyword-only short-circuit is bypassed, so deterministic eval canaries (`gbrain eval gate --embedder deterministic`, `scripts/run-eval-canary.ts`) run the vector arm with no provider key; never set on production paths — absent, behavior is byte-for-byte unchanged, and bare `hybridSearch` never touches the semantic query cache so the seam can't poison `query_cache`. `HybridSearchOpts.types?: PageType[]` (on `SearchOpts`) threads a multi-type filter into per-engine `searchKeyword` + `searchVector` + `searchKeywordChunks` as `AND p.type = ANY($N::text[])` (primary consumer `gbrain whoknows`, filters to `['person','company']`); AND-applies alongside the single-value `type` filter. `hybridSearch` resolves the embedding column at the boundary via `resolveColumn(loadRegistry(cfg), opts.embedding_column, cfg)` from `src/core/search/embedding-column.ts`, threads the `ResolvedColumn` descriptor (not a raw string) into per-engine `searchVector`, and uses `isCacheSafe(resolved, cfg)` for the cache-skip decision so a repointed `embedding` builtin doesn't leak across vector spaces. `cosineReScore` calls `engine.getEmbeddingsByChunkIds(ids, resolved.name)` so rerank uses vectors from the active column, not the hardcoded OpenAI `embedding`. The `query` MCP op accepts `embedding_column` for per-call A/B; `search` (keyword-only) rejects it. Two post-fusion stages + evidence stamp: `applyTitleBoost(results, query, titleBoost, floorThreshold)` multiplies a result's score by the resolved `title_boost` when `isTitlePhraseMatch` fires, stamps `title_match_boost`, inherits the floor-ratio gate so a title match can't shove a much-stronger page below it; `applyAliasHop(engine, results, query, opts)` normalizes the query, calls `engine.resolveAliases`, and on exact normalized-alias match surfaces that page at top-of-organic + epsilon with `alias_hit=true`; `stampEvidence(...)` runs LAST (after the alias hop, before slice) on every path — keyword-only, no-embed, and full hybrid — so MCP callers and `--explain` read the same `evidence` + `create_safety` contract. `title_boost` resolved from the mode bundle and threaded in. `runPostFusionStages` has a 4th stage (`graphSignalsEnabled`, `onGraphMeta`, `onScoreDistribution`). `base_score` stamped at function entry idempotently (captured ONCE before any boost stage mutates `score`). Each post-fusion stage stamps its multiplier: `applyBacklinkBoost`→`backlink_boost`, `applySalienceBoost`→`salience_boost`, `applyRecencyBoost`→`recency_boost`. `applyReranker` (earlier in the pipeline) stamps `reranker_delta` as a rank delta (positive = improved). `applyExactMatchBoost` in `src/core/search/intent-weights.ts` stamps `exact_match_boost` when fired. Per-stage attribution powers `gbrain search --explain` — every boost surface carries its own field so `formatResultsExplain` reads them all without coupling to internal stage ordering. with `src/core/search/sql-ranking.ts` + `src/core/operations.ts` + `src/core/types.ts`: agent-warning channel. `SearchResult.content_flag?: {reason, detail}` (new optional field in `types.ts`) is stamped post-fusion by `stampContentFlags` (the `stampEvidence` precedent) in `hybridSearch` AND in the keyword-only `search` MCP op so both retrieval paths surface the marker. `get_page` returns a top-level `content_flag` parallel field via `getContentFlag(page.frontmatter)`. `buildVisibilityClause` (sql-ranking.ts) ANDs in `QUARANTINE_FILTER_FRAGMENT` so quarantined pages are excluded from all six search call sites (alongside soft-delete + archived-source filters). Pinned by `test/sql-ranking.test.ts` + `test/e2e/quarantine-search-exclusion.test.ts`. Cross-modal routing at the embed step: `effectiveModality` resolves per-call `opts.crossModal` (literal `'auto'` → undefined) → `suggestions.suggestedModality` → `'text'`. Image route: `embedQueryMultimodal` + `searchVector({embeddingColumn: 'embedding_image'})`, skipping expansion + keyword. `'both'` route: parallel text + image vector searches merged via `rrfFusionWeighted` with `effectiveRrfK(baseRrfK, weight)` from the configured cross-modal weights. Unified routing fires when `search.unified_multimodal` is true — bypasses dual-column branching, runs `embedQueryMultimodal` + `searchVector({embeddingColumn: 'embedding_multimodal'})`, fail-open on zero rows (non-strict falls through to dual-column). LLM modality escalation fires only when no explicit per-call opt is set AND the regex returned `'text'` AND `search.cross_modal.llm_intent` is on AND `isAmbiguousModalityQuery` fires; fail-open on every error.- `docs/eval-capture.md` — stable NDJSON schema reference for gbrain-evals consumers.- `test/public-exports.test.ts` — runtime contract test (R2). Imports each of the 17 public subpaths via package name and pins a canary symbol per module. Paired with `scripts/check-exports-count.sh`.- `src/core/embedding.ts` — OpenAI text-embedding-3-large, batch, retry, backoff. `BATCH_SIZE=100` (per-recipe pre-split + recursive halving + adaptive shrink-on-miss live in the gateway; the outer paginator is for progress-callback granularity, not batch protection). `estimateEmbeddingCostUsd(tokens)` prices against the currently-configured model's rate via `currentEmbeddingPricePerMTok()` (resolves the per-1M-token rate via `lookupEmbeddingPrice(gatewayGetModel())` from `embedding-pricing.ts`, falling back to the OpenAI 3-large rate 0.13 only when the gateway is unconfigured or the model is unknown to the pricing table). `EMBEDDING_COST_PER_1K_TOKENS` retained for back-compat with direct importers/tests. `currentEmbeddingSignature(): string` returns the embedding-provenance signature `<provider:model>:<dims>` (e.g. `openai:text-embedding-3-large:1536`) stamped onto `pages.embedding_signature` at every embed-write site; DELIBERATELY excludes the chunker version (tracked separately via `pages.chunker_version`) — this signature is strictly the EMBEDDING space, so a model OR dimension swap makes the stored signature differ from current and a page becomes stale. Same unconfigured-gateway fallback as the cost helpers. (See `src/core/sync-delta.ts` + `src/core/spend-posture.ts` for the #2139 cost-gate supporting modules.) `willEmbedSynchronously({v2Enabled, serialFlag, noEmbed}): SyncEmbedMode` is the single source of truth for whether `gbrain sync --all` embeds at sync time (`'inline'`) or defers to per-source `embed-backfill` minion jobs (`'deferred'`) — mirrors `sync.ts`'s `effectiveNoEmbed` resolution exactly (`v2Enabled && !serialFlag && !noEmbed → deferred`) so cost gate and embed decision can't drift. `shouldBlockSync(costUsd, floorUsd, mode, posture='gated'): boolean` is the pure cost-gate decision: blocks ONLY when `mode === 'inline' && costUsd > floorUsd` — deferred mode never blocks (the backfill's $X/source/24h cap is the real money gate), and `posture === 'tokenmax'` never blocks (the operator declared cost isn't the constraint; an `off`/`unlimited` floor is `Infinity` and so is never exceeded). Pinned by `test/sync-cost-preview.test.ts` + `test/embedding-signature-stale.test.ts`.@@ -347,8 +347,8 @@ per-release `**vX.Y.Z:**` narration — CI enforces this- `scripts/check-jsonb-pattern.sh` — CI grep guard. Fails the build if anyone reintroduces (a) the `${JSON.stringify(x)}::jsonb` interpolation pattern (postgres.js v3 double-encodes it), or (b) `max_stalled INTEGER NOT NULL DEFAULT 1` in any schema source file (must be DEFAULT 5 to preserve SIGKILL-rescue). It also invokes `scripts/check-jsonb-params.mjs` and propagates its exit code. Wired into `bun test`.- `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 (45 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/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 by `scripts/run-unit-parallel.sh` (default-on for `bun run test`; opt out `GBRAIN_NO_SNAPSHOT=1`) and `scripts/ci-local.sh`, both of which export `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. Pinned by `test/snapshot-shape-guard.test.ts`.+- `scripts/guards-manifest.tsv` + `scripts/guard-self-test.sh` — THE single registry of `scripts/check-*` CI guards (46 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/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`.- `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.diff --git a/docs/eval-bench.md b/docs/eval-bench.mdindex 80946cfb98..4b42d8a5e5 100644--- a/docs/eval-bench.md+++ b/docs/eval-bench.md@@ -64,6 +64,21 @@ CI. Production retrieval differs via the query cache, salience freshness,expansion, etc. The gate measures retrieval quality with a fixed pipeline;your users may see different results when the cache is warm.+For a fully hermetic run (CI canaries, keyless environments), add+`--embedder deterministic` to the correctness gate: query embeddings come+from the qrels fixture's basis-vector dims (`src/eval/deterministic-embed.ts`)+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+PGLite brain seeded from the qrels fixture, gating the hybrid ranking+pipeline (keyword/title/alias arms + RRF) with synthetic vectors. 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).+### `.qrels.json` shapeTwo equivalent representations per entry:diff --git a/docs/eval/FIX_WAVE_BASELINES.md b/docs/eval/FIX_WAVE_BASELINES.mdindex 5fb12a8d2d..94738f4c25 100644--- a/docs/eval/FIX_WAVE_BASELINES.md+++ b/docs/eval/FIX_WAVE_BASELINES.md@@ -51,8 +51,14 @@ Test infra: PGLite snapshot default-on for `bun run test`. Per-PGLite-file:Full-suite wall-clock (post-snapshot): recorded in the W0 ship notes — seethe run banner of the W0 PR's `bun run test` evidence.-Retrieval canary: NOT RUN at W0 (production brain locked by live serve; W0-touches no search paths). REQUIRED before W1 lands.+Retrieval canary: PASS @ f2b40f7ef (hermetic deterministic-embedder CLI run;+recall@10=1.0000 first_relevant=1.0000 expected_top1=0.8333 vs floors+0.70/0.60/0.50; run `bun run scripts/run-eval-canary.ts` to reproduce, ledger:+.gbrain-evals/eval-results.jsonl). Honest scope: the canary gates the hybrid+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.Verified-bug status at W0 ship: cycle-lock refresh + fencing (TODO-OPS-2closed), stall-death parent unblock, started_at ×4, modality carry, importdiff --git a/openclaw.plugin.json b/openclaw.plugin.jsonindex 7529ad7d0c..36ca7f4a21 100644--- a/openclaw.plugin.json+++ b/openclaw.plugin.json@@ -1,7 +1,7 @@{"id": "gbrain-context-engine","name": "gbrain",- "version": "0.46.4.0",+ "version": "0.46.5.0","description": "Personal knowledge brain with Postgres + pgvector hybrid search","family": "bundle-plugin","configSchema": {diff --git a/package.json b/package.jsonindex 9e6a64441a..96c64b157c 100644--- a/package.json+++ b/package.json@@ -94,6 +94,10 @@"check:operations-filter-bypass": "bash scripts/check-operations-filter-bypass.sh","check:fixture-privacy": "bash scripts/check-fixture-privacy.sh","check:conversation-parser": "bun src/cli.ts eval conversation-parser test/fixtures/conversation-formats/all.jsonl --no-llm",+ "check:eval-chronicle": "bun src/cli.ts eval chronicle",+ "check:eval-canary": "bun run scripts/run-eval-canary.ts",+ "check:pagetype-exhaustive": "bash scripts/check-pagetype-exhaustive.sh",+ "check:pg-url-redaction": "bash scripts/check-pg-url-redaction.sh","check:source-scope-onboard": "bash scripts/check-source-scope-onboard.sh","postinstall": "bun run scripts/postinstall.ts","prepublish:clawhub": "bun run build:all",@@ -160,7 +164,7 @@"bun": ">=1.3.10"},"license": "MIT",- "version": "0.46.4.0",+ "version": "0.46.5.0","overrides": {"@hono/node-server": "^2.0.5","fast-uri": "^3.1.5",diff --git a/scripts/check-pg-url-redaction.sh b/scripts/check-pg-url-redaction.shindex 52dd1e1dd2..97c33a8af9 100755--- a/scripts/check-pg-url-redaction.sh+++ b/scripts/check-pg-url-redaction.sh@@ -21,7 +21,10 @@ ROOT=$(cd "$(dirname "$0")/.." && pwd)# - The redactor itself: src/core/url-redact.ts# - Test fixtures that build redacted strings from full URLs# - Documentation comments referring to the pattern-ALLOW_REGEX='url-redact\.ts|test/url-redact\.test\.ts|/\* allow-pg-url-literal \*/'+# The marker text is the exemption; its comment wrapper is not load-bearing+# (inside a /** block comment a literal `*/` would terminate the comment, so+# block-comment examples carry the bare marker).+ALLOW_REGEX='url-redact\.ts|test/url-redact\.test\.ts|allow-pg-url-literal'# The pattern matches an unredacted Postgres URL appearing in a string# literal, NOT preceded by `redactPgUrl(` or `***@`. We also match any@@ -47,6 +50,6 @@ echo "ERROR: unredacted postgres:// URL found in source. Use redactPgUrl() beforecho ""echo "$FILTERED"echo ""-echo "Allowed exemption: append \"/* allow-pg-url-literal */\" comment on the line"+echo "Allowed exemption: append an allow-pg-url-literal comment marker on the line"echo "(only for fixtures and the redactor itself)."exit 1diff --git a/scripts/check-test-isolation.sh b/scripts/check-test-isolation.shindex 1ad904a716..c016fecbe7 100755--- a/scripts/check-test-isolation.sh+++ b/scripts/check-test-isolation.sh@@ -41,6 +41,14 @@ ROOT="$(git rev-parse --show-toplevel 2>/dev/null || pwd)"cd "$ROOT"TARGET_DIR="${1:-test}"+# When scanning the default root, also lint evals/**/*.test.ts — those files+# are collected into the CI matrix (scripts/test-shard.sh) and must obey the+# same isolation rules as everything else CI executes. An explicit TARGET_DIR+# argument (guard self-test fixtures) scans only itself.+EXTRA_DIRS=""+if [ "$TARGET_DIR" = "test" ] && [ -d evals ]; then+ EXTRA_DIRS="evals"+fiALLOWLIST_FILE="$ROOT/scripts/check-test-isolation.allowlist"# Read allowlist (one filename per line, # comments allowed). Empty file@@ -72,7 +80,7 @@ is_allowlisted() {# Find non-serial unit test files (excluding test/e2e). Portable across# bash 3.2 (macOS default) and bash 4+; no mapfile.-FILE_LIST="$(find "$TARGET_DIR" -name '*.test.ts' \+FILE_LIST="$(find "$TARGET_DIR" $EXTRA_DIRS -name '*.test.ts' \-not -name '*.serial.test.ts' \-not -path "*/e2e/*" \-type f 2>/dev/null | sort)"diff --git a/scripts/check-test-real-names.sh b/scripts/check-test-real-names.shindex 394068998e..759d970e18 100755--- a/scripts/check-test-real-names.sh+++ b/scripts/check-test-real-names.sh@@ -101,10 +101,12 @@ doneIFS='|' eval 'PATTERN="${PATTERN_PARTS[*]}"'# Find tool.+# evals/ joins the scan: its *.test.ts files are collected into the CI+# matrix (scripts/test-shard.sh) and carry the same privacy bar.if command -v rg >/dev/null 2>&1; then- matches="$(rg -niH --no-heading -t ts "$PATTERN" test 2>/dev/null || true)"+ matches="$(rg -niH --no-heading -t ts "$PATTERN" test evals 2>/dev/null || true)"elif command -v grep >/dev/null 2>&1; then- matches="$(grep -rniE --include='*.test.ts' "$PATTERN" test 2>/dev/null || true)"+ matches="$(grep -rniE --include='*.test.ts' "$PATTERN" test evals 2>/dev/null || true)"elseecho "check-test-real-names: ERROR: neither rg nor grep available." >&2exit 2diff --git a/scripts/ci-local.sh b/scripts/ci-local.shindex 87f2c87d23..f4b26d6b16 100755--- a/scripts/ci-local.sh+++ b/scripts/ci-local.sh@@ -11,12 +11,12 @@# bash scripts/ci-local.sh --clean # nuke named volumes for cold debug# bash scripts/ci-local.sh --no-shard # debug: run E2E sequentially against postgres-1 only#-# 4-way E2E sharding: 4 pgvector services on host ports 5434-5437. The 36 E2E-# files split N/4 per shard; shards run in parallel. Within a shard, files run+# 4-way E2E sharding: 4 pgvector services on host ports 5434-5437. The test/e2e/ file set splits+# roughly N/4 per shard; shards run in parallel. Within a shard, files run# sequentially (TRUNCATE CASCADE no-race property documented in run-e2e.sh).# Wall-time on a 16-core host: ~6 min sequential -> ~1.5-2 min sharded.#-# Stronger than PR CI: PR CI runs only Tier 1's 2 files; this runs all 36.+# Stronger than PR CI: PR CI runs a handful of named files across its tiers; this runs every test/e2e file.set -euo pipefail@@ -231,7 +231,7 @@ elseecho "$SELECTED" | tr " " "\n" | grep -v "^$" > /tmp/e2e-selected.txtfi'else- # Empty file -> run-e2e.sh uses default glob (all 36 E2E files).+ # Empty file -> run-e2e.sh uses default glob (every test/e2e file).DIFF_E2E_PREP='> /tmp/e2e-selected.txt'fiRUN_PHASES_CMD="echo \"[runner] guards + typecheck (run once before sharding)\"diff --git a/scripts/guards-manifest.tsv b/scripts/guards-manifest.tsvindex 8d7bc6a425..95d645e390 100644--- a/scripts/guards-manifest.tsv+++ b/scripts/guards-manifest.tsv@@ -17,15 +17,15 @@# guard class selftest notescheck-no-double-retry.sh scanner yes regex hole fixed in W0 (could not match `() =>`); perl multi-line pass replaces never-installed pcregrepcheck-jsonb-pattern.sh scanner yes nested-paren hole fixed in W0; safe ::text::jsonb spelling stays unflagged-check-jsonb-params.mjs scanner yes positional $N::jsonb AST-lite scanner; argv/env root override+check-jsonb-params.mjs scanner yes positional $N::jsonb AST-lite scanner; argv/env root override; not in verify CHECKS: exercised by its unit test + self-test fixturescheck-batch-audit-site.sh scanner todo-check-bun-test-timeout.sh scanner todo+check-bun-test-timeout.sh scanner todo not in verify CHECKS: runs directly as a test.yml verify-job stepcheck-fixture-privacy.sh scanner todocheck-no-legacy-getconnection.sh scanner todo was reachable from neither verify nor CI pre-W0 (check:all only)check-no-pii-in-agent-voice.sh scanner todocheck-operations-filter-bypass.sh scanner todo-check-pagetype-exhaustive.sh scanner todo-check-pg-url-redaction.sh scanner todo+check-pagetype-exhaustive.sh scanner todo wired into verify CHECKS (v0.45.x test/eval/CI pass; was registered-but-never-executed)+check-pg-url-redaction.sh scanner todo wired into verify CHECKS (v0.45.x test/eval/CI pass; was registered-but-never-executed)check-privacy.sh scanner todocheck-progress-to-stdout.sh scanner todocheck-proposal-pii.sh scanner todo@@ -47,12 +47,12 @@ check-exports-count.sh scanner todo was reachable from neither verify nor CI precheck-trailing-newline.sh scanner todo was reachable from neither verify nor CI pre-W0 (check:all only)check-test-isolation.sh scanner todo allowlist data file: check-test-isolation.allowlistcheck-admin-build.sh buildfresh exempt runs the admin build; the build is the test-check-admin-embedded.sh buildfresh exempt embed freshness diff+check-admin-embedded.sh buildfresh exempt embed freshness diff; not in verify CHECKS: duplicates check:admin-build's buildcheck-admin-scope-drift.sh buildfresh exempt regenerates + diffscheck-bootstrap-templates.sh buildfresh exempt regenerates template tree + diffscheck-eval-glossary-fresh.sh buildfresh exempt regenerates + diffscheck-fuzz-purity.sh buildfresh exempt executes fuzz corpus-check-image-decoders-embedded.sh buildfresh exempt binary embed check+check-image-decoders-embedded.sh buildfresh exempt binary embed check; not in verify CHECKS: own bun build --compile too heavy per-verifycheck-pglite-embedded.sh buildfresh exempt binary embed checkcheck-skills-manifest-fresh.sh buildfresh exempt regenerates + diffscheck-tool-catalog-fresh.sh buildfresh exempt regenerates + diffsdiff --git a/scripts/lib/test-env.sh b/scripts/lib/test-env.shnew file mode 100644index 0000000000..64e6568540--- /dev/null+++ b/scripts/lib/test-env.sh@@ -0,0 +1,79 @@+# scripts/lib/test-env.sh — shared helpers for the test-runner family+# (test-shard.sh, run-serial-tests.sh, run-slow-tests.sh, run-unit-parallel.sh,+# run-verify-parallel.sh). Source AFTER cd'ing to the repo root:+#+# . scripts/lib/test-env.sh+#+# bash 3.2 compatible (macOS system bash): no mapfile, no wait -n, no ${var^^}.+# Every helper degrades gracefully inside the script-sandbox tests+# (test/scripts/run-unit-parallel.test.ts symlinks a minimal PATH with no+# sysctl/nproc/vm_stat/timeout and no package.json).++# ──────────────────────────────────────────────────────────────────────────+# CPU detection: Apple Silicon perf cores → Mac total physical → nproc → 4.+# Returns a single positive integer.+# ──────────────────────────────────────────────────────────────────────────+detect_cpus() {+ local n=""+ n=$(sysctl -n hw.perflevel0.physicalcpu 2>/dev/null) && [ -n "$n" ] && [ "$n" -gt 0 ] && echo "$n" && return+ n=$(sysctl -n hw.physicalcpu 2>/dev/null) && [ -n "$n" ] && [ "$n" -gt 0 ] && echo "$n" && return+ n=$(nproc 2>/dev/null) && [ -n "$n" ] && [ "$n" -gt 0 ] && echo "$n" && return+ echo 4+}++# ──────────────────────────────────────────────────────────────────────────+# Available-memory detection (MB). macOS: vm_stat free + inactive ++# speculative + purgeable pages (inactive/purgeable are reclaimable on+# pressure, which is exactly the scenario we size for). Linux: MemAvailable.+# Unknown platform → 0, and the caller skips adaptation entirely.+# ──────────────────────────────────────────────────────────────────────────+detect_available_mem_mb() {+ if command -v vm_stat >/dev/null 2>&1; then+ vm_stat 2>/dev/null | awk '+ /page size of/ { psize = $8 }+ /Pages free/ { free = $NF }+ /Pages inactive/ { inactive = $NF }+ /Pages speculative/ { spec = $NF }+ /Pages purgeable/ { purge = $NF }+ END {+ gsub(/\./, "", free); gsub(/\./, "", inactive)+ gsub(/\./, "", spec); gsub(/\./, "", purge)+ if (psize == 0) psize = 16384+ printf "%d\n", (free + inactive + spec + purge) * psize / 1048576+ }'+ return+ fi+ if [ -r /proc/meminfo ]; then+ awk '/MemAvailable/ { printf "%d\n", $2 / 1024; found = 1 } END { if (!found) print 0 }' /proc/meminfo+ return+ fi+ echo 0+}++# ──────────────────────────────────────────────────────────────────────────+# PGLite schema snapshot: build (idempotent, ~40ms when fresh; mkdir-lock+# concurrency-safe; hash folds handler-migration source) and export+# GBRAIN_PGLITE_SNAPSHOT for child bun processes. 500+ test files each+# cold-boot PGLite + replay every migration without it (~3.5x per booting+# file — see docs/TESTING.md).+#+# No-op when GBRAIN_NO_SNAPSHOT=1 or when a parent runner already exported+# the path (double-building is harmless but noisy). Non-fatal on build+# failure — tests fall back to cold init. The one-line "active" echo makes+# a silent fall-back-to-cold-init regression visible in CI logs.+# $1: label for log lines (defaults to test-env).+# ──────────────────────────────────────────────────────────────────────────+ensure_pglite_snapshot() {+ local label="${1:-test-env}"+ [ "${GBRAIN_NO_SNAPSHOT:-0}" = "1" ] && return 0+ if [ -n "${GBRAIN_PGLITE_SNAPSHOT:-}" ]; then+ echo "[$label] PGLite snapshot active (inherited): $GBRAIN_PGLITE_SNAPSHOT" >&2+ return 0+ fi+ if bun run build:pglite-snapshot >/dev/null 2>&1; then+ export GBRAIN_PGLITE_SNAPSHOT=test/fixtures/pglite-snapshot.tar+ echo "[$label] PGLite snapshot active: $GBRAIN_PGLITE_SNAPSHOT" >&2+ else+ echo "[$label] snapshot build failed (non-fatal) — tests run with cold init" >&2+ fi+}diff --git a/scripts/run-e2e.sh b/scripts/run-e2e.shindex f9badeaa23..bb3ce3507e 100755--- a/scripts/run-e2e.sh+++ b/scripts/run-e2e.sh@@ -96,6 +96,7 @@ mkdir -p "$E2E_TMP_HOME/.gbrain"for _e2e_var in $(env | grep -oE '^(CONDUCTOR_|MCP_|OPENCLAW_|HERMES_|GROK_|OPENCODE_|GBRAIN_)[A-Za-z0-9_]*' | sort -u); docase "$_e2e_var" inGBRAIN_HOME) ;; # required for HOME isolation (set above) — keep+ GBRAIN_PGLITE_SNAPSHOT) ;; # snapshot fast-path fixture (exported by ci-local.sh / runners) — keepGBRAIN_TEST_ALLOW_DATABASE_URL) ;; # #3485 preload opt-in (set above) — keepGBRAIN_E2E_ALLOW_DB) ;; # #3485 name-floor opt-in — the guard's own error# message tells operators to set it; stripping itdiff --git a/scripts/run-eval-canary.ts b/scripts/run-eval-canary.tsnew file mode 100644index 0000000000..912b0e95fa--- /dev/null+++ b/scripts/run-eval-canary.ts@@ -0,0 +1,320 @@+/**+ * scripts/run-eval-canary.ts — hermetic CLI retrieval-quality canary.+ *+ * Boots a throwaway PGLite brain under a temp GBRAIN_HOME, seeds the qrels+ * fixture corpus, then spawns the REAL gbrain CLI to run the qrels+ * correctness gate with the deterministic embedder (basis-vector query+ * embeddings). No API keys, no network, no writes to the personal brain,+ * no writes to tracked files in check mode.+ *+ * Seeding is the "V2" shape (feasibility-spike finding, BINDING): the+ * expected-top1 page carries its query text in the `timeline` column too,+ * because page-grain FTS (`pages.search_vector`) indexes title(A) ++ * timeline(C) ONLY — `compiled_truth` is deliberately unindexed. With+ * V1-style seeding (query text in compiled_truth only) the title arm votes+ * only for the sibling page and expected_top1 is structurally 0.0.+ *+ * Modes:+ * default check mode (CI): assert exit 0 + floors, print a one-line+ * summary, clean up. Writes nothing to tracked files.+ * record mode (pass the record flag) everything above PLUS append one+ * EvalRunRecord-shaped JSONL line to+ * <repo>/.gbrain-evals/eval-results.jsonl (the eval ledger).+ *+ * Honest scope: this 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.+ *+ * Budget: ≤60s under a saturated pool (two PGLite boots). If it breaches+ * ~100s under contention, move the verify entry into the serial-tests CI+ * job instead (same fallback as the chronicle eval).+ */++import { appendFileSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { dirname, join, resolve } from 'node:path';+import { fileURLToPath } from 'node:url';+import { execSync, spawnSync } from 'node:child_process';+import type { BrainEngine } from '../src/core/engine.ts';+import type { ChunkInput } from '../src/core/types.ts';+import { basisEmbedding, parseLegacyQrels } from '../src/eval/deterministic-embed.ts';+import type { LegacyQrelsQuery } from '../src/eval/deterministic-embed.ts';++const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');+const QRELS_PATH = join(ROOT, 'test', 'fixtures', 'eval-baselines', 'qrels-search.json');++// The embedding space the throwaway brain is pinned to. The gateway must be+// configured with this BEFORE initSchema (the schema's vector(dims) columns+// derive from gateway config at initSchema time — config read only, no key+// needed), and the brain's GBRAIN_HOME config.json pins the same model+dims+// so the CLI subprocess resolves 1536 too.+const EMBEDDING_MODEL = 'openai:text-embedding-3-large';+const EMBEDDING_DIMENSIONS = 1536;++// Env the child must NOT inherit: engine reroutes (a stray DATABASE_URL+// flips the engine to postgres; a brain id reroutes to a mount), embedding+// overrides (would fight the pinned 1536 space), and provider keys (the+// canary must behave identically keyed and keyless — determinism by+// construction, not by the parent's shell profile).+const CHILD_ENV_STRIP = [+ 'DATABASE_URL',+ 'GBRAIN_DATABASE_URL',+ 'GBRAIN_BRAIN_ID',+ 'GBRAIN_SOURCE',+ 'GBRAIN_EMBEDDING_MODEL',+ 'GBRAIN_EMBEDDING_DIMENSIONS',+ 'OPENAI_API_KEY',+ 'ANTHROPIC_API_KEY',+ 'ZEROENTROPY_API_KEY',+ 'VOYAGE_API_KEY',+ 'OPENROUTER_API_KEY',+ 'DASHSCOPE_API_KEY',+ 'GOOGLE_GENERATIVE_AI_API_KEY',+ 'GEMINI_API_KEY',+];++// The legacy qrels parser lives with the embedder builder — one parser for+// the shape (re-exported here for the test that drives this runner).+export { parseLegacyQrels };+export type { LegacyQrelsQuery };++/**+ * Seed the V2 canary corpus. For each query's relevant slugs:+ * - putPage typed by prefix (person/company/note), title = slug tail;+ * the expected-top1 page carries the primary text in BOTH+ * compiled_truth and timeline (the V2 amendment — timeline is what+ * page-grain FTS indexes); siblings carry "Mentioned in context of+ * <query>" in timeline.+ * - upsertChunks with the same fixture text, basisEmbedding at the+ * query's dim, token_count 10, chunk_source compiled_truth/timeline.+ */+export async function seedCanaryCorpus(engine: BrainEngine, queries: LegacyQrelsQuery[]): Promise<void> {+ const seenSlugs = new Set<string>();+ for (const q of queries) {+ for (const slug of q.relevant_slugs) {+ if (seenSlugs.has(slug)) continue;+ seenSlugs.add(slug);+ const isExpected = slug === q.first_relevant_slug;+ const primaryText = `Primary content about ${q.query}`;+ const mentionText = `Mentioned in context of ${q.query}`;+ const type = slug.startsWith('people/')+ ? 'person'+ : slug.startsWith('companies/')+ ? 'company'+ : 'note';+ await engine.putPage(slug, {+ type,+ title: slug.split('/').pop() ?? slug,+ compiled_truth: isExpected ? primaryText : '',+ // V2: the expected page's query text goes in timeline too — that is+ // the page-grain-FTS-indexed column (title A + timeline C).+ timeline: isExpected ? primaryText : mentionText,+ });+ const chunk: ChunkInput = {+ chunk_index: 0,+ chunk_text: isExpected ? primaryText : mentionText,+ chunk_source: isExpected ? 'compiled_truth' : 'timeline',+ embedding: basisEmbedding(q.embedding_dim, EMBEDDING_DIMENSIONS),+ token_count: 10,+ };+ await engine.upsertChunks(slug, [chunk]);+ }+ }+}++interface GateJson {+ verdict: 'pass' | 'fail';+ correctness_gate: {+ ran: boolean;+ summary?: {+ k: number;+ queries_total: number;+ queries_run: number;+ queries_errored: number;+ mean_recall_at_k: number;+ first_relevant_hit_rate: number;+ expected_top1_hit_rate: number;+ expected_top1_denominator: number;+ };+ thresholds?: {+ recall_at_k: number;+ first_relevant_hit: number;+ expected_top1: number;+ };+ breaches?: Array<Record<string, unknown>>;+ };+}++function shortSha(): string {+ try {+ return execSync('git rev-parse --short HEAD', { cwd: ROOT, encoding: 'utf-8' }).trim();+ } catch {+ return 'unknown';+ }+}++async function main(): Promise<number> {+ const recordMode = process.argv.includes('--record');+ const startedAt = Date.now();+ const tmpHome = mkdtempSync(join(tmpdir(), 'gbrain-eval-canary-'));+ // Keep the RUNNER's own gbrain home inside the sandbox too, so nothing in+ // the seeding path can read or write the operator's real ~/.gbrain.+ process.env.GBRAIN_HOME = tmpHome;+ try {+ const gbrainDir = join(tmpHome, '.gbrain');+ mkdirSync(gbrainDir, { recursive: true });+ const dbPath = join(gbrainDir, 'brain.pglite');+ writeFileSync(+ join(gbrainDir, 'config.json'),+ JSON.stringify(+ {+ engine: 'pglite',+ database_path: dbPath,+ embedding_model: EMBEDDING_MODEL,+ embedding_dimensions: EMBEDDING_DIMENSIONS,+ },+ null,+ 2,+ ) + '\n',+ );++ // Gateway config BEFORE initSchema (dims gotcha above). Empty env+ // snapshot: no key is consulted, and none is needed for schema sizing.+ const { configureGateway } = await import('../src/core/ai/gateway.ts');+ configureGateway({+ embedding_model: EMBEDDING_MODEL,+ embedding_dimensions: EMBEDDING_DIMENSIONS,+ env: {},+ });++ const { PGLiteEngine } = await import('../src/core/pglite-engine.ts');+ const engine = new PGLiteEngine();+ await engine.connect({ engine: 'pglite', database_path: dbPath });+ await engine.initSchema();+ const qrelsRaw = readFileSync(QRELS_PATH, 'utf-8');+ await seedCanaryCorpus(engine, parseLegacyQrels(qrelsRaw));+ // PGLite is single-writer: release the brain before the CLI child opens it.+ await engine.disconnect();++ const childEnv: Record<string, string | undefined> = { ...process.env };+ for (const k of CHILD_ENV_STRIP) delete childEnv[k];+ childEnv.GBRAIN_HOME = tmpHome;++ // Spawn the REAL CLI. cwd is the temp home (not the repo) so repo-local+ // dotfiles and Bun-auto-loaded .env files can't reroute the brain.+ const child = spawnSync(+ process.execPath,+ [join(ROOT, 'src', 'cli.ts'), 'eval', 'gate', '--qrels', QRELS_PATH, '--embedder', 'deterministic', '--json'],+ {+ cwd: tmpHome,+ env: childEnv as NodeJS.ProcessEnv,+ encoding: 'utf-8',+ timeout: 110_000,+ maxBuffer: 32 * 1024 * 1024,+ },+ );++ if (child.error) {+ process.stderr.write(`[eval-canary] FAIL: could not spawn the CLI: ${child.error.message}\n`);+ return 1;+ }+ if (child.status !== 0) {+ process.stderr.write(`[eval-canary] FAIL: gate exit=${child.status ?? 'null(timeout/signal)'}\n`);+ process.stderr.write(`[eval-canary] gate stdout tail:\n${(child.stdout ?? '').slice(-2000)}\n`);+ process.stderr.write(`[eval-canary] gate stderr tail:\n${(child.stderr ?? '').slice(-2000)}\n`);+ return 1;+ }++ // Parse the gate's JSON envelope (stdout carries only the envelope; any+ // engine warnings go to stderr).+ const stdout = child.stdout ?? '';+ const jsonStart = stdout.indexOf('{');+ if (jsonStart < 0) {+ process.stderr.write(`[eval-canary] FAIL: no JSON found on gate stdout:\n${stdout.slice(-2000)}\n`);+ return 1;+ }+ const gate = JSON.parse(stdout.slice(jsonStart)) as GateJson;+ const summary = gate.correctness_gate.summary;+ const floors = gate.correctness_gate.thresholds;+ if (gate.verdict !== 'pass' || !summary || !floors) {+ process.stderr.write(`[eval-canary] FAIL: verdict=${gate.verdict} summary=${JSON.stringify(summary)}\n`);+ return 1;+ }+ // Exit 0 already implies floors held; assert explicitly anyway so a+ // future exit-code regression in the gate can't silently pass the canary.+ const breaches: string[] = [];+ if (summary.queries_errored > 0) breaches.push(`queries_errored=${summary.queries_errored}`);+ if (summary.mean_recall_at_k < floors.recall_at_k) breaches.push(`recall ${summary.mean_recall_at_k} < ${floors.recall_at_k}`);+ if (summary.first_relevant_hit_rate < floors.first_relevant_hit) breaches.push(`first_relevant ${summary.first_relevant_hit_rate} < ${floors.first_relevant_hit}`);+ if (summary.expected_top1_denominator > 0 && summary.expected_top1_hit_rate < floors.expected_top1) {+ breaches.push(`expected_top1 ${summary.expected_top1_hit_rate} < ${floors.expected_top1}`);+ }+ if (breaches.length > 0) {+ process.stderr.write(`[eval-canary] FAIL: ${breaches.join('; ')}\n`);+ return 1;+ }++ const commit = shortSha();+ const durationMs = Date.now() - startedAt;+ process.stdout.write(+ `[eval-canary] PASS commit=${commit}` ++ ` mean_recall_at_k=${summary.mean_recall_at_k.toFixed(4)}` ++ ` first_relevant_hit_rate=${summary.first_relevant_hit_rate.toFixed(4)}` ++ ` expected_top1_hit_rate=${summary.expected_top1_hit_rate.toFixed(4)}` ++ ` floors=${floors.recall_at_k}/${floors.first_relevant_hit}/${floors.expected_top1}` ++ ` k=${summary.k} queries=${summary.queries_run}/${summary.queries_total}` ++ ` duration_ms=${durationMs}\n`,+ );++ if (recordMode) {+ // EvalRunRecord-shaped ledger line (matches src/commands/eval-run-all.ts;+ // suite widened to the canary's own name, mode 'n/a' per the+ // search-mode-independent convention).+ const record = {+ schema_version: 3,+ run_id: `${commit}-retrieval-canary-na-0`,+ ran_at: new Date().toISOString(),+ suite: 'retrieval-canary',+ mode: 'n/a',+ commit,+ seed: 0,+ params: {+ qrels: 'test/fixtures/eval-baselines/qrels-search.json',+ embedder: 'deterministic',+ k: summary.k,+ metrics: {+ mean_recall_at_k: summary.mean_recall_at_k,+ first_relevant_hit_rate: summary.first_relevant_hit_rate,+ expected_top1_hit_rate: summary.expected_top1_hit_rate,+ expected_top1_denominator: summary.expected_top1_denominator,+ queries_run: summary.queries_run,+ queries_total: summary.queries_total,+ },+ floors: {+ recall_at_k: floors.recall_at_k,+ first_relevant_hit: floors.first_relevant_hit,+ expected_top1: floors.expected_top1,+ },+ },+ status: 'completed',+ duration_ms: durationMs,+ };+ const ledgerDir = join(ROOT, '.gbrain-evals');+ mkdirSync(ledgerDir, { recursive: true });+ const ledgerPath = join(ledgerDir, 'eval-results.jsonl');+ appendFileSync(ledgerPath, JSON.stringify(record) + '\n', 'utf-8');+ process.stdout.write(`[eval-canary] recorded → ${ledgerPath}\n`);+ }++ return 0;+ } catch (err) {+ process.stderr.write(`[eval-canary] FAIL: ${(err as Error).stack ?? (err as Error).message}\n`);+ return 1;+ } finally {+ rmSync(tmpHome, { recursive: true, force: true });+ }+}++if (import.meta.main) {+ process.exit(await main());+}diff --git a/scripts/run-serial-tests.sh b/scripts/run-serial-tests.shindex a9ee62a496..03562d5ebf 100755--- a/scripts/run-serial-tests.sh+++ b/scripts/run-serial-tests.sh@@ -1,18 +1,81 @@#!/usr/bin/env bash-# scripts/run-serial-tests.sh — run *.serial.test.ts files with --max-concurrency=1.+# scripts/run-serial-tests.sh — run *.serial.test.ts files, one bun process per+# file, POOLED across files.## Serial files are tests that share file-wide state (top-level mock.module,# module-level singletons that intentionally cross test cases) and would race# under intra-file concurrency. Discovered via filename suffix; no annotation# inside the file is needed.#+# Each file gets its OWN bun process. `--max-concurrency=1` alone was not+# enough: files in the same process share the module registry, so a top-level+# `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:+# an 8.5-minute CI job whose serialization was never required by the+# quarantine contract.)+## Excluded by run-unit-shard.sh and run-unit-parallel.sh's parallel pass.# Invoked separately by run-unit-parallel.sh after the parallel pass succeeds.+#+# Knobs:+# GBRAIN_SERIAL_POOL=N pool width (default min(detect_cpus, 4),+# then memory-adapted; 1 restores the old+# fully-sequential behavior)+# GBRAIN_SERIAL_FILE_TIMEOUT=S wall-clock kill per file (default 300;+# needs timeout/gtimeout on PATH, else no wrap)+# GBRAIN_TEST_MEM_PER_FILE_MB per-process memory budget (default 1536)+# GBRAIN_TEST_NO_MEM_ADAPT=1 skip the memory clampset -euo pipefail+# #3485: serial tests need no database — strip ambient DB URLs at this+# wrapper boundary (same four-layer guard as run-slow-tests.sh / the+# parallel runner) so the bunfig preload guard passes and nothing can+# reach a real brain.+unset DATABASE_URL GBRAIN_DATABASE_URLcd "$(dirname "$0")/.."+. scripts/lib/test-env.sh++# ──────────────────────────────────────────────────────────────────────────+# EXCLUSIVE_FILES: files that must never run concurrently with anything else+# (machine-global state or contention-critical timing). They run sequentially+# AFTER the pool drains, without the wall-clock kill (a SIGKILL+# mid-registration could strand a real scheduled job). Growth guard:+# test/scripts/serial-files.test.ts fails when this list grows past 3+# entries — every addition needs a justification comment like the entries+# below.+# ──────────────────────────────────────────────────────────────────────────+EXCLUSIVE_FILES=(+ # launchd/cron lifecycle arc: install → self-disable → reinstall →+ # uninstall ordering against (PATH-shimmed) launchctl; the arc asserts+ # machine-level sequencing and is the flake-class canary.+ "test/autopilot-launchd-lifecycle.serial.test.ts"+ # hardenBrainRepo({installCron:true}) executes REAL launchctl/crontab+ # (src/core/brain-repo-durability.ts) — a concurrent or killed run could+ # strand a real scheduled job on the machine.+ "test/brain-durability-hook.serial.test.ts"+ # hardenBrainRepo's own scaffolding commit fires the just-installed+ # post-commit hook (background push) which races the synchronous+ # push-probe on the same bare remote ("cannot lock ref" →+ # needs_attention non-empty). The race is intra-call; pooled CPU+ # contention widens the window past what the assertions tolerate+ # (observed on a 4-vCPU CI runner, never locally). Sequential lane+ # restores master-era timing until the probe learns to retry ref-lock+ # contention.+ "test/brain-repo-durability.serial.test.ts"+)++is_exclusive() {+ local f="$1" e+ for e in "${EXCLUSIVE_FILES[@]}"; do+ [ "$f" = "$e" ] && return 0+ done+ return 1+}+# Use while-read for portability to macOS bash 3.2 (no mapfile).files=()while IFS= read -r f; do@@ -24,35 +87,229 @@ if [ "${#files[@]}" -eq 0 ]; thenexit 0fi-# --dry-run-list mirrors run-unit-shard.sh for inline checks/tests.+# --dry-run-list mirrors run-unit-shard.sh for inline checks/tests. Lists+# ALL discovered files, pooled and exclusive alike.if [ "${1:-}" = "--dry-run-list" ]; thenprintf '%s\n' "${files[@]}"exit 0fi-echo "[serial-tests] running ${#files[@]} file(s), one bun process per file"+ensure_pglite_snapshot "serial-tests"++# Partition into pooled vs exclusive (exclusive entries missing from the+# discovered set are simply ignored — the list names repo files, and a+# sandbox copy of this script won't have them).+pool_files=()+exclusive_present=()+for f in "${files[@]}"; do+ if is_exclusive "$f"; then+ exclusive_present+=("$f")+ else+ pool_files+=("$f")+ fi+done++# ──────────────────────────────────────────────────────────────────────────+# Pool sizing: min(detect_cpus, 4) — each pooled bun process can hold a+# PGLite WASM instance (~1.5GB) — then clamped by available memory (same+# layer-1 doctrine as run-unit-parallel.sh, 4GB OS reserve).+# ──────────────────────────────────────────────────────────────────────────+POOL="${GBRAIN_SERIAL_POOL:-}"+if [ -z "$POOL" ]; then+ POOL=$(detect_cpus)+ [ "$POOL" -gt 4 ] && POOL=4+ if [ "${GBRAIN_TEST_NO_MEM_ADAPT:-0}" != "1" ]; then+ MEM_PER_FILE_MB="${GBRAIN_TEST_MEM_PER_FILE_MB:-1536}"+ AVAIL_MB=$(detect_available_mem_mb)+ if [ "${AVAIL_MB:-0}" -gt 0 ] 2>/dev/null; then+ BUDGET_MB=$((AVAIL_MB - 4096))+ [ "$BUDGET_MB" -lt "$MEM_PER_FILE_MB" ] && BUDGET_MB="$MEM_PER_FILE_MB"+ MAX_POOL=$((BUDGET_MB / MEM_PER_FILE_MB))+ [ "$MAX_POOL" -lt 1 ] && MAX_POOL=1+ [ "$POOL" -gt "$MAX_POOL" ] && POOL="$MAX_POOL"+ fi+ fi+fi+if ! printf '%s' "$POOL" | grep -qE '^[0-9]+$' || [ "$POOL" -lt 1 ]; then+ echo "[serial-tests] ERROR: invalid pool size: $POOL" >&2+ exit 2+fi++# Wall-clock kill per pooled file: contains the exit-hang class (a bun+# process that finishes its tests but never exits). SIGTERM first, SIGKILL+# after a grace period (`timeout -k`). macOS without coreutils has neither+# binary — run unwrapped there (CI is Linux and always wraps).+PER_FILE_TIMEOUT="${GBRAIN_SERIAL_FILE_TIMEOUT:-300}"+TIMEOUT_BIN=""+command -v timeout >/dev/null 2>&1 && TIMEOUT_BIN="timeout"+[ -z "$TIMEOUT_BIN" ] && command -v gtimeout >/dev/null 2>&1 && TIMEOUT_BIN="gtimeout"++LOG_DIR=$(mktemp -d "${TMPDIR:-/tmp}/gbrain-serial.XXXXXX")+trap 'rm -rf "$LOG_DIR"' EXIT++if [ -n "$TIMEOUT_BIN" ]; then+ TIMEOUT_DESC="${PER_FILE_TIMEOUT}s via $TIMEOUT_BIN"+else+ TIMEOUT_DESC="none (no timeout/gtimeout on PATH)"+fi+echo "[serial-tests] ${#files[@]} file(s): pool=$POOL (${#exclusive_present[@]} exclusive), per-file timeout=$TIMEOUT_DESC"++# Per-test timeout is 120s (not the fast-loop 60s): pooled contention can+# push a 30-50s file past 60s — the same flake class the slow lane hardened+# against in v0.40.10. The literal `bun test --max-concurrency=1` below is+# contract-pinned by test/scripts/serial-files.test.ts.+run_one_file() {+ # $1 file, $2 log path, $3 exit-sentinel path, $4 wrap ("wrap"|"nowrap")+ local f="$1" log="$2" exitf="$3" wrap="$4" rc=0+ if [ "$wrap" = "wrap" ] && [ -n "$TIMEOUT_BIN" ]; then+ "$TIMEOUT_BIN" -k 15 "$PER_FILE_TIMEOUT" \+ bun test --max-concurrency=1 --timeout=120000 "$f" > "$log" 2>&1 || rc=$?+ else+ bun test --max-concurrency=1 --timeout=120000 "$f" > "$log" 2>&1 || rc=$?+ fi+ echo "$rc" > "$exitf"+}++start_epoch=$(date +%s)+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+ done+ (+ s=$(date +%s)+ run_one_file "$f" "$LOG_DIR/$idx.log" "$LOG_DIR/$idx.exit" "wrap"+ e=$(date +%s)+ echo "$((e - s))" > "$LOG_DIR/$idx.dur"+ ) &+ idx=$((idx + 1))+ done+ wait+fi++# Exclusive lane: sequential, unwrapped (see EXCLUSIVE_FILES comment).+if [ "${#exclusive_present[@]}" -gt 0 ]; then+ for f in "${exclusive_present[@]}"; do+ s=$(date +%s)+ run_one_file "$f" "$LOG_DIR/$idx.log" "$LOG_DIR/$idx.exit" "nowrap"+ e=$(date +%s)+ echo "$((e - s))" > "$LOG_DIR/$idx.dur"+ idx=$((idx + 1))+ done+fi++# ──────────────────────────────────────────────────────────────────────────+# Aggregate from the exit sentinels.+# exit 0 → pass+# exit 124 → killed by the per-file wall-clock timeout (real+# failure: the exit-hang class this cap exists for)+# exit 143 / 137, or a → EXTERNAL-KILL class: a stray SIGTERM/SIGKILL from+# missing sentinel outside this runner (sibling workspaces' process+# cleanup, memory jetsam — the same class+# run-unit-parallel.sh rescues). Queued for ONE+# sequential rescue re-run below; a rescue that+# fails again is a real failure. Never a silent pass.+# anything else → real failure+# ──────────────────────────────────────────────────────────────────────────+ordered_files=()+if [ "${#pool_files[@]}" -gt 0 ]; then ordered_files+=("${pool_files[@]}"); fi+if [ "${#exclusive_present[@]}" -gt 0 ]; then ordered_files+=("${exclusive_present[@]}"); fi-# Each serial file gets its OWN bun process. `--max-concurrency=1` was not-# enough: files in the same process share the module registry, so a top-level-# `mock.module(...)` in one file leaks into the next file's imports-# (eval-takes-quality-runner mocks gateway.ts and the next file fails on-# `import { resetGateway }` because the mock factory didn't export it).-# Per-file processes give true isolation; cost is ~100ms startup × N files.fail_count=0failed_files=()-for f in "${files[@]}"; do- if ! bun test --max-concurrency=1 --timeout=60000 "$f"; then- fail_count=$((fail_count + 1))- failed_files+=("$f")+rescue_files=()+# Aggregate pass count across pooled files, re-emitted below in bun's own+# " N pass" summary format so run-unit-parallel.sh's headline counter+# (bun_summary_count) still sees the serial suite's tests. Failing files'+# logs are cat'ed raw (their " N pass/fail" lines land in the stream+# directly), so only PASSING files accumulate here — no double counting.+pass_total=0+i=0+for f in "${ordered_files[@]}"; do+ dur="?"+ [ -f "$LOG_DIR/$i.dur" ] && dur=$(cat "$LOG_DIR/$i.dur")+ if [ ! -f "$LOG_DIR/$i.exit" ]; then+ echo "[serial-tests] KILLED ${dur}s $f — missing exit sentinel (external kill/OOM) — queued for serial rescue" >&2+ rescue_files+=("$f")+ else+ rc=$(cat "$LOG_DIR/$i.exit")+ if [ "$rc" = "0" ]; then+ summary=$(grep -E '^ *[0-9]+ pass' "$LOG_DIR/$i.log" | tail -1 | tr -d ' ' || true)+ n=$(printf '%s' "$summary" | grep -oE '^[0-9]+' || echo 0)+ pass_total=$((pass_total + n))+ echo "[serial-tests] PASS ${dur}s $f ${summary:+($summary)}"+ elif [ "$rc" = "137" ] && [ "$dur" != "?" ] && [ "$dur" -ge "$PER_FILE_TIMEOUT" ] 2>/dev/null; then+ # 137 with full duration = OUR timeout's SIGKILL escalation (a hang+ # that ignored SIGTERM), not an external kill — a real failure; a+ # rescue re-run would just re-hang for another ~315s.+ echo "[serial-tests] FAIL ${dur}s $f — exit 137 (hang survived SIGTERM; killed by ${PER_FILE_TIMEOUT}s per-file timeout)" >&2+ cat "$LOG_DIR/$i.log" >&2+ fail_count=$((fail_count + 1))+ failed_files+=("$f")+ elif [ "$rc" = "143" ] || [ "$rc" = "137" ]; then+ echo "[serial-tests] KILLED ${dur}s $f — exit $rc (external SIGTERM/SIGKILL) — queued for serial rescue" >&2+ rescue_files+=("$f")+ else+ note=""+ [ "$rc" = "124" ] && note=" (killed by ${PER_FILE_TIMEOUT}s per-file timeout)"+ echo "[serial-tests] FAIL ${dur}s $f — exit $rc$note" >&2+ cat "$LOG_DIR/$i.log" >&2+ fail_count=$((fail_count + 1))+ failed_files+=("$f")+ fifi+ i=$((i + 1))done+# Rescue pass: one sequential, unpooled re-run per externally-killed file.+# Phantoms pass here and the run stays green (with a rescue note); real+# failures fail again and go red. Mirrors run-unit-parallel.sh's doctrine.+if [ "${#rescue_files[@]}" -gt 0 ]; then+ echo "[serial-tests] rescue pass: ${#rescue_files[@]} externally-killed file(s), re-running serially" >&2+ for f in "${rescue_files[@]}"; do+ # Exclusive-lane files keep their no-kill contract on rescue too (the+ # lane exists because a SIGKILL mid-registration strands real state).+ wrap_mode="wrap"+ is_exclusive "$f" && wrap_mode="nowrap"+ s=$(date +%s)+ run_one_file "$f" "$LOG_DIR/$i.log" "$LOG_DIR/$i.exit" "$wrap_mode"+ e=$(date +%s)+ rc=$(cat "$LOG_DIR/$i.exit" 2>/dev/null || echo 1)+ if [ "$rc" = "0" ]; then+ summary=$(grep -E '^ *[0-9]+ pass' "$LOG_DIR/$i.log" | tail -1 | tr -d ' ' || true)+ n=$(printf '%s' "$summary" | grep -oE '^[0-9]+' || echo 0)+ pass_total=$((pass_total + n))+ echo "[serial-tests] PASS $((e - s))s $f ${summary:+($summary)} (rescued: external-kill phantom)"+ else+ echo "[serial-tests] FAIL $((e - s))s $f — exit $rc on rescue re-run" >&2+ cat "$LOG_DIR/$i.log" >&2+ fail_count=$((fail_count + 1))+ failed_files+=("$f")+ fi+ i=$((i + 1))+ done+fi++# Slowest-file table: feeds flake triage + future weight mining.+echo "[serial-tests] slowest files:"+i=0+for f in "${ordered_files[@]}"; do+ [ -f "$LOG_DIR/$i.dur" ] && echo "$(cat "$LOG_DIR/$i.dur") $f"+ i=$((i + 1))+done | sort -rn | head -10 | sed 's/^/ /'++total_epoch=$(( $(date +%s) - start_epoch ))if [ "$fail_count" -gt 0 ]; thenecho "" >&2- echo "[serial-tests] $fail_count file(s) failed:" >&2+ echo "[serial-tests] $fail_count file(s) failed (${total_epoch}s total):" >&2for f in "${failed_files[@]}"; doecho " - $f" >&2doneexit 1fi-echo "[serial-tests] all ${#files[@]} file(s) passed"+# bun-summary-format aggregate: run-unit-parallel.sh's headline counter+# (bun_summary_count awk: $1 numeric, $2 == "pass") reads this line — without+# it the serial suite's tests vanish from `bun run test`'s pass=N banner.+echo " $pass_total pass"+echo "[serial-tests] all ${#ordered_files[@]} file(s) passed in ${total_epoch}s (pool=$POOL)"diff --git a/scripts/run-slow-tests.sh b/scripts/run-slow-tests.shindex c47ce8cc90..67ac5f1cfc 100755--- a/scripts/run-slow-tests.sh+++ b/scripts/run-slow-tests.sh@@ -11,6 +11,9 @@ set -euo pipefailunset DATABASE_URL GBRAIN_DATABASE_URLcd "$(dirname "$0")/.."+. scripts/lib/test-env.sh+ensure_pglite_snapshot "run-slow-tests"+slow_files=()while IFS= read -r f; doslow_files+=("$f")diff --git a/scripts/run-unit-parallel.sh b/scripts/run-unit-parallel.shindex bfa3056d3b..e77cce1d4a 100755--- a/scripts/run-unit-parallel.sh+++ b/scripts/run-unit-parallel.sh@@ -62,54 +62,11 @@ cd "$(dirname "$0")/.."# fan-out — shards inherit a finished fixture. Opt out: GBRAIN_NO_SNAPSHOT=1# (the migration-replay canary tests clear the env themselves regardless).# ──────────────────────────────────────────────────────────────────────────-if [ "${GBRAIN_NO_SNAPSHOT:-0}" != "1" ]; then- if bun run build:pglite-snapshot >/dev/null 2>&1; then- export GBRAIN_PGLITE_SNAPSHOT=test/fixtures/pglite-snapshot.tar- else- echo "[run-unit-parallel] snapshot build failed (non-fatal) — tests run with cold init" >&2- fi-fi--# ──────────────────────────────────────────────────────────────────────────-# CPU detection: Apple Silicon perf cores → Mac total physical → nproc → 4.-# Returns a single positive integer.-# ──────────────────────────────────────────────────────────────────────────-detect_cpus() {- local n=""- n=$(sysctl -n hw.perflevel0.physicalcpu 2>/dev/null) && [ -n "$n" ] && [ "$n" -gt 0 ] && echo "$n" && return- n=$(sysctl -n hw.physicalcpu 2>/dev/null) && [ -n "$n" ] && [ "$n" -gt 0 ] && echo "$n" && return- n=$(nproc 2>/dev/null) && [ -n "$n" ] && [ "$n" -gt 0 ] && echo "$n" && return- echo 4-}--# ──────────────────────────────────────────────────────────────────────────-# Available-memory detection (MB). macOS: vm_stat free + inactive +-# speculative + purgeable pages (inactive/purgeable are reclaimable on-# pressure, which is exactly the scenario we size for). Linux: MemAvailable.-# Unknown platform → 0, and the caller skips adaptation entirely.-# ──────────────────────────────────────────────────────────────────────────-detect_available_mem_mb() {- if command -v vm_stat >/dev/null 2>&1; then- vm_stat 2>/dev/null | awk '- /page size of/ { psize = $8 }- /Pages free/ { free = $NF }- /Pages inactive/ { inactive = $NF }- /Pages speculative/ { spec = $NF }- /Pages purgeable/ { purge = $NF }- END {- gsub(/\./, "", free); gsub(/\./, "", inactive)- gsub(/\./, "", spec); gsub(/\./, "", purge)- if (psize == 0) psize = 16384- printf "%d\n", (free + inactive + spec + purge) * psize / 1048576- }'- return- fi- if [ -r /proc/meminfo ]; then- awk '/MemAvailable/ { printf "%d\n", $2 / 1024; found = 1 } END { if (!found) print 0 }' /proc/meminfo- return- fi- echo 0-}+# detect_cpus / detect_available_mem_mb / ensure_pglite_snapshot live in the+# shared lib (also sourced by test-shard.sh, run-serial-tests.sh,+# run-slow-tests.sh) — one implementation, no copy drift.+. scripts/lib/test-env.sh+ensure_pglite_snapshot "run-unit-parallel"# ──────────────────────────────────────────────────────────────────────────# Argument parsing. --shards N override wins over $SHARDS; both are clamped.diff --git a/scripts/run-verify-parallel.sh b/scripts/run-verify-parallel.shindex 322d4850f4..da84f345c8 100755--- a/scripts/run-verify-parallel.sh+++ b/scripts/run-verify-parallel.sh@@ -25,28 +25,61 @@ set -uo pipefailcd "$(dirname "$0")/.."+# detect_cpus + ensure_pglite_snapshot (the PGLite-booting eval checks use+# the snapshot fast-path when the shape matches).+. scripts/lib/test-env.sh+# ──────────────────────────────────────────────────────────────────────────-# Checks to run. Order is irrelevant (parallel), but keep stable for log-# determinism + grep-ability. Each entry is a bun-script name (the-# `package.json` "scripts" key), invoked as `bun run <name>`.+# Checks to run. Each entry is a bun-script name (the `package.json`+# "scripts" key), invoked as `bun run <name>`.+#+# ORDER MATTERS for wallclock: the spawn loop below is capped at+# GBRAIN_VERIFY_MAX_PARALLEL workers, so the heaviest checks go FIRST+# (LPT-style — makespan ≈ max(longest check, total/POOL)). The heavy block:+# typecheck (tsc), two `cp -R src` + `bun build --compile` binary builds,+# the admin vite+tsc build, the fuzz bundles, guard self-tests, the+# PGLite-booting eval checks, and the whole-tree greps. Everything after is+# sub-second; that tail keeps its historical order for grep-ability.#-# To add a check: append to this array. To skip in CI temporarily, comment-# the line — the parallel runner doesn't care about count.+# To add a check: append to the right block. To skip in CI temporarily,+# comment the line — the runner doesn't care about count.# ──────────────────────────────────────────────────────────────────────────CHECKS=(+ # ── heavy (longest-first) ──+ "typecheck"+ "check:admin-build"+ "check:wasm"+ "check:pglite-embedded"+ "check:fuzz-purity"+ # W0 fix-wave (Tier-1 #11): guard self-tests — every scanner guard proves it+ # can fail (bad fixture → exit 1) before it counts as coverage. Registry:+ # scripts/guards-manifest.tsv (package.json's stale `check:all` copy deleted).+ "check:guard-self-test"+ # Chronicle eval: $0, deterministic, exit-0-only-on-perfect (6 gold tasks).+ # 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:bootstrap-templates"+ "check:skill-brain-first"+ "check:conversation-parser"+ "check:resolver""check:privacy"- "check:proposal-pii""check:test-names"+ "check:test-isolation"+ # ── light tail (sub-second greps; historical order) ──+ "check:proposal-pii""check:jsonb""check:search-path""check:source-id-projection""check:source-config-leak""check:progress""check:no-tracked-symlinks"- "check:test-isolation"- "check:wasm"- "check:pglite-embedded"- "check:admin-build""check:admin-scope-drift""check:cli-exec""check:system-of-record"@@ -55,15 +88,11 @@ CHECKS=("check:skills-manifest""check:no-pii-agent-voice""check:synthetic-corpus-privacy"- "check:skill-brain-first"- "check:fuzz-purity""check:operations-filter-bypass""check:gateway-routed""check:worker-pool-atomicity""check:doc-history""check:fixture-privacy"- "check:conversation-parser"- "check:resolver""check:source-scope-onboard""check:no-double-retry""check:batch-audit-site"@@ -73,17 +102,14 @@ CHECKS=("check:pin-doc-privacy""check:worker-lock-renewal-shape""check:bootstrap-tag"- "check:bootstrap-templates""check:skill-refs"- # W0 fix-wave (Tier-1 #11): guard self-tests — every scanner guard proves it- # can fail (bad fixture → exit 1) before it counts as coverage. Registry:- # scripts/guards-manifest.tsv (package.json's stale `check:all` copy deleted).- "check:guard-self-test"# Previously reachable ONLY from the deleted check:all (i.e. never run):"check:newlines""check:exports-count""check:no-legacy-getconnection"- "typecheck"+ # Revived registered-but-never-executed guards (this pass):+ "check:pagetype-exhaustive"+ "check:pg-url-redaction")if [ "${#CHECKS[@]}" -eq 0 ]; then@@ -124,8 +150,22 @@ if command -v gtimeout >/dev/null 2>&1; then TIMEOUT_BIN="gtimeout"elif command -v timeout >/dev/null 2>&1; then TIMEOUT_BIN="timeout"fi+# Bounded worker pool. Unbounded fan-out ran two `cp -R src` ++# `bun build --compile` builds, the admin vite build, tsc, and ~40 greps+# simultaneously on a 4-vCPU CI runner — pushing slow checks into the+# 120s per-check timeout (the documented flake class on slower hosts).+# Default = detect_cpus so a many-core dev machine keeps its wide fan-out;+# escape hatch: GBRAIN_VERIFY_MAX_PARALLEL=999.+MAX_PAR="${GBRAIN_VERIFY_MAX_PARALLEL:-$(detect_cpus)}"+if ! printf '%s' "$MAX_PAR" | grep -qE '^[0-9]+$' || [ "$MAX_PAR" -lt 1 ]; then+ echo "ERROR: invalid GBRAIN_VERIFY_MAX_PARALLEL: $MAX_PAR" >&2+ exit 2+fi++ensure_pglite_snapshot "verify-parallel"+START_TS=$(date +%s)-echo "[verify-parallel] running ${#CHECKS[@]} checks in parallel (timeout=${TIMEOUT}s, logs=$LOG_DIR)" >&2+echo "[verify-parallel] running ${#CHECKS[@]} checks (pool=$MAX_PAR, timeout=${TIMEOUT}s, logs=$LOG_DIR)" >&2# ──────────────────────────────────────────────────────────────────────────# Spawn one background process per check. Each child captures its own exit@@ -138,6 +178,10 @@ echo "[verify-parallel] running ${#CHECKS[@]} checks in parallel (timeout=${TIMEPIDS=()SAFE_NAMES=()for c in "${CHECKS[@]}"; do+ # Throttle to the worker pool (bash 3.2 — no wait -n; jobs -rp reaps).+ while [ "$(jobs -rp | wc -l | tr -d ' ')" -ge "$MAX_PAR" ]; do+ sleep 0.1+ donesafe="${c//:/_}"SAFE_NAMES+=("$safe")LOG_FILE="$LOG_DIR/$safe.log"diff --git a/scripts/sharding.ts b/scripts/sharding.tsindex 53cbca08b4..de7a75a8f0 100644--- a/scripts/sharding.ts+++ b/scripts/sharding.ts@@ -96,6 +96,17 @@ export function computeMedian(values: number[]): number {: sorted[mid]!;}+/**+ * Quantile (nearest-rank) of a list of numbers. Empty input returns 0.+ * q in [0, 1]; q=0.75 is the missing-file fallback weight (see partition).+ */+export function computeQuantile(values: number[], q: number): number {+ if (values.length === 0) return 0;+ const sorted = [...values].sort((a, b) => a - b);+ const idx = Math.min(sorted.length - 1, Math.max(0, Math.ceil(q * sorted.length) - 1));+ return sorted[idx]!;+}+export interface PartitionOpts {/*** Weight to assign files that are absent from the weights map. Defaults@@ -133,8 +144,15 @@ export function partition(const shards: string[][] = Array.from({ length: n }, () => []);if (files.length === 0) return shards;- // Compute fallback weight from the median of present weights, unless- // the caller supplied an explicit override.+ // Compute fallback weight from the p75 of present weights, unless the+ // caller supplied an explicit override. p75, not median: the weight+ // distribution is extremely right-skewed (median ~27ms, mean ~800ms —+ // most files are trivial greps, the tail boots PGLite), and files+ // MISSING from the map skew heavy (new integration tests land unweighted+ // more often than new pure-unit tests). A median fallback modeled 45% of+ // the corpus at ~30ms and let one shard silently carry the unweighted+ // heavies; p75 over-weights small new files slightly (harmless — LPT+ // self-corrects on the next mine) instead of under-weighting big ones.let fallback: number;if (opts.fallbackWeight !== undefined) {if (!Number.isFinite(opts.fallbackWeight) || opts.fallbackWeight < 0) {@@ -144,7 +162,7 @@ export function partition(}fallback = opts.fallbackWeight;} else {- fallback = computeMedian(Array.from(weights.values()));+ fallback = computeQuantile(Array.from(weights.values()), 0.75);}// Cold-start guard: if the weights map is empty AND no explicit// fallback was supplied, every effective weight would be 0 and LPTdiff --git a/scripts/test-shard.sh b/scripts/test-shard.shindex 1e3640cc48..5e3cbde757 100755--- a/scripts/test-shard.sh+++ b/scripts/test-shard.sh@@ -56,6 +56,8 @@ ficd "$(dirname "$0")/.."+. scripts/lib/test-env.sh+# Collect non-E2E, non-serial unit test files. Slow files INCLUDED — see# header comment. Local run-unit-shard.sh excludes slow files (different# policy by design).@@ -72,7 +74,13 @@ cd "$(dirname "$0")/.."# 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.-ALL_FILES=$(find test -name '*.test.ts' \+# 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) —+# enforced by the allowlist guard in test/scripts/evals-collection.test.ts.+# The local fast loop (run-unit-shard.sh) stays test-only by design (see+# docs/TESTING.md "CI vs local: intentionally divergent file sets").+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' \@@ -94,6 +102,12 @@ if [ "$DRY_RUN_LIST" = "1" ]; thenexit 0fi+# Snapshot fast-path (after the dry-run exit so list-only calls stay+# instant): ~370 PGLite-booting matrix files pay ~3.1s cold init each+# without it. The echo inside makes silent cold-init regressions visible+# in CI logs.+ensure_pglite_snapshot "test-shard"+ALL_COUNT=$(printf '%s\n' "$ALL_FILES" | grep -c '^' || true)SHARD_COUNT=$(printf '%s\n' "$SHARD_FILES" | grep -c '^' || true)# grep -c on empty input returns 0 even with trailing newline edge cases@@ -108,4 +122,7 @@ fi# Convert newline-separated file list to argv. xargs handles the# whitespace correctly without word-splitting on spaces in paths.-printf '%s\n' "$SHARD_FILES" | xargs bun test --timeout=60000+# --max-concurrency mirrors the local runner: unbounded intra-process+# concurrency under parallel PGLite boots produced real shard deaths (the+# 22-minute matrix timeout in test.yml records 13 of them).+printf '%s\n' "$SHARD_FILES" | xargs bun test --timeout=60000 --max-concurrency="${GBRAIN_TEST_MAX_CONCURRENCY:-4}"diff --git a/scripts/test-weights.json b/scripts/test-weights.jsonindex 6221126374..6815bc4d26 100644--- a/scripts/test-weights.json+++ b/scripts/test-weights.json@@ -1,718 +1,1202 @@{- "test/active-pack-wiring.test.ts": 3,- "test/admin-agents-spend.test.ts": 4995,- "test/admin-embed-spawn.serial.test.ts": 12792,- "test/agent-cli.test.ts": 2935,- "test/agent-runner.test.ts": 2,- "test/ai/adaptive-embed-batch.test.ts": 34,- "test/ai/build-gateway-config.test.ts": 0,- "test/ai/capabilities.test.ts": 3,- "test/ai/config-no-env-mutation.test.ts": 4,- "test/ai/dims-openai.test.ts": 4,- "test/ai/dims-zeroentropy.test.ts": 4,- "test/ai/embedQuery.test.ts": 8,- "test/ai/gateway-chat.test.ts": 8,- "test/ai/gateway-tool-loop.test.ts": 9,- "test/ai/gateway.test.ts": 444,- "test/ai/header-transport.serial.test.ts": 118,- "test/ai/no-batch-cap-suppression.serial.test.ts": 98,- "test/ai/recipe-azure-openai.test.ts": 7,- "test/ai/recipe-dashscope.test.ts": 5,- "test/ai/recipe-llama-server.test.ts": 0,- "test/ai/recipe-minimax.test.ts": 1,- "test/ai/recipe-openrouter.test.ts": 1,- "test/ai/recipe-zhipu.test.ts": 3,- "test/ai/recipes-existing-regression.test.ts": 5,- "test/ai/rerank.test.ts": 16,- "test/ai/schema-templating.test.ts": 4,- "test/ai/silent-drop-regression.test.ts": 9,- "test/ai/sunset-warn.test.ts": 10,- "test/ai/voyage-code-3-recipe.test.ts": 3,- "test/ai/voyage-reranker-recipe.test.ts": 3,- "test/ai/zeroentropy-compat-fetch.test.ts": 16,- "test/ai/zeroentropy-recipe.test.ts": 1,- "test/anomalies.test.ts": 1,- "test/anthropic-model-ids.test.ts": 3,- "test/apply-migrations-pglite-spawn.serial.test.ts": 18874,- "test/apply-migrations.test.ts": 5,- "test/archive-crawler-config.test.ts": 26,- "test/artifact-abstraction.test.ts": 2,- "test/asymmetric-encoding-contract.test.ts": 1,- "test/audit-slug-fallback.serial.test.ts": 98,- "test/audit-synopsis.serial.test.ts": 99,- "test/audit/audit-writer.test.ts": 9,- "test/audit/content-sanity-audit.test.ts": 6,- "test/auto-think-phase.test.ts": 3251,- "test/autopilot-cycle-failure-classification.test.ts": 4,- "test/autopilot-cycle-handler.test.ts": 3039,- "test/autopilot-fanout-wiring.test.ts": 3,- "test/autopilot-fanout.test.ts": 24,- "test/autopilot-install.test.ts": 5,- "test/autopilot-lock-path.test.ts": 13,- "test/autopilot-nightly-probe-wiring.test.ts": 2,- "test/autopilot-reconnect-classifier.test.ts": 5,- "test/autopilot-resolve-cli.test.ts": 11,- "test/autopilot-supervisor-wiring.test.ts": 10,- "test/backfill-base.test.ts": 2,- "test/backfill-concurrency-clamp.serial.test.ts": 103,- "test/backlinks.test.ts": 23,- "test/backoff.test.ts": 8,- "test/balanced-reranker-default.test.ts": 19,- "test/batch-projection.test.ts": 1,- "test/bench-publish.test.ts": 8,- "test/bench/baseline-file.test.ts": 2,- "test/bench/correctness-gate.test.ts": 5,- "test/bench/qrels-file.test.ts": 13,- "test/book-mirror.test.ts": 431,- "test/bootstrap.test.ts": 18481,- "test/brain-allowlist.test.ts": 3257,- "test/brain-registry.serial.test.ts": 104,- "test/brain-resolver.test.ts": 125,- "test/brain-score-breakdown.test.ts": 3087,- "test/brain-score-recommendations.test.ts": 23,- "test/brain-writer-partial-scan.test.ts": 4335,- "test/brain-writer-walk-prune.test.ts": 7,- "test/brain-writer.test.ts": 3949,- "test/brainstorm-timeout.test.ts": 45,- "test/brainstorm/checkpoint.serial.test.ts": 136,- "test/brainstorm/cost-guardrails.test.ts": 13,- "test/brainstorm/distance.test.ts": 26,- "test/brainstorm/eval-brainstorm.test.ts": 13,- "test/brainstorm/lsd-mode-skip.test.ts": 2,- "test/budget-meter.test.ts": 26,- "test/budget-tracker.test.ts": 3265,- "test/build-llms.test.ts": 11,- "test/calibration-cli.test.ts": 13,- "test/calibration-profile.test.ts": 7,- "test/candidate-audit.test.ts": 9,- "test/capture-build-content.test.ts": 18,- "test/capture-runcapture.test.ts": 8,- "test/cathedral-ii-brainbench.test.ts": 9162,- "test/check-resolvable-cli.test.ts": 3600,- "test/check-resolvable.test.ts": 40,- "test/check-system-of-record.test.ts": 70,- "test/check-update.test.ts": 674,- "test/child-worker-supervisor.test.ts": 144,- "test/chunk-grain-fts.test.ts": 70996,- "test/chunker-timeout.test.ts": 27,- "test/chunker-version-gate.test.ts": 6,- "test/chunkers/code.test.ts": 129,- "test/chunkers/recursive.test.ts": 57,- "test/cjk.test.ts": 4,- "test/claw-test-cli.test.ts": 9,- "test/cli-args.test.ts": 15,- "test/cli-dispatch-thin-client.test.ts": 6027,- "test/cli-help-discoverability.test.ts": 1670,- "test/cli-multimodal-integration.test.ts": 26677,- "test/cli-options.test.ts": 1658,- "test/cli-query-image.test.ts": 56,- "test/cli.test.ts": 2633,- "test/code-callers-cli.test.ts": 2,- "test/code-def-refs.test.ts": 28662,- "test/code-edges.test.ts": 2884,- "test/code-intel/edge-densification.test.ts": 33,- "test/code-intel/eval-capture-graph.test.ts": 5,- "test/code-intel/recursive-walk.test.ts": 31107,- "test/code-intel/scope-walker-resolution.test.ts": 19,- "test/code-intel/traversal-cache.test.ts": 42036,- "test/code-retrieval-harness.test.ts": 4,- "test/commands-search.test.ts": 23985,- "test/commands/capture.test.ts": 42431,- "test/config-ensure-gitignore.test.ts": 7,- "test/config-env.test.ts": 6,- "test/config-set.test.ts": 17,- "test/config-unset.test.ts": 23831,- "test/config.test.ts": 6,- "test/connection-manager.serial.test.ts": 117,- "test/connection-resilience.test.ts": 29,- "test/console-prefix.test.ts": 5,- "test/consolidate-valid-until.test.ts": 2471,- "test/content-sanity-literals.test.ts": 2,- "test/content-sanity.test.ts": 5,- "test/context-engine.test.ts": 33,- "test/contextual-retrieval-doctor.serial.test.ts": 2755,- "test/contextual-retrieval-resolver.test.ts": 4,- "test/contextual-retrieval-service-pure.test.ts": 3,- "test/core/audit-week-file.serial.test.ts": 97,- "test/core/base-phase.test.ts": 9,- "test/core/cycle.serial.test.ts": 5563,- "test/core/diarize/payload-fitter-summarize.test.ts": 15,- "test/core/remediation-checkpoint.serial.test.ts": 129,- "test/cosine-rescore-column.test.ts": 3198,- "test/cross-brain-calibration.test.ts": 8,- "test/cross-modal-eval-aggregate.test.ts": 3,- "test/cross-modal-eval-cli.test.ts": 23,- "test/cross-modal-eval-json-repair.test.ts": 31,- "test/cross-modal-hybrid-integration.serial.test.ts": 3312,- "test/cross-modal-phase1.test.ts": 40,- "test/cross-modal-phase2.test.ts": 48,- "test/cycle-abort.test.ts": 108,- "test/cycle-consolidate.test.ts": 23952,- "test/cycle-last-full-cycle-at.test.ts": 3771,- "test/cycle-legacy-phases.test.ts": 4177,- "test/cycle-lock-per-source.test.ts": 9,- "test/cycle-pack-gating.test.ts": 5,- "test/cycle-patterns.test.ts": 2,- "test/cycle-pglite-lock-ordering.serial.test.ts": 2693,- "test/cycle-synthesize-chunker.test.ts": 21,- "test/cycle-synthesize-md-discovery.test.ts": 6,- "test/cycle-synthesize-slug-collection.test.ts": 3140,- "test/cycle-synthesize.test.ts": 17,- "test/cycle/extract-atoms-synthesize-concepts.test.ts": 60181,- "test/cycle/nightly-probe-adapters.test.ts": 6,- "test/data-research.test.ts": 17,- "test/db-lock-election.test.ts": 23346,- "test/db-lock-per-source.test.ts": 33460,- "test/db-lock-refresh.test.ts": 6,- "test/dedup.test.ts": 13,- "test/destructive-guard.test.ts": 6357,- "test/disk-walk.test.ts": 17,- "test/distribution-import-boundary.test.ts": 7,- "test/doctor-behavioral.test.ts": 5729,- "test/doctor-calibration-checks.test.ts": 5,- "test/doctor-child-orphans.test.ts": 4,- "test/doctor-cli-smoke.serial.test.ts": 4239,- "test/doctor-cycle-freshness.test.ts": 33963,- "test/doctor-cycle-phase-scope.test.ts": 7,- "test/doctor-federation-health.test.ts": 4021,- "test/doctor-fix.test.ts": 1301,- "test/doctor-frontmatter-partial.test.ts": 2,- "test/doctor-home-dir-in-worktree.test.ts": 194,- "test/doctor-minions-check.test.ts": 2697,- "test/doctor-remote.serial.test.ts": 210,- "test/doctor-report-remote.serial.test.ts": 2823,- "test/doctor-search-mode.test.ts": 3519,- "test/doctor-subagent-health.test.ts": 2972,- "test/doctor-v0_37_7_checks.test.ts": 2447,- "test/doctor-ze-checks.test.ts": 26042,- "test/doctor.test.ts": 46040,- "test/domain-aggregators.test.ts": 3512,- "test/dream-cli-flags.test.ts": 3,- "test/dream.test.ts": 26718,- "test/drift-watch.test.ts": 255,- "test/dry-fix.test.ts": 442,- "test/e2e/voyage-rerank-live.test.ts": 1,- "test/edge-extractor.test.ts": 252,- "test/effective-date.test.ts": 6,- "test/embed-backfill-submit.test.ts": 3099,- "test/embed-multimodal-batching.test.ts": 11,- "test/embed-skip.test.ts": 5,- "test/embed-stale.test.ts": 34959,- "test/embed.serial.test.ts": 2312,- "test/embedding-context.test.ts": 6,- "test/embedding-dim-check.test.ts": 4174,- "test/embedding-pricing.test.ts": 3,- "test/emotional-weight.test.ts": 4,- "test/engine-factory.test.ts": 13,- "test/engine-find-trajectory.test.ts": 3351,- "test/engine-parity-event-type.test.ts": 3251,- "test/engine-upsertFile.test.ts": 3801,- "test/engine-weight-rounding-integration.test.ts": 2367,- "test/enrichable-pack.test.ts": 8,- "test/enrichment-service.test.ts": 4,- "test/enrichment.test.ts": 3498,- "test/entity-resolve-perf.slow.test.ts": 158667,- "test/entity-resolve.test.ts": 24029,- "test/error-classify.test.ts": 3,- "test/errors.test.ts": 18,- "test/eval-candidates.test.ts": 18453,- "test/eval-capture-scrub.test.ts": 1,- "test/eval-capture.test.ts": 6,- "test/eval-compare.test.ts": 36,- "test/eval-contradictions-auto-supersession.test.ts": 3,- "test/eval-contradictions-cache.test.ts": 4601,- "test/eval-contradictions-calibration-join.test.ts": 2,- "test/eval-contradictions-calibration.test.ts": 12,- "test/eval-contradictions-cost-prompt.test.ts": 4223,- "test/eval-contradictions-cost.test.ts": 16,- "test/eval-contradictions-cross-source.test.ts": 5,- "test/eval-contradictions-date-filter.test.ts": 5,- "test/eval-contradictions-engine.test.ts": 5226,- "test/eval-contradictions-fixture-redact.test.ts": 5,- "test/eval-contradictions-integrations.test.ts": 4067,- "test/eval-contradictions-judge-errors.test.ts": 3,- "test/eval-contradictions-judge.test.ts": 32,- "test/eval-contradictions-runner.test.ts": 5998,- "test/eval-contradictions-severity.test.ts": 5,- "test/eval-contradictions-trends.test.ts": 36220,- "test/eval-contradictions/no-valid-until-write.test.ts": 33,- "test/eval-cross-modal-batch.test.ts": 141,- "test/eval-export.test.ts": 2399,- "test/eval-gate.test.ts": 3884,- "test/eval-longmemeval-e2e.slow.test.ts": 196000,- "test/eval-longmemeval.slow.test.ts": 42000,- "test/eval-prune.test.ts": 18396,- "test/eval-replay-gate.test.ts": 34958,- "test/eval-replay-metadata-skip.test.ts": 3430,- "test/eval-replay.test.ts": 16,- "test/eval-run-all.test.ts": 17,- "test/eval-schema-authoring.test.ts": 4,- "test/eval-shared-json-repair-shim.test.ts": 6,- "test/eval-takes-quality-aggregate.test.ts": 32,- "test/eval-takes-quality-boundaries.test.ts": 3193,- "test/eval-takes-quality-cli.test.ts": 13,- "test/eval-takes-quality-pricing.test.ts": 2,- "test/eval-takes-quality-receipt-name.test.ts": 4,- "test/eval-takes-quality-receipt-write.test.ts": 3213,- "test/eval-takes-quality-regress.test.ts": 14,- "test/eval-takes-quality-replay.test.ts": 2890,- "test/eval-takes-quality-rubric.test.ts": 3,- "test/eval-takes-quality-runner.serial.test.ts": 2642,- "test/eval-takes-quality-trend.test.ts": 23553,- "test/eval-trajectory.test.ts": 3424,- "test/eval-v041_2-scaffolds.test.ts": 23,- "test/eval-whoknows.test.ts": 8,- "test/eval.test.ts": 2,- "test/exit-classification.test.ts": 4,- "test/expert-types-pack.test.ts": 60,- "test/extract-db.test.ts": 3200,- "test/extract-facts-phase.test.ts": 24617,- "test/extract-from-fence.test.ts": 6,- "test/extract-fs.test.ts": 2618,- "test/extract-incremental.test.ts": 4523,- "test/extract-source-aware.test.ts": 23970,- "test/extract-takes-holder-producer-seam.test.ts": 2469,- "test/extract-takes.test.ts": 3153,- "test/extract.test.ts": 24,- "test/extractable-pack.test.ts": 76,- "test/facts-absorb-log.test.ts": 3161,- "test/facts-anti-loop.test.ts": 2478,- "test/facts-backstop-gating.test.ts": 3278,- "test/facts-backstop-integration.test.ts": 23696,- "test/facts-backstop.test.ts": 3118,- "test/facts-canonicality.test.ts": 3218,- "test/facts-classify.test.ts": 3,- "test/facts-context-injection.serial.test.ts": 2703,- "test/facts-decay.test.ts": 19,- "test/facts-doctor-shape.test.ts": 3109,- "test/facts-eligibility.test.ts": 5,- "test/facts-engine.test.ts": 12954,- "test/facts-extract-silent-no-op.test.ts": 4,- "test/facts-extract-smoke.test.ts": 6,- "test/facts-extract.test.ts": 1,- "test/facts-fence-typed.test.ts": 4,- "test/facts-fence.test.ts": 5,- "test/facts-mcp-allowlist.serial.test.ts": 2633,- "test/facts-meta-cache.test.ts": 3117,- "test/facts-migration-dim.test.ts": 3329,- "test/facts-multi-tenant.test.ts": 23425,- "test/facts-queue.test.ts": 604,- "test/facts-recall-render.test.ts": 2968,- "test/facts-separation-pglite.test.ts": 3260,- "test/facts-visibility.test.ts": 2917,- "test/fail-improve.test.ts": 132,- "test/feature-flags.test.ts": 3864,- "test/features.test.ts": 5,- "test/fence-extraction.test.ts": 3427,- "test/fence-write.test.ts": 2335,- "test/file-migration.test.ts": 4,- "test/file-resolver.test.ts": 24,- "test/file-upload-security.test.ts": 3,- "test/files.test.ts": 6,- "test/filing-audit.test.ts": 9,- "test/find-experts-op.test.ts": 3125,- "test/fix-wave-structural.test.ts": 6,- "test/founder-scorecard.test.ts": 9,- "test/friction-cli.test.ts": 21,- "test/friction.test.ts": 29,- "test/frontmatter-cli.test.ts": 2936,- "test/frontmatter-inference.test.ts": 10,- "test/frontmatter-install-hook.test.ts": 56,- "test/fuzz/filesystem-validators.test.ts": 87,- "test/fuzz/mixed-validators.test.ts": 279,- "test/fuzz/pure-validators.test.ts": 220,- "test/gateway-embed-model-override.test.ts": 1,- "test/gbrain-home-isolation.test.ts": 7,- "test/get-brain-identity.test.ts": 36332,- "test/git-remote.test.ts": 365,- "test/grade-takes-ensemble.test.ts": 30,- "test/grade-takes.test.ts": 6,- "test/graph-query.test.ts": 3163,- "test/gstack-learnings-coupling.test.ts": 15,- "test/handlers-embed-backfill.test.ts": 2978,- "test/handlers.test.ts": 25084,- "test/helpers/schema-diff-indexes.test.ts": 4,- "test/helpers/schema-diff.test.ts": 2,- "test/helpers/with-env.test.ts": 19,- "test/http-transport.test.ts": 100,- "test/hybrid-meta.serial.test.ts": 3314,- "test/hybrid-search-lite.serial.test.ts": 2849,- "test/import-checkpoint.test.ts": 5,- "test/import-file-content-sanity.test.ts": 3363,- "test/import-file.test.ts": 87,- "test/import-image-file.test.ts": 3539,- "test/import-resume.test.ts": 2811,- "test/import-source-id.test.ts": 3149,- "test/import-walker.test.ts": 1,- "test/incremental-chunking.test.ts": 3212,- "test/infer-type-pack.test.ts": 16,- "test/ingestion/daemon.test.ts": 39,- "test/ingestion/dedup.test.ts": 5,- "test/ingestion/gstack-learnings.test.ts": 8,- "test/ingestion/ingest-capture.test.ts": 53213,- "test/ingestion/markdown-greenfield.test.ts": 13,- "test/ingestion/migration-mode.test.ts": 8,- "test/ingestion/put-page-write-through.test.ts": 38741,- "test/ingestion/skillpack-load.test.ts": 15,- "test/ingestion/sources/file-watcher.test.ts": 1007,- "test/ingestion/sources/inbox-folder.test.ts": 518,- "test/ingestion/test-harness.test.ts": 68,- "test/ingestion/types.test.ts": 9,- "test/init-env-detection.test.ts": 11,- "test/init-mcp-only.test.ts": 4380,- "test/init-migrate-only.test.ts": 7098,- "test/init-mode-picker.test.ts": 2440,- "test/init-provider-picker.test.ts": 2,- "test/insert-facts-batch.test.ts": 2976,- "test/integrations-install.test.ts": 183,- "test/integrations.test.ts": 24,- "test/integrity.test.ts": 2678,- "test/intent-weights.test.ts": 4,- "test/jobs-watch-snapshot.test.ts": 12,- "test/language-manifest.test.ts": 17,- "test/lease-cap-controller.test.ts": 3161,- "test/lens-pack-manifests.test.ts": 13,- "test/levenshtein.test.ts": 3,- "test/link-extraction-code-refs.test.ts": 4,- "test/link-extraction.test.ts": 25,- "test/link-inference-pack.test.ts": 46,- "test/lint-content-sanity.test.ts": 36,- "test/lint-frontmatter.test.ts": 15,- "test/lint.test.ts": 1,- "test/list-all-sources.test.ts": 39599,- "test/llm-intent-escalation.test.ts": 6,- "test/llm-intent-hybrid-integration.serial.test.ts": 3246,- "test/loadConfig-merge.test.ts": 4,- "test/longmemeval-extract.test.ts": 2991,- "test/longmemeval-intent.test.ts": 3,- "test/longmemeval-sanitize.test.ts": 5,- "test/longmemeval-trajectory-routing.test.ts": 12926,- "test/markdown-serializer.test.ts": 8,- "test/markdown-validation.test.ts": 3,- "test/markdown.test.ts": 27,- "test/mcp-client-hardening.test.ts": 305,- "test/mcp-client.test.ts": 65,- "test/mcp-dispatch-summarize.test.ts": 6,- "test/mcp-eval-capture.test.ts": 25246,- "test/mcp-tool-defs.test.ts": 15,- "test/metric-glossary.test.ts": 16,- "test/migrate-extensions.test.ts": 3,- "test/migrate.test.ts": 102260,- "test/migration-orchestrator-v0_21_0.test.ts": 7,- "test/migration-orchestrator-v0_31_0.test.ts": 12960,- "test/migration-orchestrator-v0_46_3.serial.test.ts": 8000,- "test/migration-resume.test.ts": 9,- "test/migration-v0-29-1.serial.test.ts": 3273,- "test/migrations-cjk-wave.test.ts": 3280,- "test/migrations-registry.test.ts": 3,- "test/migrations-v0_11_0.test.ts": 14,- "test/migrations-v0_12_0.test.ts": 6,- "test/migrations-v0_12_2.test.ts": 3,- "test/migrations-v0_13_0.test.ts": 1,- "test/migrations-v0_13_1.test.ts": 23,- "test/migrations-v0_14_0.test.ts": 20,- "test/migrations-v0_16_0.test.ts": 1,- "test/migrations-v0_19_0.test.ts": 20826,- "test/migrations-v0_21_0.test.ts": 2,- "test/migrations-v0_22_4.test.ts": 1,- "test/migrations-v0_27_1.test.ts": 3248,- "test/migrations-v0_32_2.test.ts": 2510,- "test/migrations-v48-takes-weight-backfill.test.ts": 2501,- "test/migrations-v94.test.ts": 32374,- "test/minions-lease-full-retry.test.ts": 3031,- "test/minions-quiet-hours.test.ts": 3341,- "test/minions-shell-inherit.test.ts": 24,- "test/minions-shell-redact.test.ts": 19,- "test/minions-shell-validate.test.ts": 7,- "test/minions-shell.test.ts": 3268,- "test/minions.test.ts": 15231,- "test/minions/agent-audit.test.ts": 9,- "test/minions/budget-meter.test.ts": 44657,- "test/mode-switch-ux.test.ts": 3698,- "test/model-config.serial.test.ts": 101,- "test/mounts-cache.test.ts": 21,- "test/mounts-cli.test.ts": 20,- "test/multi-source-drift.test.ts": 2479,- "test/multi-source-integration.test.ts": 3120,- "test/nightly-quality-probe.test.ts": 50,- "test/notability-eval.test.ts": 36,- "test/nudge.test.ts": 16,- "test/oauth-confidential-client.test.ts": 3221,- "test/oauth-scope-probe.test.ts": 112,- "test/oauth.test.ts": 2151,- "test/op-checkpoint.test.ts": 5333,- "test/openai-compat-multimodal.test.ts": 6,- "test/operation-context-sourceid-required.test.ts": 10,- "test/operations-allow-list.test.ts": 4,- "test/operations-descriptions.test.ts": 11,- "test/operations-embedding-column.test.ts": 30,- "test/operations-find-trajectory.test.ts": 3419,- "test/operations-schema-pack.test.ts": 5842,- "test/operations-trust-boundary.test.ts": 43020,- "test/orphans.test.ts": 16921,- "test/page-lock.test.ts": 266,- "test/page-type-exhaustive.test.ts": 17,- "test/pages-soft-delete.test.ts": 15271,- "test/parallel.test.ts": 108,- "test/parent-scope.test.ts": 23673,- "test/parity.test.ts": 16,- "test/performfullsync-source-id.test.ts": 2869,- "test/pglite-engine.test.ts": 33476,- "test/pglite-lock.test.ts": 1007,- "test/phantom-redirect-engine-parity.test.ts": 3605,- "test/phantom-redirect-per-source-lock.test.ts": 3,- "test/phantom-redirect.test.ts": 7303,- "test/phase-scope-coverage.test.ts": 3,- "test/plugin-loader.test.ts": 12,- "test/post-install-advisory.test.ts": 15,- "test/post-write-lint.test.ts": 4180,- "test/postgres-engine.test.ts": 32,- "test/preferences.test.ts": 14,- "test/privacy-script-wired.test.ts": 3,- "test/privacy-strip-and-forget.test.ts": 2762,- "test/progress-tail.test.ts": 3,- "test/progress.test.ts": 215,- "test/propose-takes.test.ts": 15,- "test/providers.test.ts": 17,- "test/public-exports.test.ts": 35,- "test/publish.test.ts": 128,- "test/put-page-namespace.test.ts": 4,- "test/put-page-provenance.test.ts": 24839,- "test/qualified-names.test.ts": 4,- "test/query-cache-gate.test.ts": 31003,- "test/query-cache-knobs-hash.test.ts": 3122,- "test/query-cache.test.ts": 2565,- "test/query-image-flag.serial.test.ts": 2965,- "test/query-intent-legacy.test.ts": 8,- "test/query-intent.test.ts": 6,- "test/query-sanitization.test.ts": 4,- "test/queue-child-done.test.ts": 2548,- "test/rate-leases-uncapped.test.ts": 2884,- "test/rate-leases.test.ts": 2959,- "test/readme-hero-anchors.test.ts": 0,- "test/recall-extensions.test.ts": 4668,- "test/recall-footer.test.ts": 17,- "test/recall-rollup.test.ts": 84,- "test/recency-decay.test.ts": 5,- "test/recompute-emotional-weight.test.ts": 2,- "test/reconcile-links.serial.test.ts": 2702,- "test/regression-strict-source-id.test.ts": 4,- "test/regression-v0_16_4.test.ts": 28,- "test/regressions/gbrain-base-equivalence.test.ts": 12,- "test/regressions/v0.36.1.0-iron-rule.test.ts": 3,- "test/regressions/v0_36_frontier_cap.test.ts": 27151,- "test/regressions/v0_40_2_0-trajectory-backcompat.test.ts": 27576,- "test/reindex-code-max-cost.serial.test.ts": 2636,- "test/reindex-code-model-source.serial.test.ts": 2782,- "test/reindex-code-nudge.serial.test.ts": 2710,- "test/reindex-code.test.ts": 38123,- "test/reindex-frontmatter-connect.test.ts": 18383,- "test/reindex.test.ts": 19003,- "test/remediation-step.test.ts": 25,- "test/repair-jsonb.test.ts": 3,- "test/repo-root.test.ts": 14,- "test/report.test.ts": 2,- "test/repos-alias.test.ts": 3163,- "test/rerank-audit.test.ts": 24,- "test/resolve-prepare.test.ts": 11,- "test/resolver-merge.test.ts": 5,- "test/resolver.test.ts": 58,- "test/resolvers.test.ts": 4130,- "test/restart-sweep.test.ts": 42,- "test/retrieval-upgrade-planner.test.ts": 8375,- "test/retry-matcher.test.ts": 2,- "test/routing-eval-cli.test.ts": 1118,- "test/routing-eval.test.ts": 34,- "test/salience.test.ts": 2,- "test/scenarios.test.ts": 29,- "test/schema-bootstrap-coverage.test.ts": 6449,- "test/schema-cli-contract.test.ts": 4,- "test/schema-cli.test.ts": 3375,- "test/schema-pack-best-effort.test.ts": 9,- "test/schema-pack-lint-rules.test.ts": 11,- "test/schema-pack-load-active.serial.test.ts": 43,- "test/schema-pack-loader.test.ts": 10,- "test/schema-pack-manifest-v041_2.test.ts": 17,- "test/schema-pack-mutate-audit.test.ts": 8,- "test/schema-pack-mutate.test.ts": 80,- "test/schema-pack-pack-lock.test.ts": 65,- "test/schema-pack-query-cache-invalidator.test.ts": 22822,- "test/schema-pack-registry-reload.test.ts": 40,- "test/schema-pack-registry.test.ts": 52,- "test/schema-pack-stats.test.ts": 43032,- "test/schema-pack-sync.test.ts": 5580,- "test/schema-pack-trust-boundary.test.ts": 8,- "test/schema-verify.test.ts": 7,- "test/scope-agent-isolation.test.ts": 30,- "test/scope-normalize.test.ts": 24,- "test/scope.test.ts": 5,- "test/scripts/check-proposal-pii.test.ts": 511,- "test/scripts/check-test-isolation.test.ts": 223,- "test/scripts/run-unit-parallel.test.ts": 427,- "test/scripts/run-unit-shard.test.ts": 131,- "test/scripts/serial-files.test.ts": 41,- "test/scripts/test-shard.slow.test.ts": 32161,- "test/search-by-image-op.test.ts": 3869,- "test/search-image-column.test.ts": 30089,- "test/search-lang-symbol-kind.test.ts": 2556,- "test/search-limit.test.ts": 2909,- "test/search-mode.test.ts": 8,- "test/search-telemetry.test.ts": 25699,- "test/search-types-filter.test.ts": 3023,- "test/search.test.ts": 9,- "test/search/attribution-stamping.test.ts": 5,- "test/search/embedding-column.serial.test.ts": 109,- "test/search/explain-formatter.test.ts": 13,- "test/search/graph-signals-wire-integration.test.ts": 28358,- "test/search/graph-signals.test.ts": 14,- "test/search/hybrid-reranker-integration.serial.test.ts": 2905,- "test/search/knobs-hash-reranker.test.ts": 5,- "test/search/rerank.test.ts": 23,- "test/search/search-stats-graph-signals.test.ts": 23476,- "test/seed-pglite.test.ts": 12966,- "test/select-e2e.test.ts": 11,- "test/self-fix.test.ts": 28842,- "test/serve-http-bootstrap-token.test.ts": 2,- "test/serve-http-health.test.ts": 301,- "test/serve-stdio-lifecycle.test.ts": 1252,- "test/setup-branching.test.ts": 15,- "test/skill-brain-first.test.ts": 9,- "test/skill-manifest.test.ts": 25,- "test/skillify-check.test.ts": 554,- "test/skillify-scaffold.test.ts": 31,- "test/skillpack-apply-hunks.test.ts": 19,- "test/skillpack-bootstrap-display.test.ts": 4,- "test/skillpack-changed-since-version.test.ts": 361,- "test/skillpack-check.test.ts": 4691,- "test/skillpack-copy.test.ts": 11,- "test/skillpack-endorse.test.ts": 114,- "test/skillpack-frontmatter-sources.test.ts": 10,- "test/skillpack-harvest-lint.test.ts": 5,- "test/skillpack-harvest.test.ts": 35,- "test/skillpack-init-pack.test.ts": 50,- "test/skillpack-install.test.ts": 51,- "test/skillpack-manifest-v1.test.ts": 4,- "test/skillpack-migrate-fence.test.ts": 10,- "test/skillpack-reference-apply.test.ts": 13,- "test/skillpack-reference-pack-is-ten.test.ts": 14,- "test/skillpack-reference.test.ts": 29,- "test/skillpack-registry-client.test.ts": 27,- "test/skillpack-registry-schema.test.ts": 13,- "test/skillpack-remote-source.test.ts": 65,- "test/skillpack-rubric-doctor.test.ts": 45,- "test/skillpack-scaffold-third-party.test.ts": 17,- "test/skillpack-scaffold.test.ts": 44,- "test/skillpack-scrub-legacy.test.ts": 51,- "test/skillpack-state.test.ts": 30,- "test/skillpack-tarball.test.ts": 132,- "test/skillpack-trust-prompt.test.ts": 9,- "test/skills-conformance.test.ts": 25,- "test/slug-validation.test.ts": 12,- "test/sort-newest-first.test.ts": 120,- "test/source-config-redact.test.ts": 1,- "test/source-health.test.ts": 2940,- "test/source-id-routing.test.ts": 3687,- "test/source-id-tx-regression.test.ts": 3200,- "test/source-id.test.ts": 4,- "test/source-resolver-silent-fallback.test.ts": 40514,- "test/source-resolver-with-tier.test.ts": 1,- "test/source-resolver.test.ts": 27,- "test/sources-load.test.ts": 4120,- "test/sources-mcp.test.ts": 41488,- "test/sources-ops.test.ts": 4235,- "test/sources-resync-recovery.test.ts": 40765,- "test/sources-set-cr-mode.test.ts": 37772,- "test/sources-webhook.test.ts": 20,- "test/sources.test.ts": 11,- "test/spawn-helpers.test.ts": 18,- "test/sql-query.test.ts": 2327,- "test/sql-ranking.test.ts": 17,- "test/ssrf-validate.test.ts": 6,- "test/storage-backfill.test.ts": 4,- "test/storage-config.test.ts": 8,- "test/storage-export.test.ts": 3170,- "test/storage-pglite.test.ts": 23978,- "test/storage-status.test.ts": 12,- "test/storage-sync.test.ts": 27,- "test/storage.test.ts": 146,- "test/stub-guard-audit.test.ts": 27,- "test/subagent-aggregator.test.ts": 5,- "test/subagent-audit.test.ts": 29,- "test/subagent-handler.test.ts": 3178,- "test/subagent-prompt-too-long.test.ts": 17,- "test/subagent-transcript.test.ts": 3276,- "test/subagent-v1-v2-shim.test.ts": 4830,- "test/submit-agent.test.ts": 4992,- "test/supabase-admin.test.ts": 0,- "test/supervisor-audit.test.ts": 8,- "test/supervisor-tini.test.ts": 1,- "test/supervisor.test.ts": 326,- "test/svg-renderer.test.ts": 7,- "test/sync-all-parallel.test.ts": 6,- "test/sync-classifier-widening.test.ts": 4,- "test/sync-concurrency.test.ts": 6,- "test/sync-cost-preview.test.ts": 115,- "test/sync-failures.test.ts": 18,- "test/sync-parallel.test.ts": 22640,- "test/sync-strategy.test.ts": 15,- "test/sync-trigger-cli.test.ts": 3100,- "test/sync-walker-submodule.test.ts": 5,- "test/sync-walker-symlink.test.ts": 12,- "test/sync.test.ts": 5841,- "test/synth-enabled-default.test.ts": 3,- "test/system-prompt.test.ts": 8,- "test/take-forecast.test.ts": 7,- "test/takes-engine.test.ts": 3302,- "test/takes-fence-read-ops.serial.test.ts": 2720,- "test/takes-fence.test.ts": 132,- "test/takes-holder-semantics.test.ts": 5,- "test/takes-holder-validation.test.ts": 13,- "test/takes-mcp-allowlist.serial.test.ts": 2721,- "test/takes-resolution.test.ts": 5,- "test/takes-weight-rounding.test.ts": 6,- "test/thin-client-routing-audit.test.ts": 5,- "test/thin-client-upgrade-prompt.test.ts": 23,- "test/think-ab.test.ts": 18,- "test/think-entity-extract.test.ts": 4,- "test/think-gateway-adapter.test.ts": 33,- "test/think-intent.test.ts": 8,- "test/think-pipeline.serial.test.ts": 2723,- "test/think-sanitize-trajectory.test.ts": 7,- "test/think-trajectory-injection.test.ts": 3346,- "test/think-with-calibration.test.ts": 3,- "test/timing-safe.test.ts": 17,- "test/token-budget.test.ts": 3,- "test/trajectory-format.test.ts": 4,- "test/transcript-capture.test.ts": 246,- "test/transcription.test.ts": 20,- "test/transcripts.test.ts": 20,- "test/traverse-graph-dedup.test.ts": 2933,- "test/trust-boundary-contract.test.ts": 24,- "test/two-pass.test.ts": 3137,- "test/undo-wave.test.ts": 5,- "test/unified-multimodal.serial.test.ts": 3286,- "test/upgrade-checkpoint.serial.test.ts": 109,- "test/upgrade-reembed-prompt.test.ts": 3219,- "test/upgrade-reference-sweep.test.ts": 56,- "test/upgrade.serial.test.ts": 723,- "test/url-redact.test.ts": 2,- "test/utils.test.ts": 5,- "test/v0_29-tool-surfaces.test.ts": 4,- "test/v0_37_fix_wave.serial.test.ts": 211,- "test/v81-v82-smoke.test.ts": 3160,- "test/vector-index-lifecycle.test.ts": 5,- "test/voice-gate.test.ts": 9,- "test/voyage-multimodal.test.ts": 22,- "test/voyage-response-cap.test.ts": 1,- "test/wait-for-completion.test.ts": 3626,- "test/whoami.test.ts": 3,- "test/whoknows-doctor.test.ts": 70,- "test/whoknows.test.ts": 3,- "test/worker-rss.test.ts": 3,- "test/worker-shutdown-disconnect.test.ts": 3260,- "test/writer.test.ts": 37365,- "test/yaml-lite.test.ts": 9,- "test/ze-exposure.test.ts": 9000,- "test/ze-switch-cli.test.ts": 4227,- "test/zombie-reap.test.ts": 3-}+ "test/abort-check.test.ts": 2,+ "test/active-pack-wiring.test.ts": 4,+ "test/admin-agents-spend.test.ts": 3155,+ "test/admin-sse-eventsource.test.ts": 3,+ "test/admin-sse-handshake.test.ts": 104,+ "test/advisor-apply.test.ts": 4,+ "test/advisor-core.test.ts": 18,+ "test/advisor-mcp-client-fit.test.ts": 488,+ "test/advisor-op-gate.test.ts": 49,+ "test/advisor-ranking-eval.test.ts": 0,+ "test/agent-cli.test.ts": 487,+ "test/agent-runner.test.ts": 20,+ "test/ai-probes-models.test.ts": 12,+ "test/ai/adaptive-embed-batch.test.ts": 21,+ "test/ai/anthropic-key.test.ts": 6,+ "test/ai/build-gateway-config.test.ts": 834,+ "test/ai/capabilities.test.ts": 4,+ "test/ai/config-no-env-mutation.test.ts": 4,+ "test/ai/deepseek-reasoning-content.test.ts": 4,+ "test/ai/diagnose-embedding-dims.test.ts": 2,+ "test/ai/dims-openai.test.ts": 10,+ "test/ai/dims-qwen3-native.test.ts": 4,+ "test/ai/dims-zeroentropy.test.ts": 4,+ "test/ai/embedQuery.test.ts": 9,+ "test/ai/gateway-chat.test.ts": 5,+ "test/ai/gateway-openai-prompt-cache-key.test.ts": 10,+ "test/ai/gateway-probe-chat-model.test.ts": 4,+ "test/ai/gateway-reset-baseline.test.ts": 4,+ "test/ai/gateway-tool-loop.test.ts": 7,+ "test/ai/gateway-toolcall-pairing.test.ts": 21,+ "test/ai/gateway-tools-schema.test.ts": 22,+ "test/ai/gateway.test.ts": 824,+ "test/ai/model-resolver-slash.test.ts": 2,+ "test/ai/recipe-azure-openai.test.ts": 10,+ "test/ai/recipe-dashscope-rerank.test.ts": 5,+ "test/ai/recipe-dashscope.test.ts": 14,+ "test/ai/recipe-llama-server-reranker.test.ts": 3,+ "test/ai/recipe-llama-server.test.ts": 5,+ "test/ai/recipe-minimax.test.ts": 1,+ "test/ai/recipe-mistral.test.ts": 2,+ "test/ai/recipe-moonshot.test.ts": 3,+ "test/ai/recipe-nvidia.test.ts": 3,+ "test/ai/recipe-ollama-dims.test.ts": 5,+ "test/ai/recipe-openrouter.test.ts": 4,+ "test/ai/recipe-perplexity.test.ts": 19,+ "test/ai/recipe-zhipu.test.ts": 3,+ "test/ai/recipes-existing-regression.test.ts": 5,+ "test/ai/rerank.test.ts": 21,+ "test/ai/resolve-native-base-url.test.ts": 1,+ "test/ai/schema-templating.test.ts": 6,+ "test/ai/silent-drop-regression.test.ts": 3,+ "test/ai/voyage-code-3-recipe.test.ts": 3,+ "test/ai/zeroentropy-compat-fetch.test.ts": 8,+ "test/all-sources-sentinel.test.ts": 24,+ "test/ambient-recall-cli.test.ts": 7497,+ "test/ambient-recall-templates.test.ts": 4,+ "test/ambient-recall.test.ts": 5116,+ "test/anomalies.test.ts": 11,+ "test/anthropic-model-ids.test.ts": 1,+ "test/anthropic-pricing.test.ts": 1,+ "test/apply-migrations.test.ts": 13,+ "test/archive-crawler-config.test.ts": 9,+ "test/artifact-abstraction.test.ts": 109,+ "test/asymmetric-encoding-contract.test.ts": 3,+ "test/audit/audit-dir-preload.test.ts": 0,+ "test/audit/audit-writer.test.ts": 10,+ "test/audit/batch-retry-audit.test.ts": 11,+ "test/audit/batch-retry-redaction.test.ts": 6,+ "test/audit/content-sanity-audit.test.ts": 9,+ "test/audit/lock-renewal-audit.test.ts": 8,+ "test/audit/pool-recovery-audit.test.ts": 17,+ "test/audit/redact-connection-info.test.ts": 7,+ "test/auth-create-args.test.ts": 10,+ "test/auth-register-client-args.test.ts": 9,+ "test/auto-think-phase.test.ts": 542,+ "test/autopilot-auto-drain-wiring.test.ts": 4,+ "test/autopilot-cycle-failure-classification.test.ts": 10,+ "test/autopilot-cycle-handler.test.ts": 478,+ "test/autopilot-cycle-source-checkout.test.ts": 680,+ "test/autopilot-drain-deadlock-2050.test.ts": 2945,+ "test/autopilot-failure-cooldown.test.ts": 968,+ "test/autopilot-fanout-wiring.test.ts": 8,+ "test/autopilot-fanout.test.ts": 32,+ "test/autopilot-global-maintenance.test.ts": 1805,+ "test/autopilot-install.test.ts": 12,+ "test/autopilot-lock-path.test.ts": 2,+ "test/autopilot-lock.test.ts": 10,+ "test/autopilot-nightly-probe-wiring.test.ts": 2,+ "test/autopilot-parser-probe-wiring.test.ts": 27,+ "test/autopilot-pause-marker.test.ts": 24,+ "test/autopilot-reconnect-classifier.test.ts": 22,+ "test/autopilot-resolve-cli.test.ts": 33,+ "test/autopilot-self-disable-and-status.test.ts": 28,+ "test/autopilot-self-upgrade.test.ts": 16,+ "test/autopilot-shutdown-engine-close.test.ts": 5,+ "test/autopilot-supervisor-wiring.test.ts": 16,+ "test/backfill-base.test.ts": 8,+ "test/backlink-count-mention-filter.test.ts": 2016,+ "test/backlinks-job-default.test.ts": 4,+ "test/backlinks.test.ts": 23,+ "test/backoff.test.ts": 1,+ "test/backpressure-audit-read.test.ts": 8,+ "test/balanced-reranker-default.test.ts": 5,+ "test/batch-projection.test.ts": 6,+ "test/bench-publish.test.ts": 18,+ "test/bench/baseline-file.test.ts": 4,+ "test/bench/correctness-gate.test.ts": 4,+ "test/bench/qrels-file.test.ts": 3,+ "test/binary-self-update.test.ts": 6,+ "test/book-mirror.test.ts": 652,+ "test/bootstrap-codex-door.test.ts": 24,+ "test/bootstrap-doctor-checks.test.ts": 3055,+ "test/bootstrap-harness-writers.test.ts": 27,+ "test/bootstrap-hooks-writers.test.ts": 23,+ "test/bootstrap-lock.test.ts": 11,+ "test/bootstrap-render.test.ts": 84,+ "test/bootstrap-repo.test.ts": 49,+ "test/bootstrap.test.ts": 19209,+ "test/brain-resolver.test.ts": 17,+ "test/brain-score-breakdown.test.ts": 2033,+ "test/brain-score-recommendations.test.ts": 8,+ "test/brain-writer-partial-scan.test.ts": 2031,+ "test/brain-writer-walk-prune.test.ts": 37,+ "test/brain-writer.test.ts": 966,+ "test/brainbench-adapters.test.ts": 965,+ "test/brainbench-continuity.test.ts": 1558,+ "test/brainbench-fixtures.test.ts": 29,+ "test/brainbench-generator.test.ts": 20,+ "test/brainbench-metrics.test.ts": 7,+ "test/brainbench-scoreboard.test.ts": 10,+ "test/brainbench-writeback.test.ts": 2032,+ "test/brainstorm-timeout.test.ts": 4,+ "test/brainstorm/cost-guardrails.test.ts": 39,+ "test/brainstorm/distance.test.ts": 1,+ "test/brainstorm/eval-brainstorm.test.ts": 4,+ "test/brainstorm/judges-maxtokens.test.ts": 5,+ "test/brainstorm/lsd-mode-skip.test.ts": 24,+ "test/brainstorm/model-config.test.ts": 6,+ "test/brainstorm/save.test.ts": 3236,+ "test/budget-meter.test.ts": 11,+ "test/budget-tracker.test.ts": 433,+ "test/budget/free-local-chat-pricing.test.ts": 1,+ "test/build-llms.test.ts": 15,+ "test/by-mention.test.ts": 487,+ "test/cache-scope-key.test.ts": 1,+ "test/calibration-cli.test.ts": 12,+ "test/calibration-profile.test.ts": 9,+ "test/candidate-audit.test.ts": 20,+ "test/capability.test.ts": 3,+ "test/capture-build-content.test.ts": 21,+ "test/capture-runcapture.test.ts": 4,+ "test/cathedral-ii-brainbench.test.ts": 650,+ "test/check-bootstrap-guards.test.ts": 1307,+ "test/check-jsonb-params.test.ts": 60,+ "test/check-resolvable-cli.test.ts": 4394,+ "test/check-resolvable-openclaw-compact.test.ts": 15,+ "test/check-resolvable.test.ts": 172,+ "test/check-system-of-record.test.ts": 57,+ "test/check-update.test.ts": 1248,+ "test/child-worker-supervisor.test.ts": 1953,+ "test/chronicle-advisor.test.ts": 384,+ "test/chronicle-backfill.test.ts": 328,+ "test/chronicle-capture.test.ts": 162,+ "test/chronicle-context.test.ts": 345,+ "test/chronicle-delight.test.ts": 376,+ "test/chronicle-doctor.test.ts": 361,+ "test/chronicle-extract.test.ts": 497,+ "test/chronicle-ontology-ops.test.ts": 2110,+ "test/chronicle-ontology.test.ts": 426,+ "test/chronicle-search-boost.test.ts": 5,+ "test/chronicle-timeline-reads.test.ts": 393,+ "test/chunk-grain-fts.test.ts": 736,+ "test/chunker-timeout.test.ts": 23,+ "test/chunker-version-gate.test.ts": 2,+ "test/chunker-version-insert-default.test.ts": 362,+ "test/chunkers/cap-oversized-cjk.test.ts": 210,+ "test/chunkers/code.test.ts": 90,+ "test/chunkers/embed-estimate-home.test.ts": 680,+ "test/chunkers/recursive.test.ts": 396,+ "test/cjk.test.ts": 4,+ "test/claude-cli-recipe.test.ts": 107,+ "test/claude-code-jsonl.test.ts": 10,+ "test/claw-test-cli.test.ts": 49,+ "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-dream-engine-warn.test.ts": 4153,+ "test/cli-empty-retrieval-render.test.ts": 3,+ "test/cli-exit-verdict-pin.test.ts": 30,+ "test/cli-finish-teardown.test.ts": 2554,+ "test/cli-flag-validation.test.ts": 1931,+ "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-multimodal-integration.test.ts": 441,+ "test/cli-options.test.ts": 2858,+ "test/cli-pipe-truncation.test.ts": 1118,+ "test/cli-query-image.test.ts": 42,+ "test/cli-search-dispatch.test.ts": 11165,+ "test/cli-should-force-exit.test.ts": 15,+ "test/cli-stdin-hang.test.ts": 3369,+ "test/cli.test.ts": 4757,+ "test/client-slug-fence.test.ts": 29,+ "test/code-callers-cli.test.ts": 3,+ "test/code-def-refs.test.ts": 488,+ "test/code-edges.test.ts": 568,+ "test/code-graph-readiness.test.ts": 573,+ "test/code-intel/edge-densification.test.ts": 58,+ "test/code-intel/eval-capture-graph.test.ts": 4,+ "test/code-intel/recursive-walk.test.ts": 1801,+ "test/code-intel/scope-walker-resolution.test.ts": 38,+ "test/code-intel/traversal-cache.test.ts": 3463,+ "test/code-retrieval-harness.test.ts": 22,+ "test/code-scoped-source-resolve.test.ts": 1826,+ "test/codex-toml.test.ts": 8,+ "test/commands-search.test.ts": 401,+ "test/commands/capture.test.ts": 3175,+ "test/commands/schema-packpath.test.ts": 14,+ "test/config-ensure-gitignore.test.ts": 4,+ "test/config-env-hijack.test.ts": 9,+ "test/config-env.test.ts": 1,+ "test/config-file-plane-keys.test.ts": 10,+ "test/config-get-plane.test.ts": 7,+ "test/config-set.test.ts": 18,+ "test/config-show-object-values.test.ts": 8,+ "test/config-unset.test.ts": 373,+ "test/config.test.ts": 10,+ "test/connect.test.ts": 58,+ "test/connection-resilience.test.ts": 8,+ "test/console-prefix.test.ts": 5,+ "test/consolidate-valid-until.test.ts": 468,+ "test/content-sanity-literals.test.ts": 3,+ "test/content-sanity.test.ts": 18,+ "test/context-engine.test.ts": 43,+ "test/context/entity-salience.test.ts": 4,+ "test/context/resolve-ipc.test.ts": 10,+ "test/contextual-retrieval-resolver.test.ts": 6,+ "test/contextual-retrieval-service-pure.test.ts": 232,+ "test/conversation-parser-cli.test.ts": 26,+ "test/conversation-parser-normalize-block.test.ts": 19,+ "test/conversation-parser/llm-base.test.ts": 8,+ "test/conversation-parser/llm-fallback.test.ts": 31,+ "test/conversation-parser/llm-polish.test.ts": 8,+ "test/conversation-parser/nightly-probe.test.ts": 6,+ "test/conversation-parser/parse.test.ts": 39,+ "test/core/background-work.test.ts": 23,+ "test/core/base-phase.test.ts": 5,+ "test/core/budget/budget-tracker.test.ts": 15,+ "test/core/diarize/payload-fitter-summarize.test.ts": 7,+ "test/core/git-head.test.ts": 14,+ "test/core/retry-reconnect.test.ts": 91,+ "test/core/retry-stress.slow.test.ts": 207,+ "test/core/retry.test.ts": 653,+ "test/cosine-rescore-column.test.ts": 400,+ "test/cross-brain-calibration.test.ts": 173,+ "test/cross-modal-default-slots.test.ts": 23,+ "test/cross-modal-eval-aggregate.test.ts": 8,+ "test/cross-modal-eval-cli.test.ts": 17,+ "test/cross-modal-eval-json-repair.test.ts": 7,+ "test/cross-modal-phase1.test.ts": 6,+ "test/cross-modal-phase2.test.ts": 58,+ "test/cycle-abort.test.ts": 114,+ "test/cycle-any-abort-signal.test.ts": 217,+ "test/cycle-auto-think-config-zero.test.ts": 7,+ "test/cycle-consolidate.test.ts": 432,+ "test/cycle-dream-output-root.test.ts": 409,+ "test/cycle-enabled-phase-completeness.test.ts": 934,+ "test/cycle-extract-source.test.ts": 616,+ "test/cycle-last-full-cycle-at.test.ts": 1075,+ "test/cycle-legacy-phases.test.ts": 1799,+ "test/cycle-lock-per-source.test.ts": 120,+ "test/cycle-pack-gating.test.ts": 4,+ "test/cycle-patterns-child-outcome.test.ts": 1289,+ "test/cycle-patterns-deadline-budget.test.ts": 431,+ "test/cycle-patterns-source-scope.test.ts": 284,+ "test/cycle-patterns.test.ts": 21,+ "test/cycle-stamp-write-failure.test.ts": 1237,+ "test/cycle-synthesize-braindir-resolve.test.ts": 579,+ "test/cycle-synthesize-chunker.test.ts": 2,+ "test/cycle-synthesize-config-zero.test.ts": 24,+ "test/cycle-synthesize-md-discovery.test.ts": 18,+ "test/cycle-synthesize-slug-collection.test.ts": 415,+ "test/cycle-synthesize-subagent-timeout.test.ts": 656,+ "test/cycle-synthesize.test.ts": 18,+ "test/cycle/cycle-lock-ttl.test.ts": 3,+ "test/cycle/extract-atoms-batch.test.ts": 920,+ "test/cycle/extract-atoms-progress.test.ts": 2595,+ "test/cycle/extract-atoms-synthesize-concepts.test.ts": 4546,+ "test/cycle/extract-atoms-work-interleave.test.ts": 1095,+ "test/cycle/nightly-probe-adapters.test.ts": 1,+ "test/cycle/regression-pr-wave-r1-r2-r4.test.ts": 4,+ "test/cycle/synthesize-concepts-progress.test.ts": 1956,+ "test/cycle/synthesize-gateway-adapter.test.ts": 15,+ "test/cycle/yield-during-phase-refresh.test.ts": 1,+ "test/cycle/yield-during-phase-throttle.test.ts": 840,+ "test/data-research.test.ts": 8,+ "test/database-url-guard-preload.test.ts": 458,+ "test/db-disconnect-audit.test.ts": 25,+ "test/db-guard-coverage.test.ts": 296,+ "test/db-lock-auto-takeover.test.ts": 1961,+ "test/db-lock-election.test.ts": 1926,+ "test/db-lock-fencing.test.ts": 861,+ "test/db-lock-heartbeat-takeover.test.ts": 436,+ "test/db-lock-inspect.test.ts": 1424,+ "test/db-lock-per-source.test.ts": 1109,+ "test/db-lock-reap.test.ts": 377,+ "test/db-lock-refresh.test.ts": 7,+ "test/db-pacer.test.ts": 9,+ "test/dedup.test.ts": 9,+ "test/default-model-panels.test.ts": 15,+ "test/denied-after-list.test.ts": 357,+ "test/destructive-guard.test.ts": 4308,+ "test/disk-walk.test.ts": 9,+ "test/dispatch-localonly.test.ts": 4,+ "test/distribution-import-boundary.test.ts": 5,+ "test/docs-cli-commands.test.ts": 71,+ "test/doctor-asset-paths.test.ts": 2,+ "test/doctor-batch-retry.test.ts": 16,+ "test/doctor-behavioral.test.ts": 4869,+ "test/doctor-brain-checks-score.test.ts": 19,+ "test/doctor-calibration-checks.test.ts": 37,+ "test/doctor-categories.test.ts": 12,+ "test/doctor-cause-rank.test.ts": 27,+ "test/doctor-child-orphans.test.ts": 30,+ "test/doctor-conversation-facts-backlog.test.ts": 2420,+ "test/doctor-cycle-freshness.test.ts": 3474,+ "test/doctor-cycle-phase-scope.test.ts": 6,+ "test/doctor-drift-advice.test.ts": 61,+ "test/doctor-embedding-env-override.test.ts": 2446,+ "test/doctor-extract-atoms-backlog.test.ts": 983,+ "test/doctor-extract-health.test.ts": 317,+ "test/doctor-federation-health.test.ts": 1026,+ "test/doctor-fix.test.ts": 2824,+ "test/doctor-frontmatter-partial.test.ts": 6,+ "test/doctor-hidden-by-search-policy.test.ts": 1335,+ "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-orphan-ratio.test.ts": 4731,+ "test/doctor-parser-probe-check.test.ts": 6,+ "test/doctor-pglite-datadir.test.ts": 13,+ "test/doctor-pglite-scratch-probe.test.ts": 6472,+ "test/doctor-pool-reap-health.test.ts": 15,+ "test/doctor-raw-provenance.test.ts": 402,+ "test/doctor-remediation-plan-render.test.ts": 75,+ "test/doctor-retrieval-reflex.test.ts": 14,+ "test/doctor-scope-filter.test.ts": 47,+ "test/doctor-search-mode.test.ts": 975,+ "test/doctor-self-upgrade.test.ts": 31,+ "test/doctor-silent-death-checks.test.ts": 2184,+ "test/doctor-source-config-shape.test.ts": 10,+ "test/doctor-subagent-health.test.ts": 2043,+ "test/doctor-supervisor-singleton-pidfile.test.ts": 2017,+ "test/doctor-sync-consolidation.test.ts": 968,+ "test/doctor-timeline-metric-labels-2298.test.ts": 3717,+ "test/doctor-v0_37_7_checks.test.ts": 434,+ "test/doctor-v0_41_13_checks.test.ts": 2965,+ "test/doctor-volunteer-channels.test.ts": 18,+ "test/doctor-wedged-queue.test.ts": 1955,+ "test/doctor-worker-oom-loop.test.ts": 6,+ "test/doctor-ze-checks.test.ts": 1378,+ "test/doctor.test.ts": 4964,+ "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/drift-watch.test.ts": 16,+ "test/dry-fix.test.ts": 220,+ "test/durability-cron.test.ts": 15,+ "test/edge-extractor.test.ts": 125,+ "test/effective-date.test.ts": 2,+ "test/embed-backfill-submit.test.ts": 445,+ "test/embed-helper-migration.test.ts": 2,+ "test/embed-keyless-guard.test.ts": 15,+ "test/embed-modality-preserved.test.ts": 371,+ "test/embed-multimodal-batching.test.ts": 19,+ "test/embed-preflight.test.ts": 9,+ "test/embed-skip.test.ts": 4,+ "test/embedding-context.test.ts": 7,+ "test/embedding-dim-check-facts.test.ts": 16,+ "test/embedding-dim-check.test.ts": 1839,+ "test/embedding-migration.test.ts": 3372,+ "test/embedding-model-dims.test.ts": 27,+ "test/embedding-pricing.test.ts": 8,+ "test/embedding-signature-stale.test.ts": 1091,+ "test/emotional-weight.test.ts": 20,+ "test/engine-factory.test.ts": 0,+ "test/engine-find-trajectory.test.ts": 381,+ "test/engine-parity-event-type.test.ts": 388,+ "test/engine-resolve-slug-with-alias.test.ts": 1292,+ "test/engine-upsertFile.test.ts": 1110,+ "test/engine-weight-rounding-integration.test.ts": 364,+ "test/enrich-cycle-phase.test.ts": 799,+ "test/enrich/idempotency.test.ts": 3,+ "test/enrich/thin.test.ts": 3,+ "test/enrichable-pack.test.ts": 8,+ "test/enrichment-service.test.ts": 2,+ "test/enrichment.test.ts": 2772,+ "test/entity-card-perf.slow.test.ts": 38698,+ "test/entity-resolve-perf.slow.test.ts": 4665,+ "test/entity-resolve-slug-fallback.test.ts": 417,+ "test/entity-resolve.test.ts": 412,+ "test/env-number.test.ts": 3,+ "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-candidates.test.ts": 379,+ "test/eval-capture-drain.test.ts": 153,+ "test/eval-capture-scrub.test.ts": 31,+ "test/eval-capture.test.ts": 5,+ "test/eval-chronicle.test.ts": 334,+ "test/eval-compare.test.ts": 48,+ "test/eval-contradictions-auto-supersession.test.ts": 7,+ "test/eval-contradictions-cache.test.ts": 3386,+ "test/eval-contradictions-calibration-join.test.ts": 7,+ "test/eval-contradictions-calibration.test.ts": 1,+ "test/eval-contradictions-cost-prompt.test.ts": 1351,+ "test/eval-contradictions-cost.test.ts": 7,+ "test/eval-contradictions-cross-source.test.ts": 4,+ "test/eval-contradictions-date-filter.test.ts": 6,+ "test/eval-contradictions-engine.test.ts": 3671,+ "test/eval-contradictions-fixture-redact.test.ts": 1,+ "test/eval-contradictions-integrations.test.ts": 3245,+ "test/eval-contradictions-judge-errors.test.ts": 32,+ "test/eval-contradictions-judge.test.ts": 14,+ "test/eval-contradictions-runner.test.ts": 3601,+ "test/eval-contradictions-severity.test.ts": 6,+ "test/eval-contradictions-trends.test.ts": 2833,+ "test/eval-contradictions/cost-tracker-slash.test.ts": 7,+ "test/eval-contradictions/no-valid-until-write.test.ts": 32,+ "test/eval-conversation-parser-cli.test.ts": 12,+ "test/eval-cross-modal-batch.test.ts": 136,+ "test/eval-export.test.ts": 382,+ "test/eval-gate.test.ts": 1463,+ "test/eval-longmemeval.slow.test.ts": 4231,+ "test/eval-prune.test.ts": 1899,+ "test/eval-replay-gate.test.ts": 1541,+ "test/eval-replay-metadata-skip.test.ts": 588,+ "test/eval-replay.test.ts": 29,+ "test/eval-retrieval-quality.test.ts": 615,+ "test/eval-run-all.test.ts": 15,+ "test/eval-schema-authoring.test.ts": 1,+ "test/eval-shared-json-repair-shim.test.ts": 4,+ "test/eval-suspected-contradictions-budget-default.test.ts": 5,+ "test/eval-takes-quality-aggregate.test.ts": 5,+ "test/eval-takes-quality-boundaries.test.ts": 435,+ "test/eval-takes-quality-cli.test.ts": 14,+ "test/eval-takes-quality-pricing.test.ts": 4,+ "test/eval-takes-quality-receipt-name.test.ts": 4,+ "test/eval-takes-quality-receipt-write.test.ts": 375,+ "test/eval-takes-quality-regress.test.ts": 5,+ "test/eval-takes-quality-replay.test.ts": 366,+ "test/eval-takes-quality-rubric.test.ts": 17,+ "test/eval-takes-quality-trend.test.ts": 343,+ "test/eval-trajectory.test.ts": 917,+ "test/eval-v041_2-scaffolds.test.ts": 26,+ "test/eval-whoknows.test.ts": 5,+ "test/eval.test.ts": 9,+ "test/eval/cycle-default.test.ts": 3,+ "test/execution-env.test.ts": 1,+ "test/exit-classification.test.ts": 12,+ "test/expert-types-pack.test.ts": 61,+ "test/extract-abort.test.ts": 1928,+ "test/extract-atoms-chunk-embed.test.ts": 456,+ "test/extract-atoms-drain-handler.test.ts": 384,+ "test/extract-atoms-drain.test.ts": 5,+ "test/extract-atoms-extractable-types.test.ts": 6,+ "test/extract-atoms-page-discovery.test.ts": 5398,+ "test/extract-atoms-unpriced-model.test.ts": 19,+ "test/extract-by-mention-resume.test.ts": 474,+ "test/extract-by-mention.test.ts": 559,+ "test/extract-conversation-facts-workers.test.ts": 4,+ "test/extract-conversation-facts.test.ts": 3114,+ "test/extract-db.test.ts": 511,+ "test/extract-facts-phase.test.ts": 718,+ "test/extract-from-fence.test.ts": 4,+ "test/extract-fs-source-id.test.ts": 913,+ "test/extract-fs.test.ts": 556,+ "test/extract-incremental.test.ts": 1627,+ "test/extract-source-aware.test.ts": 468,+ "test/extract-stale.test.ts": 662,+ "test/extract-takes-from-pages-progression.test.ts": 340,+ "test/extract-takes-holder-producer-seam.test.ts": 452,+ "test/extract-takes-model-resolution.test.ts": 413,+ "test/extract-takes.test.ts": 788,+ "test/extract-workers.test.ts": 3,+ "test/extract.test.ts": 27,+ "test/extract/benchmark.test.ts": 8,+ "test/extract/receipt-writer.test.ts": 1064,+ "test/extract/status.test.ts": 16,+ "test/extractable-pack.test.ts": 73,+ "test/extractable-spec-widening.test.ts": 22,+ "test/extraction-review.test.ts": 3323,+ "test/facts-absorb-log.test.ts": 326,+ "test/facts-anti-loop.test.ts": 552,+ "test/facts-backstop-gating.test.ts": 2130,+ "test/facts-backstop-integration.test.ts": 405,+ "test/facts-backstop.test.ts": 413,+ "test/facts-canonicality.test.ts": 374,+ "test/facts-classify.test.ts": 4,+ "test/facts-decay.test.ts": 12,+ "test/facts-doctor-shape.test.ts": 405,+ "test/facts-eligibility.test.ts": 108,+ "test/facts-engine.test.ts": 426,+ "test/facts-extract-salvage.test.ts": 10,+ "test/facts-extract-silent-no-op.test.ts": 3,+ "test/facts-extract-smoke.test.ts": 6,+ "test/facts-extract-truncation.test.ts": 19,+ "test/facts-extract.test.ts": 17,+ "test/facts-fence-typed.test.ts": 10,+ "test/facts-fence.test.ts": 21,+ "test/facts-meta-cache.test.ts": 382,+ "test/facts-migration-dim.test.ts": 2470,+ "test/facts-multi-tenant.test.ts": 1948,+ "test/facts-queue-drain-pending.test.ts": 1624,+ "test/facts-queue.test.ts": 629,+ "test/facts-recall-render.test.ts": 339,+ "test/facts-reconcile-protect-cli.test.ts": 355,+ "test/facts-separation-pglite.test.ts": 1930,+ "test/facts-unknown-speaker-gate.test.ts": 10,+ "test/facts-visibility.test.ts": 362,+ "test/fail-improve.test.ts": 103,+ "test/feature-flags.test.ts": 2571,+ "test/features.test.ts": 14,+ "test/fence-extraction.test.ts": 2788,+ "test/fence-write.test.ts": 363,+ "test/file-migration.test.ts": 11,+ "test/file-resolver.test.ts": 10,+ "test/file-upload-engine-context.test.ts": 306,+ "test/file-upload-security.test.ts": 1,+ "test/files.test.ts": 11,+ "test/filing-audit.test.ts": 18,+ "test/find-experts-op.test.ts": 515,+ "test/fix-wave-structural.test.ts": 12,+ "test/flush-then-exit-harness.test.ts": 2117,+ "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-inference.test.ts": 7,+ "test/frontmatter-install-hook.test.ts": 46,+ "test/frontmatter-non-string-fields.test.ts": 5,+ "test/frontmatter-validate-slug-565.test.ts": 1689,+ "test/fuzz/filesystem-validators.test.ts": 26,+ "test/fuzz/mixed-validators.test.ts": 103,+ "test/fuzz/pure-validators.test.ts": 84,+ "test/gateway-embed-model-override.test.ts": 7,+ "test/gateway-model-messages.test.ts": 6,+ "test/gbrain-home-isolation.test.ts": 4,+ "test/get-agent-job.test.ts": 1802,+ "test/get-brain-identity.test.ts": 1492,+ "test/get-page-federated-scope.test.ts": 4423,+ "test/get-status-snapshot-op.test.ts": 316,+ "test/get-timeline-op.test.ts": 41,+ "test/git-remote.test.ts": 276,+ "test/grade-takes-ensemble.test.ts": 48,+ "test/grade-takes.test.ts": 46,+ "test/graph-query.test.ts": 514,+ "test/gstack-learnings-coupling.test.ts": 25,+ "test/guardrails.test.ts": 31,+ "test/handlers-embed-backfill.test.ts": 483,+ "test/handlers.test.ts": 774,+ "test/health-soft-delete.test.ts": 455,+ "test/helpers/agent-harness.unit.test.ts": 24,+ "test/helpers/schema-diff-indexes.test.ts": 1,+ "test/helpers/schema-diff.test.ts": 5,+ "test/helpers/with-env.test.ts": 1,+ "test/http-transport.test.ts": 131,+ "test/hybrid-recency-config.test.ts": 4,+ "test/import-abort-error.test.ts": 10,+ "test/import-checkpoint.test.ts": 495,+ "test/import-clear-failures-on-success.test.ts": 2019,+ "test/import-code-edges-source-id.test.ts": 349,+ "test/import-dedup-frontmatter-id.test.ts": 2623,+ "test/import-error-summary.test.ts": 0,+ "test/import-file-content-sanity.test.ts": 4133,+ "test/import-file.test.ts": 145,+ "test/import-git-fastpath-prune.test.ts": 53,+ "test/import-image-file.test.ts": 2935,+ "test/import-metafile-skip.test.ts": 17,+ "test/import-repo-path-guard.test.ts": 815,+ "test/import-resume.test.ts": 1631,+ "test/import-source-id.test.ts": 460,+ "test/import-walker.test.ts": 14,+ "test/import-yaml-frontmatter.test.ts": 8,+ "test/incremental-chunking.test.ts": 2063,+ "test/infer-type-pack.test.ts": 10,+ "test/ingestion/daemon.test.ts": 68,+ "test/ingestion/dedup.test.ts": 5,+ "test/ingestion/gstack-learnings.test.ts": 2,+ "test/ingestion/ingest-capture.test.ts": 2458,+ "test/ingestion/markdown-greenfield.test.ts": 12,+ "test/ingestion/migration-mode.test.ts": 21,+ "test/ingestion/put-page-write-through.test.ts": 1662,+ "test/ingestion/skillpack-load.test.ts": 19,+ "test/ingestion/sources/file-watcher.test.ts": 480,+ "test/ingestion/sources/inbox-folder.test.ts": 554,+ "test/ingestion/test-harness.test.ts": 70,+ "test/ingestion/types.test.ts": 6,+ "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-mode-picker.test.ts": 2058,+ "test/init-nudge.test.ts": 5,+ "test/init-provider-picker.test.ts": 13,+ "test/insert-facts-batch.test.ts": 380,+ "test/integrations-heartbeat-max-age.test.ts": 12,+ "test/integrations-install.test.ts": 161,+ "test/integrations.test.ts": 26,+ "test/integrity.test.ts": 2260,+ "test/intent-weights.test.ts": 8,+ "test/job-pull-policy.test.ts": 75,+ "test/jobs-format-detail.test.ts": 1,+ "test/jobs-nice-flag.test.ts": 8,+ "test/jobs-thin-client-date-rehydration.test.ts": 69,+ "test/jobs-unify-types-default-dryrun.test.ts": 1331,+ "test/jobs-watch-mode.test.ts": 11,+ "test/jobs-watch-snapshot.test.ts": 4,+ "test/language-manifest.test.ts": 104,+ "test/last-retrieved.test.ts": 292,+ "test/lease-cap-controller.test.ts": 421,+ "test/legacy-token-federated-scope.test.ts": 19,+ "test/lens-pack-manifests.test.ts": 19,+ "test/levenshtein.test.ts": 5,+ "test/link-extraction-code-refs.test.ts": 2,+ "test/link-extraction-dir-whitelist-2576.test.ts": 7,+ "test/link-extraction.test.ts": 30,+ "test/link-inference-pack.test.ts": 18,+ "test/link-source-namespaced-regex.test.ts": 650,+ "test/links-timeline-jsonb-poison.test.ts": 2157,+ "test/lint-content-sanity.test.ts": 30,+ "test/lint-fix-single-pass.test.ts": 3,+ "test/lint-frontmatter.test.ts": 19,+ "test/lint-shared-engine.test.ts": 17,+ "test/lint.test.ts": 23,+ "test/list-all-sources.test.ts": 1511,+ "test/list-clamp-local-trust.test.ts": 488,+ "test/list-pages-truncation.test.ts": 2302,+ "test/llm-intent-escalation.test.ts": 4,+ "test/loadConfig-merge.test.ts": 20,+ "test/local-federated-search-scope.test.ts": 405,+ "test/longmemeval-extract.test.ts": 349,+ "test/longmemeval-intent.test.ts": 16,+ "test/longmemeval-sanitize.test.ts": 15,+ "test/longmemeval-trajectory-routing.test.ts": 2610,+ "test/maintain.test.ts": 17,+ "test/markdown-serializer.test.ts": 7,+ "test/markdown-validation.test.ts": 11,+ "test/markdown.test.ts": 10,+ "test/mcp-client-hardening.test.ts": 290,+ "test/mcp-client.test.ts": 56,+ "test/mcp-dispatch-optional-params.test.ts": 1901,+ "test/mcp-dispatch-summarize.test.ts": 3,+ "test/mcp-eval-capture.test.ts": 1136,+ "test/mcp-stdio-source-resolution.test.ts": 22,+ "test/mcp-surface.test.ts": 405,+ "test/mcp-tool-defs.test.ts": 24,+ "test/mcp-usage.test.ts": 292,+ "test/memory-verbs-conformance.test.ts": 6235,+ "test/metric-glossary.test.ts": 15,+ "test/migrate-engine-resume.test.ts": 0,+ "test/migrate-extensions.test.ts": 2,+ "test/migrate-retry.test.ts": 124,+ "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-resume.test.ts": 18,+ "test/migration-v120.test.ts": 338,+ "test/migrations-cjk-wave.test.ts": 350,+ "test/migrations-registry.test.ts": 9,+ "test/migrations-v0_11_0.test.ts": 15,+ "test/migrations-v0_12_0.test.ts": 23,+ "test/migrations-v0_12_2.test.ts": 13,+ "test/migrations-v0_13_0.test.ts": 21,+ "test/migrations-v0_13_1-grandfather.test.ts": 3176,+ "test/migrations-v0_13_1.test.ts": 17,+ "test/migrations-v0_14_0.test.ts": 15,+ "test/migrations-v0_16_0.test.ts": 6,+ "test/migrations-v0_19_0.test.ts": 2637,+ "test/migrations-v0_21_0.test.ts": 7,+ "test/migrations-v0_22_4.test.ts": 4,+ "test/migrations-v0_27_1.test.ts": 2126,+ "test/migrations-v0_32_2.test.ts": 483,+ "test/migrations-v126.test.ts": 1885,+ "test/migrations-v128.test.ts": 465,+ "test/migrations-v48-takes-weight-backfill.test.ts": 403,+ "test/migrations-v94.test.ts": 1581,+ "test/migrations-v99.test.ts": 1760,+ "test/minions-lease-full-retry.test.ts": 445,+ "test/minions-quiet-hours.test.ts": 2009,+ "test/minions-shell-inherit.test.ts": 5,+ "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/agent-audit.test.ts": 9,+ "test/mode-switch-ux.test.ts": 800,+ "test/model-id.test.ts": 5,+ "test/model-pricing.test.ts": 7,+ "test/models-doctor-embed.test.ts": 7,+ "test/models-doctor-reranker.test.ts": 25,+ "test/models-doctor-v1-hint.test.ts": 18,+ "test/mounts-cache.test.ts": 25,+ "test/mounts-cli.test.ts": 61,+ "test/multi-source-drift.test.ts": 404,+ "test/multi-source-integration.test.ts": 2064,+ "test/niceness.test.ts": 3,+ "test/nightly-probe-config-plane.test.ts": 14,+ "test/nightly-quality-probe.test.ts": 19,+ "test/no-tracked-symlinks-guard.test.ts": 54,+ "test/notability-eval.test.ts": 21,+ "test/npm-squat-check.test.ts": 2,+ "test/nudge.test.ts": 43,+ "test/oauth-authorize-scope-default.test.ts": 355,+ "test/oauth-confidential-client.test.ts": 380,+ "test/oauth-dcr-ttl.test.ts": 2272,+ "test/oauth-scope-probe.test.ts": 8,+ "test/oauth-surface-ladder.test.ts": 2820,+ "test/oauth.test.ts": 3183,+ "test/onboard-pack-upgrade-checks.test.ts": 3181,+ "test/op-checkpoint-mentions-fingerprint.test.ts": 4,+ "test/op-checkpoint.test.ts": 5748,+ "test/openai-compat-multimodal.test.ts": 9,+ "test/openclaw-plugin-manifest.test.ts": 7,+ "test/openrouter-reranker-recipe.test.ts": 2,+ "test/operation-context-sourceid-required.test.ts": 4,+ "test/operations-allow-list.test.ts": 24,+ "test/operations-descriptions.test.ts": 6,+ "test/operations-embedding-column.test.ts": 2,+ "test/operations-find-trajectory.test.ts": 421,+ "test/operations-fuzzy-source-scope.test.ts": 2687,+ "test/operations-schema-pack.test.ts": 3424,+ "test/operations-trust-boundary.test.ts": 3504,+ "test/orphans-pure-fn.test.ts": 529,+ "test/orphans-source-scope.test.ts": 520,+ "test/orphans.test.ts": 2409,+ "test/owner-holder.test.ts": 18,+ "test/pace-mode.test.ts": 17,+ "test/page-generation-counter.test.ts": 3921,+ "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/parallel.test.ts": 122,+ "test/parent-scope.test.ts": 443,+ "test/parity.test.ts": 9,+ "test/path-confine.test.ts": 13,+ "test/performfullsync-source-id.test.ts": 638,+ "test/pglite-engine.test.ts": 1610,+ "test/pglite-init-classifier.test.ts": 17,+ "test/pglite-leftovers-check.test.ts": 9,+ "test/pglite-lock.test.ts": 7031,+ "test/pglite-repair.test.ts": 120,+ "test/pglite-resetwal.test.ts": 39,+ "test/pglite-workers-clamp.test.ts": 6,+ "test/phantom-redirect-engine-parity.test.ts": 1254,+ "test/phantom-redirect-per-source-lock.test.ts": 2,+ "test/phantom-redirect.test.ts": 4511,+ "test/phase-scope-coverage.test.ts": 1,+ "test/plugin-loader.test.ts": 11,+ "test/post-install-advisory.test.ts": 40,+ "test/post-write-lint.test.ts": 3590,+ "test/postgres-disconnect-bounded.test.ts": 2504,+ "test/postgres-engine-config-reconnect.test.ts": 21,+ "test/postgres-engine-getter-selfheal.test.ts": 15,+ "test/postgres-engine-rls-scope.test.ts": 8,+ "test/postgres-engine-singleton-ownership.test.ts": 4,+ "test/postgres-engine.test.ts": 13,+ "test/postgres-execute-raw-direct.test.ts": 33,+ "test/preferences.test.ts": 14,+ "test/privacy-script-wired.test.ts": 9,+ "test/privacy-strip-and-forget.test.ts": 440,+ "test/process-cleanup.test.ts": 3035,+ "test/process-watchdog.test.ts": 5,+ "test/progress-tail.test.ts": 3,+ "test/progress.test.ts": 330,+ "test/progressive-batch/orchestrator.test.ts": 77,+ "test/progressive-batch/retrofit-wrap.test.ts": 9,+ "test/propose-takes-per-claim.test.ts": 1903,+ "test/propose-takes.test.ts": 49,+ "test/providers-test-model-base-url.test.ts": 1,+ "test/providers.test.ts": 2,+ "test/public-exports.test.ts": 52,+ "test/publish-gates.test.ts": 9,+ "test/publish.test.ts": 120,+ "test/put-page-dedup-fence.test.ts": 1499,+ "test/put-page-empty-guard.test.ts": 1614,+ "test/put-page-namespace.test.ts": 8,+ "test/put-page-provenance.test.ts": 2382,+ "test/put-page-writer-lint.test.ts": 2084,+ "test/qualified-names.test.ts": 2,+ "test/quarantine-cli.test.ts": 1672,+ "test/quarantine.test.ts": 10,+ "test/query-cache-gate.test.ts": 917,+ "test/query-cache.test.ts": 2149,+ "test/query-intent-concept.test.ts": 5,+ "test/query-intent-legacy.test.ts": 6,+ "test/query-intent.test.ts": 10,+ "test/query-sanitization.test.ts": 4,+ "test/queue-child-done.test.ts": 490,+ "test/queue-getstats-wedge.test.ts": 398,+ "test/queue-lock-retry.test.ts": 14,+ "test/queue-stall-parent-unblock.test.ts": 415,+ "test/queue-started-at-retry.test.ts": 991,+ "test/rate-leases-uncapped.test.ts": 782,+ "test/rate-leases.test.ts": 431,+ "test/readme-hero-anchors.test.ts": 5,+ "test/recall-extensions.test.ts": 2447,+ "test/recall-footer.test.ts": 17,+ "test/recall-rollup.test.ts": 78,+ "test/recency-decay.test.ts": 6,+ "test/recompute-emotional-weight.test.ts": 7,+ "test/reconcile-links-cli-reachability.test.ts": 547,+ "test/redos-hardening.test.ts": 16,+ "test/register-client-source-normalize.test.ts": 3,+ "test/regression-strict-source-id.test.ts": 7,+ "test/regression-v0_16_4.test.ts": 13,+ "test/regressions/gbrain-base-equivalence.test.ts": 14,+ "test/regressions/v0.36.1.0-iron-rule.test.ts": 9,+ "test/regressions/v0_36_frontier_cap.test.ts": 2207,+ "test/regressions/v0_40_2_0-trajectory-backcompat.test.ts": 2006,+ "test/reindex-code.test.ts": 738,+ "test/reindex-cost-refusal.test.ts": 13,+ "test/reindex-frontmatter-connect.test.ts": 1889,+ "test/reindex-preserve-tags.test.ts": 2493,+ "test/reindex.test.ts": 519,+ "test/relational-ab.test.ts": 2763,+ "test/relational-fanout.test.ts": 447,+ "test/relational-intent.test.ts": 1,+ "test/relational-recall.test.ts": 412,+ "test/release-workflow.test.ts": 21,+ "test/remediation-step.test.ts": 8,+ "test/remote-ping-status-field.test.ts": 0,+ "test/repair-jsonb.test.ts": 12,+ "test/repo-root.test.ts": 9,+ "test/repo-visibility.test.ts": 134,+ "test/report.test.ts": 7,+ "test/repos-alias.test.ts": 1994,+ "test/request-tools.test.ts": 408,+ "test/rerank-audit.test.ts": 7,+ "test/resolve-ipc-v2.test.ts": 1187,+ "test/resolve-prepare.test.ts": 3,+ "test/resolver-merge.test.ts": 1,+ "test/resolver.test.ts": 141,+ "test/resolvers.test.ts": 4159,+ "test/restart-sweep.test.ts": 44,+ "test/retrieval-quality-harness.test.ts": 16,+ "test/retrieval-reflex.test.ts": 475,+ "test/retrieval-upgrade-planner.test.ts": 6111,+ "test/retry-matcher.test.ts": 18,+ "test/routing-eval-cli.test.ts": 1309,+ "test/routing-eval.test.ts": 9,+ "test/rrf-source-key.test.ts": 7,+ "test/rss-default.test.ts": 25,+ "test/salience.test.ts": 0,+ "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-migrate-link-source-mentions.test.ts": 443,+ "test/schema-pack-best-effort.test.ts": 8,+ "test/schema-pack-expand-type-filter.test.ts": 3,+ "test/schema-pack-infer-type-and-subtype.test.ts": 5,+ "test/schema-pack-lint-rules.test.ts": 13,+ "test/schema-pack-loader.test.ts": 21,+ "test/schema-pack-manifest-v041_2.test.ts": 7,+ "test/schema-pack-merge.test.ts": 10,+ "test/schema-pack-mutate-audit.test.ts": 18,+ "test/schema-pack-mutate.test.ts": 83,+ "test/schema-pack-pack-lock.test.ts": 66,+ "test/schema-pack-page-to-alias.test.ts": 894,+ "test/schema-pack-page-to-link.test.ts": 1168,+ "test/schema-pack-query-cache-invalidator.test.ts": 710,+ "test/schema-pack-registry-reload.test.ts": 42,+ "test/schema-pack-registry.test.ts": 1,+ "test/schema-pack-retype.test.ts": 3796,+ "test/schema-pack-rewrite-links-batch.test.ts": 743,+ "test/schema-pack-stats.test.ts": 2897,+ "test/schema-pack-sync.test.ts": 2743,+ "test/schema-pack-trust-boundary.test.ts": 6,+ "test/schema-pack-unify-types-handler.test.ts": 1611,+ "test/schema-pack/scaffold-extractable.test.ts": 9,+ "test/schema-verify.test.ts": 18,+ "test/scope-agent-isolation.test.ts": 5,+ "test/scope-normalize.test.ts": 13,+ "test/scope.test.ts": 5,+ "test/scripts/check-engine-dynamic-import.test.ts": 5332,+ "test/scripts/check-key-files-current-state.test.ts": 126,+ "test/scripts/check-proposal-pii.test.ts": 506,+ "test/scripts/check-skill-refs.test.ts": 1077,+ "test/scripts/check-test-isolation.test.ts": 279,+ "test/scripts/check-worker-lock-renewal-shape.test.ts": 30,+ "test/scripts/check-worker-pool-atomicity.test.ts": 117,+ "test/scripts/ci-cache-hash.test.ts": 1649,+ "test/scripts/evals-collection.test.ts": 996,+ "test/scripts/mine-shard-weights.test.ts": 10,+ "test/scripts/run-serial-pool.test.ts": 3082,+ "test/scripts/run-unit-parallel.test.ts": 1328,+ "test/scripts/run-unit-shard.test.ts": 195,+ "test/scripts/run-verify-parallel.test.ts": 2917,+ "test/scripts/serial-files.test.ts": 95,+ "test/scripts/sharding.test.ts": 8,+ "test/scripts/test-shard.slow.test.ts": 576,+ "test/search-alias-resolved-boost.test.ts": 783,+ "test/search-by-image-op.test.ts": 1044,+ "test/search-compiled-truth-boost-scope.test.ts": 4,+ "test/search-image-column.test.ts": 724,+ "test/search-lang-symbol-kind.test.ts": 346,+ "test/search-limit.test.ts": 348,+ "test/search-mode.test.ts": 9,+ "test/search-telemetry.test.ts": 400,+ "test/search-types-filter.test.ts": 424,+ "test/search.test.ts": 15,+ "test/search/alias-hop.test.ts": 1346,+ "test/search/alias-normalize.test.ts": 18,+ "test/search/attribution-stamping.test.ts": 5,+ "test/search/autocut-eval.test.ts": 4,+ "test/search/autocut.test.ts": 8,+ "test/search/evidence.test.ts": 5,+ "test/search/explain-formatter.test.ts": 23,+ "test/search/graph-signals-wire-integration.test.ts": 559,+ "test/search/graph-signals.test.ts": 30,+ "test/search/knobs-hash-reranker.test.ts": 12,+ "test/search/page-aliases-engine.test.ts": 2235,+ "test/search/per-call-mode.test.ts": 3,+ "test/search/pre-migration-failopen.test.ts": 2402,+ "test/search/query-embed-deadline.test.ts": 4044,+ "test/search/query-op-adaptive-return.test.ts": 4,+ "test/search/query-op-autocut.test.ts": 16,+ "test/search/reindex-aliases.test.ts": 840,+ "test/search/rerank.test.ts": 14,+ "test/search/return-policy.test.ts": 7,+ "test/search/search-diagnose.test.ts": 455,+ "test/search/search-stats-graph-signals.test.ts": 381,+ "test/search/searchvector-maxpool.test.ts": 2023,+ "test/search/telemetry-rank1.test.ts": 1669,+ "test/search/title-boost-stage.test.ts": 9,+ "test/search/title-match.test.ts": 11,+ "test/search/title-retrieval-arm.test.ts": 2566,+ "test/secret-scan.test.ts": 12,+ "test/select-e2e.test.ts": 25,+ "test/self-fix.test.ts": 1984,+ "test/self-upgrade-pending.test.ts": 25,+ "test/self-upgrade.test.ts": 28,+ "test/serve-http-bootstrap-token.test.ts": 115,+ "test/serve-http-cors.test.ts": 114,+ "test/serve-http-embedding-width.test.ts": 361,+ "test/serve-http-health.test.ts": 378,+ "test/serve-http-lifecycle.test.ts": 128,+ "test/serve-http-oauth-token-rate-limit.test.ts": 98,+ "test/serve-http-trust-proxy.test.ts": 95,+ "test/serve-skills-publish-nudge.test.ts": 192,+ "test/serve-stdio-lifecycle.test.ts": 1388,+ "test/session-state-gc.test.ts": 424,+ "test/setup-branching.test.ts": 7,+ "test/skill-brain-first.test.ts": 27,+ "test/skill-catalog-block-scalar.test.ts": 1,+ "test/skill-catalog-security.test.ts": 9,+ "test/skill-catalog-transports.test.ts": 1029,+ "test/skill-catalog.test.ts": 21,+ "test/skill-currency.test.ts": 10,+ "test/skill-manifest.test.ts": 12,+ "test/skill-preconditions.test.ts": 19,+ "test/skill-trigger-index.test.ts": 8,+ "test/skillify-check.test.ts": 1259,+ "test/skillify-scaffold.test.ts": 12,+ "test/skillopt/adversarial/resume-after-crash.test.ts": 13,+ "test/skillopt/apply-edits.test.ts": 2,+ "test/skillopt/audit.test.ts": 28,+ "test/skillopt/batch.test.ts": 3,+ "test/skillopt/benchmark.test.ts": 10,+ "test/skillopt/bootstrap-from-skill.test.ts": 27,+ "test/skillopt/held-out.test.ts": 21,+ "test/skillopt/lock.test.ts": 2790,+ "test/skillopt/lr-schedule.test.ts": 3,+ "test/skillopt/reflect.test.ts": 21,+ "test/skillopt/rejected-buffer.test.ts": 12,+ "test/skillopt/rollout-schema.test.ts": 16,+ "test/skillopt/rollout.test.ts": 1,+ "test/skillopt/score.test.ts": 8,+ "test/skillopt/validate-gate-abort.test.ts": 5,+ "test/skillopt/version-store.test.ts": 23,+ "test/skillopt/write-capture.test.ts": 1400,+ "test/skillpack-apply-hunks.test.ts": 24,+ "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-copy.test.ts": 12,+ "test/skillpack-endorse.test.ts": 95,+ "test/skillpack-frontmatter-sources.test.ts": 8,+ "test/skillpack-harvest-lint.test.ts": 7,+ "test/skillpack-harvest.test.ts": 17,+ "test/skillpack-init-brain-pack.test.ts": 4,+ "test/skillpack-init-pack.test.ts": 59,+ "test/skillpack-install.test.ts": 69,+ "test/skillpack-manifest-v1.test.ts": 8,+ "test/skillpack-migrate-fence.test.ts": 16,+ "test/skillpack-nag-state.test.ts": 30,+ "test/skillpack-reference-apply.test.ts": 26,+ "test/skillpack-reference-pack-is-ten.test.ts": 8,+ "test/skillpack-reference.test.ts": 17,+ "test/skillpack-registry-client.test.ts": 18,+ "test/skillpack-registry-schema.test.ts": 2,+ "test/skillpack-remote-source.test.ts": 73,+ "test/skillpack-rubric-doctor.test.ts": 38,+ "test/skillpack-scaffold-third-party.test.ts": 42,+ "test/skillpack-scaffold.test.ts": 34,+ "test/skillpack-scrub-legacy.test.ts": 7,+ "test/skillpack-state.test.ts": 5,+ "test/skillpack-status.test.ts": 10,+ "test/skillpack-tarball.test.ts": 129,+ "test/skillpack-trust-prompt.test.ts": 32,+ "test/skills-conformance.test.ts": 42,+ "test/skills-integrity.test.ts": 32,+ "test/slug-unicode-scripts.test.ts": 15,+ "test/slug-validation.test.ts": 9,+ "test/snapshot-shape-guard.test.ts": 14,+ "test/sort-newest-first.test.ts": 2,+ "test/source-config-redact.test.ts": 1,+ "test/source-health.test.ts": 643,+ "test/source-id-routing.test.ts": 949,+ "test/source-id-tx-regression.test.ts": 2082,+ "test/source-id.test.ts": 15,+ "test/source-resolver-silent-fallback.test.ts": 1784,+ "test/source-resolver-sole-non-default.test.ts": 8,+ "test/source-resolver-with-tier.test.ts": 27,+ "test/source-resolver.test.ts": 8,+ "test/source-scope-resolver.test.ts": 3,+ "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-resync-recovery.test.ts": 3664,+ "test/sources-set-cr-mode.test.ts": 1632,+ "test/sources-webhook.test.ts": 19,+ "test/sources.test.ts": 17,+ "test/spawn-helpers.test.ts": 4,+ "test/spend-off-switch.test.ts": 0,+ "test/sql-query.test.ts": 1445,+ "test/sql-ranking.test.ts": 6,+ "test/ssrf-validate.test.ts": 12,+ "test/status-autopilot-lock.test.ts": 9,+ "test/status-sections.test.ts": 38,+ "test/status-thin-client-skew.test.ts": 32,+ "test/storage-backfill.test.ts": 26,+ "test/storage-config.test.ts": 7,+ "test/storage-export.test.ts": 462,+ "test/storage-pglite.test.ts": 455,+ "test/storage-status.test.ts": 2,+ "test/storage-sync.test.ts": 34,+ "test/storage.test.ts": 130,+ "test/stub-guard-audit.test.ts": 8,+ "test/subagent-aggregator.test.ts": 12,+ "test/subagent-audit.test.ts": 13,+ "test/subagent-handler.test.ts": 637,+ "test/subagent-prompt-too-long.test.ts": 9,+ "test/subagent-transcript.test.ts": 979,+ "test/subagent-v1-v2-shim.test.ts": 2039,+ "test/submit-agent.test.ts": 2361,+ "test/submit-queue-state.test.ts": 3090,+ "test/sum-stale-chunk-chars.test.ts": 1044,+ "test/supabase-admin.test.ts": 20,+ "test/supervisor-audit.test.ts": 11,+ "test/supervisor-build-worker-args.test.ts": 6,+ "test/supervisor-db-lock.test.ts": 332,+ "test/supervisor-pid.test.ts": 3,+ "test/supervisor-tini.test.ts": 9,+ "test/supervisor-wedge.test.ts": 1960,+ "test/supervisor.test.ts": 2128,+ "test/surface-audit.test.ts": 8,+ "test/svg-renderer.test.ts": 3,+ "test/sweep.test.ts": 745,+ "test/sync-all-missing-path.test.ts": 7,+ "test/sync-all-parallel.test.ts": 8,+ "test/sync-baseline-guard.test.ts": 1,+ "test/sync-brain-op-source-id.test.ts": 2005,+ "test/sync-break-lock-all.test.ts": 3058,+ "test/sync-classifier-widening.test.ts": 2,+ "test/sync-concurrency.test.ts": 2,+ "test/sync-cost-estimate.test.ts": 220,+ "test/sync-cost-preview.test.ts": 25,+ "test/sync-delete-batch.slow.test.ts": 3258,+ "test/sync-delete-batch.test.ts": 1893,+ "test/sync-deleted-slug-embed.test.ts": 2254,+ "test/sync-delta.test.ts": 262,+ "test/sync-discover-git-root-stderr.test.ts": 374,+ "test/sync-failures.test.ts": 62,+ "test/sync-git-autoinit.test.ts": 2652,+ "test/sync-hard-deadline.test.ts": 3,+ "test/sync-isSyncable-shape.test.ts": 13,+ "test/sync-monorepo.test.ts": 2985,+ "test/sync-no-embed-sentinel.test.ts": 49,+ "test/sync-nudge-status-gate.test.ts": 11,+ "test/sync-parallel.test.ts": 4736,+ "test/sync-path-containment.test.ts": 13,+ "test/sync-reconcile-mass-delete.test.ts": 12,+ "test/sync-rename-batch.test.ts": 1061,+ "test/sync-sole-non-default-routing.test.ts": 1127,+ "test/sync-strategy.test.ts": 3,+ "test/sync-timeout-cli-dispatch.test.ts": 620,+ "test/sync-timeout.test.ts": 2,+ "test/sync-trigger-cli.test.ts": 317,+ "test/sync-walker-submodule.test.ts": 6,+ "test/sync-walker-symlink.test.ts": 52,+ "test/sync.test.ts": 6850,+ "test/synth-enabled-default.test.ts": 14,+ "test/synthesize-chunk-budget.test.ts": 35,+ "test/system-prompt.test.ts": 3,+ "test/take-forecast.test.ts": 4,+ "test/takes-command-source-scope.test.ts": 35,+ "test/takes-engine.test.ts": 434,+ "test/takes-extract-json.test.ts": 7,+ "test/takes-fence.test.ts": 18,+ "test/takes-holder-semantics.test.ts": 20,+ "test/takes-holder-validation.test.ts": 21,+ "test/takes-list-subcommand.test.ts": 338,+ "test/takes-resolution.test.ts": 2,+ "test/takes-source-scope.test.ts": 409,+ "test/takes-weight-rounding.test.ts": 12,+ "test/template-repo-generator.test.ts": 13,+ "test/text-safe.test.ts": 12,+ "test/thin-client-routing-audit.test.ts": 6,+ "test/thin-client-source-scope.test.ts": 8,+ "test/thin-client-upgrade-prompt.test.ts": 38,+ "test/think-ab.test.ts": 23,+ "test/think-cost.test.ts": 22,+ "test/think-entity-extract.test.ts": 6,+ "test/think-gaps.test.ts": 6,+ "test/think-gateway-adapter.test.ts": 192,+ "test/think-intent.test.ts": 2,+ "test/think-max-output-tokens.test.ts": 5,+ "test/think-pages-block.test.ts": 17,+ "test/think-sanitize-trajectory.test.ts": 27,+ "test/think-trajectory-injection.test.ts": 2248,+ "test/think-with-calibration.test.ts": 7,+ "test/timeline-date-batch.test.ts": 567,+ "test/timeline-dedup-repair.test.ts": 308,+ "test/timeline-entry-subagent-fence.test.ts": 4,+ "test/timeout.test.ts": 70,+ "test/timing-safe.test.ts": 32,+ "test/token-budget.test.ts": 4,+ "test/token-mint.test.ts": 341,+ "test/tool-catalog.test.ts": 15,+ "test/trajectory-format.test.ts": 32,+ "test/trajectory.test.ts": 15,+ "test/transcript-capture.test.ts": 245,+ "test/transcription-injection.test.ts": 4,+ "test/transcription.test.ts": 0,+ "test/transcripts.test.ts": 28,+ "test/traverse-graph-dedup.test.ts": 459,+ "test/trust-boundary-contract.test.ts": 2,+ "test/truthful-catalog.e2e-lite.test.ts": 2420,+ "test/tty-harness.test.ts": 1323,+ "test/turn-context.test.ts": 1858,+ "test/two-pass.test.ts": 412,+ "test/undo-wave.test.ts": 8,+ "test/unfederate-read-scope-2928.test.ts": 1243,+ "test/upgrade-reembed-prompt.test.ts": 369,+ "test/upgrade-reference-sweep.test.ts": 155,+ "test/url-redact.test.ts": 4,+ "test/utils.test.ts": 4,+ "test/v0_29-tool-surfaces.test.ts": 6,+ "test/v81-v82-smoke.test.ts": 446,+ "test/validate-params.test.ts": 24,+ "test/vector-ef-search.test.ts": 2512,+ "test/vector-index-lifecycle.test.ts": 6,+ "test/voice-gate.test.ts": 17,+ "test/volunteer-context.test.ts": 560,+ "test/volunteer-events-delivery.test.ts": 5,+ "test/voyage-multimodal.test.ts": 23,+ "test/voyage-response-cap.test.ts": 2,+ "test/wait-for-completion.test.ts": 1002,+ "test/watch-command.test.ts": 920,+ "test/whoami.test.ts": 5,+ "test/whoknows-doctor.test.ts": 18,+ "test/whoknows.test.ts": 4,+ "test/worker-conn-resilience-1720.test.ts": 133,+ "test/worker-lock-renewal-shape.test.ts": 5,+ "test/worker-lock-renewal.test.ts": 30,+ "test/worker-pool.test.ts": 60,+ "test/worker-promote-reconnect.test.ts": 12,+ "test/worker-rss.test.ts": 29,+ "test/worker-shutdown-disconnect.test.ts": 518,+ "test/worker-supervised-db-probe.test.ts": 539,+ "test/worker-watchdog-trigger.test.ts": 2037,+ "test/write-through.test.ts": 2119,+ "test/write-verify-guard.test.ts": 1036,+ "test/writer.test.ts": 6150,+ "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 filediff --git a/src/commands/eval-gate.ts b/src/commands/eval-gate.tsindex fda0b35f6c..9853d4640f 100644--- a/src/commands/eval-gate.ts+++ b/src/commands/eval-gate.ts@@ -40,7 +40,7 @@ import {parseQrelsFile,type QrelsFile,} from '../core/bench/qrels-file.ts';-import { runCorrectnessGate, type CorrectnessResult } from '../core/bench/correctness-gate.ts';+import { runCorrectnessGate, type CorrectnessGateOpts, type CorrectnessResult } from '../core/bench/correctness-gate.ts';import { replayCore, type ReplaySummary } from './eval-replay.ts';interface GateOpts {@@ -55,6 +55,18 @@ interface GateOpts {thresholdRecallAtK?: number;thresholdFirstRelevantHit?: number;thresholdExpectedTop1?: number;+ /**+ * Hermetic embedder selector. The only accepted value is 'deterministic':+ * query embeddings come from the qrels fixture's basis-vector dims+ * (src/eval/deterministic-embed.ts) instead of the gateway, so the+ * correctness gate runs with no API keys. Correctness-gate-only; rejected+ * when combined with the baseline regression gate (replay re-embeds+ * captured queries via the gateway). Cache safety: this path drives bare+ * `hybridSearch`, which never reads or writes the semantic query cache+ * (both live in `hybridSearchCached`), so deterministic runs cannot+ * poison cached production results by construction.+ */+ embedder?: string;}interface Breach {@@ -139,6 +151,10 @@ function parseArgs(args: string[]): GateOpts {opts.thresholdExpectedTop1 = Number(next);i++;break;+ case '--embedder':+ opts.embedder = next;+ i++;+ break;default:break;}@@ -169,6 +185,13 @@ Thresholds (override baseline metadata; CLI > embedded > defaults):--threshold-expected-top1 FLOAT Correctness: expected_top1-hit-rate floor (default ${DEFAULT_QRELS_THRESHOLDS.expected_top1})-k, --k N Top-K for recall@K (default ${DEFAULT_QRELS_THRESHOLDS.k})+Hermetic mode (correctness gate only):+ --embedder deterministic Embed queries as the qrels fixture's basis+ vectors instead of calling the gateway —+ no API keys, fully reproducible (eval+ canaries/CI). Rejected together with the+ baseline regression gate.+Output:--json Print JSON envelope to stdout-h, --help Show this help@@ -286,6 +309,7 @@ function runCorrectnessGateDispatch(qrelsPath: string,k: number,cliOverrides: Pick<GateOpts, 'thresholdRecallAtK' | 'thresholdFirstRelevantHit' | 'thresholdExpectedTop1'>,+ searchFn?: CorrectnessGateOpts['searchFn'],): Promise<GateResult['correctness_gate']> {return (async () => {let qrelsFile: QrelsFile;@@ -312,7 +336,7 @@ function runCorrectnessGateDispatch(let result: CorrectnessResult;try {- result = await runCorrectnessGate(engine, qrelsFile, { k });+ result = await runCorrectnessGate(engine, qrelsFile, { k, ...(searchFn ? { searchFn } : {}) });} catch (err) {return {ran: true,@@ -448,6 +472,29 @@ export async function runEvalGate(engine: BrainEngine, args: string[]): Promise<process.exit(2);}+ // Hermetic embedder validation. Only 'deterministic' is supported; the+ // regression gate is out of scope (replay re-embeds captured queries via+ // the gateway, which needs a provider key — defeating the hermetic point).+ if (opts.embedder !== undefined) {+ if (opts.embedder !== 'deterministic') {+ console.error(+ `Error: unsupported embedder "${opts.embedder}" — the only supported value is "deterministic".`,+ );+ process.exit(2);+ }+ if (opts.baseline) {+ console.error(+ 'Error: the deterministic embedder cannot be combined with the baseline regression gate ' ++ '(replay re-embeds captured queries via the gateway). Use it with the qrels correctness gate only.',+ );+ process.exit(2);+ }+ if (!opts.qrels) {+ console.error('Error: the deterministic embedder requires a qrels file.');+ process.exit(2);+ }+ }+const result: GateResult = {schema_version: 1,verdict: 'pass',@@ -468,11 +515,35 @@ export async function runEvalGate(engine: BrainEngine, args: string[]): Promise<if (opts.qrels) {const k = opts.k ?? DEFAULT_QRELS_THRESHOLDS.k;++ // Deterministic embedder: build a searchFn that threads basis-vector+ // query embeddings (derived from the qrels fixture itself) into bare+ // hybridSearch via the queryEmbedFn seam. The rest of the pipeline+ // (keyword/title/alias arms, RRF, boosts) runs exactly as production.+ let deterministicSearchFn: CorrectnessGateOpts['searchFn'] | undefined;+ if (opts.embedder === 'deterministic') {+ let queryEmbedFn: (text: string) => Float32Array;+ try {+ const { buildQrelsQueryEmbedFn } = await import('../eval/deterministic-embed.ts');+ queryEmbedFn = buildQrelsQueryEmbedFn(readFileSync(opts.qrels, 'utf-8'));+ } catch (err) {+ console.error(+ `Error: could not build the deterministic embedder from ${opts.qrels}: ${(err as Error).message}`,+ );+ process.exit(2);+ }+ const { hybridSearch } = await import('../core/search/hybrid.ts');+ deterministicSearchFn = async (e, q, o) => {+ const results = await hybridSearch(e, q, { limit: o.limit, queryEmbedFn });+ return results.map(r => ({ source_id: r.source_id, slug: r.slug }));+ };+ }+result.correctness_gate = await runCorrectnessGateDispatch(engine, opts.qrels, k, {thresholdRecallAtK: opts.thresholdRecallAtK,thresholdFirstRelevantHit: opts.thresholdFirstRelevantHit,thresholdExpectedTop1: opts.thresholdExpectedTop1,- });+ }, deterministicSearchFn);if (result.correctness_gate.breaches && result.correctness_gate.breaches.length > 0) {result.verdict = 'fail';}diff --git a/src/core/audit/redact-connection-info.ts b/src/core/audit/redact-connection-info.tsindex 95bdbc254c..d56ad4d1d3 100644--- a/src/core/audit/redact-connection-info.ts+++ b/src/core/audit/redact-connection-info.ts@@ -8,7 +8,7 @@* connection string into the error message:* - `connection to server at "db.example.supabase.com" (1.2.3.4), port 5432 failed: ...`* - `FATAL: password authentication failed for user "postgres"`- * - `could not connect to server: postgresql://user:pass@host:5432/db`+ * - `could not connect to server: postgresql://user:pass@host:5432/db` (allow-pg-url-literal)** If an operator pastes a JSONL audit dump into a GitHub issue or Slack,* those errors leak credentials. The project's audit-as-debug-tool@@ -34,7 +34,7 @@ interface RedactPattern {* occurrences in a single string get redacted.*/const PATTERNS: ReadonlyArray<RedactPattern> = [- // postgres:// and postgresql:// URLs. Includes user:pass@host:port/db+ // postgres:// and postgresql:// URLs. Includes user:pass@host:port/db /* allow-pg-url-literal */// shapes plus query-string variants. Terminator is whitespace or// common JSON/markdown delimiters.{ kind: 'pg_url', re: /postgres(?:ql)?:\/\/[^\s"'>)]+/gi },diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex 0e28f26110..dfc41a7669 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -45,7 +45,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'edges-backfill': ['--aliases', '--all', '--all-sources', '--brain', '--concurrency', '--federated', '--help', '--include-null-signature', '--json', '--max-age', '--max-chunks', '--max-cost-usd', '--no-extract', '--no-federated', '--older-than', '--path', '--pattern', '--pending', '--repo', '--reset', '--resolve', '--restore-only', '--source', '--stale', '--supersessions', '--thin', '--timeout', '--workers'],'embed': ['--aliases', '--all', '--background', '--batch-size', '--brain', '--brain-wide-max-cost-usd', '--break-lock', '--catch-up', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--fast', '--fix', '--follow', '--force', '--force-break-lock', '--from-pages', '--help', '--http', '--include-null-signature', '--json', '--lang', '--markdown', '--max-age', '--max-cost-usd', '--model', '--multimodal', '--name', '--near-symbol', '--no', '--no-embed', '--no-embedding', '--no-extract', '--pace', '--pace-max-concurrency', '--parallel', '--path', '--pattern', '--pending', '--pglite', '--prefix', '--priority', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--reset', '--resolve', '--restore-only', '--serial', '--slugs', '--source', '--stale', '--supabase', '--supersessions', '--surface', '--symbol-kind', '--thin', '--timeout', '--to', '--token-ttl', '--version'],'enrich': ['--aliases', '--all', '--all-sources', '--allow-empty', '--apply', '--asof', '--auto', '--background', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--brain-wide-max-cost-usd', '--break-lock', '--budget-usd-per-day', '--by-mention', '--clone-dir', '--code', '--concurrency', '--confirm-destructive', '--content', '--date', '--days', '--detail', '--dry-run', '--embedding-dimensions', '--embedding-model', '--entities', '--explain', '--fast', '--federated', '--file', '--fix', '--follow', '--force', '--force-break-lock', '--from-pages', '--help', '--http', '--image', '--include-null-signature', '--json', '--judge-model', '--kind', '--lang', '--limit', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-usd', '--min-context', '--mode', '--model', '--multimodal', '--near-symbol', '--no', '--no-embed', '--no-embedding', '--no-extract', '--offset', '--older-than', '--order', '--path', '--pattern', '--pending', '--progress-interval', '--progress-json', '--quiet', '--reenrich-after', '--remediate', '--reset', '--resolve', '--restore-only', '--resume', '--save', '--session', '--session-id', '--since', '--slug', '--slugs', '--source', '--source-id', '--stale', '--stats', '--supersessions', '--surface', '--symbol-kind', '--thin', '--thin-threshold', '--timeout', '--to', '--token-ttl', '--trusted-extraction', '--types', '--url', '--url-managed', '--version', '--with-db', '--workers', '--yes'],- 'eval': ['--ab-relational', '--against', '--aliases', '--all', '--allow-regression', '--background', '--baseline', '--batch', '--brain', '--brain-wide-max-cost-usd', '--budget-usd', '--budget-usd-answer', '--budget-usd-retrieval', '--committed-baseline', '--compare', '--compare-limit', '--concurrent', '--config-a', '--config-b', '--corpus', '--cycles', '--days', '--dedup-cosine', '--dedup-max-per-page', '--dedup-type-ratio', '--dimensions', '--distance-min', '--embedding-dimensions', '--embedding-model', '--expand', '--explain', '--fast', '--fixtures', '--follow', '--force', '--from-capture', '--from-db', '--from-pages', '--gold', '--grounding-min', '--harness', '--help', '--http', '--include-holdout', '--include-null-signature', '--input', '--json', '--judge', '--justification', '--k', '--limit', '--llm', '--max-pair-chars', '--max-tokens', '--max-usd', '--md', '--metric', '--min-recall', '--mode', '--model', '--models', '--modes', '--multimodal', '--name', '--no', '--no-cache', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-llm', '--older-than', '--out', '--output', '--output-dir', '--parallel', '--pattern', '--pending', '--progress-interval', '--progress-json', '--qrels', '--queries-file', '--query', '--questions', '--quiet', '--receipt-dir', '--refresh-cache', '--remediate', '--reset', '--resolve', '--rrf-k', '--rubric-version', '--runs', '--sampling', '--save', '--seed', '--severity', '--short', '--show-toplevel', '--since', '--skip-replay', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slug-prefix', '--source', '--stale', '--strategy', '--strict', '--suite', '--suites', '--supersessions', '--surface', '--task', '--thin', '--threshold', '--threshold-expected-top1', '--threshold-first-relevant-hit', '--threshold-jaccard', '--threshold-latency-multiplier', '--threshold-recall-at-k', '--threshold-top1', '--timeout', '--to', '--token-ttl', '--tool', '--top-k', '--top-regressions', '--until', '--update-baseline', '--usefulness-min', '--verbose', '--version', '--with-code-intel', '--yes'],+ 'eval': ['--ab-relational', '--against', '--aliases', '--all', '--allow-regression', '--background', '--baseline', '--batch', '--brain', '--brain-wide-max-cost-usd', '--budget-usd', '--budget-usd-answer', '--budget-usd-retrieval', '--committed-baseline', '--compare', '--compare-limit', '--concurrent', '--config-a', '--config-b', '--corpus', '--cycles', '--days', '--dedup-cosine', '--dedup-max-per-page', '--dedup-type-ratio', '--dimensions', '--distance-min', '--embedder', '--embedding-dimensions', '--embedding-model', '--expand', '--explain', '--fast', '--fixtures', '--follow', '--force', '--from-capture', '--from-db', '--from-pages', '--gold', '--grounding-min', '--harness', '--help', '--http', '--include-holdout', '--include-null-signature', '--input', '--json', '--judge', '--justification', '--k', '--limit', '--llm', '--max-pair-chars', '--max-tokens', '--max-usd', '--md', '--metric', '--min-recall', '--mode', '--model', '--models', '--modes', '--multimodal', '--name', '--no', '--no-cache', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-llm', '--older-than', '--out', '--output', '--output-dir', '--parallel', '--pattern', '--pending', '--progress-interval', '--progress-json', '--qrels', '--queries-file', '--query', '--questions', '--quiet', '--receipt-dir', '--refresh-cache', '--remediate', '--reset', '--resolve', '--rrf-k', '--rubric-version', '--runs', '--sampling', '--save', '--seed', '--severity', '--short', '--show-toplevel', '--since', '--skip-replay', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slug-prefix', '--source', '--stale', '--strategy', '--strict', '--suite', '--suites', '--supersessions', '--surface', '--task', '--thin', '--threshold', '--threshold-expected-top1', '--threshold-first-relevant-hit', '--threshold-jaccard', '--threshold-latency-multiplier', '--threshold-recall-at-k', '--threshold-top1', '--timeout', '--to', '--token-ttl', '--tool', '--top-k', '--top-regressions', '--until', '--update-baseline', '--usefulness-min', '--verbose', '--version', '--with-code-intel', '--yes'],'export': ['--aliases', '--all', '--background', '--brain', '--brain-wide-max-cost-usd', '--dir', '--explain', '--federated', '--fix', '--follow', '--help', '--include-null-signature', '--json', '--lang', '--markdown', '--multimodal', '--near-symbol', '--no-extract', '--no-federated', '--path', '--pattern', '--pending', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--repo', '--reset', '--resolve', '--restore-only', '--slug-prefix', '--source', '--stale', '--supersessions', '--symbol-kind', '--thin', '--timeout', '--type'],'extract': ['--aliases', '--all', '--background', '--brain', '--brain-wide-max-cost-usd', '--by-mention', '--catch-up', '--code', '--concurrency', '--dir', '--dry-run', '--explain', '--federated', '--follow', '--from-meetings', '--help', '--include-frontmatter', '--include-null-signature', '--infer-dates', '--json', '--kind', '--lang', '--markdown', '--max-age', '--max-cost-usd', '--multimodal', '--name-status', '--near-symbol', '--ner', '--no-extract', '--no-federated', '--older-than', '--pack', '--path', '--pattern', '--pending', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--repo', '--reset', '--resolve', '--restore-only', '--run-id', '--since', '--slug', '--source', '--source-id', '--stale', '--strategy', '--supersessions', '--symbol-kind', '--thin', '--timeout', '--type', '--verbose', '--workers', '--yes'],'extract-conversation-facts': ['--aliases', '--all', '--all-sources', '--background', '--brain', '--brain-wide-max-cost-usd', '--break-lock', '--by-mention', '--clone-dir', '--code', '--concurrency', '--confirm-destructive', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--fix', '--follow', '--force', '--force-break-lock', '--help', '--include-null-signature', '--json', '--judge-model', '--lang', '--limit', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-runtime', '--model', '--multimodal', '--near-symbol', '--no', '--no-embed', '--no-embedding', '--no-extract', '--older-than', '--override-disabled', '--path', '--pattern', '--pending', '--pglite', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--reset', '--resolve', '--restore-only', '--segment-limit', '--session', '--since', '--sleep', '--slug', '--source', '--source-id', '--stale', '--supabase', '--supersessions', '--symbol-kind', '--thin', '--timeout', '--to', '--types', '--url', '--url-managed', '--version', '--workers', '--yes'],diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.tsindex 9b87a32722..81bd50bf27 100644--- a/src/core/pglite-engine.ts+++ b/src/core/pglite-engine.ts@@ -117,35 +117,85 @@ const PGLITE_EDGE_BATCH_MAX_BIND_PARAMS = 30_000;// silently fall through to a normal initSchema (snapshot is just an// optimization, never authoritative).let _snapshotWarnLogged = false;++// Per-process memo. MIGRATIONS + PGLITE_SCHEMA_SQL are static for the life of+// the process, so the schema hash is too; the version file and the ~42MB tar+// are read once per (path, process) instead of once per engine construction+// (a full suite constructs 600+ engines — the un-memoized loader re-read the+// tar and re-hashed 131 migration handler sources every time, ~84MB of+// transient allocation per call). A null entry means the path is terminally+// unusable this process (missing/stale/torn) — no retry per construction.+// The dims/model shape gate is deliberately NOT memoized: tests reconfigure+// the gateway mid-process (zembed/1280) and a mismatched engine must fall+// back to cold init even when an earlier engine loaded this same snapshot.+// Accepted limitation: a snapshot file rewritten mid-process is not observed;+// the only writer (build-pglite-snapshot.ts) runs before test fan-out.+let _snapshotSchemaHashMemo: string | null = null;+// blob stays null until the FIRST caller whose shape gate passes — a process+// whose gateway shape never matches the snapshot (the zembed/1280 test+// files) never pays the 42MB tar read at all.+const _snapshotFileMemo = new Map<string, { versionLines: string[]; blob: Blob | null } | null>();+let _snapshotTarReads = 0;++export function __snapshotMemoStatsForTests(): { tarReads: number; memoEntries: number } {+ return { tarReads: _snapshotTarReads, memoEntries: _snapshotFileMemo.size };+}++export function __resetSnapshotMemoForTests(): void {+ _snapshotSchemaHashMemo = null;+ _snapshotFileMemo.clear();+ _snapshotTarReads = 0;+ _snapshotWarnLogged = false;+}+export function tryLoadSnapshot(snapshotPath: string): Blob | null {try {- // Lazy require so production builds without these imports don't crash.- // eslint-disable-next-line @typescript-eslint/no-require-imports- const fs = require('node:fs') as typeof import('node:fs'); // engine-dynamic-import-ok- const crypto = require('node:crypto') as typeof import('node:crypto'); // engine-dynamic-import-ok- const { MIGRATIONS } = require('./migrate.ts') as typeof import('./migrate.ts'); // engine-dynamic-import-ok- const { PGLITE_SCHEMA_SQL } = require('./pglite-schema.ts') as typeof import('./pglite-schema.ts'); // engine-dynamic-import-ok-- if (!fs.existsSync(snapshotPath)) {- if (!_snapshotWarnLogged) {- // eslint-disable-next-line no-console- console.warn(`[pglite] GBRAIN_PGLITE_SNAPSHOT set but file missing: ${snapshotPath} — using normal init.`);- _snapshotWarnLogged = true;+ let entry = _snapshotFileMemo.get(snapshotPath);+ if (entry === null) return null; // terminally unusable this process+ if (entry === undefined) {+ // First touch of this path in this process — do the file work once.+ // Lazy require so production builds without these imports don't crash.+ // eslint-disable-next-line @typescript-eslint/no-require-imports+ const fs = require('node:fs') as typeof import('node:fs'); // engine-dynamic-import-ok+ const crypto = require('node:crypto') as typeof import('node:crypto'); // engine-dynamic-import-ok+ const { MIGRATIONS } = require('./migrate.ts') as typeof import('./migrate.ts'); // engine-dynamic-import-ok+ const { PGLITE_SCHEMA_SQL } = require('./pglite-schema.ts') as typeof import('./pglite-schema.ts'); // engine-dynamic-import-ok++ if (!fs.existsSync(snapshotPath)) {+ if (!_snapshotWarnLogged) {+ // eslint-disable-next-line no-console+ console.warn(`[pglite] GBRAIN_PGLITE_SNAPSHOT set but file missing: ${snapshotPath} — using normal init.`);+ _snapshotWarnLogged = true;+ }+ _snapshotFileMemo.set(snapshotPath, null);+ return null;}- return null;- }- const versionPath = snapshotPath.replace(/\.tar(?:\.gz)?$/, '.version');- if (!fs.existsSync(versionPath)) {- if (!_snapshotWarnLogged) {- // eslint-disable-next-line no-console- console.warn(`[pglite] snapshot version file missing: ${versionPath} — using normal init.`);- _snapshotWarnLogged = true;+ const versionPath = snapshotPath.replace(/\.tar(?:\.gz)?$/, '.version');+ if (!fs.existsSync(versionPath)) {+ if (!_snapshotWarnLogged) {+ // eslint-disable-next-line no-console+ console.warn(`[pglite] snapshot version file missing: ${versionPath} — using normal init.`);+ _snapshotWarnLogged = true;+ }+ _snapshotFileMemo.set(snapshotPath, null);+ return null;}- return null;+ if (_snapshotSchemaHashMemo === null) {+ _snapshotSchemaHashMemo = computeSnapshotSchemaHash(MIGRATIONS, PGLITE_SCHEMA_SQL, crypto);+ }+ const versionLines = fs.readFileSync(versionPath, 'utf8').trim().split('\n');+ if (_snapshotSchemaHashMemo !== (versionLines[0] ?? '')) {+ if (!_snapshotWarnLogged) {+ // eslint-disable-next-line no-console+ console.warn(`[pglite] snapshot stale (schema hash mismatch) — using normal init. Rebuild with: bun run build:pglite-snapshot`);+ _snapshotWarnLogged = true;+ }+ _snapshotFileMemo.set(snapshotPath, null);+ return null;+ }+ entry = { versionLines, blob: null };+ _snapshotFileMemo.set(snapshotPath, entry);}- const expectedHash = computeSnapshotSchemaHash(MIGRATIONS, PGLITE_SCHEMA_SQL, crypto);- const versionLines = fs.readFileSync(versionPath, 'utf8').trim().split('\n');- const actualHash = versionLines[0] ?? '';// W0 fix-wave: the version file's dims=/model= lines record the embedding// shape the snapshot was BAKED with. A snapshot whose vector(dims) columns@@ -154,6 +204,8 @@ export function tryLoadSnapshot(snapshotPath: string): Blob | null {// fixture went default-on). Resolve our would-be shape through the same// gateway-with-default fallback initSchema uses and refuse a mismatch.// Version files without the shape lines (pre-W0) are treated as stale.+ // Re-evaluated on EVERY call against the CURRENT gateway config — never+ // memoized (see memo comment above).let wantDims: number | string = DEFAULT_EMBEDDING_DIMENSIONS;let wantModel: string = DEFAULT_EMBEDDING_MODEL;try {@@ -161,25 +213,30 @@ export function tryLoadSnapshot(snapshotPath: string): Blob | null {wantDims = gw.getEmbeddingDimensions();wantModel = gw.getEmbeddingModel();} catch { /* gateway not configured — defaults, same as initSchema */ }- const shapeOk = versionLines[1] === `dims=${wantDims}` && versionLines[2] === `model=${wantModel}`;+ const shapeOk = entry.versionLines[1] === `dims=${wantDims}` && entry.versionLines[2] === `model=${wantModel}`;if (!shapeOk) {if (!_snapshotWarnLogged) {// eslint-disable-next-line no-console- console.warn(`[pglite] snapshot embedding shape mismatch (want dims=${wantDims} model=${wantModel}, have ${versionLines[1] ?? 'none'} ${versionLines[2] ?? ''}) — using normal init. Rebuild with: bun run build:pglite-snapshot`);+ console.warn(`[pglite] snapshot embedding shape mismatch (want dims=${wantDims} model=${wantModel}, have ${entry.versionLines[1] ?? 'none'} ${entry.versionLines[2] ?? ''}) — using normal init. Rebuild with: bun run build:pglite-snapshot`);_snapshotWarnLogged = true;}return null;}- if (expectedHash !== actualHash) {- if (!_snapshotWarnLogged) {- // eslint-disable-next-line no-console- console.warn(`[pglite] snapshot stale (schema hash mismatch) — using normal init. Rebuild with: bun run build:pglite-snapshot`);- _snapshotWarnLogged = true;+ if (entry.blob === null) {+ // Tar read deferred until the first shape-matching caller (see memo+ // comment above). A torn/unreadable tar is terminal for the process.+ try {+ // eslint-disable-next-line @typescript-eslint/no-require-imports+ const fs = require('node:fs') as typeof import('node:fs'); // engine-dynamic-import-ok+ const buf = fs.readFileSync(snapshotPath);+ _snapshotTarReads += 1;+ entry.blob = new Blob([new Uint8Array(buf.buffer as ArrayBuffer, buf.byteOffset, buf.byteLength)]);+ } catch {+ _snapshotFileMemo.set(snapshotPath, null);+ return null;}- return null;}- const buf = fs.readFileSync(snapshotPath);- return new Blob([buf]);+ return entry.blob;} catch {// Any failure -> fall through to normal init. Never block tests.return null;diff --git a/src/core/search/hybrid.ts b/src/core/search/hybrid.tsindex a77d8f6e21..ca7c793d3f 100644--- a/src/core/search/hybrid.ts+++ b/src/core/search/hybrid.ts@@ -812,6 +812,21 @@ export interface HybridSearchOpts extends SearchOpts {*/_queryEmbedDeadline?: QueryEmbedDeadline;+ /**+ * Hermetic eval canaries/CI — non-semantic embeddings. When set, the query+ * embedding for the TEXT vector arm comes from this function (e.g. qrels+ * basis vectors) INSTEAD of the gateway's query-embed path, and the+ * no-embedding-provider keyword-only short-circuit is bypassed — so the+ * vector arm runs with no provider key configured at all. Never set on+ * production paths; when absent, behavior is byte-for-byte unchanged.+ *+ * Cache note: bare `hybridSearch` neither reads nor writes the semantic+ * query cache by construction — both the lookup and the store live only in+ * `hybridSearchCached` — so a deterministic-embedding eval run through this+ * seam cannot poison `query_cache` for production queries.+ */+ queryEmbedFn?: (text: string) => Float32Array | Promise<Float32Array>;+/*** INTERNAL — cache-consult outcome threaded from `hybridSearchCached` into* the inner `hybridSearch` so the ONE telemetry record per search (emitted@@ -1264,7 +1279,10 @@ export async function hybridSearch(earlyModality === 'both' ||mayEscalateToMultimodal) &&isAvailable('embedding', multimodalProviderProbe);- if (!isAvailable('embedding', providerProbe) && !willTryMultimodal) {+ // Hermetic eval canaries/CI: a caller-supplied queryEmbedFn produces the+ // vector-arm query embedding without the gateway, so provider+ // availability is irrelevant — skip the keyword-only short-circuit.+ if (!opts?.queryEmbedFn && !isAvailable('embedding', providerProbe) && !willTryMultimodal) {// v0.43 — fuse the relational arm with keyword so typed-edge answers// survive on the no-embedding-provider path (the relational win is most// valuable exactly when vector is unavailable). The title arm fuses here@@ -1502,12 +1520,20 @@ export async function hybridSearch(// share one ~6s budget); direct callers get a fresh deadline. On timeout// the embed rejects → salvage below (or keyword-only when all reject).const embedDl = opts?._queryEmbedDeadline ?? makeQueryEmbedDeadline();+ // Hermetic eval canaries/CI: queryEmbedFn (non-semantic deterministic+ // embeddings) replaces the gateway query-embed for the text vector arm.+ // No deadline needed — it's a synchronous-ish local computation with no+ // network. Absent queryEmbedFn, the bounded gateway path is unchanged.+ const embedOneQuery = (q: string): Promise<Float32Array> =>+ opts?.queryEmbedFn+ ? Promise.resolve(opts.queryEmbedFn(q))+ : embedQueryBounded(q, embedOpts, embedDl);if (!searchSalvageEnabled()) {// ENG-7 kill switch (GBRAIN_SEARCH_SALVAGE=off): pre-wave// all-or-nothing fan-outs — one variant's failure abandons every// embedding and falls back to keyword-only.try {- const embeddings = await Promise.all(queries.map(q => embedQueryBounded(q, embedOpts, embedDl)));+ const embeddings = await Promise.all(queries.map(q => embedOneQuery(q)));queryEmbedding = embeddings[0];const textLists = await Promise.all(embeddings.map(emb => engine.searchVector(emb, searchOpts)),@@ -1537,7 +1563,7 @@ export async function hybridSearch(// WP2/T3 (ENG-15) salvage fan-outs: allSettled on BOTH the embed// fan-out and the searchVector fan-out so one variant's failure no// longer abandons the survivors (the query-vs-search asymmetry fix).- const settled = await Promise.allSettled(queries.map(q => embedQueryBounded(q, embedOpts, embedDl)));+ const settled = await Promise.allSettled(queries.map(q => embedOneQuery(q)));const okEmbeds: Float32Array[] = [];const embedFailures: unknown[] = [];for (const s of settled) {diff --git a/src/eval/deterministic-embed.ts b/src/eval/deterministic-embed.tsnew file mode 100644index 0000000000..99035e8820--- /dev/null+++ b/src/eval/deterministic-embed.ts@@ -0,0 +1,83 @@+/**+ * Deterministic basis-vector embeddings for hermetic eval canaries/CI.+ *+ * NON-SEMANTIC embeddings: each query embeds as a unit basis vector at a+ * fixed dimension, so retrieval through the full hybrid pipeline (vector ++ * keyword/title/alias arms + RRF) is exactly reproducible with no API keys,+ * no network, and no provider drift. Used by the qrels correctness gate's+ * deterministic embedder path and the retrieval canary runner+ * (scripts/run-eval-canary.ts). Mirrors the basis-vector convention in+ * test/eval-replay-gate.test.ts and test/fixtures/eval-baselines/+ * qrels-search.json (each fixture query carries an `embedding_dim`).+ */++/** Unit basis vector with 1.0 at `idx % dim` and 0.0 elsewhere. */+export function basisEmbedding(idx: number, dim = 1536): Float32Array {+ const emb = new Float32Array(dim);+ emb[idx % dim] = 1.0;+ return emb;+}++/**+ * 32-bit FNV-1a hash. Deterministic, dependency-free; used only to derive a+ * stable fallback basis dimension for query texts not present in the qrels+ * fixture.+ */+export function fnv1a(text: string): number {+ let h = 0x811c9dc5;+ for (let i = 0; i < text.length; i++) {+ h ^= text.charCodeAt(i);+ h = Math.imul(h, 0x01000193);+ }+ return h | 0;+}++export interface LegacyQrelsQuery {+ query_id: string;+ query: string;+ embedding_dim: number;+ relevant_slugs: string[];+ first_relevant_slug: string;+}++/**+ * Parse the legacy qrels fixture shape+ * ({queries: [{query, embedding_dim, relevant_slugs, first_relevant_slug}]}).+ * THE single parser for this shape — the canary runner and the embedder+ * builder both consume it. Throws on malformed JSON or a missing `queries`+ * array (callers surface a usage error; the gate's own qrels parser reports+ * shape problems in detail).+ */+export function parseLegacyQrels(raw: string): LegacyQrelsQuery[] {+ const parsed = JSON.parse(raw) as { queries?: unknown };+ if (!Array.isArray(parsed.queries)) {+ throw new Error('qrels fixture missing "queries" array');+ }+ return parsed.queries as LegacyQrelsQuery[];+}++/**+ * Build a query-embed function from a raw qrels fixture (the legacy shape:+ * `{queries: [{query, embedding_dim, ...}]}`). Known query texts map to+ * `basisEmbedding(embedding_dim)`; unknown texts fall back to a+ * deterministic FNV-1a-derived basis dimension in [100, 1099] — outside the+ * fixture's low dims, so an unknown query can never accidentally vote for a+ * fixture page's basis direction (fixture dims are small integers).+ *+ * Throws on malformed JSON or a missing `queries` array (caller surfaces a+ * usage error; the gate's own qrels parser reports shape problems in detail).+ */+export function buildQrelsQueryEmbedFn(qrelsRaw: string): (text: string) => Float32Array {+ const queries = parseLegacyQrels(qrelsRaw);+ const dimByQuery = new Map<string, number>();+ for (const q of queries) {+ if (typeof (q as { query?: unknown })?.query === 'string' && typeof (q as { embedding_dim?: unknown })?.embedding_dim === 'number') {+ dimByQuery.set(q.query, q.embedding_dim);+ }+ }+ return (text: string): Float32Array => {+ const dim = dimByQuery.get(text);+ if (dim !== undefined) return basisEmbedding(dim);+ return basisEmbedding(100 + (Math.abs(fnv1a(text)) % 1000));+ };+}diff --git a/templates/bootstrap/template-repo/README.md b/templates/bootstrap/template-repo/README.mdindex 5675b6c0c8..b7a5ef9d65 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.46.4.0 -->+<!-- gbrain-template-stamp: 0.46.5.0 -->This repository is the **"Use this template"** distribution artifact for a[gbrain](https://github.com/garrytan/gbrain) personal-agent workspace — the samediff --git a/test/chunk-grain-fts.test.ts b/test/chunk-grain-fts.test.tsindex 3bc157b225..6888cddc98 100644--- a/test/chunk-grain-fts.test.ts+++ b/test/chunk-grain-fts.test.ts@@ -20,6 +20,24 @@import { describe, test, expect, beforeAll, afterAll } from 'bun:test';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { MIGRATIONS } from '../src/core/migrate.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';++// ONE engine for the whole file (was three describe-scoped engines = three+// full PGLite boots for 11 tests). Each data-bearing describe resets state+// in its own beforeAll and re-seeds — required, not just hygiene: the+// 'refactor' corpus of the searchKeyword describe would otherwise pollute+// the searchKeywordChunks describe's expectations.+let engine: PGLiteEngine;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+});++afterAll(async () => {+ await engine.disconnect();+}, 30_000);describe('Cathedral II v28 migration — search_vector backfill', () => {test('v28 migration exists in registry', () => {@@ -44,12 +62,8 @@ describe('Cathedral II v28 migration — search_vector backfill', () => {});describe('Cathedral II Layer 3 — searchKeyword external contract', () => {- let engine: PGLiteEngine;-beforeAll(async () => {- engine = new PGLiteEngine();- await engine.connect({});- await engine.initSchema();+ await resetPgliteState(engine);// Two pages, each with multiple chunks that match "refactor" so we can// verify the dedup pass returns one chunk per page. upsertChunks fires@@ -86,10 +100,6 @@ describe('Cathedral II Layer 3 — searchKeyword external contract', () => {]);});- afterAll(async () => {- await engine.disconnect();- }, 30_000);-test('returns one row per matched page (dedup to best chunk per page)', async () => {const results = await engine.searchKeyword('refactor');const slugs = results.map(r => r.slug).sort();@@ -121,12 +131,8 @@ describe('Cathedral II Layer 3 — searchKeyword external contract', () => {});describe('Cathedral II Layer 3 — searchKeywordChunks (internal primitive)', () => {- let engine: PGLiteEngine;-beforeAll(async () => {- engine = new PGLiteEngine();- await engine.connect({});- await engine.initSchema();+ await resetPgliteState(engine);// Page with multiple matching chunks so chunk-grain results can// return two chunks from the same page (no dedup).@@ -143,10 +149,6 @@ describe('Cathedral II Layer 3 — searchKeywordChunks (internal primitive)', ()]);});- afterAll(async () => {- await engine.disconnect();- }, 30_000);-test('does not dedup: can return multiple chunks from the same page', async () => {const results = await engine.searchKeywordChunks('refactor', { limit: 20 });const slugs = results.map(r => r.slug);@@ -174,12 +176,8 @@ describe('Cathedral II Layer 3 — searchKeywordChunks (internal primitive)', ()});describe('Cathedral II Layer 3 — doc-comment weight precedence (A4 foundation)', () => {- let engine: PGLiteEngine;-beforeAll(async () => {- engine = new PGLiteEngine();- await engine.connect({});- await engine.initSchema();+ await resetPgliteState(engine);// Two pages, each with one chunk. Alpha's chunk has the target term// 'hexagon' in its doc_comment (weight A); Beta's chunk has it in@@ -217,10 +215,6 @@ describe('Cathedral II Layer 3 — doc-comment weight precedence (A4 foundation));});- afterAll(async () => {- await engine.disconnect();- }, 30_000);-test('doc-comment match outranks body-text match on the same term', async () => {const results = await engine.searchKeyword('hexagon');expect(results.length).toBeGreaterThan(0);diff --git a/test/eval-canary.test.ts b/test/eval-canary.test.tsnew file mode 100644index 0000000000..a669e920b4--- /dev/null+++ b/test/eval-canary.test.ts@@ -0,0 +1,186 @@+/**+ * test/eval-canary.test.ts — hermetic retrieval canary (deterministic+ * embedder + runner script).+ *+ * Pins:+ * 1. basisEmbedding determinism + dims (src/eval/deterministic-embed.ts).+ * 2. buildQrelsQueryEmbedFn maps fixture queries to their basis dims and+ * falls back deterministically (FNV-1a-derived dim) for unknown texts.+ * 3. scripts/run-eval-canary.ts end-to-end in check mode: real CLI+ * subprocess, exit 0, metrics at/above the qrels default floors.+ * 4. Determinism: two in-process runs of the correctness gate through the+ * 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.+ */++import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';+import { readFileSync } from 'node:fs';+import { join, resolve } from 'node:path';+import { execSync, spawnSync } from 'node:child_process';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { basisEmbedding, buildQrelsQueryEmbedFn, fnv1a } from '../src/eval/deterministic-embed.ts';+import { parseLegacyQrels, seedCanaryCorpus } from '../scripts/run-eval-canary.ts';+import { runCorrectnessGate, type CorrectnessGateOpts } from '../src/core/bench/correctness-gate.ts';+import { parseQrelsFile, DEFAULT_QRELS_THRESHOLDS } from '../src/core/bench/qrels-file.ts';+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+// ---------------------------------------------------------------------------++describe('basisEmbedding', () => {+ test('default dim 1536, 1.0 at idx, 0.0 elsewhere', () => {+ const e = basisEmbedding(5);+ expect(e.length).toBe(1536);+ expect(e[5]).toBe(1.0);+ expect(e[0]).toBe(0.0);+ expect(e.reduce((s, v) => s + v, 0)).toBe(1.0);+ });++ test('custom dim + idx wraparound', () => {+ const e = basisEmbedding(103, 100);+ expect(e.length).toBe(100);+ expect(e[3]).toBe(1.0); // 103 % 100+ expect(e.reduce((s, v) => s + v, 0)).toBe(1.0);+ });++ test('deterministic across calls', () => {+ expect([...basisEmbedding(42)]).toEqual([...basisEmbedding(42)]);+ });+});++// ---------------------------------------------------------------------------+// 2. buildQrelsQueryEmbedFn+// ---------------------------------------------------------------------------++describe('buildQrelsQueryEmbedFn', () => {+ const raw = readFileSync(QRELS_PATH, 'utf-8');++ test('maps every fixture query to its embedding_dim basis vector', () => {+ const fn = buildQrelsQueryEmbedFn(raw);+ const fixture = parseLegacyQrels(raw);+ expect(fixture.length).toBeGreaterThanOrEqual(10);+ for (const q of fixture) {+ expect([...fn(q.query)]).toEqual([...basisEmbedding(q.embedding_dim)]);+ }+ });++ test('unknown text falls back to a deterministic FNV-1a-derived dim in [100, 1099]', () => {+ const fn = buildQrelsQueryEmbedFn(raw);+ const unknown = 'a query text that is definitely not in the fixture';+ const a = fn(unknown);+ const b = fn(unknown);+ expect([...a]).toEqual([...b]);+ const idx = a.findIndex(v => v === 1.0);+ expect(idx).toBe(100 + (Math.abs(fnv1a(unknown)) % 1000));+ expect(idx).toBeGreaterThanOrEqual(100);+ expect(idx).toBeLessThanOrEqual(1099);+ });++ test('throws on malformed input', () => {+ expect(() => buildQrelsQueryEmbedFn('not json')).toThrow();+ expect(() => buildQrelsQueryEmbedFn('{"no_queries": true}')).toThrow(/queries/);+ });+});++// ---------------------------------------------------------------------------+// 4. In-process determinism through the queryEmbedFn seam+// ---------------------------------------------------------------------------++describe('correctness gate through the queryEmbedFn seam', () => {+ 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));+ const queryEmbedFn = buildQrelsQueryEmbedFn(raw);+ const qrels = parseQrelsFile(raw);+ const searchFn: NonNullable<CorrectnessGateOpts['searchFn']> = async (e, q, o) => {+ const results = await hybridSearch(e, q, { limit: o.limit, queryEmbedFn });+ return results.map(r => ({ source_id: r.source_id, slug: r.slug }));+ };++ const a = await runCorrectnessGate(engine, qrels, { searchFn });+ const b = await runCorrectnessGate(engine, qrels, { searchFn });++ expect(a.summary).toEqual(b.summary);+ expect(a.per_query).toEqual(b.per_query);++ expect(a.summary.queries_errored).toBe(0);+ expect(a.summary.mean_recall_at_k).toBeGreaterThanOrEqual(DEFAULT_QRELS_THRESHOLDS.recall_at_k);+ expect(a.summary.first_relevant_hit_rate).toBeGreaterThanOrEqual(DEFAULT_QRELS_THRESHOLDS.first_relevant_hit);+ expect(a.summary.expected_top1_denominator).toBeGreaterThan(0);+ expect(a.summary.expected_top1_hit_rate).toBeGreaterThanOrEqual(DEFAULT_QRELS_THRESHOLDS.expected_top1);+ }, 60_000);+});++// ---------------------------------------------------------------------------+// 3 + 5. Runner end-to-end (check mode) + tracked-file invariance+// ---------------------------------------------------------------------------++describe('run-eval-canary.ts (check mode)', () => {+ // Captured by the end-to-end test; asserted separately below so a+ // tracked-file write shows up as its own named failure.+ let statusBefore: string | null = null;+ let statusAfter: string | null = null;+ let runExit: number | null = null;++ test('spawns the real CLI gate hermetically and passes the floors', () => {+ // Status scoped to the paths check mode could plausibly touch — a+ // whole-tree porcelain diff flakes when a concurrent shard sibling (or a+ // developer save) creates an unrelated file during the ~30s window.+ const STATUS_SCOPE = 'git status --porcelain -- .gbrain-evals test/fixtures docs/eval';+ statusBefore = execSync(STATUS_SCOPE, { cwd: ROOT, encoding: 'utf-8' });+ const child = spawnSync(+ process.execPath,+ [join(ROOT, 'scripts', 'run-eval-canary.ts')],+ // Outer budget strictly above the runner's inner CLI-child timeout so+ // the runner's own diagnostics always win the race.+ { cwd: ROOT, encoding: 'utf-8', timeout: 118_000 },+ );+ statusAfter = execSync(STATUS_SCOPE, { cwd: ROOT, encoding: 'utf-8' });+ runExit = child.status;++ const combined = (child.stdout ?? '') + (child.stderr ?? '');+ expect(child.status).toBe(0);++ const m = combined.match(+ /mean_recall_at_k=([\d.]+) first_relevant_hit_rate=([\d.]+) expected_top1_hit_rate=([\d.]+)/,+ );+ expect(m).not.toBeNull();+ expect(Number(m![1])).toBeGreaterThanOrEqual(DEFAULT_QRELS_THRESHOLDS.recall_at_k);+ expect(Number(m![2])).toBeGreaterThanOrEqual(DEFAULT_QRELS_THRESHOLDS.first_relevant_hit);+ expect(Number(m![3])).toBeGreaterThanOrEqual(DEFAULT_QRELS_THRESHOLDS.expected_top1);+ }, 120_000);++ test('check mode writes nothing to tracked files (git status unchanged)', () => {+ // Guard: the end-to-end test above must have actually run + passed spawn.+ expect(runExit).toBe(0);+ expect(statusBefore).not.toBeNull();+ expect(statusAfter).toBe(statusBefore!);+ });+});diff --git a/test/eval-gate.test.ts b/test/eval-gate.test.tsindex bbf05ea9d9..9569aaecdd 100644--- a/test/eval-gate.test.ts+++ b/test/eval-gate.test.ts@@ -141,6 +141,52 @@ describe('eval gate: usage errors', () => {});});+describe('eval gate: embedder flag validation', () => {+ // The hermetic-canary embedder option accepts exactly one value and only+ // composes with the correctness (qrels) gate. A regression that silently+ // accepts a bad value would fall through to the keyed gateway path and+ // defeat the hermetic guarantee.+ const REAL_QRELS = 'test/fixtures/eval-baselines/qrels-search.json';++ test('unsupported embedder value → exit 2', async () => {+ const out = await withExitCapture(() =>+ runEvalGate(engine, ['--embedder', 'semantic', '--qrels', REAL_QRELS]),+ );+ expect(out.exitCode).toBe(2);+ });++ test('deterministic embedder combined with the baseline gate → exit 2', async () => {+ const out = await withExitCapture(() =>+ runEvalGate(engine, [+ '--embedder', 'deterministic',+ '--baseline', '/tmp/does-not-exist-12345.ndjson',+ '--qrels', REAL_QRELS,+ ]),+ );+ expect(out.exitCode).toBe(2);+ });++ test('deterministic embedder without a qrels file → exit 2', async () => {+ const out = await withExitCapture(() =>+ runEvalGate(engine, ['--embedder', 'deterministic']),+ );+ expect(out.exitCode).toBe(2);+ });++ test('deterministic embedder with a malformed qrels file → exit 2', async () => {+ const { mkdtempSync, writeFileSync } = await import('node:fs');+ const { tmpdir } = await import('node:os');+ const { join } = await import('node:path');+ const dir = mkdtempSync(join(tmpdir(), 'gate-embedder-'));+ const bad = join(dir, 'malformed.json');+ writeFileSync(bad, '{"not_queries": []}');+ const out = await withExitCapture(() =>+ runEvalGate(engine, ['--embedder', 'deterministic', '--qrels', bad]),+ );+ expect(out.exitCode).toBe(2);+ });+});+describe('eval gate: regression-only path', () => {test('malformed baseline → surfaces as breach (verdict fail, exit 1)', async () => {const dir = mkdtempSync(join(tmpdir(), 'eval-gate-test-'));diff --git a/test/eval-replay-gate.test.ts b/test/eval-replay-gate.test.tsindex 0484761ed9..16ea1c8cf5 100644--- a/test/eval-replay-gate.test.ts+++ b/test/eval-replay-gate.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 { basisEmbedding } from '../src/eval/deterministic-embed.ts';import type { ChunkInput } from '../src/core/types.ts';// ---------------------------------------------------------------------------@@ -72,12 +73,9 @@ function loadFixture(): QrelFixture {return fix;}-/** Basis vector with 1.0 at `idx` and 0.0 elsewhere. Mirrors search-quality.test.ts. */-function basisEmbedding(idx: number, dim = 1536): Float32Array {- const emb = new Float32Array(dim);- emb[idx % dim] = 1.0;- return emb;-}+// basisEmbedding (1.0 at `idx`, 0.0 elsewhere) is imported from+// src/eval/deterministic-embed.ts — the shared home for hermetic+// basis-vector embeddings (also used by the retrieval canary)./*** Seed each relevant slug with a chunk whose embedding aligns with thediff --git a/test/migrate.test.ts b/test/migrate.test.tsindex a17fcdf207..0dc903b3ce 100644--- a/test/migrate.test.ts+++ b/test/migrate.test.ts@@ -569,7 +569,7 @@ describe('migration v35 — auto_rls_event_trigger structural guards', () => {// 1. Structural — assert the migration SQL literally contains the helper// CREATE INDEX + DROP INDEX (deterministic, fast, catches the regression// even at 0-row scale where wall-clock can't distinguish O(n²) from O(1)).-// 2. Behavioral — populate 1000 duplicates and assert the migration completes+// 2. Behavioral — populate 200 duplicates and assert the migration completes// under the wall-clock cap. Sanity check at small scale; the structural// assertion is the real guard.@@ -962,7 +962,7 @@ describe('migrate runner v67 — typed-claim columns materialized on PGLite', ()});});-describe('migrate: v8 (links_dedup) regression — must be fast on 1K duplicate rows', () => {+describe('migrate: v8 (links_dedup) regression — must be fast on 200 duplicate rows', () => {let engine: PGLiteEngine;beforeAll(async () => {@@ -975,7 +975,7 @@ describe('migrate: v8 (links_dedup) regression — must be fast on 1K duplicateawait engine.disconnect();});- test('1000 duplicate links dedup completes in <90s and leaves table deduped', async () => {+ test('200 duplicate links dedup completes in <90s and leaves table deduped', async () => {// Set up: drop BOTH the old (v8) and new (v11) unique constraints so// duplicates can be inserted, then reset version so v8 + v11 re-run.// v11 replaces the v8 constraint name; we drop whichever is present.@@ -989,15 +989,19 @@ describe('migrate: v8 (links_dedup) regression — must be fast on 1K duplicateconst fromId = (await db.query(`SELECT id FROM pages WHERE slug = 'p/from'`)).rows[0].id;const toId = (await db.query(`SELECT id FROM pages WHERE slug = 'p/to'`)).rows[0].id;- // Insert 1000 duplicates of the same (from, to, type) row- for (let i = 0; i < 1000; i++) {+ // Insert 200 duplicates of the same (from, to, type) row+ // 200 rows, not 1000: the O(n²) shape this gate guards is still+ // unmistakable at 200 (minutes vs sub-second dedup) and the insert loop+ // stops burning ~15-25s of suite budget per test on row traffic that+ // adds no discriminating power.+ for (let i = 0; i < 200; i++) {await db.query(`INSERT INTO links (from_page_id, to_page_id, link_type, context) VALUES ($1, $2, $3, $4)`,[fromId, toId, 'mention', `dup-${i}`]);}const beforeCount = (await db.query(`SELECT COUNT(*)::int AS c FROM links`)).rows[0].c;- expect(beforeCount).toBe(1000);+ expect(beforeCount).toBe(200);// Reset version to 7 so v8 + v9 + v10 + v11 re-runawait engine.setConfig('version', '7');@@ -1039,7 +1043,7 @@ describe('migrate: v8 (links_dedup) regression — must be fast on 1K duplicate});});-describe('migrate: v9 (timeline_dedup_index) regression — must be fast on 1K duplicate rows', () => {+describe('migrate: v9 (timeline_dedup_index) regression — must be fast on 200 duplicate rows', () => {let engine: PGLiteEngine;beforeAll(async () => {@@ -1052,22 +1056,26 @@ describe('migrate: v9 (timeline_dedup_index) regression — must be fast on 1K dawait engine.disconnect();});- test('1000 duplicate timeline entries dedup completes in <90s and leaves table deduped', async () => {+ test('200 duplicate timeline entries dedup completes in <90s and leaves table deduped', async () => {const db = (engine as any).db;await db.exec(`DROP INDEX IF EXISTS idx_timeline_dedup`);await engine.putPage('p/timeline', { type: 'concept', title: 'TL', compiled_truth: '', timeline: '' });const pageId = (await db.query(`SELECT id FROM pages WHERE slug = 'p/timeline'`)).rows[0].id;- // Insert 1000 duplicates of the same (page_id, date, summary) row- for (let i = 0; i < 1000; i++) {+ // Insert 200 duplicates of the same (page_id, date, summary) row+ // 200 rows, not 1000: the O(n²) shape this gate guards is still+ // unmistakable at 200 (minutes vs sub-second dedup) and the insert loop+ // stops burning ~15-25s of suite budget per test on row traffic that+ // adds no discriminating power.+ for (let i = 0; i < 200; i++) {await db.query(`INSERT INTO timeline_entries (page_id, date, source, summary, detail) VALUES ($1, $2::date, $3, $4, $5)`,[pageId, '2024-01-15', `src-${i}`, 'Founded NovaMind', `detail-${i}`]);}const beforeCount = (await db.query(`SELECT COUNT(*)::int AS c FROM timeline_entries`)).rows[0].c;- expect(beforeCount).toBe(1000);+ expect(beforeCount).toBe(200);await engine.setConfig('version', '7');diff --git a/test/scripts/evals-collection.test.ts b/test/scripts/evals-collection.test.tsnew file mode 100644index 0000000000..afbbca4101--- /dev/null+++ b/test/scripts/evals-collection.test.ts@@ -0,0 +1,58 @@+/**+ * Guard for the evals/ → CI-matrix collection (scripts/test-shard.sh).+ *+ * evals/**\/*.test.ts files run in the keyless 10-shard matrix. This repo's+ * eval HARNESSES are key-requiring by default (Anthropic/OpenAI), so a new+ * test file dropped under evals/ could silently start spending tokens in CI+ * or fail keyless. Growth is therefore allowlist-gated: every collected+ * evals file must be named here, and adding one asserts you checked it runs+ * with NO API keys and NO network (mirror of the serial runner's+ * EXCLUSIVE_FILES guard).+ */++import { describe, expect, it } from "bun:test";+import { execFileSync } from "child_process";+import { resolve } from "path";++const REPO_ROOT = resolve(import.meta.dir, "..", "..");++// Keyless-verified evals test files. Verify before adding:+// env -u ANTHROPIC_API_KEY -u OPENAI_API_KEY bun test <file>+const KEYLESS_ALLOWLIST = new Set([+ // pure-function scoring/CI-parsing helpers; imports no gateway (verified)+ "evals/functional-area-resolver/harness-runner.test.ts",+]);++describe("evals/ collection into the CI matrix", () => {+ const collected = (): string[] => {+ const lists: string[] = [];+ // Union across all shards = the full collected set.+ for (let i = 1; i <= 10; i++) {+ const out = execFileSync(+ "bash",+ ["scripts/test-shard.sh", "--dry-run-list", String(i), "10"],+ { cwd: REPO_ROOT, encoding: "utf-8" },+ );+ lists.push(out);+ }+ return lists+ .join("\n")+ .split("\n")+ .map((s) => s.trim())+ .filter((f) => f.startsWith("evals/"));+ };++ it("every collected evals file is on the keyless allowlist", () => {+ const files = collected();+ expect(files.length).toBeGreaterThan(0); // the collection itself works+ const unlisted = files.filter((f) => !KEYLESS_ALLOWLIST.has(f));+ expect(unlisted).toEqual([]);+ });++ it("every allowlisted file is actually collected (no dead entries)", () => {+ const files = new Set(collected());+ for (const f of KEYLESS_ALLOWLIST) {+ expect(files.has(f)).toBe(true);+ }+ });+});diff --git a/test/scripts/run-serial-pool.test.ts b/test/scripts/run-serial-pool.test.tsnew file mode 100644index 0000000000..bf0891f026--- /dev/null+++ b/test/scripts/run-serial-pool.test.ts@@ -0,0 +1,175 @@+/**+ * Behavioral tests for scripts/run-serial-tests.sh's POOLED execution:+ *+ * 1. All-pass: pooled files run concurrently, one-line PASS summaries,+ * exit 0.+ * 2. One failing file: exit 1, full log echoed, failed-files summary.+ * 3. Hung file: killed by the per-file wall-clock timeout (exit 124/137+ * surfaced with a timeout note) — the exit-hang class containment.+ * Skipped when no timeout/gtimeout binary exists on the host.+ *+ * The missing-sentinel(=failure) and EXCLUSIVE_FILES growth guards are+ * source-pinned in test/scripts/serial-files.test.ts; these tests exercise+ * the live pool in a minimal-PATH sandbox (same pattern as+ * run-unit-parallel.test.ts).+ */++import { describe, it, expect, beforeAll, afterAll } from 'bun:test';+import { execFileSync } from 'child_process';+import { mkdtempSync, mkdirSync, writeFileSync, rmSync, copyFileSync, chmodSync, symlinkSync } from 'fs';+import { tmpdir } from 'os';+import { dirname, join, resolve } from 'path';++const REPO_ROOT = resolve(import.meta.dir, '..', '..');++let ROOT: string;+let ENV: Record<string, string>;+let hasTimeoutBin = false;++function stageSandbox(): string {+ const root = mkdtempSync(join(tmpdir(), 'gbrain-serial-pool-'));+ mkdirSync(join(root, 'scripts', 'lib'), { recursive: true });+ mkdirSync(join(root, 'test'), { recursive: true });+ for (const s of ['run-serial-tests.sh', 'lib/test-env.sh']) {+ mkdirSync(dirname(join(root, 'scripts', s)), { recursive: true });+ copyFileSync(resolve(REPO_ROOT, 'scripts', s), join(root, 'scripts', s));+ }+ chmodSync(join(root, 'scripts', 'run-serial-tests.sh'), 0o755);++ const bin = join(root, 'bin');+ mkdirSync(bin);+ const tools = [+ 'bash', 'sh', 'env', 'dirname', 'basename', 'mktemp', 'date', 'sleep',+ 'cat', 'tail', 'head', 'rm', 'mkdir', 'grep', 'sed', 'awk', 'wc', 'tr',+ 'find', 'sort', 'bun', 'timeout', 'gtimeout',+ ];+ for (const tool of tools) {+ const p = Bun.which(tool);+ if (p) {+ symlinkSync(p, join(bin, tool));+ if (tool === 'timeout' || tool === 'gtimeout') hasTimeoutBin = true;+ }+ }+ return root;+}++function runScript(extraEnv: Record<string, string> = {}): { code: number; out: string } {+ try {+ const out = execFileSync('bash', [join(ROOT, 'scripts', 'run-serial-tests.sh')], {+ cwd: ROOT,+ encoding: 'utf-8',+ env: { ...ENV, ...extraEnv },+ stdio: ['ignore', 'pipe', 'pipe'],+ });+ return { code: 0, out };+ } catch (err) {+ const e = err as { status?: number; stdout?: string; stderr?: string };+ return { code: e.status ?? -1, out: `${e.stdout ?? ''}${e.stderr ?? ''}` };+ }+}++const PASSING = `import { describe, it, expect } from 'bun:test';+describe('passing', () => { it('works', () => { expect(1 + 1).toBe(2); }); });`;++const FAILING = `import { describe, it, expect } from 'bun:test';+describe('failing', () => { it('POOL_SENTINEL_ASSERTION breaks', () => { expect(1).toBe(2); }); });`;++const HANGING = `import { it } from 'bun:test';+it('hangs forever', async () => { await new Promise(() => {}); });`;++beforeAll(() => {+ ROOT = stageSandbox();+ ENV = {+ PATH: join(ROOT, 'bin'),+ HOME: process.env.HOME ?? ROOT,+ TMPDIR: process.env.TMPDIR ?? '/tmp',+ // Sandbox has no package.json — skip the snapshot build path entirely.+ GBRAIN_NO_SNAPSHOT: '1',+ GBRAIN_SERIAL_POOL: '2',+ };+});++afterAll(() => {+ rmSync(ROOT, { recursive: true, force: true });+});++describe('pooled serial runner', () => {+ it('runs pooled files and passes with one-line summaries', () => {+ writeFileSync(join(ROOT, 'test', 'a-ok.serial.test.ts'), PASSING);+ writeFileSync(join(ROOT, 'test', 'b-ok.serial.test.ts'), PASSING);+ const r = runScript();+ expect(r.code).toBe(0);+ expect(r.out).toContain('PASS');+ expect(r.out).toContain('test/a-ok.serial.test.ts');+ expect(r.out).toContain('test/b-ok.serial.test.ts');+ expect(r.out).toContain('all 2 file(s) passed');+ expect(r.out).toContain('pool=2');+ rmSync(join(ROOT, 'test', 'a-ok.serial.test.ts'));+ rmSync(join(ROOT, 'test', 'b-ok.serial.test.ts'));+ });++ it('a failing file fails the run with its full log and a failed-files summary', () => {+ writeFileSync(join(ROOT, 'test', 'a-ok.serial.test.ts'), PASSING);+ writeFileSync(join(ROOT, 'test', 'z-bad.serial.test.ts'), FAILING);+ const r = runScript();+ expect(r.code).toBe(1);+ // Full bun log of the failing file is echoed (its assertion name shows).+ expect(r.out).toContain('POOL_SENTINEL_ASSERTION');+ expect(r.out).toContain('1 file(s) failed');+ expect(r.out).toContain('test/z-bad.serial.test.ts');+ // The passing sibling still reports PASS (pool completes, no fail-fast).+ expect(r.out).toContain('PASS');+ rmSync(join(ROOT, 'test', 'a-ok.serial.test.ts'));+ rmSync(join(ROOT, 'test', 'z-bad.serial.test.ts'));+ });++ it('--dry-run-list lists every serial file without running anything', () => {+ writeFileSync(join(ROOT, 'test', 'a-ok.serial.test.ts'), PASSING);+ const out = execFileSync(+ 'bash',+ [join(ROOT, 'scripts', 'run-serial-tests.sh'), '--dry-run-list'],+ { cwd: ROOT, encoding: 'utf-8', env: ENV },+ );+ expect(out.trim().split('\n')).toEqual(['test/a-ok.serial.test.ts']);+ rmSync(join(ROOT, 'test', 'a-ok.serial.test.ts'));+ });++ it('an externally-SIGTERMed file is rescued by a sequential re-run (phantom stays green)', () => {+ // Self-kills with SIGTERM on first run (exit 143 — the external-kill+ // class: sibling-workspace cleanup, memory jetsam), passes on the+ // rescue re-run. Mirrors run-unit-parallel's oom-once fixture.+ const sentinel = join(ROOT, 'test', 'killed-once.sentinel');+ const KILLED_ONCE = `import { it, expect } from 'bun:test';+import { existsSync, writeFileSync } from 'fs';+it('passes after one external SIGTERM', () => {+ const sentinel = ${JSON.stringify(sentinel)};+ if (!existsSync(sentinel)) {+ writeFileSync(sentinel, '1');+ process.kill(process.pid, 'SIGTERM');+ }+ expect(1).toBe(1);+});`;+ writeFileSync(join(ROOT, 'test', 'k-killed.serial.test.ts'), KILLED_ONCE);+ try {+ const r = runScript();+ // (The "queued for serial rescue" line goes to stderr, which the+ // success path of runScript doesn't capture — the stdout rescue+ // marker + exit 0 are the contract.)+ expect(r.out).toContain('rescued: external-kill phantom');+ expect(r.code).toBe(0);+ } finally {+ rmSync(join(ROOT, 'test', 'k-killed.serial.test.ts'), { force: true });+ rmSync(sentinel, { force: true });+ }+ }, 60000);++ it('a hung file is killed by the per-file wall-clock timeout', () => {+ if (!hasTimeoutBin) return; // macOS without coreutils: no wrapper, documented+ writeFileSync(join(ROOT, 'test', 'h-hang.serial.test.ts'), HANGING);+ const r = runScript({ GBRAIN_SERIAL_FILE_TIMEOUT: '3' });+ expect(r.code).toBe(1);+ expect(r.out).toContain('per-file timeout');+ expect(r.out).toContain('test/h-hang.serial.test.ts');+ rmSync(join(ROOT, 'test', 'h-hang.serial.test.ts'));+ }, 60000);+});diff --git a/test/scripts/run-unit-parallel.test.ts b/test/scripts/run-unit-parallel.test.tsindex 9c7f324554..ffefbd0aa1 100644--- a/test/scripts/run-unit-parallel.test.ts+++ b/test/scripts/run-unit-parallel.test.ts@@ -23,12 +23,15 @@ import { describe, it, expect, beforeAll, afterAll } from 'bun:test';import { execFileSync, spawnSync } from 'child_process';import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, rmSync, copyFileSync, chmodSync, symlinkSync } from 'fs';import { tmpdir } from 'os';-import { join, resolve } from 'path';+import { dirname, join, resolve } from 'path';const REPO_ROOT = resolve(import.meta.dir, '..', '..');const PARALLEL_SH_SRC = resolve(REPO_ROOT, 'scripts/run-unit-parallel.sh');const SHARD_SH_SRC = resolve(REPO_ROOT, 'scripts/run-unit-shard.sh');const SERIAL_SH_SRC = resolve(REPO_ROOT, 'scripts/run-serial-tests.sh');+// The runners `source scripts/lib/test-env.sh` — every sandbox copy of a+// runner must stage the lib too or the source line fails at startup.+const TESTENV_SH_SRC = resolve(REPO_ROOT, 'scripts/lib/test-env.sh');let TMPROOT: string;@@ -37,8 +40,9 @@ beforeAll(() => {// and 4 fixture test files (3 pass, 1 fail). The wrapper's `find test`// expression will pick them up via cwd.TMPROOT = mkdtempSync(join(tmpdir(), 'gbrain-parallel-test-'));- mkdirSync(join(TMPROOT, 'scripts'), { recursive: true });+ mkdirSync(join(TMPROOT, 'scripts', 'lib'), { recursive: true });mkdirSync(join(TMPROOT, 'test'), { recursive: true });+ copyFileSync(TESTENV_SH_SRC, join(TMPROOT, 'scripts', 'lib', 'test-env.sh'));copyFileSync(PARALLEL_SH_SRC, join(TMPROOT, 'scripts', 'run-unit-parallel.sh'));copyFileSync(SHARD_SH_SRC, join(TMPROOT, 'scripts', 'run-unit-shard.sh'));@@ -190,7 +194,8 @@ describe('run-unit-parallel.sh no-timeout-binary fallback (rc from shard wait, nFROOT = mkdtempSync(join(tmpdir(), 'gbrain-parallel-fallback-'));mkdirSync(join(FROOT, 'scripts'), { recursive: true });mkdirSync(join(FROOT, 'test'), { recursive: true });- for (const s of ['run-unit-parallel.sh', 'run-unit-shard.sh', 'run-serial-tests.sh']) {+ for (const s of ['run-unit-parallel.sh', 'run-unit-shard.sh', 'run-serial-tests.sh', 'lib/test-env.sh']) {+ mkdirSync(dirname(join(FROOT, 'scripts', s)), { recursive: true });copyFileSync(resolve(REPO_ROOT, 'scripts', s), join(FROOT, 'scripts', s));chmodSync(join(FROOT, 'scripts', s), 0o755);}@@ -275,7 +280,8 @@ describe('run-unit-parallel.sh OOM rescue lane', () => {OROOT = mkdtempSync(join(tmpdir(), 'gbrain-parallel-oom-'));mkdirSync(join(OROOT, 'scripts'), { recursive: true });mkdirSync(join(OROOT, 'test'), { recursive: true });- for (const s of ['run-unit-parallel.sh', 'run-unit-shard.sh', 'run-serial-tests.sh']) {+ for (const s of ['run-unit-parallel.sh', 'run-unit-shard.sh', 'run-serial-tests.sh', 'lib/test-env.sh']) {+ mkdirSync(dirname(join(OROOT, 'scripts', s)), { recursive: true });copyFileSync(resolve(REPO_ROOT, 'scripts', s), join(OROOT, 'scripts', s));chmodSync(join(OROOT, 'scripts', s), 0o755);}diff --git a/test/scripts/run-verify-parallel.test.ts b/test/scripts/run-verify-parallel.test.tsindex 8b8e64ac3b..fae4b76f9d 100644--- a/test/scripts/run-verify-parallel.test.ts+++ b/test/scripts/run-verify-parallel.test.ts@@ -61,6 +61,52 @@ describe("run-verify-parallel.sh — CLI contract", () => {});});+describe("guard registration ⇒ execution coverage", () => {+ // guard-self-test.sh enforces that every scripts/check-* guard is+ // REGISTERED in guards-manifest.tsv, but nothing enforced that a+ // registered guard actually EXECUTES anywhere — five guards sat+ // registered-but-dead until the v0.45.x test/eval/CI pass. This closes+ // the loop: every manifest guard must be reachable from verify's CHECKS+ // (via a package.json script that invokes its file), or be explicitly+ // exempted HERE with the reason it runs elsewhere / deliberately not.+ const EXECUTION_EXEMPT: Record<string, string> = {+ "check-bun-test-timeout.sh":+ "runs directly as a test.yml verify-job step (not via CHECKS — avoids a package.json edit)",+ "check-jsonb-params.mjs":+ "exercised by test/check-jsonb-params.test.ts + guard self-test fixtures",+ "check-admin-embedded.sh":+ "duplicates check:admin-build's vite+tsc build; embed freshness covered there",+ "check-image-decoders-embedded.sh":+ "runs its own bun build --compile — too heavy for per-verify cadence",+ };++ it("every manifest guard is executed by verify or explicitly exempt", () => {+ const manifestLines = readFileSync("scripts/guards-manifest.tsv", "utf8")+ .split("\n")+ .filter((l) => l.trim() && !l.startsWith("#"));+ const guards = manifestLines.map((l) => l.split("\t")[0]!).filter(Boolean);+ expect(guards.length).toBeGreaterThan(30);++ const pkg = JSON.parse(readFileSync("package.json", "utf8")) as {+ scripts: Record<string, string>;+ };+ const dry = spawnSync("bash", [SCRIPT, "--dry-list"], { encoding: "utf8" });+ expect(dry.status).toBe(0);+ const executed = new Set(dry.stdout.trim().split("\n"));++ const missing: string[] = [];+ for (const g of guards) {+ if (EXECUTION_EXEMPT[g]) continue;+ const invokingKeys = Object.entries(pkg.scripts)+ .filter(([, cmd]) => cmd.includes(`scripts/${g}`))+ .map(([key]) => key);+ const covered = invokingKeys.some((k) => executed.has(k));+ if (!covered) missing.push(g);+ }+ expect(missing).toEqual([]);+ });+});+describe("run-verify-parallel.sh — failure surfacing (synthetic dispatcher)", () => {// We can't inject a fake check into the real script without touching the// CHECKS array. Instead, we write a SMALLER synthetic dispatcher that@@ -203,13 +249,15 @@ describe("run-verify-parallel.sh — no-timeout-binary fallback rc capture (regrfunction makeFallbackHarness(): { root: string; env: Record<string, string> } {const root = mkdtempSync(join(tmpdir(), "verify-fallback-"));- mkdirSync(join(root, "scripts"), { recursive: true });+ mkdirSync(join(root, "scripts", "lib"), { recursive: true });copyFileSync(SCRIPT, join(root, "scripts", "run-verify-parallel.sh"));+ // The dispatcher sources the shared runner lib — stage it too (E3).+ copyFileSync("scripts/lib/test-env.sh", join(root, "scripts", "lib", "test-env.sh"));const bin = join(root, "bin");mkdirSync(bin);// Everything the dispatcher and its subshells invoke, minus timeout bins.- for (const tool of ["bash", "sh", "env", "dirname", "mktemp", "date", "sleep", "cat", "tail", "head", "rm", "mkdir", "pkill", "grep", "sed", "awk"]) {+ for (const tool of ["bash", "sh", "env", "dirname", "mktemp", "date", "sleep", "cat", "tail", "head", "rm", "mkdir", "pkill", "grep", "sed", "awk", "wc", "tr"]) {const p = Bun.which(tool);if (p) symlinkSync(p, join(bin, tool));}diff --git a/test/scripts/serial-files.test.ts b/test/scripts/serial-files.test.tsindex 1d5ad56e39..b50c9de1f6 100644--- a/test/scripts/serial-files.test.ts+++ b/test/scripts/serial-files.test.ts@@ -18,7 +18,7 @@import { describe, it, expect } from 'bun:test';import { execFileSync } from 'child_process';-import { readFileSync } from 'fs';+import { existsSync, readFileSync } from 'fs';import { resolve } from 'path';const REPO_ROOT = resolve(import.meta.dir, '..', '..');@@ -68,3 +68,31 @@ describe('run-serial-tests.sh contract', () => {expect(overlap).toEqual([]);});});++describe('EXCLUSIVE_FILES (pooled-runner opt-out) guards', () => {+ const src = () => readFileSync(SERIAL_SH, 'utf-8');+ const entries = () =>+ [...src().matchAll(/^\s*"(test\/[^"]+\.serial\.test\.ts)"\s*$/gm)].map(m => m[1]);++ it('every exclusive entry exists on disk and is discovered by the runner', () => {+ const listed = dryRunList(SERIAL_SH);+ const e = entries();+ expect(e.length).toBeGreaterThan(0);+ for (const f of e) {+ expect(existsSync(resolve(REPO_ROOT, f))).toBe(true);+ expect(listed).toContain(f);+ }+ });++ it('the exclusive list does not silently grow (quarantine-growth guard)', () => {+ // Exclusivity re-serializes the runner one file at a time — the exact+ // 8.5-minute disease the pool removed. Each entry must carry a+ // justification comment; past 3 entries, stop and rethink the design+ // (per-file PATH shims are usually the right fix) instead of quarantining.+ expect(entries().length).toBeLessThanOrEqual(3);+ });++ it('a missing exit sentinel is a failure, never a silent pass', () => {+ expect(src()).toMatch(/missing exit sentinel/);+ });+});diff --git a/test/scripts/sharding.test.ts b/test/scripts/sharding.test.tsindex bd42f169e1..ff365147a2 100644--- a/test/scripts/sharding.test.ts+++ b/test/scripts/sharding.test.ts@@ -7,6 +7,7 @@import { describe, expect, it } from "bun:test";import {computeMedian,+ computeQuantile,imbalanceRatio,loadWeights,partition,@@ -83,20 +84,32 @@ describe("partition — happy path", () => {});describe("partition — fallback semantics", () => {- it("missing weights default to corpus median", () => {- // weights = {a:100, b:50}, median = 75. Files c + d are unknown → 75 each.+ it("missing weights default to corpus p75 (missing files skew heavy)", () => {+ // weights = {a:100, b:50}, p75 (nearest-rank of [50,100] at 0.75) = 100.+ // Files c + d are unknown → 100 each.const weights: WeightMap = new Map([["a", 100],["b", 50],]);const out = partition(["a", "b", "c", "d"], weights, 2);- // Effective weights: a=100, b=50, c=75, d=75. LPT: 100→s0, 75→s1 (c),- // 75→s1 (d, ties broken alpha)... actually: 100→s0=100, 75→s1=75,- // 75→s1 vs s0 → s1=150, 50→s0=150. Balanced 150/150.+ // Effective weights: a=100, b=50, c=100, d=100. Exact LPT placement of+ // ties is implementation-defined — assert the invariant instead: totals+ // differ by ≤ the fallback (the LPT bound), and every file landed once.const totalsEffective = out.map((s) =>- s.reduce((acc, f) => acc + (weights.get(f) ?? 75), 0),+ s.reduce((acc, f) => acc + (weights.get(f) ?? 100), 0),);- expect(totalsEffective[0]).toBe(totalsEffective[1]);+ expect(Math.abs(totalsEffective[0]! - totalsEffective[1]!)).toBeLessThanOrEqual(100);+ const flat = out.flat().sort();+ expect(flat).toEqual(["a", "b", "c", "d"]);+ });++ it("computeQuantile: nearest-rank p75 on a skewed corpus", () => {+ // Right-skewed like the real weights file: p75 lands in the tail's+ // foothills, far above the median.+ expect(computeQuantile([1, 1, 1, 1000], 0.75)).toBe(1);+ expect(computeQuantile([1, 2, 3, 4], 0.75)).toBe(3);+ expect(computeQuantile([50, 100], 0.75)).toBe(100);+ expect(computeQuantile([], 0.75)).toBe(0);});it("explicit fallback override beats median", () => {diff --git a/test/scripts/test-shard.slow.test.ts b/test/scripts/test-shard.slow.test.tsindex e3e4c18cd5..59368548d3 100644--- a/test/scripts/test-shard.slow.test.ts+++ b/test/scripts/test-shard.slow.test.ts@@ -130,33 +130,68 @@ describe('test-shard.sh — LPT balance contract', () => {});function totalsFor(shards: string[][]): number[] {- // Use 30ms as the cold-start fallback (matches mine-shard-weights- // median observation). When weights are loaded, missing files get- // the corpus median anyway via sharding.ts.+ // p75 fallback mirroring sharding.ts's computeQuantile choice (the+ // weight distribution is right-skewed and missing files skew heavy).+ const sorted = Array.from(weightsMap.values()).sort((a, b) => a - b);const fallback = weightsLoaded- ? Array.from(weightsMap.values()).sort((a, b) => a - b)[- Math.floor(weightsMap.size / 2)- ] ?? 30+ ? sorted[Math.min(sorted.length - 1, Math.ceil(0.75 * sorted.length) - 1)] ?? 30: 1;return shards.map((s) =>s.reduce((acc, f) => acc + (weightsMap.get(f) ?? fallback), 0),);}- it('4-shard wallclock imbalance ratio ≤ 1.5', () => {- const shards = [1, 2, 3, 4].map(s => dryRunList(s, 4));- for (const s of shards) expect(s.length).toBeGreaterThan(0);- const totals = totalsFor(shards);- const ratio = Math.max(...totals) / Math.min(...totals);- expect(ratio).toBeLessThanOrEqual(1.5);+ // CI runs THIS many shards (test.yml matrix). The old version of this+ // test asserted 4- and 6-shard splits — configurations nothing runs.+ const CI_SHARDS = 10;++ it('CI_SHARDS matches the test.yml matrix (parsed, not regexed)', () => {+ const fs = require('fs');+ const yaml = require('js-yaml');+ const wf = yaml.load(+ fs.readFileSync(resolve(REPO_ROOT, '.github/workflows/test.yml'), 'utf8'),+ ) as { jobs: { test: { strategy: { matrix: { shard: unknown[] } } } } };+ const matrix = wf.jobs.test.strategy.matrix.shard;+ expect(Array.isArray(matrix)).toBe(true);+ expect(matrix.length).toBe(CI_SHARDS);});- it('6-shard wallclock imbalance ratio ≤ 1.5', () => {- const shards = [1, 2, 3, 4, 5, 6].map(s => dryRunList(s, 6));+ it(`${CI_SHARDS}-shard wallclock imbalance ratio ≤ 1.5 (the configuration CI actually runs)`, () => {+ const shards = Array.from({ length: CI_SHARDS }, (_, i) => dryRunList(i + 1, CI_SHARDS));for (const s of shards) expect(s.length).toBeGreaterThan(0);const totals = totalsFor(shards);const ratio = Math.max(...totals) / Math.min(...totals);expect(ratio).toBeLessThanOrEqual(1.5);+ }, 60_000);++ // The two guards below are what make the ratio assertion above MEAN+ // something: recomputing totals with the same weights the partitioner+ // used is near-tautological — unless the weights actually cover the+ // corpus and refer to real files. Weight rot (files added without a+ // re-mine, or renamed away from their entries) used to be invisible:+ // 45% of the corpus once rode a 30ms median fallback while really+ // averaging ~4s, and the "balanced" partition was balanced on fiction.+ it('weights cover ≥70% of matrix-eligible files (anti-rot gate)', () => {+ const all = Array.from(+ new Set(Array.from({ length: CI_SHARDS }, (_, i) => dryRunList(i + 1, CI_SHARDS)).flat()),+ );+ expect(all.length).toBeGreaterThan(0);+ const covered = all.filter((f) => weightsMap.has(f)).length;+ const coverage = covered / all.length;+ // Regenerate from the latest green Test run:+ // bun run scripts/mine-shard-weights.ts --run <run id>+ expect(coverage).toBeGreaterThanOrEqual(0.7);+ }, 60_000);++ it('no stale weight keys — every entry names a tracked file', () => {+ const tracked = new Set(+ execFileSync('git', ['ls-files', 'test', 'evals'], { cwd: REPO_ROOT, encoding: 'utf-8' })+ .split('\n')+ .map((s) => s.trim())+ .filter(Boolean),+ );+ const stale = [...weightsMap.keys()].filter((k) => !tracked.has(k));+ expect(stale).toEqual([]);});it('6-shard partition is deterministic across runs', () => {diff --git a/test/snapshot-shape-guard.test.ts b/test/snapshot-shape-guard.test.tsindex a91880c965..9b6b0b36ba 100644--- a/test/snapshot-shape-guard.test.ts+++ b/test/snapshot-shape-guard.test.ts@@ -12,7 +12,12 @@ import { mkdtempSync, rmSync, writeFileSync } from 'fs';import { tmpdir } from 'os';import { join } from 'path';import * as crypto from 'node:crypto';-import { tryLoadSnapshot, computeSnapshotSchemaHash } from '../src/core/pglite-engine.ts';+import {+ tryLoadSnapshot,+ computeSnapshotSchemaHash,+ __snapshotMemoStatsForTests,+ __resetSnapshotMemoForTests,+} from '../src/core/pglite-engine.ts';import { MIGRATIONS } from '../src/core/migrate.ts';import { PGLITE_SCHEMA_SQL } from '../src/core/pglite-schema.ts';import { getEmbeddingDimensions, getEmbeddingModel } from '../src/core/ai/gateway.ts';@@ -21,6 +26,7 @@ let dir: string;beforeEach(() => {dir = mkdtempSync(join(tmpdir(), 'gbrain-snap-guard-'));+ __resetSnapshotMemoForTests();});afterEach(() => {@@ -63,6 +69,41 @@ test('matching hash + shape loads the blob', () => {expect(blob!.size).toBeGreaterThan(0);});+test('memo: same path is read once per process, blob identical across calls', () => {+ const tar = writeFixture(`${currentHash()}\ndims=${getEmbeddingDimensions()}\nmodel=${getEmbeddingModel()}\n`);+ const b1 = tryLoadSnapshot(tar);+ const afterFirst = __snapshotMemoStatsForTests().tarReads;+ const b2 = tryLoadSnapshot(tar);+ const afterSecond = __snapshotMemoStatsForTests().tarReads;+ expect(b1).not.toBeNull();+ expect(b2).toBe(b1); // same Blob instance — the tar was not re-read+ expect(afterFirst).toBe(1);+ expect(afterSecond).toBe(1);+});++test('memo: shape refusal is per-call, never cached as terminal — and costs zero tar reads', () => {+ // Hash matches but dims mismatch: the version entry is memoized yet every+ // call re-runs the shape gate against the CURRENT gateway config — an+ // engine with a matching config later in the same process could still+ // load this snapshot (the zembed/1280 poisoning guard staying hot behind+ // the memo). The 42MB tar read is deferred until a shape-MATCHING caller,+ // so a process that only ever refuses never reads it at all.+ const tar = writeFixture(`${currentHash()}\ndims=99999\nmodel=${getEmbeddingModel()}\n`);+ expect(tryLoadSnapshot(tar)).toBeNull();+ expect(__snapshotMemoStatsForTests().tarReads).toBe(0);+ expect(__snapshotMemoStatsForTests().memoEntries).toBe(1); // entry exists — not terminal+ expect(tryLoadSnapshot(tar)).toBeNull();+ expect(__snapshotMemoStatsForTests().tarReads).toBe(0);+});++test('memo: stale hash is terminal — tar never read, repeat calls short-circuit', () => {+ const tar = writeFixture(`deadbeef\ndims=${getEmbeddingDimensions()}\nmodel=${getEmbeddingModel()}\n`);+ expect(tryLoadSnapshot(tar)).toBeNull();+ expect(__snapshotMemoStatsForTests().tarReads).toBe(0);+ expect(tryLoadSnapshot(tar)).toBeNull();+ expect(__snapshotMemoStatsForTests().tarReads).toBe(0);+});+test('D5.13: a migration handler edit changes the hash (sql-only hashing missed 19 handler migrations)', () => {const base = [{ version: 1, name: 'a', sql: 'CREATE TABLE t(x int)' },