* 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>
139 lines
6.5 KiB
JavaScript
139 lines
6.5 KiB
JavaScript
'use strict';
|
|
|
|
const path = require('node:path');
|
|
|
|
/**
|
|
* require-registered-exit
|
|
*
|
|
* Issue #3910 (epic #3889 Phase 6): "the raw terminator is banned by
|
|
* construction." A raw `process.exit(...)` call bypasses the registered
|
|
* exit-contract machinery in src/cli-exit.cts (ExitError/runMain for a CLI
|
|
* path, terminateNow for a hook) — the whole point of ADR-3889 is that
|
|
* EVERY process termination is projected through one of those two seams, so
|
|
* a bare `process.exit()` re-opens exactly the "nothing fails with success"
|
|
* defect class the epic exists to close.
|
|
*
|
|
* Flags: any `CallExpression` whose callee is a `MemberExpression` with
|
|
* `object.name === 'process'` and `property.name === 'exit'` — i.e.
|
|
* `process.exit(...)`.
|
|
*
|
|
* Does NOT flag `process.exitCode = N` — that assignment is the CORRECT
|
|
* drain-then-exit pattern `runMain` itself uses, and conflating the two is
|
|
* what inflated this epic's original raw-`process.exit()` census 2x (a
|
|
* `MemberExpression` assignment target is never a `CallExpression`, so this
|
|
* rule's `CallExpression`-only selector already excludes it structurally;
|
|
* see the negative-control tests in tests/eslint-rules.test.cjs).
|
|
*
|
|
* ── Allowlist (exactly two sites, repo-wide) ────────────────────────────────
|
|
*
|
|
* 1. The body of `terminateNow` in src/cli-exit.cts — the single sanctioned
|
|
* terminator (ADR-3889 §3: write-then-terminate, the only place exit code
|
|
* 2 — the hook-protocol deny — may be produced). Detected STRUCTURALLY
|
|
* below (any process.exit() call lexically nested inside a function
|
|
* declaration/expression named `terminateNow`, AND the file's basename is
|
|
* `cli-exit.cts`), not by a path+line number, which rots the instant the
|
|
* function grows or moves. The basename constraint is required in
|
|
* addition to the name check: without it, any function named
|
|
* `terminateNow` anywhere in the repo would silently inherit the
|
|
* allowlist, widening the rule's trust boundary to a name that can be
|
|
* typo'd or copy-pasted into an unrelated module.
|
|
*
|
|
* 2. gsd-core/bin/gsd-tools.cjs's `ensureRuntimeBuild` bootstrap-failure path
|
|
* (see its own inline `// eslint-disable-next-line local/require-registered-exit`
|
|
* comment). That call runs BEFORE `./lib/cli-exit.cjs` is even required —
|
|
* the registered-exit seam does not exist yet at that point in the
|
|
* process's lifetime, so there is nothing to route through. An inline
|
|
* disable directive WITH a reason comment at that one call site was
|
|
* chosen over a hardcoded path in this rule for the same reason
|
|
* terminateNow's allowlisting is structural rather than path-based: a
|
|
* path-keyed allowlist here would silently stop protecting the file the
|
|
* moment its bootstrap code moved, while an inline directive travels with
|
|
* the call site and fails loudly (an unused-disable lint error) if the
|
|
* surrounding code changes such that it is no longer needed.
|
|
*
|
|
* ── Known limits (documented, deliberately out of scope) ────────────────────
|
|
*
|
|
* The rule matches a literal `CallExpression` shaped exactly like
|
|
* `process.exit(...)` (a non-computed MemberExpression on an Identifier
|
|
* named `process` with a property named `exit`). It does NOT do scope/flow
|
|
* analysis, so it cannot catch:
|
|
*
|
|
* - `process['exit'](0)` — computed member access (same identifier, but
|
|
* `callee.computed` is true so the property-name check never runs).
|
|
* - `const e = process.exit; e(1);` — aliasing the function reference to a
|
|
* local binding before calling it; by the time the alias is called, the
|
|
* callee is a plain Identifier, not a MemberExpression on `process`.
|
|
* - `process.exit.call(null, 1)` / `process.exit.apply(null, [1])` —
|
|
* invoking `process.exit` indirectly via Function.prototype.call/apply;
|
|
* the outer CallExpression's callee is `process.exit.call`, not
|
|
* `process.exit` itself.
|
|
*
|
|
* Catching these would require binding/scope-aware analysis (tracking that a
|
|
* local variable or a `.call`/`.apply` receiver resolves back to
|
|
* `process.exit`), which is a materially different and more expensive class
|
|
* of rule. Out of scope for this issue. See the pinning tests in
|
|
* tests/eslint-rules.test.cjs ("KNOWN LIMIT (pinned, not endorsed)") that
|
|
* assert these are NOT flagged today — if a future change starts catching
|
|
* one of them, those tests will fail loudly instead of the change silently
|
|
* altering the rule's reach.
|
|
*/
|
|
|
|
/**
|
|
* True if `node` (a CallExpression) is lexically nested inside a function
|
|
* declaration or function expression named `name`, walking up the ESLint
|
|
* `.parent` chain. Used to allowlist the terminateNow body structurally —
|
|
* see the module doc comment above.
|
|
*/
|
|
function isInsideFunctionNamed(node, name) {
|
|
let current = node.parent;
|
|
while (current) {
|
|
if (
|
|
(current.type === 'FunctionDeclaration' || current.type === 'FunctionExpression') &&
|
|
current.id &&
|
|
current.id.type === 'Identifier' &&
|
|
current.id.name === name
|
|
) {
|
|
return true;
|
|
}
|
|
current = current.parent;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
/** @type {import('eslint').Rule.RuleModule} */
|
|
const rule = {
|
|
meta: {
|
|
type: 'problem',
|
|
docs: {
|
|
description:
|
|
'Disallow raw process.exit() outside terminateNow — route CLI paths through runMain/ExitError, hooks through terminateNow, and drain-only exits through process.exitCode',
|
|
category: 'Best Practices',
|
|
},
|
|
schema: [],
|
|
messages: {
|
|
rawProcessExit:
|
|
'Raw process.exit() is banned outside terminateNow (ADR-3889). Use runMain/ExitError '
|
|
+ '(src/cli-exit.cts) for a CLI entrypoint, terminateNow (src/cli-exit.cts) for a hook that '
|
|
+ 'must write-then-terminate immediately, or set process.exitCode and let the process drain '
|
|
+ 'naturally when nothing needs an immediate hard exit.',
|
|
},
|
|
},
|
|
create(context) {
|
|
return {
|
|
CallExpression(node) {
|
|
const callee = node.callee;
|
|
if (callee.type !== 'MemberExpression' || callee.computed) return;
|
|
if (callee.object.type !== 'Identifier' || callee.object.name !== 'process') return;
|
|
if (callee.property.type !== 'Identifier' || callee.property.name !== 'exit') return;
|
|
|
|
const filename = context.filename ?? context.getFilename();
|
|
if (path.basename(filename) === 'cli-exit.cts' && isInsideFunctionNamed(node, 'terminateNow')) return;
|
|
|
|
context.report({ node, messageId: 'rawProcessExit' });
|
|
},
|
|
};
|
|
},
|
|
};
|
|
|
|
module.exports = rule;
|