Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
test: isolation-lint R5 (configureGateway requires resetGateway) and restore the gateway in every leaking file (#5467)
time-attack409b0051b75c
diff --git a/docs/TESTING.md b/docs/TESTING.mdindex 72ca297dd0..d425f3a1f3 100644--- a/docs/TESTING.md+++ b/docs/TESTING.md@@ -1443,18 +1443,17 @@ cross-subsystem duplicate entries, and byte caps for the entry docs and referenc### Test-isolation lint and helpers-**This section is the canonical home of the test-isolation discipline** — CONTRIBUTING.md and other docs link here rather than restating the rules.--The cross-file flake class is enforced statically by `scripts/check-test-isolation.sh`, wired into `bun run verify`. Rules (non-serial unit files only; `*.serial.test.ts` and `test/e2e/*` are skipped):+**The canonical home of the test-isolation rules** (other docs link here). `scripts/check-test-isolation.sh` (in `bun run verify`) enforces them on non-serial unit files; `*.serial.test.ts` and `test/e2e/*` are skipped:| Rule | What it bans | Fix ||---|---|---|-| **R1** | `process.env.X = ...`, bracket assignment, `delete process.env.X`, `Object.assign(process.env, ...)`, `Reflect.set(process.env, ...)` | Use `withEnv()` from `test/helpers/with-env.ts`, OR rename file to `*.serial.test.ts` |-| **R2** | `mock.module(...)` anywhere in the file | Rename file to `*.serial.test.ts` (no DI on production code for testability) |+| **R1** | `process.env.X = ...`, bracket assignment, `delete`, `Object.assign(process.env, ...)`, `Reflect.set(process.env, ...)` | `withEnv()` (`test/helpers/with-env.ts`) or `*.serial.test.ts` |+| **R2** | `mock.module(...)` anywhere in the file | `*.serial.test.ts` (no DI on production code for testability) || **R3** | `new PGLiteEngine(` outside ~50 lines after a `beforeAll(` line | Use the canonical block (below) inside `beforeAll(` |-| **R4** | Files creating `new PGLiteEngine(` without `engine.disconnect(` inside an `afterAll(` block | Add `afterAll(() => engine.disconnect())` |+| **R4** | `new PGLiteEngine(` without `engine.disconnect(` in an `afterAll(` block | Add `afterAll(() => engine.disconnect())` |+| **R5** | `configureGateway(` with no `resetGateway(` (comments ignored): the global gateway leaks to later files | `afterAll(() => resetGateway())`; a child-script-only call takes `isolation-lint: R5-subprocess-only` |-Files that violated these rules at the isolation-lint baseline are listed in `scripts/check-test-isolation.allowlist`. **The allow-list MUST shrink over time** — never add new entries.+Files that violated these rules at the lint baseline are listed in `scripts/check-test-isolation.allowlist`. **The allow-list MUST shrink over time**: never add entries.#### Opt-in naming rulediff --git a/scripts/check-test-isolation.sh b/scripts/check-test-isolation.shindex 030361c3bb..3f750b738c 100755--- a/scripts/check-test-isolation.sh+++ b/scripts/check-test-isolation.sh@@ -18,6 +18,13 @@# R4: any file that creates `new PGLiteEngine(` must call `.disconnect(`# inside an `afterAll(` block. Without disconnect, engines leak across# file boundaries within a shard process.+# R5: any file that calls `configureGateway(` must also call+# `resetGateway(` (in afterAll/afterEach). The AI gateway is+# PROCESS-GLOBAL; a leaked config (embed model/dims, keys, base URLs)+# reaches every later file in the shard and sizes its PGLite schema,+# so e.g. a leaked LiteLLM embed model made eval-canary fail with+# "expected 1280 dimensions, not 1536" once a shard reshuffle put the+# leaker first. Comment-only mentions are ignored.## Scope:# - Recursively scans `test/**/*.test.ts`.@@ -43,8 +50,12 @@ set -euo pipefail. "$(dirname "$0")/lib/guard-candidates.sh"-ROOT="$(git rev-parse --show-toplevel 2>/dev/null || pwd)"+# GBRAIN_GUARD_ROOT (guard self-test): lint a fixture tree, whose unit files+# end in .test.fixture.ts so the real lint and `bun test` never collect them.+ROOT="${GBRAIN_GUARD_ROOT:-$(git rev-parse --show-toplevel 2>/dev/null || pwd)}"cd "$ROOT"+TEST_SUFFIX='.test.ts'+[ -n "${GBRAIN_GUARD_ROOT:-}" ] && TEST_SUFFIX='.test.fixture.ts'AS_PARALLEL=0if [ "${1:-}" = "--as-parallel" ]; then@@ -95,8 +106,8 @@ is_allowlisted() {if [ "$AS_PARALLEL" = 1 ]; thenFILE_LIST="$(printf '%s\n' "$@")"else-FILE_LIST="$(find "$TARGET_DIR" $EXTRA_DIRS -name '*.test.ts' \- -not -name '*.serial.test.ts' \+FILE_LIST="$(find "$TARGET_DIR" $EXTRA_DIRS -name "*$TEST_SUFFIX" \+ -not -name "*.serial$TEST_SUFFIX" \-not -path "*/e2e/*" \-type f 2>/dev/null | sort)"fi@@ -104,7 +115,8 @@ fiENV_MUTATION_PATTERN='process\.env\.[A-Za-z_][A-Za-z_0-9]*[[:space:]]*=[^=]|process\.env\[[^]]+\][[:space:]]*=[^=]|delete[[:space:]]+process\.env\.|delete[[:space:]]+process\.env\[|Object\.assign[[:space:]]*\([[:space:]]*process\.env|Reflect\.set[[:space:]]*\([[:space:]]*process\.env'MODULE_MOCK_PATTERN='mock\.module[[:space:]]*\('ENGINE_PATTERN='new PGLiteEngine[[:space:]]*\('-CANDIDATES="$(guard_candidates -E -e "$ENV_MUTATION_PATTERN" -e "$MODULE_MOCK_PATTERN" -e "$ENGINE_PATTERN" <<< "$FILE_LIST")"+GATEWAY_PATTERN='configureGateway[[:space:]]*\('+CANDIDATES="$(guard_candidates -E -e "$ENV_MUTATION_PATTERN" -e "$MODULE_MOCK_PATTERN" -e "$ENGINE_PATTERN" -e "$GATEWAY_PATTERN" <<< "$FILE_LIST")"violations=0file_count=0@@ -168,6 +180,21 @@ while IFS= read -r f; doemit_violation "$f" "R4" "creates PGLiteEngine but missing afterAll(() => engine.disconnect()); engine leaks across files in the shard process" ""fifi++ # R5: configureGateway() requires a resetGateway() restore. Comment lines+ # (// or JSDoc *) are stripped first so prose mentions don't count. A call+ # that only runs in a spawned child process (template-string script) cannot+ # leak; such a file opts out with a `isolation-lint: R5-subprocess-only`+ # comment naming why.+ cg_lines=$(grep -nE "$GATEWAY_PATTERN" "$f" 2>/dev/null \+ | grep -vE '^[0-9]+:[[:space:]]*(//|\*|/\*)' || true)+ if [ -n "$cg_lines" ] && ! grep -qF 'isolation-lint: R5-subprocess-only' "$f" 2>/dev/null; then+ reset_lines=$(grep -nE 'resetGateway[[:space:]]*\(' "$f" 2>/dev/null \+ | grep -vE '^[0-9]+:[[:space:]]*(//|\*|/\*)' || true)+ if [ -z "$reset_lines" ]; then+ emit_violation "$f" "R5" "calls configureGateway() but never resetGateway(); the process-global gateway leaks to later files in the shard. Add afterAll(() => resetGateway()) or rename to *.serial.test.ts" "$cg_lines"+ fi+ fidone <<EOF$FILE_LISTEOF@@ -181,6 +208,8 @@ if [ $violations -gt 0 ]; thenecho " - For mock.module(), rename to *.serial.test.ts (quarantine)"echo " - For PGLiteEngine, follow the canonical pattern in"echo " test/helpers/reset-pglite.ts JSDoc and CLAUDE.md."+ echo " - For configureGateway(), add afterAll(() => resetGateway())"+ echo " (restores the preload's legacy 1536-d baseline)."echoecho "Or, if this is a baseline file from before the lint shipped,"echo "add it to scripts/check-test-isolation.allowlist (with a TODO"diff --git a/scripts/guards-manifest.tsv b/scripts/guards-manifest.tsvindex b6dc9114c2..1ea2d92eb4 100644--- a/scripts/guards-manifest.tsv+++ b/scripts/guards-manifest.tsv@@ -44,7 +44,7 @@ check-gateway-routed-no-direct-anthropic.sh scanner yes no runtime @anthropic-aicheck-engine-dynamic-import.sh scanner yes .ts companion is its implementation, not a separate guard; scans engine façades, their module dirs, engine-sql/ and schema-migrations/; GBRAIN_GUARD_ROOT seamcheck-key-files-current-state.sh scanner todocheck-trailing-newline.sh scanner yes tracked src/test/root text files end with a newline (guard fixtures excluded); GBRAIN_GUARD_ROOT seam scans with find-check-test-isolation.sh scanner todo allowlist data file: check-test-isolation.allowlist+check-test-isolation.sh scanner yes allowlist data file: check-test-isolation.allowlist; fixture mode (GBRAIN_GUARD_ROOT) lints *.test.fixture.ts (bad: R5, bad-r1: R1)check-compile-autoload.sh scanner yes every `bun build --compile` invocation (CLI one-liners + TS spawn arrays) in package.json/.github/scripts/docs/CLAUDE.md/CONTRIBUTING.md must carry --no-compile-autoload-bunfig (a cwd bunfig.toml preload runs before cli-preflight in a compiled binary); also every curated help record in src/cli/command-table.ts loads its src/cli/help/<name>.ts module through a literal () => import() (D3), and every spec module has a recordcheck-admin-build.sh buildfresh exempt runs the admin build; the build is the testcheck-admin-embedded.sh buildfresh exempt embed freshness diff; not in verify CHECKS: duplicates check:admin-build's builddiff --git a/test/cycle-consolidate-threshold-5363.test.ts b/test/cycle-consolidate-threshold-5363.test.tsindex 659bf1337c..12c4e6689c 100644--- a/test/cycle-consolidate-threshold-5363.test.ts+++ b/test/cycle-consolidate-threshold-5363.test.ts@@ -11,7 +11,7 @@import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';import { PGLiteEngine } from '../src/core/pglite-engine.ts';-import { configureGateway } from '../src/core/ai/gateway.ts';+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';import { parseClusterThreshold, runPhaseConsolidate } from '../src/core/cycle/phases/consolidate.ts';let engine: PGLiteEngine;@@ -28,6 +28,7 @@ beforeAll(async () => {});afterAll(async () => {+ resetGateway(); // R5: restore the preload baseline for later files in this shardawait engine.disconnect();});diff --git a/test/cycle-consolidate.test.ts b/test/cycle-consolidate.test.tsindex e254304ea2..92bfd94da1 100644--- a/test/cycle-consolidate.test.ts+++ b/test/cycle-consolidate.test.ts@@ -10,7 +10,7 @@import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';import { PGLiteEngine } from '../src/core/pglite-engine.ts';-import { configureGateway } from '../src/core/ai/gateway.ts';+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';import { runPhaseConsolidate } from '../src/core/cycle/phases/consolidate.ts';let engine: PGLiteEngine;@@ -36,6 +36,7 @@ beforeAll(async () => {});afterAll(async () => {+ resetGateway(); // R5: restore the preload baseline for later files in this shardawait engine.disconnect();});diff --git a/test/doctor-embedding-width.test.ts b/test/doctor-embedding-width.test.tsindex 76ba049156..10cc51de66 100644--- a/test/doctor-embedding-width.test.ts+++ b/test/doctor-embedding-width.test.ts@@ -4,7 +4,7 @@ import { resetPgliteState } from './helpers/reset-pglite.ts';import {checkEmbeddingWidthConsistency,} from '../src/commands/doctor.ts';-import { configureGateway } from '../src/core/ai/gateway.ts';+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';let engine: PGLiteEngine;@@ -15,6 +15,7 @@ beforeAll(async () => {});afterAll(async () => {+ resetGateway(); // R5: restore the preload baseline for later files in this shardawait engine.disconnect();});diff --git a/test/doctor-federation-health.test.ts b/test/doctor-federation-health.test.tsindex 13f3d9db74..75220fa893 100644--- a/test/doctor-federation-health.test.ts+++ b/test/doctor-federation-health.test.ts@@ -9,7 +9,7 @@import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';import type { BrainEngine } from '../src/core/engine.ts';import { PGLiteEngine } from '../src/core/pglite-engine.ts';-import { configureGateway } from '../src/core/ai/gateway.ts';+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';import { checkFederationHealth } from '../src/commands/doctor.ts';let engine: PGLiteEngine;@@ -41,6 +41,7 @@ beforeAll(async () => {}, 30000);afterAll(async () => {+ resetGateway(); // R5: restore the preload baseline for later files in this shardawait engine.disconnect();});diff --git a/test/e2e/cross-modal-eval.test.ts b/test/e2e/cross-modal-eval.test.tsindex 619dcdf9ac..5204ad2e99 100644--- a/test/e2e/cross-modal-eval.test.ts+++ b/test/e2e/cross-modal-eval.test.ts@@ -17,7 +17,7 @@ import { mkdtempSync, readdirSync, readFileSync, rmSync } from 'fs';import { tmpdir } from 'os';import { join } from 'path';-import { configureGateway } from '../../src/core/ai/gateway.ts';+import { configureGateway, resetGateway } from '../../src/core/ai/gateway.ts';let tempDir: string;@@ -41,6 +41,7 @@ beforeEach(() => {afterEach(() => {rmSync(tempDir, { recursive: true, force: true });mock.restore();+ resetGateway();});function makeChatStub(scoresBySlot: Record<string, number[]>) {diff --git a/test/engine-find-trajectory.test.ts b/test/engine-find-trajectory.test.tsindex 931b663739..43a0c6cb2e 100644--- a/test/engine-find-trajectory.test.ts+++ b/test/engine-find-trajectory.test.ts@@ -15,7 +15,7 @@import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';import { PGLiteEngine } from '../src/core/pglite-engine.ts';-import { configureGateway } from '../src/core/ai/gateway.ts';+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';import {detectRegressions,computeDriftScore,@@ -44,6 +44,7 @@ beforeAll(async () => {});afterAll(async () => {+ resetGateway(); // R5: restore the preload baseline for later files in this shardawait engine.disconnect();});diff --git a/test/engine-surface-coverage.test.ts b/test/engine-surface-coverage.test.tsindex d1b6680872..112aacbf0f 100644--- a/test/engine-surface-coverage.test.ts+++ b/test/engine-surface-coverage.test.ts@@ -37,7 +37,7 @@ import { describe, test, expect, beforeAll, afterAll } from 'bun:test';import { readdirSync, readFileSync } from 'node:fs';import { join } from 'node:path';import { PGLiteEngine } from '../src/core/pglite-engine.ts';-import { configureGateway } from '../src/core/ai/gateway.ts';+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';const DIM = 1536;@@ -356,6 +356,7 @@ describe('uncovered-method smokes (seeded PGLite)', () => {afterAll(async () => {await engine.disconnect();+ resetGateway(); // R5: restore the preload baseline for later files in this shard});test('kind discriminator (readonly instance property, not on the prototype)', () => {diff --git a/test/fact-embedding-opt-out.test.ts b/test/fact-embedding-opt-out.test.tsindex 5f2bb14131..6e4a415b6e 100644--- a/test/fact-embedding-opt-out.test.ts+++ b/test/fact-embedding-opt-out.test.ts@@ -15,7 +15,7 @@ import type { BrainEngine } from '../src/core/engine.ts';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { serializePageToMarkdown } from '../src/core/markdown.ts';import { operationsByName } from '../src/core/operations.ts';-import { configureGateway, __setChatTransportForTests, __setEmbedTransportForTests } from '../src/core/ai/gateway.ts';+import { configureGateway, resetGateway, __setChatTransportForTests, __setEmbedTransportForTests } from '../src/core/ai/gateway.ts';import { writeSingleFact } from '../src/core/facts/write-single.ts';import { extractFactsFromTurnWithOutcome } from '../src/core/facts/extract.ts';import { startPersistenceConsumer } from '../src/core/persistence/service.ts';@@ -41,6 +41,7 @@ beforeEach(() => {}) as never);});afterEach(() => { __setEmbedTransportForTests(null); __setChatTransportForTests(null); });+afterAll(() => { resetGateway(); }); // R5: restore the preload baseline for later files in this shardasync function seedEntity(engine: BrainEngine, root: string): Promise<void> {const person = await engine.putPage(ENTITY, { type: 'person', title: 'Opt Out Example', compiled_truth: '# Opt Out Example' }, { sourceId: 'default' });diff --git a/test/fixtures/guards/check-test-isolation.sh/bad-r1/test/env-mutation.test.fixture.ts b/test/fixtures/guards/check-test-isolation.sh/bad-r1/test/env-mutation.test.fixture.tsnew file mode 100644index 0000000000..56d16943e8--- /dev/null+++ b/test/fixtures/guards/check-test-isolation.sh/bad-r1/test/env-mutation.test.fixture.ts@@ -0,0 +1,4 @@+import { test } from 'bun:test';++// R1: a process.env write leaks to later files in the shard.+test('x', () => { process.env.GBRAIN_TEST_EXAMPLE = '1'; });diff --git a/test/fixtures/guards/check-test-isolation.sh/bad/test/gateway-leak.test.fixture.ts b/test/fixtures/guards/check-test-isolation.sh/bad/test/gateway-leak.test.fixture.tsnew file mode 100644index 0000000000..d28791e9df--- /dev/null+++ b/test/fixtures/guards/check-test-isolation.sh/bad/test/gateway-leak.test.fixture.ts@@ -0,0 +1,5 @@+import { beforeAll } from 'bun:test';+import { configureGateway } from '../../../../../../src/core/ai/gateway.ts';++// R5: the process-global gateway is configured and never reset.+beforeAll(() => configureGateway({ embedding_model: 'litellm:example', env: {} }));diff --git a/test/fixtures/guards/check-test-isolation.sh/good/test/gateway-reset.test.fixture.ts b/test/fixtures/guards/check-test-isolation.sh/good/test/gateway-reset.test.fixture.tsnew file mode 100644index 0000000000..6656147fd7--- /dev/null+++ b/test/fixtures/guards/check-test-isolation.sh/good/test/gateway-reset.test.fixture.ts@@ -0,0 +1,6 @@+import { afterAll, beforeAll } from 'bun:test';+import { configureGateway, resetGateway } from '../../../../../../src/core/ai/gateway.ts';++// configureGateway() is paired with resetGateway(); a comment mention is ignored.+beforeAll(() => configureGateway({ embedding_model: 'litellm:example', env: {} }));+afterAll(() => resetGateway());diff --git a/test/fixtures/guards/check-test-isolation.sh/good/test/gateway-subprocess.test.fixture.ts b/test/fixtures/guards/check-test-isolation.sh/good/test/gateway-subprocess.test.fixture.tsnew file mode 100644index 0000000000..acebd92d37--- /dev/null+++ b/test/fixtures/guards/check-test-isolation.sh/good/test/gateway-subprocess.test.fixture.ts@@ -0,0 +1,5 @@+// isolation-lint: R5-subprocess-only — the call below runs in a spawned child's script string.+const script = `+ configureGateway({ env: {} });+`;+void script;diff --git a/test/get-page-content-roundtrip-2225.test.ts b/test/get-page-content-roundtrip-2225.test.tsindex 2ac3feeec0..89fd0d7365 100644--- a/test/get-page-content-roundtrip-2225.test.ts+++ b/test/get-page-content-roundtrip-2225.test.ts@@ -18,7 +18,7 @@import { describe, test, expect, beforeAll, afterAll } from 'bun:test';import { PGLiteEngine } from '../src/core/pglite-engine.ts';-import { configureGateway } from '../src/core/ai/gateway.ts';+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';import { operations, type OperationContext } from '../src/core/operations.ts';import type { GBrainConfig } from '../src/core/config.ts';import { OperationError } from '../src/core/ops/contract.ts';@@ -50,6 +50,7 @@ beforeAll(async () => {}, 120_000);afterAll(async () => {+ resetGateway(); // R5: restore the preload baseline for later files in this shardawait engine.disconnect();}, 30_000);diff --git a/test/nightly-probe-exit-isolation.test.ts b/test/nightly-probe-exit-isolation.test.tsindex e963896311..a6e5b046d9 100644--- a/test/nightly-probe-exit-isolation.test.ts+++ b/test/nightly-probe-exit-isolation.test.ts@@ -18,6 +18,8 @@ function run(script: string) {}}+// isolation-lint: R5-subprocess-only — configureGateway() below runs inside the+// spawned child's script string, never in this shard process, so it cannot leak.describe('embedded nightly probe failures (#5095)', () => {test('missing chat configuration is audited before embedding work and rate-limited', () => {const child = run(`diff --git a/test/query-embedding-opt-out.test.ts b/test/query-embedding-opt-out.test.tsindex 6ee842b4a7..d0ede4ec69 100644--- a/test/query-embedding-opt-out.test.ts+++ b/test/query-embedding-opt-out.test.ts@@ -14,7 +14,7 @@ import type { BrainEngine } from '../src/core/engine.ts';import type { OperationContext } from '../src/core/operations.ts';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { operationsByName } from '../src/core/operations.ts';-import { configureGateway, __setEmbedTransportForTests } from '../src/core/ai/gateway.ts';+import { configureGateway, resetGateway, __setEmbedTransportForTests } from '../src/core/ai/gateway.ts';import { embedQuery } from '../src/core/embedding.ts';import { runThink } from '../src/core/think/index.ts';import { dispatchToolCall } from '../src/mcp/dispatch.ts';@@ -44,6 +44,7 @@ beforeEach(() => {}) as never);});afterEach(() => { __setEmbedTransportForTests(null); });+afterAll(() => { resetGateway(); }); // R5: restore the preload baseline for later files in this shardfunction ctxOf(engine: BrainEngine, meta: Array<{ key: string; value: unknown }>): OperationContext {return { engine: engine as never, config: { engine: engine.kind } as never, logger: console as never, dryRun: false, remote: false, sourceId: 'default',diff --git a/test/repair-extractor-facts.test.ts b/test/repair-extractor-facts.test.tsindex e34a3f9c63..658f76ef7e 100644--- a/test/repair-extractor-facts.test.ts+++ b/test/repair-extractor-facts.test.ts@@ -41,7 +41,7 @@ import { managedBrain } from './helpers/managed-brain.ts';import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';import { withEnv } from './helpers/with-env.ts';-import { configureGateway, __setEmbedTransportForTests } from '../src/core/ai/gateway.ts';+import { configureGateway, resetGateway, __setEmbedTransportForTests } from '../src/core/ai/gateway.ts';import { startPersistenceConsumer } from '../src/core/persistence/service.ts';import { LEGACY_EMBEDDING_CONFIG } from './helpers/legacy-embedding-config.ts';@@ -428,6 +428,7 @@ for (const backend of testBackends()) {} });} finally {__setEmbedTransportForTests(null);+ resetGateway(); // R5: restore the preload baseline for later tests and files in this shard}}, 180_000);});diff --git a/test/scripts/check-test-isolation.test.ts b/test/scripts/check-test-isolation.test.tsindex 267cf4aa51..bf6db1ab8a 100644--- a/test/scripts/check-test-isolation.test.ts+++ b/test/scripts/check-test-isolation.test.ts@@ -236,6 +236,93 @@ describe('check-test-isolation.sh', () => {});});+ describe('R5 — configureGateway() requires resetGateway()', () => {+ it('flags configureGateway without any resetGateway', () => {+ const r = runLintIn([+ {+ path: 'gw-leak.test.ts',+ contents:+ `import { beforeAll } from 'bun:test';\n` ++ `import { configureGateway } from '../src/core/ai/gateway.ts';\n` ++ `beforeAll(() => configureGateway({ embedding_model: 'litellm:x', env: {} }));\n`,+ },+ ]);+ expect(r.status).toBe(1);+ expect(r.stdout).toContain('R5');+ expect(r.stdout).toContain('gw-leak.test.ts');+ });++ it('flags a dynamic-import configureGateway call', () => {+ const r = runLintIn([+ {+ path: 'gw-dyn.test.ts',+ contents: `test('x', async () => { (await import('../src/core/ai/gateway.ts')).configureGateway({ env: {} }); });\n`,+ },+ ]);+ expect(r.status).toBe(1);+ expect(r.stdout).toContain('R5');+ });++ it('does NOT flag configureGateway paired with afterAll(resetGateway)', () => {+ const r = runLintIn([+ {+ path: 'gw-ok.test.ts',+ contents:+ `import { beforeAll, afterAll } from 'bun:test';\n` ++ `import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';\n` ++ `beforeAll(() => configureGateway({ env: {} }));\n` ++ `afterAll(() => resetGateway());\n`,+ },+ ]);+ expect(r.status).toBe(0);+ });++ it('a resetGateway() mention inside a comment does NOT satisfy R5', () => {+ const r = runLintIn([+ {+ path: 'gw-comment-reset.test.ts',+ contents:+ `// a co-sharded test that calls resetGateway() would reshuffle us\n` ++ `configureGateway({ env: {} });\n`,+ },+ ]);+ expect(r.status).toBe(1);+ expect(r.stdout).toContain('R5');+ });++ it('a configureGateway() mention only in comments is NOT flagged', () => {+ const r = runLintIn([+ {+ path: 'gw-comment-only.test.ts',+ contents:+ `/**\n * configureGateway() pushes the snapshot (push seam)\n */\n` ++ `// configureGateway() is not called here\n` ++ `test('x', () => {});\n`,+ },+ ]);+ expect(r.status).toBe(0);+ });++ it('skips *.serial.test.ts', () => {+ const r = runLintIn([+ { path: 'gw.serial.test.ts', contents: `configureGateway({ env: {} });\n` },+ ]);+ expect(r.status).toBe(0);+ });++ it('honors the R5-subprocess-only pragma (call runs in a spawned child)', () => {+ const r = runLintIn([+ {+ path: 'gw-subprocess.test.ts',+ contents:+ `// isolation-lint: R5-subprocess-only — script string runs in a child process\n` ++ `const script = \`\n configureGateway({ env: {} });\n\`;\n`,+ },+ ]);+ expect(r.status).toBe(0);+ });+ });+describe('scope', () => {it('skips *.serial.test.ts files entirely', () => {const r = runLintIn([diff --git a/test/search/arm-confidence-hybrid.test.ts b/test/search/arm-confidence-hybrid.test.tsindex caca16d3e6..a89c07ed71 100644--- a/test/search/arm-confidence-hybrid.test.ts+++ b/test/search/arm-confidence-hybrid.test.ts@@ -24,7 +24,7 @@import { describe, test, expect, beforeAll, afterAll } from 'bun:test';import { PGLiteEngine } from '../../src/core/pglite-engine.ts';import { installFixtureChunks } from '../helpers/page-projection.ts';-import { configureGateway } from '../../src/core/ai/gateway.ts';+import { configureGateway, resetGateway } from '../../src/core/ai/gateway.ts';import { hybridSearch } from '../../src/core/search/hybrid.ts';import { basisEmbedding } from '../../src/eval/deterministic-embed.ts';import type { HybridSearchMeta } from '../../src/core/types.ts';@@ -87,6 +87,7 @@ beforeAll(async () => {}, 120_000);afterAll(async () => {+ resetGateway(); // R5: restore the preload baseline for later files in this shardawait engine.disconnect();});diff --git a/test/search/concept-weights.test.ts b/test/search/concept-weights.test.tsindex eaf5d6351a..7c174d1c51 100644--- a/test/search/concept-weights.test.ts+++ b/test/search/concept-weights.test.ts@@ -22,7 +22,7 @@import { describe, test, expect, beforeAll, afterAll } from 'bun:test';import { PGLiteEngine } from '../../src/core/pglite-engine.ts';import { installFixtureChunks } from '../helpers/page-projection.ts';-import { configureGateway } from '../../src/core/ai/gateway.ts';+import { configureGateway, resetGateway } from '../../src/core/ai/gateway.ts';import { hybridSearch } from '../../src/core/search/hybrid.ts';import { classifyQueryIntent } from '../../src/core/search/query-intent.ts';import { basisEmbedding } from '../../src/eval/deterministic-embed.ts';@@ -81,6 +81,7 @@ beforeAll(async () => {}, 120_000);afterAll(async () => {+ resetGateway(); // R5: restore the preload baseline for later files in this shardawait engine.disconnect();});diff --git a/test/search/expansion-variant-budget.test.ts b/test/search/expansion-variant-budget.test.tsindex e936582f09..d81dcb8226 100644--- a/test/search/expansion-variant-budget.test.ts+++ b/test/search/expansion-variant-budget.test.ts@@ -27,7 +27,7 @@import { describe, test, expect, beforeAll, afterAll } from 'bun:test';import { PGLiteEngine } from '../../src/core/pglite-engine.ts';import { installFixtureChunks } from '../helpers/page-projection.ts';-import { configureGateway } from '../../src/core/ai/gateway.ts';+import { configureGateway, resetGateway } from '../../src/core/ai/gateway.ts';import { hybridSearch } from '../../src/core/search/hybrid.ts';import { basisEmbedding } from '../../src/eval/deterministic-embed.ts';import type { HybridSearchMeta } from '../../src/core/types.ts';@@ -87,6 +87,7 @@ beforeAll(async () => {}, 120_000);afterAll(async () => {+ resetGateway(); // R5: restore the preload baseline for later files in this shardawait engine.disconnect();}, 60_000);diff --git a/test/search/metadata-boost-gate-hybrid.test.ts b/test/search/metadata-boost-gate-hybrid.test.tsindex b945c2cc7b..51001da561 100644--- a/test/search/metadata-boost-gate-hybrid.test.ts+++ b/test/search/metadata-boost-gate-hybrid.test.ts@@ -26,7 +26,7 @@import { describe, test, expect, beforeAll, afterAll } from 'bun:test';import { PGLiteEngine } from '../../src/core/pglite-engine.ts';import { installFixtureChunks } from '../helpers/page-projection.ts';-import { configureGateway } from '../../src/core/ai/gateway.ts';+import { configureGateway, resetGateway } from '../../src/core/ai/gateway.ts';import { hybridSearch } from '../../src/core/search/hybrid.ts';import { basisEmbedding } from '../../src/eval/deterministic-embed.ts';import type { HybridSearchMeta, SearchResult } from '../../src/core/types.ts';@@ -108,6 +108,7 @@ beforeAll(async () => {}, 120_000);afterAll(async () => {+ resetGateway(); // R5: restore the preload baseline for later files in this shardawait engine.disconnect();}, 60_000);diff --git a/test/search/searchvector-escalation.test.ts b/test/search/searchvector-escalation.test.tsindex bb239c2e62..6e938b0e77 100644--- a/test/search/searchvector-escalation.test.ts+++ b/test/search/searchvector-escalation.test.ts@@ -19,7 +19,7 @@import { describe, test, expect, beforeAll, afterAll } from 'bun:test';import { PGLiteEngine } from '../../src/core/pglite-engine.ts';import { installFixtureChunks } from '../helpers/page-projection.ts';-import { configureGateway } from '../../src/core/ai/gateway.ts';+import { configureGateway, resetGateway } from '../../src/core/ai/gateway.ts';import type { ChunkInput } from '../../src/core/types.ts';let engine: PGLiteEngine;@@ -83,6 +83,7 @@ beforeAll(async () => {}, 120_000);afterAll(async () => {+ resetGateway(); // R5: restore the preload baseline for later files in this shardawait engine.disconnect();});diff --git a/test/search/searchvector-maxpool.test.ts b/test/search/searchvector-maxpool.test.tsindex dc646aa7ef..0ef86d00ab 100644--- a/test/search/searchvector-maxpool.test.ts+++ b/test/search/searchvector-maxpool.test.ts@@ -24,7 +24,7 @@import { describe, test, expect, beforeAll, afterAll } from 'bun:test';import { PGLiteEngine } from '../../src/core/pglite-engine.ts';import { installFixtureChunks } from '../helpers/page-projection.ts';-import { configureGateway } from '../../src/core/ai/gateway.ts';+import { configureGateway, resetGateway } from '../../src/core/ai/gateway.ts';import type { ChunkInput } from '../../src/core/types.ts';let engine: PGLiteEngine;@@ -95,6 +95,7 @@ beforeAll(async () => {}, 60_000);afterAll(async () => {+ resetGateway(); // R5: restore the preload baseline for later files in this shardawait engine.disconnect();}, 60_000);diff --git a/test/search/title-arm-exact.test.ts b/test/search/title-arm-exact.test.tsindex 91da13e8f7..2298dbbc11 100644--- a/test/search/title-arm-exact.test.ts+++ b/test/search/title-arm-exact.test.ts@@ -17,7 +17,7 @@ import type { BrainEngine } from '../../src/core/engine.ts';import type { SearchOpts } from '../../src/core/types.ts';import { PGLiteEngine } from '../../src/core/pglite-engine.ts';import { hybridSearch, hybridSearchCached } from '../../src/core/search/hybrid.ts';-import { configureGateway } from '../../src/core/ai/gateway.ts';+import { configureGateway, resetGateway } from '../../src/core/ai/gateway.ts';import { installFixtureChunks } from '../helpers/page-projection.ts';import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';import { testBackends } from '../helpers/test-backends.ts';@@ -47,7 +47,7 @@ for (const kind of testBackends()) {afterAll(async () => {await close?.();- configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: DIM, env: { ...process.env } });+ resetGateway(); // R5: restore the preload baseline for later files in this shard});beforeEach(async () => {diff --git a/test/search/title-retrieval-arm.test.ts b/test/search/title-retrieval-arm.test.tsindex ee614ac274..cc8cc3653e 100644--- a/test/search/title-retrieval-arm.test.ts+++ b/test/search/title-retrieval-arm.test.ts@@ -34,7 +34,7 @@ import {boundWebsearchQuery,buildOrFallbackWebsearchQuery,} from '../../src/core/search/sql-ranking.ts';-import { configureGateway } from '../../src/core/ai/gateway.ts';+import { configureGateway, resetGateway } from '../../src/core/ai/gateway.ts';let engine: PGLiteEngine;@@ -55,12 +55,9 @@ beforeAll(async () => {afterAll(async () => {await engine.disconnect();- // Restore the preload-equivalent gateway for sibling files in this shard.- configureGateway({- embedding_model: 'openai:text-embedding-3-large',- embedding_dimensions: DIM,- env: { ...process.env },- });+ // R5: restore the preload baseline for sibling files in this shard; resetGateway()+ // re-applies the registered baseline factory, so it cannot drift from it.+ resetGateway();});beforeEach(async () => {diff --git a/test/write-attribution-cycle.test.ts b/test/write-attribution-cycle.test.tsindex b3bcf8c546..98003f742c 100644--- a/test/write-attribution-cycle.test.ts+++ b/test/write-attribution-cycle.test.ts@@ -33,7 +33,7 @@ import { persistSynthesis, type ThinkResult } from '../src/core/think/index.ts';import { writeReceipt } from '../src/core/extract/receipt-writer.ts';import { renderFactsTable } from '../src/core/facts-fence.ts';import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';-import { configureGateway, type ChatResult } from '../src/core/ai/gateway.ts';+import { configureGateway, resetGateway, type ChatResult } from '../src/core/ai/gateway.ts';import { LEGACY_EMBEDDING_CONFIG } from './helpers/legacy-embedding-config.ts';import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';import { withEnv } from './helpers/with-env.ts';@@ -54,6 +54,7 @@ beforeAll(async () => {}}, 120_000);afterAll(async () => {+ resetGateway(); // R5: restore the preload baseline for later files in this shardfor (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }await closePostgres?.();rmSync(scratch, { recursive: true, force: true });diff --git a/test/write-attribution-import.test.ts b/test/write-attribution-import.test.tsindex 918d0621d9..3a03946998 100644--- a/test/write-attribution-import.test.ts+++ b/test/write-attribution-import.test.ts@@ -17,7 +17,7 @@ import { PGLiteEngine } from '../src/core/pglite-engine.ts';import type { BrainEngine } from '../src/core/engine.ts';import { importFromFile } from '../src/core/import-file.ts';import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';-import { configureGateway } from '../src/core/ai/gateway.ts';+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';import { LEGACY_EMBEDDING_CONFIG } from './helpers/legacy-embedding-config.ts';import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';import { revisionActor, unmanagedBrain } from './helpers/unmanaged-attribution.ts';@@ -35,6 +35,7 @@ beforeAll(async () => {}}, 120_000);afterAll(async () => {+ resetGateway(); // R5: restore the preload baseline for later files in this shardfor (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }await closePostgres?.();rmSync(scratch, { recursive: true, force: true });diff --git a/test/write-attribution-legacy.test.ts b/test/write-attribution-legacy.test.tsindex e36c5562e9..5e6e0b4f58 100644--- a/test/write-attribution-legacy.test.ts+++ b/test/write-attribution-legacy.test.ts@@ -27,7 +27,7 @@ import { extractTakes } from '../src/core/cycle/extract-takes.ts';import { runRepairCommand } from '../src/commands/repair.ts';import { renderFactsTable } from '../src/core/facts-fence.ts';import { renderTakesFence } from '../src/core/takes-fence.ts';-import { configureGateway } from '../src/core/ai/gateway.ts';+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';import { LEGACY_EMBEDDING_CONFIG } from './helpers/legacy-embedding-config.ts';import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';@@ -44,6 +44,7 @@ beforeAll(async () => {}}, 120_000);afterAll(async () => {+ resetGateway(); // R5: restore the preload baseline for later files in this shardfor (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }await closePostgres?.();rmSync(scratch, { recursive: true, force: true });diff --git a/test/write-attribution-misc.test.ts b/test/write-attribution-misc.test.tsindex 9d82bc5def..e1cbbf3a62 100644--- a/test/write-attribution-misc.test.ts+++ b/test/write-attribution-misc.test.ts@@ -27,7 +27,7 @@ import { softDeleteSyncPages } from '../src/core/company-brain/profile.ts';import { makeIngestCaptureHandler } from '../src/core/minions/handlers/ingest-capture.ts';import { writeDerivedFacts } from '../src/core/persistence/derived-facts.ts';import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';-import { configureGateway } from '../src/core/ai/gateway.ts';+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';import { LEGACY_EMBEDDING_CONFIG } from './helpers/legacy-embedding-config.ts';import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';import { withEnv } from './helpers/with-env.ts';@@ -46,6 +46,7 @@ beforeAll(async () => {}}, 120_000);afterAll(async () => {+ resetGateway(); // R5: restore the preload baseline for later files in this shardfor (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }await closePostgres?.();rmSync(scratch, { recursive: true, force: true });diff --git a/test/write-attribution-schema-pack.test.ts b/test/write-attribution-schema-pack.test.tsindex cbe3a01529..da6353a617 100644--- a/test/write-attribution-schema-pack.test.ts+++ b/test/write-attribution-schema-pack.test.ts@@ -24,7 +24,7 @@ import { runSyncCore } from '../src/core/schema-pack/sync.ts';import { __setPackLocatorForTests, _resetPackLocatorForTests } from '../src/core/schema-pack/load-active.ts';import { _resetPackCacheForTests } from '../src/core/schema-pack/registry.ts';import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';-import { configureGateway } from '../src/core/ai/gateway.ts';+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';import { LEGACY_EMBEDDING_CONFIG } from './helpers/legacy-embedding-config.ts';import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';import { withEnv } from './helpers/with-env.ts';@@ -43,6 +43,7 @@ beforeAll(async () => {}}, 120_000);afterAll(async () => {+ resetGateway(); // R5: restore the preload baseline for later files in this shard_resetPackLocatorForTests();_resetPackCacheForTests();for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }diff --git a/test/write-attribution-sync.test.ts b/test/write-attribution-sync.test.tsindex 92fe9c3699..ee503874e9 100644--- a/test/write-attribution-sync.test.ts+++ b/test/write-attribution-sync.test.ts@@ -21,7 +21,7 @@ import { PGLiteEngine } from '../src/core/pglite-engine.ts';import type { BrainEngine } from '../src/core/engine.ts';import { performSync } from '../src/commands/sync.ts';import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';-import { configureGateway } from '../src/core/ai/gateway.ts';+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';import { LEGACY_EMBEDDING_CONFIG } from './helpers/legacy-embedding-config.ts';import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';import { makeGitFixture } from './helpers/git-fixture.ts';@@ -46,6 +46,7 @@ beforeAll(async () => {}}, 120_000);afterAll(async () => {+ resetGateway(); // R5: restore the preload baseline for later files in this shardfor (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }await closePostgres?.();rmSync(home, { recursive: true, force: true });diff --git a/test/write-attribution-timeline-10k.slow.test.ts b/test/write-attribution-timeline-10k.slow.test.tsindex a54d07dd43..df676a2b0b 100644--- a/test/write-attribution-timeline-10k.slow.test.ts+++ b/test/write-attribution-timeline-10k.slow.test.ts@@ -16,7 +16,7 @@ import { PGLiteEngine } from '../src/core/pglite-engine.ts';import type { BrainEngine } from '../src/core/engine.ts';import { extractTimelineFromDB } from '../src/commands/extract-timeline-db.ts';import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';-import { configureGateway } from '../src/core/ai/gateway.ts';+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';import { LEGACY_EMBEDDING_CONFIG } from './helpers/legacy-embedding-config.ts';import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';import { unmanagedBrain } from './helpers/unmanaged-attribution.ts';@@ -34,6 +34,7 @@ beforeAll(async () => {}}, 120_000);afterAll(async () => {+ resetGateway(); // R5: restore the preload baseline for later files in this shardfor (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }await closePostgres?.();});diff --git a/test/write-attribution-timeline.test.ts b/test/write-attribution-timeline.test.tsindex 813cc3f2f8..6317ab8449 100644--- a/test/write-attribution-timeline.test.ts+++ b/test/write-attribution-timeline.test.ts@@ -23,7 +23,7 @@ import { writeTimelineEntryThrough } from '../src/core/timeline-write-through.tsimport { importFromContent } from '../src/core/import-file.ts';import { writePageThrough, _resetWriteThroughCacheForTest } from '../src/core/write-through.ts';import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';-import { configureGateway } from '../src/core/ai/gateway.ts';+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';import { LEGACY_EMBEDDING_CONFIG } from './helpers/legacy-embedding-config.ts';import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';import { asCreator, revisionActor, rowActors, unmanagedBrain, type UnmanagedBrain } from './helpers/unmanaged-attribution.ts';@@ -43,6 +43,7 @@ beforeAll(async () => {}}, 120_000);afterAll(async () => {+ resetGateway(); // R5: restore the preload baseline for later files in this shardfor (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }await closePostgres?.();rmSync(scratch, { recursive: true, force: true });diff --git a/test/write-attribution.test.ts b/test/write-attribution.test.tsindex 26a43ffe4d..4479a832ed 100644--- a/test/write-attribution.test.ts+++ b/test/write-attribution.test.ts@@ -30,7 +30,7 @@ import { replaceDerivedFactsForPage } from '../src/core/persistence/derived-factimport type { Principal } from '../src/core/persistence/model.ts';import { renderFactsTable } from '../src/core/facts-fence.ts';import { renderTakesFence } from '../src/core/takes-fence.ts';-import { configureGateway, __setEmbedTransportForTests } from '../src/core/ai/gateway.ts';+import { configureGateway, resetGateway, __setEmbedTransportForTests } from '../src/core/ai/gateway.ts';import { LEGACY_EMBEDDING_CONFIG } from './helpers/legacy-embedding-config.ts';import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';@@ -60,6 +60,7 @@ beforeAll(async () => {}}, 120_000);afterAll(async () => {+ resetGateway(); // R5: restore the preload baseline for later files in this shardfor (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }await closePostgres?.();rmSync(home, { recursive: true, force: true });