* enhance(#3910): move the last src/ terminators onto the seam Phase 6 bans the raw terminator by construction, which it cannot do while violations stand. A census found 12 sites the rule would flag; nine of the ten unsanctioned ones were owned by no phase of the epic at all — a coverage hole in the decomposition, since P0-P2 are infra, P3 the gate modules, P4 the scanners, P5 the fragments, P7 the hooks, P8 io.cts, and P6 itself only adds the rule. `src/**/*.cts` now holds exactly 2 raw exits, both inside `terminateNow`, the single sanctioned site. `io.cts`'s `error()` is the interesting one. It was first called substantive on "dozens of callers, contract risk" — asserted, not measured, and the measurement refuted it: 289 call sites, zero inside a try whose catch would swallow a throw. The real obstacle was structural instead: `terminateNow` cannot emit exit 1, because ADR-3889 §1 makes 0 and 1 unallocatable and `nameForExitCode(1)` throws. So the only route is `ExitError` under `runMain`, which sets exitCode and writes stderr only when the error carries a user message — keeping the existing stderr write and throwing a message-less ExitError is observably identical. That census was still too narrow, and running the CLI proved it. It asked whether the CALL sits in a try/catch; the two regressions that surfaced were interceptors elsewhere on the stack: - `command-routing-hub.cts`'s `dispatch()` swallowed the ExitError into a HandlerFailure, so the caller emitted a duplicated, wrong stderr line on every Hub-routed path. It now rethrows ExitError explicitly — the same shape `gsd-tools.cjs` already used at two dispatch sites, so this follows an established idiom rather than inventing one. - the profile-pipeline router's deliberately un-awaited `.catch(e => error(...))` turned an ExitError rejection into an uncaught exception; it now mirrors runMain's handling. `edge-probe` and `ui-consideration-probe` gained `runMain` wrappers because probe-core's new throwing default would otherwise have escaped them. A follow-up sweep of every dispatcher — 19 command routers, the Hub, the gsd-tools dispatch seams — found no further swallowing catch. The admitted bound: ~1260 non-rethrowing catches repo-wide were scanned structurally but not individually classified. Both real regressions were found by execution, not by reading, so the suite is the detector that matters here. `gsd-tools.cjs:253` stays a raw exit deliberately: it is the ensureRuntimeBuild bootstrap, which runs before cli-exit is required, so the seam does not yet exist. It needs a second allowlist entry, which means #3910's "single allowlist entry" criterion is unachievable as written. Verification runs on the remote runner. Refs #3910 * enhance(#3910): ban the raw terminator by construction Adds local/require-registered-exit and registers it on all four globs: src/**/*.cts, scripts/**/*.cjs, hooks/**/*.js, gsd-core/bin/**/*.cjs. Registering on the .cts glob is load-bearing, not redundant — the emitted .cjs mirrors are globally eslint-ignored, so a rule registered only on the emitted globs is blind to the sources. That is the #3496 lesson, and it is how the previous guard became invisible: n/no-process-exit was 'error' in one block yet fired zero times on all three surfaces that mattered. The dead n/no-process-exit: 'off' block for hooks is deleted in the same PR. Phase 7 migrated every hook, so the exemption now protects nothing. Two allowlist entries, not the one #3910 anticipated. terminateNow's body is detected STRUCTURALLY — a process.exit lexically inside a function of that name — rather than by a path and line number that rots. The second is gsd-tools.cjs's ensureRuntimeBuild bootstrap, an inline disable with its reason at the call site: it runs before ./lib/cli-exit.cjs is required, so the seam does not exist yet and no migration is possible. #3910's 'single allowlist entry' criterion is therefore unachievable as written, and is amended with the measurement rather than quietly missed. The rule is proven able to FAIL, per glob: four positive controls, one for each registered glob. A guard that cannot be shown to fire is not a guard. Four matching negative controls pin process.exitCode as never-flagged — conflating it with process.exit is what inflated this epic's original census 2x. An allowlist case and a near-miss (same shape, different function name) fix the structural detection in place. Verification runs on the remote runner. Refs #3910 * fix(#3910): stop the detached catch from throwing, and scope the allowlist Review findings, one of them a regression the previous fix introduced. _handlePipelineRejection called error() from inside a DETACHED .catch(). error() now throws, so that throw became an unhandled promise rejection — and on Node >=15 with --unhandled-rejections=throw, Node dumps a raw stack trace with absolute paths on top of the clean Error: line. That was impossible before this branch, because process.exit(1) terminated synchronously before any rejection machinery could observe it. The handler now writes byte-identical stderr itself, in both plain and --json-errors form, and sets exitCode in place. This was the THIRD interceptor found, and like the first two it surfaced by running the CLI rather than by reading code. The rule's terminateNow allowlist had no path constraint, so any function anywhere named terminateNow across all four globs inherited it. It now requires the structural nesting check AND a cli-exit.cts basename — still no line numbers to rot. The four per-glob positive controls only varied a filename inside RuleTester, which never resolves eslint.config.mjs. Since the rule is filename-agnostic, all four exercised identical logic and none proved the rule was WIRED — this epic's own failure mode. A registration test now asserts the rule resolves for a real path in each glob, and it is proven able to fail: removing one glob's registration flips the resolved value from [2] to undefined. Three evasions the rule cannot catch (computed member, aliasing, .call/.apply) are documented in its header and pinned by tests, labelled as known limits rather than endorsed, so a future change that starts catching them is a deliberate diff. Refs #3910 * docs(#3910): document the raw-terminator ban Reference and Explanation via a new docs/features fragment (FEATURES.md is generated from it, not hand-edited). How-To: docs/how-to/resolve-a-raw-terminator-finding.md, indexed from docs/README.md — a contributor whose code trips the rule picks among three replacements by surface (runMain/ExitError for a CLI path, terminateNow for a hook, process.exitCode where the process should drain), and needs to know why process.exitCode is correct and never flagged, since conflating the two is what inflated this epic's original census 2x. The page also names the three patterns the rule cannot catch and says plainly that using one to dodge it is a review finding, not a fix — documenting them without that sentence would read as a sanctioned workaround. docs/INVENTORY.md deliberately untouched: eslint-rules/ is not a tracked family in the manifest (verified — a regen produced a zero diff), so a hand-written row would desync the table from the family it claims to belong to. Refs #3910 * fix(#3910): a catch that sniffs the message swallows an ExitError The remote run returned 41 failures, and one of them was a live production regression rather than a test artifact. `cmdMilestoneComplete`'s unstarted-phase guard re-threw only when `e.message.startsWith('Cannot mark milestone complete:')`. `error()` used to `process.exit(1)`, uncatchable, so the guard always fired. It now throws an ExitError carrying no message, the string test fails, and the ExitError was silently swallowed — the guard stopped blocking milestone completion entirely. Proven against the real CLI: pre-fix, a milestone with an unstarted phase archived at exit 0; post-fix it is blocked at exit 1 with the intended message. That is a guard that silently stopped guarding, which is this epic's thesis appearing inside the phase meant to enforce it. Worth stating plainly: an earlier census DID examine this site, saw a `throw e`, and classified it as rethrowing. It was wrong — the rethrow is conditional, and a conditional rethrow on an inspected message is indistinguishable from an unconditional one unless you read the predicate. So the class was swept rather than patched where it was tripped over. An AST census of every CatchClause across src/, gsd-core/bin/ and scripts/ found 38 conditional rethrows. Two more had the same defect and are fixed the same way: `config.cts`'s `'No config.json'` sniff and `gsd-tools.cjs`'s `e.name === 'WindowsError'`. The remaining 25 are provably unreachable — every one wraps a bare fs, YAML, manifest-require or git-exec primitive that cannot throw ExitError — and two were scanner false positives, both explained. Each fix is an unconditional `instanceof ExitError` rethrow placed BEFORE any inspection, matching the idiom command-routing-hub and gsd-tools already used. Residual bound, stated rather than implied: zero known-reachable unfixed sites, contingent only on error() never later being called inside one of those 25 primitive try blocks. The remaining failures were harness artifacts, and the harnesses were corrected to the new contract rather than the assertions weakened. Tests that mocked `process.exit` to observe termination now catch ExitError and assert its code; tests parsing stderr as a single JSON object still assert exactly that, with their ad-hoc `node -e` scripts wrapped in runMain so it is true. milestone and phase-resolution-parity needed no test change — they were correctly written against the real bug and are what caught it. Verification runs on the remote runner. Refs #3910 * chore(#3910): backfill the changeset PR number Also reframes the fragment to lead with the user-visible change — the milestone guard blocking again — rather than the narrowest of the three fixes. Refs #3910 --------- Co-authored-by: sim <sim@local>
This commit is contained in:
@@ -853,6 +853,7 @@ const commands = require('../gsd-core/bin/lib/commands.cjs');
|
||||
const configCli = require('../gsd-core/bin/lib/config.cjs');
|
||||
const { loadConfigResolved, CONFIG_DEFAULTS } = require('../gsd-core/bin/lib/config-loader.cjs');
|
||||
const io = require('../gsd-core/bin/lib/io.cjs');
|
||||
const { ExitError } = require('../gsd-core/bin/lib/cli-exit.cjs');
|
||||
const { PHASE_NUMBER_TOKEN_SOURCE } = require('../gsd-core/bin/lib/phase-id.cjs');
|
||||
const { DYNAMIC_KEY_PATTERNS } = require('../gsd-core/bin/lib/config-schema.cjs');
|
||||
|
||||
@@ -906,11 +907,11 @@ function runCommit(tmpDir, message, files) {
|
||||
return JSON.parse(out);
|
||||
}
|
||||
|
||||
/** Drives cmdConfigSet in-process, sentinel-exit style (mirrors
|
||||
* tests/config-get-default.test.cjs's runExpectError) for the one negative
|
||||
* (A4) case that must exercise error()'s process.exit(1) path. */
|
||||
/** Drives cmdConfigSet in-process (mirrors tests/config-get-default.test.cjs's
|
||||
* runExpectError) for the one negative (A4) case that must exercise error()'s
|
||||
* ExitError-throwing path (ADR-3889 — error() throws ExitError directly, it
|
||||
* no longer calls process.exit()). */
|
||||
function runConfigSetExpectError(tmpDir, keyPath, value) {
|
||||
const origExit = process.exit;
|
||||
const origWriteSync = fs.writeSync;
|
||||
io.setJsonErrorMode(true);
|
||||
let stderr = '';
|
||||
@@ -923,14 +924,12 @@ function runConfigSetExpectError(tmpDir, keyPath, value) {
|
||||
stderr += chunk;
|
||||
return Buffer.byteLength(chunk);
|
||||
};
|
||||
class _ExitSignal extends Error {}
|
||||
process.exit = () => { throw new _ExitSignal('exit'); };
|
||||
try {
|
||||
configCli.cmdConfigSet(tmpDir, keyPath, value, true);
|
||||
assert.fail('expected cmdConfigSet to throw ExitError');
|
||||
} catch (e) {
|
||||
if (!(e instanceof _ExitSignal)) throw e;
|
||||
if (!(e instanceof ExitError)) throw e;
|
||||
} finally {
|
||||
process.exit = origExit;
|
||||
fs.writeSync = origWriteSync;
|
||||
io.setJsonErrorMode(false);
|
||||
}
|
||||
|
||||
@@ -32,28 +32,28 @@ const config = require(path.join(__dirname, '..', 'gsd-core', 'bin', 'lib', 'con
|
||||
// is bound to io.error at load, so we drive io directly to (a) get structured stderr
|
||||
// we can assert a typed `reason` on, and (b) restore the mode after each error probe.
|
||||
const io = require(path.join(__dirname, '..', 'gsd-core', 'bin', 'lib', 'io.cjs'));
|
||||
// ADR-3889: error() throws ExitError instead of calling process.exit()
|
||||
// directly. The `runExpectError`/`runInProcessAt`/`runScopedExpectError`
|
||||
// harnesses below now catch ExitError directly rather than mocking
|
||||
// process.exit with a throwable sentinel — mocking process.exit no longer
|
||||
// observes anything, since error() never calls it.
|
||||
const { ExitError } = require(path.join(__dirname, '..', 'gsd-core', 'bin', 'lib', 'cli-exit.cjs'));
|
||||
|
||||
/**
|
||||
* cmdConfigGet's error() path (gsd-core/bin/lib/io.cjs) calls process.exit(1)
|
||||
* directly (it predates the ExitError/runMain seam used by the CLI
|
||||
* entrypoint's non-error paths). Intercepting process.exit with a throwable
|
||||
* sentinel lets the error path be exercised in-process without killing the
|
||||
* test worker.
|
||||
* cmdConfigGet's error() path (gsd-core/bin/lib/io.cjs) now throws ExitError
|
||||
* directly (ADR-3889) instead of calling process.exit(1). The harnesses below
|
||||
* catch that ExitError directly — no process.exit mock / throwable sentinel
|
||||
* is needed anymore.
|
||||
*
|
||||
* The sentinel carries the ORIGINAL error message (not a generic "process.exit(1)").
|
||||
* That matters for cmdConfigGet's "no config.json" branch, whose `error()` sits inside
|
||||
* a try/catch that reclassifies any throw NOT starting with "No config.json" as a parse
|
||||
* failure (a guard that is dead in production, where process.exit terminates first, but
|
||||
* becomes live once process.exit is a throwing seam). Carrying the real message makes
|
||||
* that guard re-throw — modeling the single, faithful production termination instead of
|
||||
* a spurious second error() call with the wrong reason.
|
||||
* cmdConfigGet's "no config.json" branch sits inside a try/catch that used to
|
||||
* reclassify any throw NOT starting with "No config.json" as a parse failure.
|
||||
* Because an ExitError carries no message (`.message` defaults to
|
||||
* "process exit 1"), that message-sniffing check could never match it — a
|
||||
* real production bug this PR also fixes at src/config.cts (an unconditional
|
||||
* `instanceof ExitError` re-throw now guards it). The `writeCount === 1`
|
||||
* assertion in these harnesses is what would have caught it: a
|
||||
* fall-through-and-reclassify shows up as a second stderr write.
|
||||
*/
|
||||
class _ExitSignal extends Error {
|
||||
constructor(code, message) {
|
||||
super(message ?? `process.exit(${code})`);
|
||||
this.code = code;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* bin/lib/io.cjs's output()/error() write directly to the raw fd (1 or 2)
|
||||
@@ -131,14 +131,13 @@ describe('config-get --default flag (#1893)', () => {
|
||||
|
||||
function runExpectError(...args) {
|
||||
const { keyPath, raw, defaultValue } = parseConfigGetArgs(args);
|
||||
const origExit = process.exit;
|
||||
const origWriteSync = fs.writeSync;
|
||||
io.setJsonErrorMode(true); // structured stderr line lets the sentinel carry the message + assert reason
|
||||
let exitCount = 0;
|
||||
let exitCode;
|
||||
io.setJsonErrorMode(true); // structured stderr line lets the payload carry the reason
|
||||
let writeCount = 0;
|
||||
let stderr = '';
|
||||
fs.writeSync = (fd, ...rest) => {
|
||||
if (fd !== 2) return origWriteSync.call(fs, fd, ...rest);
|
||||
writeCount++;
|
||||
const [data, offset = 0, length] = rest;
|
||||
const chunk = Buffer.isBuffer(data)
|
||||
? data.subarray(offset, offset + (length ?? data.length - offset)).toString('utf8')
|
||||
@@ -150,27 +149,27 @@ describe('config-get --default flag (#1893)', () => {
|
||||
const parts = stderr.split('\n').filter(Boolean);
|
||||
try { return JSON.parse(parts[parts.length - 1]); } catch { return {}; }
|
||||
};
|
||||
process.exit = (code) => {
|
||||
exitCount++;
|
||||
exitCode = code;
|
||||
// Carry the just-emitted error message so cmdConfigGet's seam guard re-throws
|
||||
// (single, faithful fire) instead of catching + reclassifying into a 2nd error().
|
||||
throw new _ExitSignal(code, lastError().message);
|
||||
};
|
||||
// ADR-3889: error() now throws ExitError directly (rather than calling
|
||||
// process.exit()), so the real termination contract is caught here
|
||||
// instead of via a process.exit mock.
|
||||
let exitCode;
|
||||
try {
|
||||
config.cmdConfigGet(tmpDir, keyPath, raw, defaultValue);
|
||||
assert.fail('expected cmdConfigGet to throw ExitError');
|
||||
} catch (e) {
|
||||
if (!(e instanceof _ExitSignal)) throw e;
|
||||
if (!(e instanceof ExitError)) throw e;
|
||||
exitCode = e.code;
|
||||
} finally {
|
||||
process.exit = origExit;
|
||||
fs.writeSync = origWriteSync;
|
||||
io.setJsonErrorMode(false);
|
||||
}
|
||||
assert.ok(exitCode !== 0 && exitCode !== undefined, 'Expected non-zero exit code');
|
||||
// Faithfulness guard: production process.exit terminates, so error() fires exactly
|
||||
// once. A count of 2 means the throwing-exit seam was caught + reclassified (the bug
|
||||
// this harness redesign fixes) — fail loudly rather than report a wrong reason.
|
||||
assert.equal(exitCount, 1, 'error() must fire exactly once (production process.exit terminates)');
|
||||
// Faithfulness guard: error() must fire exactly once. A count of 2 means
|
||||
// the guard's ExitError was caught by a message-sniffing catch and
|
||||
// reclassified into a 2nd error() call (the exact Part-2 defect class —
|
||||
// an ExitError has no message, so `.message.startsWith(...)` conditions
|
||||
// never match it and it falls through to a wrong, generic branch).
|
||||
assert.equal(writeCount, 1, 'error() must fire exactly once');
|
||||
const payload = lastError();
|
||||
return { status: exitCode, reason: payload.reason, message: payload.message, stderr };
|
||||
}
|
||||
@@ -277,14 +276,13 @@ describe('config-get --default flag (#1893)', () => {
|
||||
|
||||
function runExpectError(...args) {
|
||||
const { keyPath, raw, defaultValue } = parseConfigGetArgs(args);
|
||||
const origExit = process.exit;
|
||||
const origWriteSync = fs.writeSync;
|
||||
io.setJsonErrorMode(true);
|
||||
let exitCount = 0;
|
||||
let exitCode;
|
||||
let writeCount = 0;
|
||||
let stderr = '';
|
||||
fs.writeSync = (fd, ...rest) => {
|
||||
if (fd !== 2) return origWriteSync.call(fs, fd, ...rest);
|
||||
writeCount++;
|
||||
const [data, offset = 0, length] = rest;
|
||||
const chunk = Buffer.isBuffer(data)
|
||||
? data.subarray(offset, offset + (length ?? data.length - offset)).toString('utf8')
|
||||
@@ -296,22 +294,21 @@ describe('config-get --default flag (#1893)', () => {
|
||||
const parts = stderr.split('\n').filter(Boolean);
|
||||
try { return JSON.parse(parts[parts.length - 1]); } catch { return {}; }
|
||||
};
|
||||
process.exit = (code) => {
|
||||
exitCount++;
|
||||
exitCode = code;
|
||||
throw new _ExitSignal(code, lastError().message);
|
||||
};
|
||||
// ADR-3889: error() throws ExitError directly; catch it here rather
|
||||
// than mocking process.exit.
|
||||
let exitCode;
|
||||
try {
|
||||
config.cmdConfigGet(tmpDir, keyPath, raw, defaultValue);
|
||||
assert.fail('expected cmdConfigGet to throw ExitError');
|
||||
} catch (e) {
|
||||
if (!(e instanceof _ExitSignal)) throw e;
|
||||
if (!(e instanceof ExitError)) throw e;
|
||||
exitCode = e.code;
|
||||
} finally {
|
||||
process.exit = origExit;
|
||||
fs.writeSync = origWriteSync;
|
||||
io.setJsonErrorMode(false);
|
||||
}
|
||||
assert.ok(exitCode !== 0 && exitCode !== undefined, 'Expected non-zero exit code');
|
||||
assert.equal(exitCount, 1, 'error() must fire exactly once (production process.exit terminates)');
|
||||
assert.equal(writeCount, 1, 'error() must fire exactly once');
|
||||
const payload = lastError();
|
||||
return { status: exitCode, reason: payload.reason, message: payload.message, stderr };
|
||||
}
|
||||
@@ -491,7 +488,6 @@ describe('config-get --default flag (#1893)', () => {
|
||||
// fresh for every fc run (unique mkdtemp per run body, cleaned up in a
|
||||
// finally — no shared/leaked state across runs).
|
||||
function runInProcessAt(dir, keyPath) {
|
||||
const origExit = process.exit;
|
||||
const origWriteSync = fs.writeSync;
|
||||
io.setJsonErrorMode(true);
|
||||
let stdout = '';
|
||||
@@ -507,17 +503,15 @@ describe('config-get --default flag (#1893)', () => {
|
||||
else if (fd === 2) stderr += chunk;
|
||||
return Buffer.byteLength(chunk);
|
||||
};
|
||||
process.exit = (code) => {
|
||||
exited = true;
|
||||
exitCode = code;
|
||||
throw new _ExitSignal(code, '');
|
||||
};
|
||||
// ADR-3889: error() throws ExitError directly; catch it here rather
|
||||
// than mocking process.exit.
|
||||
try {
|
||||
config.cmdConfigGet(dir, keyPath, true, undefined);
|
||||
} catch (e) {
|
||||
if (!(e instanceof _ExitSignal)) throw e;
|
||||
if (!(e instanceof ExitError)) throw e;
|
||||
exited = true;
|
||||
exitCode = e.code;
|
||||
} finally {
|
||||
process.exit = origExit;
|
||||
fs.writeSync = origWriteSync;
|
||||
io.setJsonErrorMode(false);
|
||||
}
|
||||
@@ -1415,23 +1409,24 @@ describe('#2702: workstream config-get inherits from root config', () => {
|
||||
const { keyPath, raw, defaultValue } = parseConfigGetArgs(args);
|
||||
const saved = process.env.GSD_WORKSTREAM;
|
||||
process.env.GSD_WORKSTREAM = 'alpha';
|
||||
const origExit = process.exit;
|
||||
const origWriteSync = fs.writeSync;
|
||||
io.setJsonErrorMode(true);
|
||||
let exitCode;
|
||||
let stderr = '';
|
||||
fs.writeSync = (fd, ...rest) => {
|
||||
if (fd !== 2) return origWriteSync.call(fs, fd, ...rest);
|
||||
stderr += String(rest[0]);
|
||||
return Buffer.byteLength(String(rest[0]));
|
||||
};
|
||||
process.exit = (code) => { exitCode = code; throw new _ExitSignal(code); };
|
||||
// ADR-3889: error() throws ExitError directly; catch it here rather
|
||||
// than mocking process.exit.
|
||||
let exitCode;
|
||||
try {
|
||||
config.cmdConfigGet(tmpDir, keyPath, raw, defaultValue);
|
||||
assert.fail('expected cmdConfigGet to throw ExitError');
|
||||
} catch (e) {
|
||||
if (!(e instanceof _ExitSignal)) throw e;
|
||||
if (!(e instanceof ExitError)) throw e;
|
||||
exitCode = e.code;
|
||||
} finally {
|
||||
process.exit = origExit;
|
||||
fs.writeSync = origWriteSync;
|
||||
io.setJsonErrorMode(false);
|
||||
if (saved === undefined) delete process.env.GSD_WORKSTREAM;
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
* - local/no-raw-rmsync-in-tests
|
||||
* - local/no-adhoc-markdown-parsing
|
||||
* - local/require-subprocess-timeout
|
||||
* - local/require-registered-exit
|
||||
*/
|
||||
|
||||
const { test, describe } = require('node:test');
|
||||
@@ -30,6 +31,7 @@ const noTautologicalAssert = require('../eslint-rules/no-tautological-assert.cjs
|
||||
const noAdhocMarkdownParsing = require('../eslint-rules/no-adhoc-markdown-parsing.cjs');
|
||||
const noDuplicateFoldMarker = require('../eslint-rules/no-duplicate-fold-marker.cjs');
|
||||
const requireSubprocessTimeout = require('../eslint-rules/require-subprocess-timeout.cjs');
|
||||
const requireRegisteredExit = require('../eslint-rules/require-registered-exit.cjs');
|
||||
|
||||
const ruleTester = new RuleTester({
|
||||
languageOptions: {
|
||||
@@ -3183,3 +3185,304 @@ describe('require-subprocess-timeout rule', () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// ─── require-registered-exit (#3910, epic #3889 Phase 6) ──────────────────
|
||||
//
|
||||
// See .gsd/phase/enhance-3910-ban-raw-terminator/50-test-matrix.md for the
|
||||
// enumerated input-class matrix these tests implement.
|
||||
|
||||
describe('require-registered-exit rule', () => {
|
||||
test('rule module exports a create function', () => {
|
||||
assert.strictEqual(typeof requireRegisteredExit.create, 'function');
|
||||
});
|
||||
|
||||
// ── Positive control: one per registered glob (matrix rows 1-4) ──────────
|
||||
|
||||
test('invalid: process.exit() at top level — src/**/*.cts glob', () => {
|
||||
ruleTester.run('require-registered-exit', requireRegisteredExit, {
|
||||
valid: [],
|
||||
invalid: [
|
||||
{
|
||||
code: `process.exit(0);`,
|
||||
filename: 'src/some-module.cts',
|
||||
errors: [{ messageId: 'rawProcessExit' }],
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test('invalid: process.exit() at top level — scripts/**/*.cjs glob', () => {
|
||||
ruleTester.run('require-registered-exit', requireRegisteredExit, {
|
||||
valid: [],
|
||||
invalid: [
|
||||
{
|
||||
code: `process.exit(1);`,
|
||||
filename: 'scripts/some-script.cjs',
|
||||
errors: [{ messageId: 'rawProcessExit' }],
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test('invalid: process.exit() at top level — hooks/**/*.js glob', () => {
|
||||
ruleTester.run('require-registered-exit', requireRegisteredExit, {
|
||||
valid: [],
|
||||
invalid: [
|
||||
{
|
||||
code: `process.exit(2);`,
|
||||
filename: 'hooks/some-hook.js',
|
||||
errors: [{ messageId: 'rawProcessExit' }],
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test('invalid: process.exit() at top level — gsd-core/bin/**/*.cjs glob', () => {
|
||||
ruleTester.run('require-registered-exit', requireRegisteredExit, {
|
||||
valid: [],
|
||||
invalid: [
|
||||
{
|
||||
code: `process.exit(1);`,
|
||||
filename: 'gsd-core/bin/gsd-tools.cjs',
|
||||
errors: [{ messageId: 'rawProcessExit' }],
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
// ── Negative control: process.exitCode must NEVER be flagged (matrix rows 5-8) ──
|
||||
//
|
||||
// Required negative control: conflating process.exitCode (the CORRECT
|
||||
// drain-then-exit pattern) with process.exit() is what inflated this
|
||||
// epic's original raw-exit census 2x.
|
||||
|
||||
test('valid: process.exitCode = 1 is not flagged — src/**/*.cts glob', () => {
|
||||
ruleTester.run('require-registered-exit', requireRegisteredExit, {
|
||||
valid: [
|
||||
{ code: `process.exitCode = 1;`, filename: 'src/some-module.cts' },
|
||||
],
|
||||
invalid: [],
|
||||
});
|
||||
});
|
||||
|
||||
test('valid: process.exitCode = 1 is not flagged — scripts/**/*.cjs glob', () => {
|
||||
ruleTester.run('require-registered-exit', requireRegisteredExit, {
|
||||
valid: [
|
||||
{ code: `process.exitCode = 1;`, filename: 'scripts/some-script.cjs' },
|
||||
],
|
||||
invalid: [],
|
||||
});
|
||||
});
|
||||
|
||||
test('valid: process.exitCode = 1 is not flagged — hooks/**/*.js glob', () => {
|
||||
ruleTester.run('require-registered-exit', requireRegisteredExit, {
|
||||
valid: [
|
||||
{ code: `process.exitCode = 1;`, filename: 'hooks/some-hook.js' },
|
||||
],
|
||||
invalid: [],
|
||||
});
|
||||
});
|
||||
|
||||
test('valid: process.exitCode = 1 is not flagged — gsd-core/bin/**/*.cjs glob', () => {
|
||||
ruleTester.run('require-registered-exit', requireRegisteredExit, {
|
||||
valid: [
|
||||
{ code: `process.exitCode = 1;`, filename: 'gsd-core/bin/gsd-tools.cjs' },
|
||||
],
|
||||
invalid: [],
|
||||
});
|
||||
});
|
||||
|
||||
// ── Allowlist boundary: the ONE sanctioned terminator (matrix rows 9-11) ──
|
||||
|
||||
test('valid: process.exit() lexically inside a function named terminateNow is allowlisted', () => {
|
||||
ruleTester.run('require-registered-exit', requireRegisteredExit, {
|
||||
valid: [
|
||||
{
|
||||
code: `
|
||||
function terminateNow(outcome, payload) {
|
||||
try {
|
||||
process.exit(0);
|
||||
} catch (err) {
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
`,
|
||||
filename: 'src/cli-exit.cts',
|
||||
},
|
||||
],
|
||||
invalid: [],
|
||||
});
|
||||
});
|
||||
|
||||
test('invalid: near-miss — same shape, function named something else IS flagged', () => {
|
||||
ruleTester.run('require-registered-exit', requireRegisteredExit, {
|
||||
valid: [],
|
||||
invalid: [
|
||||
{
|
||||
code: `
|
||||
function notTerminateNow(outcome, payload) {
|
||||
process.exit(0);
|
||||
}
|
||||
`,
|
||||
filename: 'src/cli-exit.cts',
|
||||
errors: [{ messageId: 'rawProcessExit' }],
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test('invalid: a top-level process.exit() is flagged even when an unrelated terminateNow exists elsewhere in the same file (allowlist is structural nesting, not file-wide)', () => {
|
||||
ruleTester.run('require-registered-exit', requireRegisteredExit, {
|
||||
valid: [],
|
||||
invalid: [
|
||||
{
|
||||
code: `
|
||||
function terminateNow() {
|
||||
// unrelated to the top-level exit below
|
||||
}
|
||||
process.exit(0);
|
||||
`,
|
||||
filename: 'src/cli-exit.cts',
|
||||
errors: [{ messageId: 'rawProcessExit' }],
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
// ── Independence (matrix rows 12-13) ──────────────────────────────────────
|
||||
|
||||
test('valid: a bare (non-process) exit(...) call is not flagged', () => {
|
||||
ruleTester.run('require-registered-exit', requireRegisteredExit, {
|
||||
valid: [
|
||||
{
|
||||
code: `
|
||||
function exit(code) { return code; }
|
||||
exit(0);
|
||||
`,
|
||||
filename: 'src/some-module.cts',
|
||||
},
|
||||
],
|
||||
invalid: [],
|
||||
});
|
||||
});
|
||||
|
||||
test('valid: computed member access process["exit"](0) is not flagged (documented boundary, name-based matching only)', () => {
|
||||
ruleTester.run('require-registered-exit', requireRegisteredExit, {
|
||||
valid: [
|
||||
{ code: `process['exit'](0);`, filename: 'src/some-module.cts' },
|
||||
],
|
||||
invalid: [],
|
||||
});
|
||||
});
|
||||
|
||||
// ── Finding 5: KNOWN LIMITS, pinned — the rule does NOT catch these evasions
|
||||
// today. These tests do not endorse the patterns; they pin the CURRENT
|
||||
// behavior so that a future change which starts catching one of them is a
|
||||
// visible, deliberate diff (an intentionally-failing pinning test) rather
|
||||
// than a silent behavior change discovered later. See the rule's header
|
||||
// doc comment for the same limits documented for a human reader.
|
||||
|
||||
test('KNOWN LIMIT (pinned, not endorsed): aliasing process.exit to a local binding evades detection', () => {
|
||||
ruleTester.run('require-registered-exit', requireRegisteredExit, {
|
||||
valid: [
|
||||
{
|
||||
code: `const e = process.exit; e(1);`,
|
||||
filename: 'src/some-module.cts',
|
||||
},
|
||||
],
|
||||
invalid: [],
|
||||
});
|
||||
});
|
||||
|
||||
test('KNOWN LIMIT (pinned, not endorsed): process.exit.call(...) evades detection', () => {
|
||||
ruleTester.run('require-registered-exit', requireRegisteredExit, {
|
||||
valid: [
|
||||
{
|
||||
code: `process.exit.call(null, 1);`,
|
||||
filename: 'src/some-module.cts',
|
||||
},
|
||||
],
|
||||
invalid: [],
|
||||
});
|
||||
});
|
||||
|
||||
test('KNOWN LIMIT (pinned, not endorsed): process.exit.apply(...) evades detection', () => {
|
||||
ruleTester.run('require-registered-exit', requireRegisteredExit, {
|
||||
valid: [
|
||||
{
|
||||
code: `process.exit.apply(null, [1]);`,
|
||||
filename: 'src/some-module.cts',
|
||||
},
|
||||
],
|
||||
invalid: [],
|
||||
});
|
||||
});
|
||||
|
||||
// ── Allowlist is basename-AND-name gated, not name-only (finding: any file
|
||||
// named terminateNow would otherwise inherit the allowlist for free) ───────
|
||||
|
||||
test('invalid: a function named terminateNow in a file that is NOT cli-exit.cts is still flagged', () => {
|
||||
ruleTester.run('require-registered-exit', requireRegisteredExit, {
|
||||
valid: [],
|
||||
invalid: [
|
||||
{
|
||||
code: `
|
||||
function terminateNow(outcome, payload) {
|
||||
process.exit(0);
|
||||
}
|
||||
`,
|
||||
filename: 'src/some-other-module.cts',
|
||||
errors: [{ messageId: 'rawProcessExit' }],
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test('invalid: a function named terminateNow in gsd-core/bin/gsd-tools.cjs (not cli-exit.cts) is still flagged', () => {
|
||||
ruleTester.run('require-registered-exit', requireRegisteredExit, {
|
||||
valid: [],
|
||||
invalid: [
|
||||
{
|
||||
code: `
|
||||
function terminateNow(outcome, payload) {
|
||||
process.exit(0);
|
||||
}
|
||||
`,
|
||||
filename: 'gsd-core/bin/gsd-tools.cjs',
|
||||
errors: [{ messageId: 'rawProcessExit' }],
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
// ── Finding 4: registration proof, not just filename-agnostic rule logic ──
|
||||
//
|
||||
// The RuleTester cases above vary `filename` directly, which RuleTester
|
||||
// never resolves against eslint.config.mjs — they prove the rule's AST
|
||||
// logic, not that it is actually WIRED to the four globs. This proves
|
||||
// wiring: it resolves the real config for one representative path per
|
||||
// glob and asserts the rule is enabled there. This test fails if a glob
|
||||
// registration is ever removed from eslint.config.mjs (verified live:
|
||||
// temporarily deleting the gsd-core/bin/**/*.cjs registration flipped
|
||||
// this test red before it was restored).
|
||||
test('the rule is registered at error for one representative path per glob in the real config', async () => {
|
||||
const REPO_ROOT = path.join(__dirname, '..');
|
||||
const eslint = new ESLint({ cwd: REPO_ROOT });
|
||||
const representativePaths = [
|
||||
path.join(REPO_ROOT, 'src', 'cli-exit.cts'),
|
||||
path.join(REPO_ROOT, 'scripts', 'affected-tests-lib.cjs'),
|
||||
path.join(REPO_ROOT, 'hooks', 'gsd-check-update.js'),
|
||||
path.join(REPO_ROOT, 'gsd-core', 'bin', 'gsd-tools.cjs'),
|
||||
];
|
||||
for (const p of representativePaths) {
|
||||
// Sequential config resolution (not a hot loop) — no-await-in-loop is
|
||||
// not registered on this glob, so no disable directive is needed here.
|
||||
const config = await eslint.calculateConfigForFile(p);
|
||||
assert.deepStrictEqual(
|
||||
config.rules['local/require-registered-exit'],
|
||||
[2],
|
||||
`expected local/require-registered-exit to be registered at error for ${path.relative(REPO_ROOT, p)}`,
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -28,6 +28,7 @@ const estimateCli = require('../gsd-core/bin/lib/estimate-cli.cjs');
|
||||
// H1 below can assert a typed `reason`, mirroring tests/config-get-default.test.cjs's
|
||||
// established in-process CLI-error-path pattern.
|
||||
const io = require('../gsd-core/bin/lib/io.cjs');
|
||||
const { ExitError } = require('../gsd-core/bin/lib/cli-exit.cjs');
|
||||
|
||||
/** Write a phase dir containing a PLAN with an estimate and a SUMMARY with actuals. */
|
||||
function writePhase(tmpDir, phaseDir, { estTokens, actTokens, tasks = 3, commits = 4 }) {
|
||||
@@ -544,23 +545,17 @@ describe('sentinel phases must not skew calibration (#3882)', () => {
|
||||
// cross-platform IO-failure-injection rule) already used in
|
||||
// tests/phase-locator.test.cjs for `listAllPhaseDirs`'s own unreadable case.
|
||||
describe('unreadable phases directory refuses calibration (#3882, ADR-3473 §8.5)', () => {
|
||||
class _ExitSignal extends Error {
|
||||
constructor(code, message) {
|
||||
super(message ?? `process.exit(${code})`);
|
||||
this.code = code;
|
||||
}
|
||||
}
|
||||
|
||||
/** Runs cmdEstimateCalibrate in-process with process.exit + stderr(fd 2) captured. */
|
||||
/** Runs cmdEstimateCalibrate in-process, catching the ExitError error()
|
||||
* throws (ADR-3889 — error() no longer calls process.exit() directly) with
|
||||
* stderr(fd 2) captured. */
|
||||
function runCalibrateExpectError(tmpDir) {
|
||||
const origExit = process.exit;
|
||||
const origWriteSync = fs.writeSync;
|
||||
io.setJsonErrorMode(true);
|
||||
let exitCount = 0;
|
||||
let exitCode;
|
||||
let writeCount = 0;
|
||||
let stderr = '';
|
||||
fs.writeSync = (fd, ...rest) => {
|
||||
if (fd !== 2) return origWriteSync.call(fs, fd, ...rest);
|
||||
writeCount++;
|
||||
const [data, offset = 0, length] = rest;
|
||||
const chunk = Buffer.isBuffer(data)
|
||||
? data.subarray(offset, offset + (length ?? data.length - offset)).toString('utf8')
|
||||
@@ -572,22 +567,19 @@ describe('unreadable phases directory refuses calibration (#3882, ADR-3473 §8.5
|
||||
const parts = stderr.split('\n').filter(Boolean);
|
||||
try { return JSON.parse(parts[parts.length - 1]); } catch { return {}; }
|
||||
};
|
||||
process.exit = (code) => {
|
||||
exitCount++;
|
||||
exitCode = code;
|
||||
throw new _ExitSignal(code, lastError().message);
|
||||
};
|
||||
let exitCode;
|
||||
try {
|
||||
estimateCli.cmdEstimateCalibrate(tmpDir, [], false);
|
||||
assert.fail('expected cmdEstimateCalibrate to throw ExitError');
|
||||
} catch (e) {
|
||||
if (!(e instanceof _ExitSignal)) throw e;
|
||||
if (!(e instanceof ExitError)) throw e;
|
||||
exitCode = e.code;
|
||||
} finally {
|
||||
process.exit = origExit;
|
||||
fs.writeSync = origWriteSync;
|
||||
io.setJsonErrorMode(false);
|
||||
}
|
||||
assert.ok(exitCode !== 0 && exitCode !== undefined, 'expected a non-zero exit code');
|
||||
assert.equal(exitCount, 1, 'error() must fire exactly once (production process.exit terminates)');
|
||||
assert.equal(writeCount, 1, 'error() must fire exactly once');
|
||||
return { status: exitCode, ...lastError() };
|
||||
}
|
||||
|
||||
|
||||
@@ -18,6 +18,7 @@ const os = require('node:os');
|
||||
const fs = require('node:fs');
|
||||
|
||||
const io = require('../gsd-core/bin/lib/io.cjs');
|
||||
const { ExitError } = require('../gsd-core/bin/lib/cli-exit.cjs');
|
||||
const { runNode } = require('./helpers/process-seam.cjs');
|
||||
const { toLegacyResult } = require('./helpers/git-fixture.cjs');
|
||||
const { PROBE_TIMEOUT_MS } = require('./helpers/timeouts.cjs');
|
||||
@@ -186,12 +187,25 @@ describe('output()', () => {
|
||||
|
||||
describe('error()', () => {
|
||||
const ioPath = path.resolve(__dirname, '../gsd-core/bin/lib/io.cjs');
|
||||
const cliExitPath = path.resolve(__dirname, '../gsd-core/bin/lib/cli-exit.cjs');
|
||||
|
||||
// ADR-3889: io.error() now throws ExitError instead of calling
|
||||
// process.exit() directly. A bare `node -e` script that calls io.error()
|
||||
// with no termination seam would let that ExitError escape as an uncaught
|
||||
// exception (a stack trace on stderr, not the single "Error: <msg>" line
|
||||
// error() itself already wrote). Every harness script below wraps the
|
||||
// error() call in runMain — the sanctioned entrypoint seam — so the
|
||||
// process terminates exactly the way a real CLI invocation would: the one
|
||||
// stderr write error() performs itself, then `process.exitCode = err.code`
|
||||
// with nothing further written (ExitError from error() carries no message,
|
||||
// so runMain's own "hasUserMessage" stderr write is a no-op here).
|
||||
|
||||
test('plain-text mode: writes "Error: <msg>" to stderr and exits 1', () => {
|
||||
const script = `
|
||||
const io = require(${JSON.stringify(ioPath)});
|
||||
const { runMain } = require(${JSON.stringify(cliExitPath)});
|
||||
io.setJsonErrorMode(false);
|
||||
io.error('something went wrong');
|
||||
runMain(() => { io.error('something went wrong'); });
|
||||
`;
|
||||
const result = runScript(script);
|
||||
assert.strictEqual(result.status, 1);
|
||||
@@ -202,8 +216,9 @@ describe('error()', () => {
|
||||
test('plain-text mode: default reason does not appear in stderr text', () => {
|
||||
const script = `
|
||||
const io = require(${JSON.stringify(ioPath)});
|
||||
const { runMain } = require(${JSON.stringify(cliExitPath)});
|
||||
io.setJsonErrorMode(false);
|
||||
io.error('no reason code expected');
|
||||
runMain(() => { io.error('no reason code expected'); });
|
||||
`;
|
||||
const result = runScript(script);
|
||||
assert.strictEqual(result.status, 1);
|
||||
@@ -214,8 +229,9 @@ describe('error()', () => {
|
||||
test('JSON-error mode: writes structured JSON to stderr and exits 1', () => {
|
||||
const script = `
|
||||
const io = require(${JSON.stringify(ioPath)});
|
||||
const { runMain } = require(${JSON.stringify(cliExitPath)});
|
||||
io.setJsonErrorMode(true);
|
||||
io.error('structured error', io.ERROR_REASON.SDK_FAIL_FAST);
|
||||
runMain(() => { io.error('structured error', io.ERROR_REASON.SDK_FAIL_FAST); });
|
||||
`;
|
||||
const result = runScript(script);
|
||||
assert.strictEqual(result.status, 1);
|
||||
@@ -229,8 +245,9 @@ describe('error()', () => {
|
||||
test('JSON-error mode: defaults reason to UNKNOWN when not supplied', () => {
|
||||
const script = `
|
||||
const io = require(${JSON.stringify(ioPath)});
|
||||
const { runMain } = require(${JSON.stringify(cliExitPath)});
|
||||
io.setJsonErrorMode(true);
|
||||
io.error('no reason given');
|
||||
runMain(() => { io.error('no reason given'); });
|
||||
`;
|
||||
const result = runScript(script);
|
||||
assert.strictEqual(result.status, 1);
|
||||
@@ -249,8 +266,9 @@ describe('error()', () => {
|
||||
for (const [expected, key] of cases) {
|
||||
const script = `
|
||||
const io = require(${JSON.stringify(ioPath)});
|
||||
const { runMain } = require(${JSON.stringify(cliExitPath)});
|
||||
io.setJsonErrorMode(true);
|
||||
io.error('test', io.ERROR_REASON.${key});
|
||||
runMain(() => { io.error('test', io.ERROR_REASON.${key}); });
|
||||
`;
|
||||
const result = runScript(script);
|
||||
assert.strictEqual(result.status, 1, `key=${key}`);
|
||||
@@ -442,24 +460,36 @@ describe('bug #1008: io.output() tolerates a full / slow non-blocking pipe', ()
|
||||
});
|
||||
|
||||
describe('bug #1008: io.error() tolerates a full non-blocking stderr pipe', () => {
|
||||
test('retries on EAGAIN, emits the full message, and still exits', (t) => {
|
||||
// ADR-3889: error() throws ExitError instead of calling process.exit()
|
||||
// directly, so mocking process.exit and asserting doesNotThrow no longer
|
||||
// matches the contract — error() now DOES throw, on purpose, and the
|
||||
// termination semantics (translating that throw into a process exit code)
|
||||
// belong to runMain() at the entrypoint, not to error() itself. This test
|
||||
// asserts the real contract directly: catch the ExitError and check its
|
||||
// `code`.
|
||||
test('retries on EAGAIN, emits the full message, and throws ExitError(1)', () => {
|
||||
const written = [];
|
||||
let calls = 0;
|
||||
let exitCode = null;
|
||||
t.mock.method(process, 'exit', (code) => { exitCode = code; }); // neutralize the hard exit
|
||||
t.mock.method(fs, 'writeSync', (fd, data, offset, length) => {
|
||||
const restore = fs.writeSync;
|
||||
fs.writeSync = (fd, data, offset, length) => {
|
||||
calls += 1;
|
||||
if (calls === 1) throw bug1008WriteError('EAGAIN', -11);
|
||||
assert.equal(fd, 2, 'error() must write to stderr');
|
||||
const chunk = bug1008ChunkOf(data, offset, length);
|
||||
written.push(chunk);
|
||||
return Buffer.byteLength(chunk, 'utf8');
|
||||
});
|
||||
|
||||
assert.doesNotThrow(() => io.error('boom', io.ERROR_REASON.UNKNOWN));
|
||||
};
|
||||
try {
|
||||
assert.throws(
|
||||
() => io.error('boom', io.ERROR_REASON.UNKNOWN),
|
||||
(err) => err instanceof ExitError && err.code === 1,
|
||||
'error() must throw ExitError(1) after a retried write',
|
||||
);
|
||||
} finally {
|
||||
fs.writeSync = restore;
|
||||
}
|
||||
assert.ok(calls >= 2, 'error() should retry after EAGAIN');
|
||||
assert.equal(written.join(''), 'Error: boom\n');
|
||||
assert.equal(exitCode, 1, 'error() must still exit(1) after a retried write');
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
Reference in New Issue
Block a user