Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
chore(isolation-lint): R9, a process-global hook needs its undo in an after-hook
garrytanc84d379291c8
diff --git a/docs/TESTING.md b/docs/TESTING.mdindex ea67154014..0495edf161 100644--- a/docs/TESTING.md+++ b/docs/TESTING.md@@ -1461,6 +1461,7 @@ cross-subsystem duplicate entries, and byte caps for the entry docs and referenc| **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 into the next file, and an inline restore does not survive a throw or a `-t` filter | `afterEach(() => resetGateway())` (#6514) |+| **R9** | A process-global hook with no undo in an `afterEach`/`afterAll` hook (comments ignored): `installOutputCapture(` or `startCliSocketServer(` without `_uninstallOutputCaptureForTests`, `redirectStdoutLoggingToStderr(` or an inline `_resetStdoutRedirectForTests(` without the reset in a hook, `installSigchldHandler(` without `_uninstallSigchldHandlerForTests`. Each patches console, stderr or a signal listener for every later file in the shard (#7494) | `afterEach(() => _uninstallOutputCaptureForTests())` (or the named undo) |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 ff9c41d9ae..9633489d04 100755--- a/scripts/check-test-isolation.sh+++ b/scripts/check-test-isolation.sh@@ -48,6 +48,16 @@# directory created and removed by another file mid-walk fails them with# ENOENT (import-file.test.ts did this to test-reads-source-smell).# Use mkdtempSync(join(tmpdir(), '...')).+# R9: a file that installs one of the process-global hooks below must undo+# it from an afterEach/afterAll hook (an inline undo does not survive a+# throw or a -t filter). Each installer patches console, stderr, signal+# listeners or a module scope for the rest of the shard process: the+# cli-socket output capture left by cli-socket.test.ts failed+# cli-socket-context.test.ts in a shared shard (#7494), and the stdio+# redirect left console.log bound to stderr. Comments do not count.+# installOutputCapture( / startCliSocketServer( -> _uninstallOutputCaptureForTests+# redirectStdoutLoggingToStderr( / _resetStdoutRedirectForTests( -> _resetStdoutRedirectForTests+# installSigchldHandler( -> _uninstallSigchldHandlerForTests## Scope:# - Recursively scans `test/**/*.test.ts`.@@ -218,7 +228,37 @@ UNCONFIGURE_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" -e "$UNCONFIGURE_PATTERN" -e "$SOURCE_TREE_SCRATCH_PATTERN" <<< "$FILE_LIST")"+# R9: installer pattern|restorer name, one pair per line.+PAIRED_RULES='installOutputCapture[[:space:]]*\(|startCliSocketServer[[:space:]]*\(|_uninstallOutputCaptureForTests+redirectStdoutLoggingToStderr[[:space:]]*\(|_resetStdoutRedirectForTests[[:space:]]*\(|_resetStdoutRedirectForTests+installSigchldHandler[[:space:]]*\(|_uninstallSigchldHandlerForTests'+PAIRED_PATTERN='installOutputCapture[[:space:]]*\(|startCliSocketServer[[:space:]]*\(|redirectStdoutLoggingToStderr[[:space:]]*\(|_resetStdoutRedirectForTests[[:space:]]*\(|installSigchldHandler[[:space:]]*\('+# R9: same comment removal and after-hook tracking as UNCONFIGURE_CODE_SCAN,+# with the installer pattern in trig and the restorer name in rest.+PAIRED_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 ~ rest) restored = 1; if (depth <= 0) in_after = 0; next }+ if (code ~ /after(Each|All)[[:space:]]*\(/) {+ if (code ~ rest) restored = 1+ depth = opens - closes; if (depth > 0) in_after = 1; next+ }+ if (code ~ trig && 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" -e "$SOURCE_TREE_SCRATCH_PATTERN" -e "$PAIRED_PATTERN" <<< "$FILE_LIST")"violations=0file_count=0@@ -312,6 +352,19 @@ while IFS= read -r f; doif [ -n "$scratch_lines" ]; thenemit_violation "$f" "R8" "scratch directory inside the source tree; tree walkers in the same lane (test-reads-source-smell) fail with ENOENT when it is created or removed mid-walk. Use mkdtempSync(join(tmpdir(), '...'))" "$scratch_lines"fi+ # R9: a process-global hook installed with no after-hook undo.+ if grep -qE "$PAIRED_PATTERN" "$f" 2>/dev/null; then+ while IFS= read -r pair; do+ trig="${pair%|*}"; rest="${pair##*|}"+ grep -qE "$trig" "$f" 2>/dev/null || continue+ unrestored=$(awk -v trig="$trig" -v rest="$rest" "$PAIRED_CODE_SCAN" "$f" 2>/dev/null || true)+ if [ -n "$unrestored" ]; then+ emit_violation "$f" "R9" "process-global hook installed with no $rest() in an afterEach/afterAll hook; it stays installed for every later file in the shard. Add afterEach(() => $rest()) or rename to *.serial.test.ts" "$unrestored"+ fi+ done <<PAIRS+$PAIRED_RULES+PAIRS+ fidone <<EOF$FILE_LISTEOF@@ -332,6 +385,8 @@ if [ $violations -gt 0 ]; thenecho " - For __unconfigureGatewayForTests(), call resetGateway() in"echo " afterEach or afterAll; it puts back the preload's baseline gateway."echo " - For a scratch directory, use mkdtempSync(join(tmpdir(), '...'))."+ echo " - For a process-global hook (R9), call its named undo from afterEach"+ echo " or afterAll."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/test/scripts/check-test-isolation-r9.test.ts b/test/scripts/check-test-isolation-r9.test.tsnew file mode 100644index 0000000000..136a6f5e71--- /dev/null+++ b/test/scripts/check-test-isolation-r9.test.ts@@ -0,0 +1,106 @@+/**+ * Fixture tests for rule R9 of scripts/check-test-isolation.sh: a non-serial unit file that installs a process-global+ * hook (the cli-socket output capture, the stdio console redirect, the SIGCHLD reaper) must undo it from an+ * afterEach/afterAll hook. Each one patches console, stderr, a signal listener or a module scope for the rest of the+ * shard process: cli-socket.test.ts left the capture installed and cli-socket-context.test.ts failed in the same shard.+ *+ * 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 = 'global-hook.test.ts'): { status: number; stdout: string } {+ const dir = mkdtempSync(join(tmpdir(), 'lint-isolation-r9-'));+ 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, test } from 'bun:test';\n`;+const CAPTURE = `test('captured', () => { installOutputCapture(); });\n`;++describe('check-test-isolation.sh R9: a process-global hook must be undone from an after-hook', () => {+ it('bad fixture: the output capture installed with no undo fails, naming the call line and the undo', () => {+ const r = lintOne(IMPORTS + CAPTURE);+ expect(r.status).toBe(1);+ expect(r.stdout).toContain('test/global-hook.test.ts');+ expect(r.stdout).toContain('rule R9');+ expect(r.stdout).toContain('_uninstallOutputCaptureForTests');+ expect(r.stdout).toContain("2:test('captured', () => { installOutputCapture(); });");+ });++ it('bad fixture: starting a cli-socket serve installs the capture too', () => {+ const r = lintOne(IMPORTS + `test('serve', async () => { (await startCliSocketServer({} as never))?.close(); });\n`);+ expect(r.status).toBe(1);+ expect(r.stdout).toContain('rule R9');+ });++ it('bad fixture: an inline undo in the test body is not an after-hook undo', () => {+ const r = lintOne(IMPORTS + `test('t', () => { try { installOutputCapture(); } finally { _uninstallOutputCaptureForTests(); } });\n`);+ expect(r.status).toBe(1);+ expect(r.stdout).toContain('rule R9');+ });++ it('bad fixtures: the stdio redirect reset only inline, and the SIGCHLD reaper with no undo', () => {+ for (const [body, undo] of [+ [`test('serve', () => { runServeStub(); _resetStdoutRedirectForTests(); });\n`, '_resetStdoutRedirectForTests'],+ [`test('redirect', () => { redirectStdoutLoggingToStderr(); });\n`, '_resetStdoutRedirectForTests'],+ [`test('reap', () => { installSigchldHandler(); });\n`, '_uninstallSigchldHandlerForTests'],+ ] as const) {+ const r = lintOne(IMPORTS + body);+ expect(r.status).toBe(1);+ expect(r.stdout).toContain('rule R9');+ expect(r.stdout).toContain(undo);+ }+ });++ it('good fixtures: an afterEach or afterAll undo passes, in block, arrow and reference form', () => {+ for (const hook of [+ `afterEach(() => { _uninstallOutputCaptureForTests(); });\n`,+ `afterEach(() => _uninstallOutputCaptureForTests());\n`,+ `afterAll(() => {\n _uninstallOutputCaptureForTests();\n});\n`,+ `afterEach(_uninstallOutputCaptureForTests);\n`,+ ]) {+ const r = lintOne(IMPORTS + CAPTURE + hook);+ expect(r.stdout).toContain('check-test-isolation: OK');+ expect(r.status).toBe(0);+ }+ expect(lintOne(IMPORTS + `test('reap', () => { installSigchldHandler(); });\nafterAll(() => _uninstallSigchldHandlerForTests());\n`).status).toBe(0);+ expect(lintOne(IMPORTS + `test('serve', () => { redirectStdoutLoggingToStderr(); });\nafterEach(() => _resetStdoutRedirectForTests());\n`).status).toBe(0);+ });++ it('an undo that only appears in a comment does not count', () => {+ for (const undo of [+ `// afterEach(() => _uninstallOutputCaptureForTests()) lives in a sibling file\n`,+ `/**\n * afterAll(_uninstallOutputCaptureForTests) would go here.\n */\n`,+ ]) {+ const r = lintOne(IMPORTS + CAPTURE + undo);+ expect(r.status).toBe(1);+ expect(r.stdout).toContain('rule R9');+ }+ });++ it('an installer mention that only appears in a comment is not a call', () => {+ for (const mention of [+ `// installOutputCapture() is what the serve calls\n`,+ `/*\n installSigchldHandler();\n*/\n`,+ ]) {+ expect(lintOne(mention + `test('u', () => {});\n`).status).toBe(0);+ }+ });++ it('serial files are out of scope for R9', () => {+ expect(lintOne(IMPORTS + CAPTURE, 'global-hook.serial.test.ts').status).toBe(0);+ });+});