enhance(#3910): the raw terminator is banned by construction (#3980)

* 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:
Tom Boucher
2026-08-28 03:15:39 -04:00
committed by GitHub
parent 9f219d05ba
commit d98b55562c
26 changed files with 1001 additions and 162 deletions

View File

@@ -11,6 +11,9 @@ import fs from 'node:fs';
import path from 'node:path';
import { requireSafePath } from './security.cjs';
import { collectSections } from './markdown-sectionizer.cjs';
// eslint-disable-next-line @typescript-eslint/no-require-imports
import cliExitModule = require('./cli-exit.cjs');
const { ExitError, runMain } = cliExitModule;
const STATUS_REJECT_SET = new Set(['superseded', 'rejected', 'deprecated']);
@@ -462,12 +465,15 @@ function main(argv: string[]): void {
}
if (require.main === module) {
try {
main(process.argv.slice(2));
} catch (error) {
process.stderr.write(`Error: ${(error as Error).message}\n`);
process.exit(1);
}
runMain(() => {
try {
main(process.argv.slice(2));
} catch (err) {
// ExitError with a message so runMain's catch writes it verbatim
// (byte-identical to the prior `Error: ${message}\n` process.exit(1)).
throw new ExitError(1, `Error: ${(err as Error).message}`);
}
});
}
export = {

View File

@@ -20,8 +20,16 @@
* Invariants:
* - Hub always routes through CJS handlers. There is no SDK path (#175).
* - Hub never prints to stdout/stderr, never calls process.exit.
* - Hub never throws — all internal throws are caught and converted to
* { ok: false, kind: 'HandlerFailure', message, cause }.
* - Hub never throws for an ordinary handler exception — those are caught
* and converted to { ok: false, kind: 'HandlerFailure', message, cause }.
* - EXCEPTION (ADR-3889): a thrown ExitError (the process-exit seam in
* src/cli-exit.cts, e.g. from io.cts's error()) is deliberately
* RE-THROWN, never converted — the throwing handler has already written
* its own stderr and is terminating with a specific exit code; wrapping
* it as a HandlerFailure would re-derive a generic message from
* ExitError's constructor default and print a second, wrong stderr line.
* It propagates through every caller up to the runMain() at the CLI
* entrypoint, the only place ExitError is meant to be caught.
* - The kind taxonomy is closed. Callers switch on ERROR_KINDS values.
* - Each error variant carries ONLY its own typed payload (#176).
* No cross-variant `message`/`details` escape hatches.
@@ -35,6 +43,9 @@ import { makeDispatchEvent } from './observability/event.cjs';
// eslint-disable-next-line @typescript-eslint/no-require-imports
import observabilityLogger = require('./observability/logger.cjs');
const { createNoOpLogger } = observabilityLogger;
// eslint-disable-next-line @typescript-eslint/no-require-imports
import cliExitModule = require('./cli-exit.cjs');
const { ExitError } = cliExitModule;
// ─── Error kind constants ─────────────────────────────────────────────────────
@@ -325,6 +336,24 @@ function createHub({ cjsRegistry, manifest, logger }: HubOptions = {}): { dispat
try {
result = _dispatch(req);
} catch (err) {
// ADR-3889: a handler that calls io.cts's error() (or otherwise throws
// ExitError directly) is deliberately terminating the CLI with a
// specific exit code and a stderr write it has ALREADY performed
// itself. Swallowing that into a HandlerFailure and re-deriving a
// message from err.message (ExitError's generic "process exit N"
// constructor default, since error() passes no message) would both
// duplicate the stderr output and discard the real exit code — this
// was invisible before ADR-3889 because io.cts's error() called
// process.exit() directly, which this try/catch could never observe
// (a process.exit() call terminates synchronously; it does not throw
// and unwind through here). Re-throwing preserves that same
// non-observability now that the termination mechanism is a throw:
// it propagates past this hub, past every non-family-router caller,
// up to the runMain() at the CLI entrypoint, which is the ONLY place
// ExitError is meant to be caught.
if (err instanceof ExitError) {
throw err;
}
if (err instanceof Error) {
result = makeHandlerFailure(err.message, err);
} else {

View File

@@ -13,6 +13,9 @@ import os from 'node:os';
import io = require('./io.cjs');
const { output, error, ERROR_REASON } = io;
// eslint-disable-next-line @typescript-eslint/no-require-imports
import cliExitMod = require('./cli-exit.cjs');
const { ExitError } = cliExitMod;
// eslint-disable-next-line @typescript-eslint/no-require-imports
import configLoader = require('./config-loader.cjs');
const { CONFIG_DEFAULTS } = configLoader;
import { platformWriteSync, platformEnsureDir } from './shell-command-projection.cjs';
@@ -1012,6 +1015,15 @@ function cmdConfigGet(cwd: string, keyPath: string | undefined, raw: boolean, de
error('No config.json found at ' + configPath, ERROR_REASON.CONFIG_NO_FILE);
}
} catch (err) {
// ADR-3889: error() now throws ExitError (carries no message) instead of
// calling process.exit() directly. The message-sniffing check below
// (`.startsWith('No config.json')`) can never match an ExitError raised
// by the "no config.json" error() call above it — ExitError.message
// defaults to `process exit ${code}` when no message is passed — so
// without this unconditional guard that ExitError falls through and gets
// re-wrapped as a WRONG reason (CONFIG_PARSE_FAILED instead of
// CONFIG_NO_FILE) with a nonsense message, plus a duplicate stderr write.
if (err instanceof ExitError) throw err;
if ((err as Error).message.startsWith('No config.json')) throw err;
error('Failed to read config.json: ' + (err as Error).message, ERROR_REASON.CONFIG_PARSE_FAILED);
}

View File

@@ -28,6 +28,9 @@ import {
analyzeCoverage as coreAnalyzeCoverage,
runProbeCli,
} from './probe-core.cjs';
// eslint-disable-next-line @typescript-eslint/no-require-imports
import cliExitModule = require('./cli-exit.cjs');
const { runMain } = cliExitModule;
/** The five data/behavior shapes a requirement can exhibit. */
export type Shape = 'numeric-range' | 'collection' | 'text' | 'stateful' | 'io';
@@ -233,9 +236,14 @@ export function analyzeCoverage(
* `require.main === module` so it runs only when the compiled `.cjs` is executed directly.
*/
if (require.main === module) {
runProbeCli(
(requirements, resolutions) =>
analyzeCoverage(requirements as Requirement[], resolutions as Resolution<EdgeVerification>[]),
{ usage: 'edge-probe.cjs <requirements.json> [resolutions.json]' },
);
// runProbeCli's default `exit` now throws ExitError (src/probe-core.cts) rather
// than calling process.exit directly, so this entry point must run under
// runMain to translate that throw into process.exitCode.
runMain(() => {
runProbeCli(
(requirements, resolutions) =>
analyzeCoverage(requirements as Requirement[], resolutions as Resolution<EdgeVerification>[]),
{ usage: 'edge-probe.cjs <requirements.json> [resolutions.json]' },
);
});
}

View File

@@ -14,7 +14,7 @@ import path from 'node:path';
import { platformWriteSync, platformEnsureDir } from './shell-command-projection.cjs';
// eslint-disable-next-line @typescript-eslint/no-require-imports
import cliExitModule = require('./cli-exit.cjs');
const { setJsonErrorMode, getJsonErrorMode, EXIT_ENVELOPE_REASON } = cliExitModule;
const { setJsonErrorMode, getJsonErrorMode, EXIT_ENVELOPE_REASON, ExitError } = cliExitModule;
// ─── Temp-file helpers (needed by output()) ──────────────────────────────────
@@ -281,7 +281,10 @@ function error(message: string, reason: ErrorReasonValue = ERROR_REASON.UNKNOWN,
} else {
writeAllSync(2, 'Error: ' + message + '\n');
}
process.exit(1);
// No message passed to ExitError: the stderr write above is already done,
// byte-identical to the prior process.exit(1) behavior, and ExitError with
// no message means runMain's catch adds nothing further to stderr.
throw new ExitError(1);
}
export = {

View File

@@ -29,6 +29,9 @@ const { resolveQuickTaskSummaryFile } = auditMod;
import ioMod = require('./io.cjs');
const { output, error } = ioMod;
// eslint-disable-next-line @typescript-eslint/no-require-imports
import cliExitMod = require('./cli-exit.cjs');
const { ExitError } = cliExitMod;
// eslint-disable-next-line @typescript-eslint/no-require-imports
import stateContract = require('./state-contract.cjs');
const { publishStateContract } = stateContract;
// eslint-disable-next-line @typescript-eslint/no-require-imports
@@ -739,6 +742,12 @@ function cmdMilestoneComplete(cwd: string, version: string, options: MilestoneCo
);
}
} catch (e) {
// ADR-3889: error() now throws ExitError (carries no message) instead
// of calling process.exit() directly, so it can no longer be detected
// by sniffing e.message — an ExitError from our own guard above must be
// re-thrown UNCONDITIONALLY, before any message inspection, or the
// guard silently stops blocking milestone completion.
if (e instanceof ExitError) throw e;
// If the error came from our guard, re-throw it; otherwise skip silently.
const message = e instanceof Error ? e.message : String(e);
if (message && message.startsWith('Cannot mark milestone complete:')) throw e;

View File

@@ -27,6 +27,9 @@
*/
import fs from 'node:fs';
// eslint-disable-next-line @typescript-eslint/no-require-imports
import cliExitModule = require('./cli-exit.cjs');
const { ExitError } = cliExitModule;
/** Resolution lifecycle — shared across every probe adapter. */
export type Status = 'resolved' | 'dismissed' | 'unresolved';
@@ -692,7 +695,7 @@ export function runProbeCli(
const readFile = options.readFile ?? ((p: string) => fs.readFileSync(p, 'utf8'));
const write = options.write ?? ((s: string) => { process.stdout.write(s); });
const writeErr = options.writeErr ?? ((s: string) => { process.stderr.write(s); });
const exit = options.exit ?? ((code: number) => { process.exit(code); });
const exit = options.exit ?? ((code: number) => { throw new ExitError(code); });
const reqPath: string | undefined = argv[2];
const resPath: string | undefined = argv[3];

View File

@@ -19,6 +19,9 @@ import readline from 'node:readline';
// eslint-disable-next-line @typescript-eslint/no-require-imports
import ioModule = require('./io.cjs');
const { output, error, reapStaleTempFiles, ensureGsdTempDir, GSD_TEMP_DIR } = ioModule;
// eslint-disable-next-line @typescript-eslint/no-require-imports
import cliExitModule = require('./cli-exit.cjs');
const { ExitError } = cliExitModule;
// ─── Types ────────────────────────────────────────────────────────────────────
@@ -321,7 +324,7 @@ function cmdScanSessions(overridePath: string | null | undefined, options: { jso
}
}
process.stdout.write(`\nTotal: ${projects.length} projects\n`);
process.exit(0);
throw new ExitError(0);
}
}
@@ -460,10 +463,10 @@ async function cmdExtractMessages(projectArg: string, options: { sessionId?: str
if (sessionsSkipped > 0 && sessionsProcessed > 0) {
process.stdout.write(JSON.stringify(result, null, 2));
process.exit(2);
throw new ExitError(2);
} else if (sessionsProcessed === 0 && sessionsSkipped > 0) {
process.stdout.write(JSON.stringify(result, null, 2));
process.exit(1);
throw new ExitError(1);
} else {
output(result, raw, undefined);
}

View File

@@ -19,6 +19,9 @@
*/
import fs from 'node:fs';
// eslint-disable-next-line @typescript-eslint/no-require-imports
import cliExitModule = require('./cli-exit.cjs');
const { ExitError, runMain } = cliExitModule;
/** The logical SPEC sections the spec-less probe fallback cares about. */
export type SpecSectionKey = 'edges' | 'prohibitions';
@@ -114,11 +117,13 @@ const VALID_KEYS: readonly SpecSectionKey[] = ['edges', 'prohibitions'];
// 2 only on a usage error (missing args / bad key). `require.main === module` so it runs only when
// the compiled `.cjs` is executed directly, never when imported by tests.
if (require.main === module) {
const specFile = process.argv[2];
const key = process.argv[3] as SpecSectionKey | undefined;
if (!specFile || !key || !VALID_KEYS.includes(key)) {
process.stderr.write('usage: spec-section.cjs <specFile> <edges|prohibitions>\n');
process.exit(2);
}
process.stdout.write(JSON.stringify(specSectionStatus(specFile, key)) + '\n');
runMain(() => {
const specFile = process.argv[2];
const key = process.argv[3] as SpecSectionKey | undefined;
if (!specFile || !key || !VALID_KEYS.includes(key)) {
process.stderr.write('usage: spec-section.cjs <specFile> <edges|prohibitions>\n');
throw new ExitError(2);
}
process.stdout.write(JSON.stringify(specSectionStatus(specFile, key)) + '\n');
});
}

View File

@@ -13,6 +13,9 @@ import { escapeRegex } from './pattern.cjs';
import ioMod = require('./io.cjs');
const { output, error } = ioMod;
// eslint-disable-next-line @typescript-eslint/no-require-imports
import cliExitModule = require('./cli-exit.cjs');
const { ExitError } = cliExitModule;
// eslint-disable-next-line @typescript-eslint/no-require-imports
import stateContract = require('./state-contract.cjs');
const { publishStateContract } = stateContract;
// eslint-disable-next-line @typescript-eslint/no-require-imports
@@ -541,7 +544,7 @@ function cmdStateLoad(cwd: string, raw: boolean): void {
`state_exists=${stateExists}`,
];
process.stdout.write(lines.join('\n'));
process.exit(0);
throw new ExitError(0);
}
output(result, false, undefined);

View File

@@ -28,6 +28,9 @@
// eslint-disable-next-line @typescript-eslint/no-require-imports
import ioMod = require('./io.cjs');
const { output: coreOutput } = ioMod;
// eslint-disable-next-line @typescript-eslint/no-require-imports
import cliExitModule = require('./cli-exit.cjs');
const { ExitError } = cliExitModule;
// ─── Types ────────────────────────────────────────────────────────────────────
@@ -85,7 +88,7 @@ export function cmdTeamsStatus(cwd: string, opts: { active?: boolean }): void {
if (opts.active) {
// --active mode: no output, exit code encodes the boolean
process.exit(status.active ? 0 : 1);
throw new ExitError(status.active ? 0 : 1);
}
// Default: emit JSON to stdout via io.output, exit 0

View File

@@ -31,6 +31,9 @@ import {
analyzeCoverage as coreAnalyzeCoverage,
runProbeCli,
} from './probe-core.cjs';
// eslint-disable-next-line @typescript-eslint/no-require-imports
import cliExitModule = require('./cli-exit.cjs');
const { runMain } = cliExitModule;
/** The six UI element kinds a described component can be (the closed relevance axis, D-03). */
export type UIElementKind =
@@ -307,9 +310,14 @@ export function autoResolve(items: UIConsideration[]): Resolution<UIVerification
* so it runs only when the compiled `.cjs` is executed directly.
*/
if (require.main === module) {
runProbeCli(
(elements, resolutions) =>
analyzeCoverage(elements as Element[], resolutions as Resolution<UIVerification>[]),
{ usage: 'ui-consideration-probe.cjs <elements.json> [resolutions.json]' },
);
// runProbeCli's default `exit` now throws ExitError (src/probe-core.cts) rather
// than calling process.exit directly, so this entry point must run under
// runMain to translate that throw into process.exitCode.
runMain(() => {
runProbeCli(
(elements, resolutions) =>
analyzeCoverage(elements as Element[], resolutions as Resolution<UIVerification>[]),
{ usage: 'ui-consideration-probe.cjs <elements.json> [resolutions.json]' },
);
});
}