Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

test: restore a saved process.exitCode with ?? 0 (Bun keeps a code assigned undefined)

garrytan813f7b1e663a
diff --git a/test/backup-invalidation.serial.test.ts b/test/backup-invalidation.serial.test.ts
index 3b30152519..c25b965967 100644
--- a/test/backup-invalidation.serial.test.ts
+++ b/test/backup-invalidation.serial.test.ts
@@ -153,7 +153,7 @@ beforeEach(() => {
afterEach(() => {
__setBackupStatusPathForTests(null);
_resetCliExitVerdictForTests();
- process.exitCode = savedExitCode;
+ process.exitCode = savedExitCode ?? 0;
for (const [k, v] of Object.entries(saved)) {
if (v === undefined) delete process.env[k];
else process.env[k] = v;
diff --git a/test/cli-finish-teardown.test.ts b/test/cli-finish-teardown.test.ts
index 3298e5afc5..60b586c29a 100644
--- a/test/cli-finish-teardown.test.ts
+++ b/test/cli-finish-teardown.test.ts
@@ -252,7 +252,7 @@ describe('finishCliTeardown — backstop on hung teardown', () => {
await teardown;
} finally {
_resetCliExitVerdictForTests();
- process.exitCode = prevCode;
+ process.exitCode = prevCode ?? 0;
}
});
@@ -278,7 +278,7 @@ describe('finishCliTeardown — backstop on hung teardown', () => {
await teardown;
} finally {
_resetCliExitVerdictForTests();
- process.exitCode = prevCode;
+ process.exitCode = prevCode ?? 0;
}
});
@@ -305,7 +305,7 @@ describe('finishCliTeardown — backstop on hung teardown', () => {
resolveHang();
await teardown;
} finally {
- process.exitCode = prevCode;
+ process.exitCode = prevCode ?? 0;
}
});
});
@@ -334,7 +334,7 @@ describe('verdict channel — immune to PGLite WASM process.exitCode writes', ()
expect(currentExitCode()).toBe(1);
} finally {
_resetCliExitVerdictForTests();
- process.exitCode = prevCode;
+ process.exitCode = prevCode ?? 0;
}
});
@@ -428,7 +428,7 @@ describe('flushThenExit', () => {
expect(exits).toEqual([3]);
expect(process.exitCode).toBe(3); // belt-and-braces for natural exit
} finally {
- process.exitCode = prevCode;
+ process.exitCode = prevCode ?? 0;
}
});
@@ -461,7 +461,7 @@ describe('flushThenExit', () => {
expect(exits).toEqual([0]);
expect(fencedAt).toBeGreaterThanOrEqual(0);
} finally {
- process.exitCode = prevCode;
+ process.exitCode = prevCode ?? 0;
}
});
@@ -489,7 +489,7 @@ describe('flushThenExit', () => {
expect(exits).toEqual([0]);
expect(Date.now() - t0).toBeGreaterThanOrEqual(100);
} finally {
- process.exitCode = prevCode;
+ process.exitCode = prevCode ?? 0;
}
});
@@ -515,7 +515,7 @@ describe('flushThenExit', () => {
await sleep(50);
expect(exits).toEqual([0]);
} finally {
- process.exitCode = prevCode;
+ process.exitCode = prevCode ?? 0;
}
});
@@ -535,7 +535,7 @@ describe('flushThenExit', () => {
expect(exits).toEqual([0]); // grace 0: exit right after the fence
});
} finally {
- process.exitCode = prevCode;
+ process.exitCode = prevCode ?? 0;
}
});
@@ -571,7 +571,7 @@ describe('flushThenExit', () => {
await sleep(400);
expect(exits).toEqual([0]); // exactly one exit despite guard + late cb
} finally {
- process.exitCode = prevCode;
+ process.exitCode = prevCode ?? 0;
}
});
});
diff --git a/test/commands/capture.test.ts b/test/commands/capture.test.ts
index 5a85cb773e..6830dd22cf 100644
--- a/test/commands/capture.test.ts
+++ b/test/commands/capture.test.ts
@@ -66,7 +66,7 @@ async function runCaptureExpectingExit(args: string[]): Promise<{ exitCode: numb
} finally {
console.error = origErr;
setCliExitVerdict(originalVerdict);
- process.exitCode = originalExitCode;
+ process.exitCode = originalExitCode ?? 0;
}
return { exitCode, stderr: errCaptured.join('\n') };
}
diff --git a/test/doctor-skills-dir.test.ts b/test/doctor-skills-dir.test.ts
index 88ce4e75f6..7103e147d2 100644
--- a/test/doctor-skills-dir.test.ts
+++ b/test/doctor-skills-dir.test.ts
@@ -82,7 +82,7 @@ async function runDoctorJson(args: string[], env: Record<string, string | undefi
} finally {
console.log = origLog;
process.exit = origExit;
- process.exitCode = origExitCode;
+ process.exitCode = origExitCode ?? 0;
}
const lines = captured.join('').split('\n');
for (let i = lines.length - 1; i >= 0; i--) {
diff --git a/test/helpers/managed-connector-job-contract.ts b/test/helpers/managed-connector-job-contract.ts
index 8f63d56b89..a2ba40c687 100644
--- a/test/helpers/managed-connector-job-contract.ts
+++ b/test/helpers/managed-connector-job-contract.ts
@@ -946,7 +946,7 @@ const cases: Record<ContractCase, (state: CaseState) => Promise<void>> = {
let exit: number | string | undefined;
try {
await runExtract(engine, ['timeline', '--source', 'db', '--source-id', state.sourceId]);
- } finally { exit = process.exitCode; process.exitCode = exitBefore; }
+ } finally { exit = process.exitCode; process.exitCode = exitBefore ?? 0; }
const findings = await detectorFindings(state);
if (findings.length) throw new Error(`${findings.join('; ')} (exit ${String(exit ?? 0)}, timeline rows ${await count()})`);
expect(await count()).toBe(1);
diff --git a/test/large-pages/segmented-semantic-writes.test.ts b/test/large-pages/segmented-semantic-writes.test.ts
index 9c60764443..6482cedd74 100644
--- a/test/large-pages/segmented-semantic-writes.test.ts
+++ b/test/large-pages/segmented-semantic-writes.test.ts
@@ -143,7 +143,7 @@ for (const kind of testBackends()) {
expect(removed).toContain('Already out of core');
expect(removed).toBe(await core(INLINE, ['remove']));
expect(verdict()).toBe(0);
- } finally { console.log = log; console.error = err; _resetCliExitVerdictForTests(); process.exitCode = exitCode; }
+ } finally { console.log = log; console.error = err; _resetCliExitVerdictForTests(); process.exitCode = exitCode ?? 0; }
}, 600_000);
test('sources reconcile previews a drifted segmented page as it previews the inline twin', async () => {
diff --git a/test/migrate-engine-completeness.serial.test.ts b/test/migrate-engine-completeness.serial.test.ts
index 92108fa8d8..6505baea32 100644
--- a/test/migrate-engine-completeness.serial.test.ts
+++ b/test/migrate-engine-completeness.serial.test.ts
@@ -155,7 +155,7 @@ describe('runMigrateEngine — facts + config completeness (#4350)', () => {
if (source) await source.disconnect();
if (target) await target.disconnect();
_resetCliExitVerdictForTests();
- process.exitCode = prevExitCode;
+ process.exitCode = prevExitCode ?? 0;
if (prevGbrainHome !== undefined) process.env.GBRAIN_HOME = prevGbrainHome; else delete process.env.GBRAIN_HOME;
if (prevDatabaseUrl !== undefined) process.env.DATABASE_URL = prevDatabaseUrl;
if (prevGbrainDatabaseUrl !== undefined) process.env.GBRAIN_DATABASE_URL = prevGbrainDatabaseUrl;
@@ -251,7 +251,7 @@ describe('runMigrateEngine — facts-only foreign target guard', () => {
if (source) await source.disconnect();
if (target) await target.disconnect();
_resetCliExitVerdictForTests();
- process.exitCode = prevExitCode;
+ process.exitCode = prevExitCode ?? 0;
if (prevGbrainHome !== undefined) process.env.GBRAIN_HOME = prevGbrainHome; else delete process.env.GBRAIN_HOME;
if (prevDatabaseUrl !== undefined) process.env.DATABASE_URL = prevDatabaseUrl;
if (prevGbrainDatabaseUrl !== undefined) process.env.GBRAIN_DATABASE_URL = prevGbrainDatabaseUrl;
diff --git a/test/migrate-engine-page-copy-failure.serial.test.ts b/test/migrate-engine-page-copy-failure.serial.test.ts
index d514993e17..a09cd5e6a9 100644
--- a/test/migrate-engine-page-copy-failure.serial.test.ts
+++ b/test/migrate-engine-page-copy-failure.serial.test.ts
@@ -231,7 +231,7 @@ describe('runMigrateEngine — per-page failures are surfaced, not swallowed (#3
if (source) await source.disconnect();
if (verifyEngine) await verifyEngine.disconnect();
_resetCliExitVerdictForTests();
- process.exitCode = prevExitCode;
+ process.exitCode = prevExitCode ?? 0;
if (prevGbrainHome !== undefined) process.env.GBRAIN_HOME = prevGbrainHome; else delete process.env.GBRAIN_HOME;
if (prevDatabaseUrl !== undefined) process.env.DATABASE_URL = prevDatabaseUrl;
if (prevGbrainDatabaseUrl !== undefined) process.env.GBRAIN_DATABASE_URL = prevGbrainDatabaseUrl;
@@ -311,7 +311,7 @@ describe('runMigrateEngine — per-page failures are surfaced, not swallowed (#3
if (source) await source.disconnect();
if (verifyEngine) await verifyEngine.disconnect();
_resetCliExitVerdictForTests();
- process.exitCode = prevExitCode;
+ process.exitCode = prevExitCode ?? 0;
if (prevGbrainHome !== undefined) process.env.GBRAIN_HOME = prevGbrainHome; else delete process.env.GBRAIN_HOME;
if (prevDatabaseUrl !== undefined) process.env.DATABASE_URL = prevDatabaseUrl;
if (prevGbrainDatabaseUrl !== undefined) process.env.GBRAIN_DATABASE_URL = prevGbrainDatabaseUrl;
@@ -376,7 +376,7 @@ describe('runMigrateEngine — per-page failures are surfaced, not swallowed (#3
if (source) await source.disconnect();
if (verifyEngine) await verifyEngine.disconnect();
_resetCliExitVerdictForTests();
- process.exitCode = prevExitCode;
+ process.exitCode = prevExitCode ?? 0;
if (prevGbrainHome !== undefined) process.env.GBRAIN_HOME = prevGbrainHome; else delete process.env.GBRAIN_HOME;
if (prevDatabaseUrl !== undefined) process.env.DATABASE_URL = prevDatabaseUrl;
if (prevGbrainDatabaseUrl !== undefined) process.env.GBRAIN_DATABASE_URL = prevGbrainDatabaseUrl;
diff --git a/test/migrate-engine-pagination.serial.test.ts b/test/migrate-engine-pagination.serial.test.ts
index ddd33c95da..cb5b7a40e8 100644
--- a/test/migrate-engine-pagination.serial.test.ts
+++ b/test/migrate-engine-pagination.serial.test.ts
@@ -106,7 +106,7 @@ async function migrate(afterListing?: (source: PGLiteEngine) => Promise<void>) {
if (source) await source.disconnect();
if (target) await target.disconnect();
_resetCliExitVerdictForTests();
- process.exitCode = prev.exitCode;
+ process.exitCode = prev.exitCode ?? 0;
if (prev.home !== undefined) process.env.GBRAIN_HOME = prev.home; else delete process.env.GBRAIN_HOME;
if (prev.url !== undefined) process.env.DATABASE_URL = prev.url;
if (prev.gbrainUrl !== undefined) process.env.GBRAIN_DATABASE_URL = prev.gbrainUrl;
diff --git a/test/repair-conversation-labels.test.ts b/test/repair-conversation-labels.test.ts
index 3686d7616c..405334eb76 100644
--- a/test/repair-conversation-labels.test.ts
+++ b/test/repair-conversation-labels.test.ts
@@ -91,7 +91,7 @@ async function capture(run: () => Promise<unknown>): Promise<{ out: string; exit
console.error = () => {};
process.stdout.write = ((chunk: string | Uint8Array) => { lines.push(String(chunk)); return true; }) as typeof process.stdout.write;
try { await run(); return { out: lines.join('\n'), exitCode: process.exitCode }; }
- finally { console.log = log; console.error = error; process.stdout.write = stdout; process.exitCode = previous; }
+ finally { console.log = log; console.error = error; process.stdout.write = stdout; process.exitCode = previous ?? 0; }
}
async function repair(engine: BrainEngine, args: string[]): Promise<RepairJson> {
const { out } = await capture(() => runRepairCommand(engine, ['conversation-labels', ...args, '--json']));
diff --git a/test/repair-rename-identity-6729.test.ts b/test/repair-rename-identity-6729.test.ts
index 47f2fcc381..9f8651f81b 100644
--- a/test/repair-rename-identity-6729.test.ts
+++ b/test/repair-rename-identity-6729.test.ts
@@ -292,7 +292,7 @@ for (const kind of testBackends()) describe(`gbrain repair rename-identity (#672
// large Postgres brain) sets exit 1, which is not this test's subject, so the prior exit code is restored after it.
const priorExitCode = process.exitCode;
const allOut = await repair(['--all', '--apply', '--json']);
- process.exitCode = priorExitCode;
+ process.exitCode = priorExitCode ?? 0;
const all = JSON.parse(allOut) as { results: Array<{ kind: string }>; explicit_kinds: Array<{ kind: string; code: string; preview_command: string; docs: string }> };
expect(all.results.map(r => r.kind)).not.toContain('rename-identity');
expect(all.explicit_kinds).toContainEqual({ kind: 'rename-identity', code: 'explicit_kind_required', preview_command: 'gbrain repair rename-identity', docs: 'docs/guides/repair.md#explicit-only-repair-kinds' });
diff --git a/test/scripts/exit-code-restore.test.ts b/test/scripts/exit-code-restore.test.ts
new file mode 100644
index 0000000000..a3ad9cd95c
--- /dev/null
+++ b/test/scripts/exit-code-restore.test.ts
@@ -0,0 +1,52 @@
+/**
+ * A test that saves `process.exitCode` and restores it later must restore
+ * `saved ?? 0`. In Bun, assigning `undefined` does not clear an earlier
+ * value (`bun -e 'process.exitCode=1; process.exitCode=undefined'` exits 1),
+ * so restoring a code that was never set keeps whatever the test body set,
+ * and the file exits 1 with every test passing. The PGLite arm hid this:
+ * PGLite's Emscripten runtime writes `process.exitCode`, so the saved value
+ * was defined whenever that arm ran first, and only the Postgres-only run of
+ * test/large-pages/segmented-semantic-writes.test.ts exited 1 (GBRA-135).
+ */
+import { describe, expect, test } from 'bun:test';
+import { readdirSync, readFileSync } from 'node:fs';
+import { join, relative } from 'node:path';
+
+const REPO = join(import.meta.dir, '..', '..');
+
+/** `file:line` of every restore of a saved exit code that lacks the `?? 0` fallback. */
+function unsafeExitCodeRestores(path: string, source: string): string[] {
+ const saved = new Set<string>();
+ for (const m of source.matchAll(/\b([A-Za-z_$][\w$]*)\s*[=:]\s*process\.exitCode\b/g)) saved.add(m[1]!);
+ const found: string[] = [];
+ source.split('\n').forEach((line, i) => {
+ for (const m of line.matchAll(/process\.exitCode\s*=\s*([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*)\s*(?=;|\}|$)/g)) {
+ if (saved.has(m[1]!.split('.').pop()!)) found.push(`${path}:${i + 1}`);
+ }
+ });
+ return found;
+}
+
+function testSources(dir: string): string[] {
+ return readdirSync(dir, { withFileTypes: true }).flatMap(entry => {
+ const path = join(dir, entry.name);
+ if (entry.isDirectory()) return entry.name === 'fixtures' ? [] : testSources(path);
+ return entry.name.endsWith('.ts') ? [path] : [];
+ });
+}
+
+describe('saved process.exitCode restores', () => {
+ test('every restore of a saved exit code falls back to 0', () => {
+ const unsafe = testSources(join(REPO, 'test')).filter(path => path !== import.meta.path).flatMap(path => unsafeExitCodeRestores(relative(REPO, path), readFileSync(path, 'utf8')));
+ expect(unsafe).toEqual([]);
+ });
+
+ test('the scan flags a bare restore of a saved code and accepts the fallback', () => {
+ const bare = 'const prev = process.exitCode;\ntry { run(); } finally { process.exitCode = prev; }\n';
+ const member = 'const old = { exitCode: process.exitCode };\nprocess.exitCode = old.exitCode;\n';
+ expect(unsafeExitCodeRestores('t.ts', bare)).toEqual(['t.ts:2']);
+ expect(unsafeExitCodeRestores('t.ts', member)).toEqual(['t.ts:2']);
+ expect(unsafeExitCodeRestores('t.ts', bare.replace('= prev;', '= prev ?? 0;'))).toEqual([]);
+ expect(unsafeExitCodeRestores('t.ts', 'process.exitCode = code;\n')).toEqual([]);
+ });
+});
diff --git a/test/sweep.test.ts b/test/sweep.test.ts
index bb15d7b734..fef92f5ea5 100644
--- a/test/sweep.test.ts
+++ b/test/sweep.test.ts
@@ -973,7 +973,7 @@ describe('runSweep CLI arg parsing [CX2-5]', () => {
console.log = origLog;
console.error = origErr;
_resetCliExitVerdictForTests();
- process.exitCode = savedExitCode; // setCliExitVerdict mirrors here — undo
+ process.exitCode = savedExitCode ?? 0; // setCliExitVerdict mirrors here — undo
}
}