Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

test(think): the unconfigured-gateway fixtures stop reaching the provider; lint R7 guards the restore

garrytan81def60a7f75
diff --git a/docs/TESTING.md b/docs/TESTING.md
index 6697a4f5d2..4a9c6d5128 100644
--- a/docs/TESTING.md
+++ b/docs/TESTING.md
@@ -1453,6 +1453,7 @@ cross-subsystem duplicate entries, and byte caps for the entry docs and referenc
| **R4** | `new PGLiteEngine(` without `engine.disconnect(` in an `afterAll(` block | `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` |
| **R6** | `currentExitCode(` with no verdict reset outside an after-hook | `beforeEach(() => _resetCliExitVerdictForTests())` |
+| **R7** | `__unconfigureGatewayForTests(` or `_clearGatewayForTests(` with no `resetGateway(` in an `afterEach`/`afterAll` hook (comments ignored): an empty gateway leaks to the next file's `beforeAll`, and an inline restore does not survive a throw or a `-t` filter | `afterEach(() => resetGateway())`; note that `resetGateway()` alone re-applies the preload's configured baseline and is not "unconfigured" (#6514) |
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.
diff --git a/scripts/check-test-isolation.sh b/scripts/check-test-isolation.sh
index 1b83f5058e..c1c8b159a6 100755
--- a/scripts/check-test-isolation.sh
+++ b/scripts/check-test-isolation.sh
@@ -35,6 +35,13 @@
# connectors sync), so a reset only in afterEach still reads the
# previous file's verdict in its first test: edge-proposals-json-bigint
# failed this way three times after a shard reshuffle.
+# R7: a file whose code calls `__unconfigureGatewayForTests(` or
+# `_clearGatewayForTests(` must call `resetGateway(` from an
+# afterEach/afterAll hook (or pass it as the hook: `afterEach(resetGateway)`).
+# An unconfigured gateway is process-global too: the next file's
+# beforeAll then sizes its PGLite schema from nothing, and a `-t`
+# filtered run or a throw before an inline restore leaves it empty.
+# Comments do not count either way (#6514).
#
# Scope:
# - Recursively scans `test/**/*.test.ts`.
@@ -176,7 +183,34 @@ GATEWAY_CODE_SCAN='
}
END { if (calls != "" && !restored) printf "%s", calls }
'
-CANDIDATES="$(guard_candidates -E -e "$ENV_MUTATION_PATTERN" -e "$MODULE_MOCK_PATTERN" -e "$ENGINE_PATTERN" -e "$GATEWAY_PATTERN" -e "$VERDICT_PATTERN" <<< "$FILE_LIST")"
+UNCONFIGURE_PATTERN='(__unconfigureGatewayForTests|_clearGatewayForTests)[[:space:]]*\('
+# R7: same comment removal; a resetGateway call counts only inside an
+# afterEach/afterAll block (brace depth from the hook's line) or on the
+# hook line itself. Prints the unconfigure lines when no hook restore is left.
+UNCONFIGURE_CODE_SCAN='
+ in_block {
+ if (index($0, "*/") == 0) next
+ in_block = 0
+ next
+ }
+ /^[[:space:]]*\/\*/ {
+ if (index(substr($0, index($0, "/*") + 2), "*/") == 0) in_block = 1
+ next
+ }
+ {
+ code = $0
+ sub(/(^|[[:space:];,(){}])\/\/.*$/, "", code)
+ opens = gsub(/\{/, "{", code); closes = gsub(/\}/, "}", code)
+ if (in_after) { depth += opens - closes; if (code ~ /resetGateway[[:space:]]*\(/) restored = 1; if (depth <= 0) in_after = 0; next }
+ if (code ~ /after(Each|All)[[:space:]]*\(/) {
+ if (code ~ /resetGateway/) restored = 1
+ depth = opens - closes; if (depth > 0) in_after = 1; next
+ }
+ if (code ~ /(__unconfigureGatewayForTests|_clearGatewayForTests)[[:space:]]*\(/ && code !~ /import/) calls = calls NR ":" $0 "\n"
+ }
+ END { if (calls != "" && !restored) printf "%s", calls }
+'
+CANDIDATES="$(guard_candidates -E -e "$ENV_MUTATION_PATTERN" -e "$MODULE_MOCK_PATTERN" -e "$ENGINE_PATTERN" -e "$GATEWAY_PATTERN" -e "$VERDICT_PATTERN" -e "$UNCONFIGURE_PATTERN" <<< "$FILE_LIST")"
violations=0
file_count=0
@@ -258,6 +292,13 @@ while IFS= read -r f; do
emit_violation "$f" "R6" "currentExitCode() read with no baseline; the verdict is process-global, so the first test reads whatever the previous file in the shard left. Call _resetCliExitVerdictForTests() in beforeEach (or before the run it checks), not only in afterEach" "$unbased"
fi
fi
+ # R7: the gateway is unconfigured but no after-hook puts the baseline back.
+ if grep -qE "$UNCONFIGURE_PATTERN" "$f" 2>/dev/null; then
+ unrestored=$(awk "$UNCONFIGURE_CODE_SCAN" "$f" 2>/dev/null || true)
+ if [ -n "$unrestored" ]; then
+ emit_violation "$f" "R7" "__unconfigureGatewayForTests()/_clearGatewayForTests() with no resetGateway() in an afterEach/afterAll hook; an empty gateway is process-global, so the next file's beforeAll sizes its schema from nothing. Add afterEach(() => resetGateway()) (an inline restore does not survive a throw or a -t filter) or rename to *.serial.test.ts" "$unrestored"
+ fi
+ fi
done <<EOF
$FILE_LIST
EOF
@@ -275,6 +316,8 @@ if [ $violations -gt 0 ]; then
echo " puts back the preload's baseline gateway for the next file."
echo " - For currentExitCode(), reset the verdict in beforeEach (or right"
echo " before the run it checks) with _resetCliExitVerdictForTests()."
+ echo " - For __unconfigureGatewayForTests(), call resetGateway() in"
+ echo " afterEach or afterAll; it puts back the preload's baseline gateway."
echo
echo "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/test/chronicle-upgrade-notice-5876.test.ts b/test/chronicle-upgrade-notice-5876.test.ts
index d910b9d108..2f4183815a 100644
--- a/test/chronicle-upgrade-notice-5876.test.ts
+++ b/test/chronicle-upgrade-notice-5876.test.ts
@@ -10,7 +10,7 @@
* stale unset advice comes back.
* Seams: the provider view is passed in (pricing/provider state is config, not under test here).
*/
-import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { CHRONICLE_ACK_KEY, CHRONICLE_NOTICE_SHOWN_KEY } from '../src/core/chronicle/config.ts';
import { autoChronicleUpgradeNotice, printAutoChronicleUpgradeNotice } from '../src/core/chronicle/upgrade-notice.ts';
@@ -25,6 +25,8 @@ const priced = { model: 'anthropic:claude-sonnet-4-6', priced: true, chatAvailab
beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }, 120_000);
afterAll(async () => { await engine.disconnect(); });
+// The unconfigured-gateway case restores inline; the hook covers a throw before that restore (isolation lint R7).
+afterEach(() => { resetGateway(); });
beforeEach(async () => { for (const k of ['auto_chronicle', CHRONICLE_ACK_KEY, CHRONICLE_NOTICE_SHOWN_KEY]) await engine.unsetConfig(k); });
describe('auto_chronicle upgrade notice', () => {
diff --git a/test/scripts/check-test-isolation-r7.test.ts b/test/scripts/check-test-isolation-r7.test.ts
new file mode 100644
index 0000000000..f46969d033
--- /dev/null
+++ b/test/scripts/check-test-isolation-r7.test.ts
@@ -0,0 +1,91 @@
+/**
+ * Fixture tests for rule R7 of scripts/check-test-isolation.sh (#6514): a non-serial unit file that calls
+ * `__unconfigureGatewayForTests(` or `_clearGatewayForTests(` must put the preload's baseline gateway back from an
+ * afterEach/afterAll hook. The unit lane shares one gateway object per shard process, so an unconfigured gateway left
+ * behind by a throw or a `-t` filtered run reaches the next file's `beforeAll`.
+ *
+ * Same harness as test/scripts/check-test-isolation.test.ts: the lint runs in a tmpdir on hand-written fake files.
+ * This file is itself subject to the lint; its fixture strings go verbatim into the tmpdir, never into this process.
+ */
+
+import { describe, it, expect } from 'bun:test';
+import { spawnSync } from 'child_process';
+import { mkdtempSync, mkdirSync, writeFileSync } from 'fs';
+import { tmpdir } from 'os';
+import { join, resolve } from 'path';
+
+const REPO_ROOT = resolve(import.meta.dir, '..', '..');
+const LINT_SH = resolve(REPO_ROOT, 'scripts/check-test-isolation.sh');
+
+function lintOne(contents: string, path = 'gateway-unconfigure.test.ts'): { status: number; stdout: string } {
+ const dir = mkdtempSync(join(tmpdir(), 'lint-isolation-r7-'));
+ mkdirSync(join(dir, 'test'), { recursive: true });
+ mkdirSync(join(dir, 'scripts'), { recursive: true });
+ writeFileSync(join(dir, 'test', path), contents);
+ writeFileSync(join(dir, 'scripts/check-test-isolation.allowlist'), '');
+ const r = spawnSync('bash', [LINT_SH, 'test'], { cwd: dir, encoding: 'utf-8' });
+ return { status: r.status ?? -1, stdout: r.stdout };
+}
+
+const IMPORTS = `import { afterAll, afterEach, beforeAll, test } from 'bun:test';\n` +
+ `import { __unconfigureGatewayForTests, _clearGatewayForTests, resetGateway } from '../src/core/ai/gateway.ts';\n`;
+const UNCONFIGURE = `test('unconfigured', () => { __unconfigureGatewayForTests(); });\n`;
+
+describe('check-test-isolation.sh R7: an unconfigured gateway must be restored from an after-hook', () => {
+ it('bad fixture: unconfigure with no after-hook restore fails, naming the call line', () => {
+ const r = lintOne(IMPORTS + UNCONFIGURE);
+ expect(r.status).toBe(1);
+ expect(r.stdout).toContain('test/gateway-unconfigure.test.ts');
+ expect(r.stdout).toContain('rule R7');
+ expect(r.stdout).toContain("3:test('unconfigured', () => { __unconfigureGatewayForTests(); });");
+ });
+
+ it('bad fixture: an inline restore in the test body is not an after-hook restore', () => {
+ const r = lintOne(IMPORTS + `test('unconfigured', () => { try { __unconfigureGatewayForTests(); } finally { resetGateway(); } });\n`);
+ expect(r.status).toBe(1);
+ expect(r.stdout).toContain('rule R7');
+ });
+
+ it('bad fixture: _clearGatewayForTests is covered too', () => {
+ const r = lintOne(IMPORTS + `test('cleared', () => { _clearGatewayForTests(); });\n`);
+ expect(r.status).toBe(1);
+ expect(r.stdout).toContain('rule R7');
+ });
+
+ it('good fixtures: an afterEach or afterAll restore passes, in block, arrow and reference form', () => {
+ for (const hook of [
+ `afterEach(() => { resetGateway(); });\n`,
+ `afterEach(() => resetGateway());\n`,
+ `afterAll(() => {\n resetGateway();\n});\n`,
+ `afterEach(resetGateway);\n`,
+ ]) {
+ const r = lintOne(IMPORTS + UNCONFIGURE + hook);
+ expect(r.stdout).toContain('check-test-isolation: OK');
+ expect(r.status).toBe(0);
+ }
+ });
+
+ it('a restore that only appears in a comment does not count', () => {
+ for (const reset of [
+ `// afterEach(() => resetGateway()) lives in a sibling file\n`,
+ `/**\n * afterAll(resetGateway) would go here.\n */\n`,
+ ]) {
+ const r = lintOne(IMPORTS + UNCONFIGURE + reset);
+ expect(r.status).toBe(1);
+ expect(r.stdout).toContain('rule R7');
+ }
+ });
+
+ it('an unconfigure mention that only appears in a comment is not a call', () => {
+ for (const mention of [
+ `// __unconfigureGatewayForTests() is what the fixture should have used\n`,
+ `/*\n _clearGatewayForTests();\n*/\n`,
+ ]) {
+ expect(lintOne(mention + `test('u', () => {});\n`).status).toBe(0);
+ }
+ });
+
+ it('serial files are out of scope for R7', () => {
+ expect(lintOne(IMPORTS + UNCONFIGURE, 'gateway-unconfigure.serial.test.ts').status).toBe(0);
+ });
+});
diff --git a/test/think-gateway-adapter.test.ts b/test/think-gateway-adapter.test.ts
index f798fd1a58..5411c8dade 100644
--- a/test/think-gateway-adapter.test.ts
+++ b/test/think-gateway-adapter.test.ts
@@ -12,15 +12,22 @@
* - model-id normalization (bare → provider-prefixed)
* - response-shape conversion (ChatResult → Anthropic.Message)
*
- * These tests pin the four spec points. Hermetic — no real LLM call.
+ * These tests pin the four spec points. Hermetic — no real LLM call: the "unconfigured" fixtures use
+ * `__unconfigureGatewayForTests()` (since #3554 `resetGateway()` re-applies the preload's configured baseline, so
+ * it is NOT "unconfigured" and sent two real HTTPS requests to the provider with the fake key, #6514). Forced probe:
+ * `GBRAIN_TEST_NET_LOG=$L bun test --preload ./test/helpers/no-network-preload.ts test/think-gateway-adapter.test.ts`
+ * is 17/17 with an empty net log; the old fixtures were 16/17 with two provider URLs in the log.
*/
-import { describe, test, expect } from 'bun:test';
+import { describe, test, expect, afterEach } from 'bun:test';
import { __thinkAdapter } from '../src/core/think/index.ts';
-import { resetGateway } from '../src/core/ai/gateway.ts';
+import { resetGateway, __unconfigureGatewayForTests } from '../src/core/ai/gateway.ts';
import { AIConfigError } from '../src/core/ai/errors.ts';
import { withEnv, emptyHome } from './helpers/with-env.ts';
+// A filtered run must not leave the gateway empty for the next file's beforeAll (the #3554 baseline).
+afterEach(() => { resetGateway(); });
+
describe('think gateway adapter — response shape conversion', () => {
test('chatResultToMessage maps ChatResult.text to Anthropic.Message content[0].text', () => {
const out = __thinkAdapter.chatResultToMessage(
@@ -134,7 +141,7 @@ describe('think gateway adapter — #1698 slash form + explicit-model fork', ()
await withEnv({ ANTHROPIC_API_KEY: 'sk-test-fake' }, async () => {
// Build valid clients (key present → probe ok) but leave the gateway UNCONFIGURED
// so gateway.chat() throws AIConfigError (requireConfig) at create() time.
- resetGateway();
+ __unconfigureGatewayForTests();
const params: any = {
model: 'anthropic:claude-sonnet-4-6',
max_tokens: 16,
@@ -146,7 +153,8 @@ describe('think gateway adapter — #1698 slash form + explicit-model fork', ()
'anthropic:claude-sonnet-4-6', { explicitModel: true },
);
expect(explicitClient).not.toBeNull();
- await expect(explicitClient!.create(params)).rejects.toThrow();
+ // Specifically the config error: a network/auth error from a configured gateway must not satisfy this fork.
+ await expect(explicitClient!.create(params)).rejects.toBeInstanceOf(AIConfigError);
const gracefulClient = await __thinkAdapter.tryBuildGatewayClient(
'anthropic:claude-sonnet-4-6', { explicitModel: false },
@@ -169,7 +177,7 @@ describe('think gateway adapter — #1698 slash form + explicit-model fork', ()
await withEnv(
{ ANTHROPIC_API_KEY: undefined, DEEPSEEK_API_KEY: undefined, OPENAI_API_KEY: undefined, GBRAIN_HOME: emptyHome() },
async () => {
- resetGateway(); // unconfigured → gateway.chat() throws AIConfigError at create()
+ __unconfigureGatewayForTests(); // unconfigured → gateway.chat() throws AIConfigError at create()
// deepseek:deepseek-chat passes validateModelId (real recipe + chat touchpoint) — the
// A9 non-anthropic model. probeChatModel returns ok (no anthropic key check) → builds.
const client = await __thinkAdapter.tryBuildGatewayClient(
@@ -183,7 +191,7 @@ describe('think gateway adapter — #1698 slash form + explicit-model fork', ()
messages: [{ role: 'user', content: 'hi' }],
};
// The backstop fires: explicit → AIConfigError rethrown, NOT the graceful sentinel.
- await expect(client!.create(params)).rejects.toThrow();
+ await expect(client!.create(params)).rejects.toBeInstanceOf(AIConfigError);
},
);
});