Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
test(isolation): orphan-ratio resets the CLI exit verdict its runDoctor sets; verdict readers set their own baseline (lint R6)
garrytan85f21a232984
diff --git a/docs/TESTING.md b/docs/TESTING.mdindex 102d882651..fce84c23b7 100644--- a/docs/TESTING.md+++ b/docs/TESTING.md@@ -1452,6 +1452,7 @@ cross-subsystem duplicate entries, and byte caps for the entry docs and referenc| **R3** | `new PGLiteEngine(` outside ~50 lines after a `beforeAll(` line | Use the canonical block (below) inside `beforeAll(` || **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` |+| **R6** | `currentExitCode(` with no verdict reset outside an after-hook: the process-wide CLI exit verdict a previous file left (a doctor or remediate run sets 1) is what the first test reads | `beforeEach(() => _resetCliExitVerdictForTests())`, or reset right before the run it checks; a test that drives a verdict-setting command also resets after it |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.shindex 83086724e6..1b83f5058e 100755--- a/scripts/check-test-isolation.sh+++ b/scripts/check-test-isolation.sh@@ -27,6 +27,14 @@# after a reshuffle ran a LiteLLM-configuring file first. Comments do# not count either way. A file whose only calls run inside a spawned# child's script string carries `isolation-lint: R5-subprocess-only`.+# R6: a file whose code reads the CLI exit verdict (`currentExitCode(`)+# must set its own baseline outside an after-hook: a+# `_resetCliExitVerdictForTests(` or `setCliExitVerdict(0)` call in a+# before-hook or before its run. The verdict is one value per process+# and any command a test drives can leave it at 1 (doctor, remediate,+# 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.## Scope:# - Recursively scans `test/**/*.test.ts`.@@ -125,6 +133,31 @@ GATEWAY_OPT_OUT='isolation-lint: R5-subprocess-only'# the line start, whitespace or punctuation (so a URL's :// survives).# Block comments opening mid-line are left alone: a glob such as# 'test/*.ts' would otherwise swallow the rest of the file.+VERDICT_PATTERN='currentExitCode[[:space:]]*\('+# R6: same comment removal as GATEWAY_CODE_SCAN; a reset inside an+# afterEach/afterAll block (tracked by brace depth from the hook's line)+# does not count as a baseline. Prints the reads when no baseline is left.+VERDICT_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 (depth <= 0) in_after = 0; next }+ if (code ~ /after(Each|All)[[:space:]]*\(/) { depth = opens - closes; if (depth > 0) in_after = 1; next }+ if (code ~ /_resetCliExitVerdictForTests[[:space:]]*\(|setCliExitVerdict[[:space:]]*\([[:space:]]*0[[:space:]]*\)/) baseline = 1+ if (code ~ /currentExitCode[[:space:]]*\(/ && code !~ /import/) reads = reads NR ":" $0 "\n"+ }+ END { if (reads != "" && !baseline) printf "%s", reads }+'GATEWAY_CODE_SCAN='in_block {if (index($0, "*/") == 0) next@@ -143,7 +176,7 @@ 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" <<< "$FILE_LIST")"+CANDIDATES="$(guard_candidates -E -e "$ENV_MUTATION_PATTERN" -e "$MODULE_MOCK_PATTERN" -e "$ENGINE_PATTERN" -e "$GATEWAY_PATTERN" -e "$VERDICT_PATTERN" <<< "$FILE_LIST")"violations=0file_count=0@@ -217,6 +250,14 @@ while IFS= read -r f; doemit_violation "$f" "R5" "configureGateway() with no resetGateway(); the gateway is process-global, so this config reaches every later file in the shard. Add afterAll(() => resetGateway()) or rename to *.serial.test.ts" "$unrestored"fifi++ # R6: the CLI exit verdict is read with no baseline outside an after-hook.+ if grep -qE "$VERDICT_PATTERN" "$f" 2>/dev/null; then+ unbased=$(awk "$VERDICT_CODE_SCAN" "$f" 2>/dev/null || true)+ if [ -n "$unbased" ]; then+ 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+ fidone <<EOF$FILE_LISTEOF@@ -232,6 +273,8 @@ if [ $violations -gt 0 ]; thenecho " test/helpers/reset-pglite.ts JSDoc and CLAUDE.md."echo " - For configureGateway(), call resetGateway() in afterAll; it"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()."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 4d58b29dcf..1641f0f060 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 yes allowlist data file: check-test-isolation.allowlist; fixture mode (GBRAIN_GUARD_ROOT) lints *.test.fixture.ts (bad: R5, bad-r1: R1)+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, bad-r6: R6)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/connectors-sync-cli.test.ts b/test/connectors-sync-cli.test.tsindex ad3af767ee..b6740ae19e 100644--- a/test/connectors-sync-cli.test.ts+++ b/test/connectors-sync-cli.test.ts@@ -1,4 +1,4 @@-import { afterEach, describe, expect, test } from 'bun:test';+import { afterEach, beforeEach, describe, expect, test } from 'bun:test';import { mkdtempSync, rmSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';@@ -10,6 +10,8 @@ import { renderCliError } from '../src/core/agent-output.ts';const tempHomes: string[] = [];+beforeEach(() => { _resetCliExitVerdictForTests(); });+afterEach(() => {for (const home of tempHomes.splice(0)) rmSync(home, { recursive: true, force: true });_resetCliExitVerdictForTests();diff --git a/test/edge-proposals-json-bigint.test.ts b/test/edge-proposals-json-bigint.test.tsindex a18ea94779..c0bd19c7f1 100644--- a/test/edge-proposals-json-bigint.test.ts+++ b/test/edge-proposals-json-bigint.test.ts@@ -3,7 +3,7 @@* returns BigInt ids (Postgres `bigint` columns). The CLI normalizes ids at* the row boundary: a safe integer becomes a number, anything larger a string.*/-import { afterEach, describe, expect, spyOn, test } from 'bun:test';+import { afterEach, beforeEach, describe, expect, spyOn, test } from 'bun:test';import { runEdgeProposals } from '../src/commands/edge-proposals.ts';import { _resetCliExitVerdictForTests, currentExitCode } from '../src/core/cli-force-exit.ts';import type { BrainEngine } from '../src/core/engine.ts';@@ -34,6 +34,7 @@ async function capture(engine: BrainEngine, args: string[]): Promise<string> {return lines.join('\n');}+beforeEach(() => { _resetCliExitVerdictForTests(); });afterEach(() => { _resetCliExitVerdictForTests(); process.exitCode = 0; });describe('#6193 edge-proposals --json with BigInt ids', () => {diff --git a/test/fixtures/guards/check-test-isolation.sh/bad-r6/test/verdict-after-only.test.fixture.ts b/test/fixtures/guards/check-test-isolation.sh/bad-r6/test/verdict-after-only.test.fixture.tsnew file mode 100644index 0000000000..d4d823ec26--- /dev/null+++ b/test/fixtures/guards/check-test-isolation.sh/bad-r6/test/verdict-after-only.test.fixture.ts@@ -0,0 +1,8 @@+import { afterEach, expect, test } from 'bun:test';+import { _resetCliExitVerdictForTests, currentExitCode } from '../../../../../../src/core/cli-force-exit.ts';++// R6: the verdict is reset only after each test, so the first test reads the previous file's verdict.+afterEach(() => {+ _resetCliExitVerdictForTests();+});+test('x', () => { expect(currentExitCode()).toBe(0); });diff --git a/test/fixtures/guards/check-test-isolation.sh/good/test/verdict-baseline.test.fixture.ts b/test/fixtures/guards/check-test-isolation.sh/good/test/verdict-baseline.test.fixture.tsnew file mode 100644index 0000000000..52b56a8889--- /dev/null+++ b/test/fixtures/guards/check-test-isolation.sh/good/test/verdict-baseline.test.fixture.ts@@ -0,0 +1,6 @@+import { beforeEach, expect, test } from 'bun:test';+import { _resetCliExitVerdictForTests, currentExitCode } from '../../../../../../src/core/cli-force-exit.ts';++// Each test starts from its own verdict baseline.+beforeEach(() => { _resetCliExitVerdictForTests(); });+test('x', () => { expect(currentExitCode()).toBe(0); });diff --git a/test/jobs-authorize-legacy-select.test.ts b/test/jobs-authorize-legacy-select.test.tsindex 2a99f9d5df..b6d9fb3240 100644--- a/test/jobs-authorize-legacy-select.test.ts+++ b/test/jobs-authorize-legacy-select.test.ts@@ -29,6 +29,7 @@ beforeAll(async () => {}, 60_000);afterAll(async () => { await engine?.disconnect(); }, 60_000);beforeEach(async () => {+ _resetCliExitVerdictForTests();await engine.executeRaw('DELETE FROM minion_jobs');await engine.executeRaw('DELETE FROM op_checkpoints WHERE op = $1', [PREVIEW_APPROVAL_OP]);});diff --git a/test/jobs-cancel-select.test.ts b/test/jobs-cancel-select.test.tsindex ec60ef70ad..46e9950665 100644--- a/test/jobs-cancel-select.test.ts+++ b/test/jobs-cancel-select.test.ts@@ -26,6 +26,7 @@ beforeAll(async () => {}, 60_000);afterAll(async () => { await engine?.disconnect(); }, 60_000);beforeEach(async () => {+ _resetCliExitVerdictForTests();await engine.executeRaw('DELETE FROM minion_jobs');await engine.executeRaw('DELETE FROM op_checkpoints WHERE op = $1', [PREVIEW_APPROVAL_OP]);});diff --git a/test/orphan-ratio-connector-renders.test.ts b/test/orphan-ratio-connector-renders.test.tsindex f354a13c7d..18bfabcc95 100644--- a/test/orphan-ratio-connector-renders.test.ts+++ b/test/orphan-ratio-connector-renders.test.ts@@ -12,6 +12,7 @@ import { resetPgliteState } from './helpers/reset-pglite.ts';import { findOrphans } from '../src/commands/orphans.ts';import { runDoctor, type DoctorReport } from '../src/commands/doctor.ts';import { setCliOptions } from '../src/core/cli-options.ts';+import { _resetCliExitVerdictForTests } from '../src/core/cli-force-exit.ts';let engine: PGLiteEngine;@@ -56,6 +57,7 @@ async function doctorCheck(args: string[]) {if (!(e instanceof Error && e.message === '__exit')) throw e;} finally {console.log = log; console.error = err; (process as { exit: unknown }).exit = exit;+ _resetCliExitVerdictForTests();}for (let i = out.length - 1; i >= 0; i--) {try {diff --git a/test/repair-fences.test.ts b/test/repair-fences.test.tsindex 5d910eb9e1..edd4f6e388 100644--- a/test/repair-fences.test.ts+++ b/test/repair-fences.test.ts@@ -26,7 +26,7 @@* Why new: the fences kind is new in PR4.* Seams: __setChatTransportForTests (no provider call); test/postgres-unit-arms.txt runs the Postgres arm.*/-import { afterAll, afterEach, beforeAll, expect, test } from 'bun:test';+import { afterAll, afterEach, beforeAll, beforeEach, expect, test } from 'bun:test';import { execFileSync } from 'node:child_process';import { randomUUID } from 'node:crypto';import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';@@ -104,6 +104,7 @@ beforeAll(async () => {legacyEngine = new PGLiteEngine(); await legacyEngine.connect({}); await legacyEngine.initSchema();}, 120_000);+beforeEach(() => { _resetCliExitVerdictForTests(); });afterEach(() => { __setChatTransportForTests(null); _resetCliExitVerdictForTests(); });afterAll(async () => {