* 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:
5
.changeset/graceful-moles-travel.md
Normal file
5
.changeset/graceful-moles-travel.md
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
---
|
||||||
|
type: Changed
|
||||||
|
pr: 3980
|
||||||
|
---
|
||||||
|
**`milestone complete` blocks again when the roadmap still lists unstarted phases** — that guard had been silently swallowed, so milestones could be archived with work outstanding and nothing said so. Two more guards that inspected an error's message before deciding whether to re-raise were failing the same way and are fixed with it, and `extract-messages`/`profile-sample` no longer dump a raw Node stack trace on top of their error line. A new lint rule now rejects a raw `process.exit()` outside the sanctioned terminator, so a guard cannot quietly stop guarding this way again. (#3910)
|
||||||
@@ -200,6 +200,7 @@
|
|||||||
- ["Failure Is a Value" — Strict Argv Rejection and the `--pick` Absence Contract](#3884-failure-is-a-value--strict-argv-rejection-and-the---pick-absence-contract)
|
- ["Failure Is a Value" — Strict Argv Rejection and the `--pick` Absence Contract](#3884-failure-is-a-value--strict-argv-rejection-and-the---pick-absence-contract)
|
||||||
- [No Silent Swallow, No Verdict From Dropped Data](#3885-no-silent-swallow-no-verdict-from-dropped-data)
|
- [No Silent Swallow, No Verdict From Dropped Data](#3885-no-silent-swallow-no-verdict-from-dropped-data)
|
||||||
- [Runtime Marker Resolution, Derived Codex Sandbox, and In-Phase Short-Form Dependencies](#3897-runtime-marker-resolution-derived-codex-sandbox-and-in-phase-short-form-dependencies)
|
- [Runtime Marker Resolution, Derived Codex Sandbox, and In-Phase Short-Form Dependencies](#3897-runtime-marker-resolution-derived-codex-sandbox-and-in-phase-short-form-dependencies)
|
||||||
|
- [The Raw Terminator Is Banned by Construction](#3910-the-raw-terminator-is-banned-by-construction)
|
||||||
- [Hooks Declare Their Crash Policy](#3911-hooks-declare-their-crash-policy)
|
- [Hooks Declare Their Crash Policy](#3911-hooks-declare-their-crash-policy)
|
||||||
- [Reachable Lint Rules and a Non-Destructive Quick-Task Append](#3951-reachable-lint-rules-and-a-non-destructive-quick-task-append)
|
- [Reachable Lint Rules and a Non-Destructive Quick-Task Append](#3951-reachable-lint-rules-and-a-non-destructive-quick-task-append)
|
||||||
|
|
||||||
@@ -3921,6 +3922,56 @@ happens, matching the retired behavior exactly.
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
### 3910. The Raw Terminator Is Banned by Construction
|
||||||
|
|
||||||
|
**Purpose:** Make a bare `process.exit(...)` a lint error everywhere it matters, so the
|
||||||
|
"nothing fails with success" defect class ADR-3889 exists to close cannot silently reopen
|
||||||
|
through a new call site.
|
||||||
|
|
||||||
|
**What changed (ADR-3889 Phase 6, #3910):**
|
||||||
|
|
||||||
|
- New rule `local/require-registered-exit` (`eslint-rules/require-registered-exit.cjs`) flags
|
||||||
|
any `CallExpression` shaped exactly like `process.exit(...)`. It does **not** flag
|
||||||
|
`process.exitCode = N` — that assignment is the correct drain-then-exit pattern `runMain`
|
||||||
|
itself uses, and the two are structurally distinct (an assignment target is never a
|
||||||
|
`CallExpression`).
|
||||||
|
- Registered on four globs: `src/**/*.cts`, `scripts/**/*.cjs`, `hooks/**/*.js`,
|
||||||
|
`gsd-core/bin/**/*.cjs` (`eslint.config.mjs:420-426,545-547,574-576,601`). Registering on
|
||||||
|
`src/**/*.cts` — not only the emitted `gsd-core/bin/lib/*.cjs` mirrors, which are globally
|
||||||
|
eslint-ignored (ADR-457) — is load-bearing: a rule registered only on the emitted surface is
|
||||||
|
blind to the real sources, the same way `n/no-process-exit` went invisible (#3496).
|
||||||
|
- The dead `n/no-process-exit: 'off'` carve-out for `hooks/**` is deleted: Phase 7 (#3911)
|
||||||
|
migrated every enforcement hook onto `terminateNow`, so it protected nothing.
|
||||||
|
- Exactly two allowlist entries, repo-wide:
|
||||||
|
1. The body of `terminateNow` in `src/cli-exit.cts` — detected **structurally** (any
|
||||||
|
`process.exit()` lexically nested inside a function named `terminateNow`, *and* the file's
|
||||||
|
basename is `cli-exit.cts`), not by path+line, so it does not rot when the function moves.
|
||||||
|
2. `gsd-core/bin/gsd-tools.cjs`'s `ensureRuntimeBuild` bootstrap-failure path, via an inline
|
||||||
|
`// eslint-disable-next-line local/require-registered-exit` with a stated reason — it runs
|
||||||
|
*before* `./lib/cli-exit.cjs` is even required, so the registered-exit seam does not exist
|
||||||
|
yet at that point in the process's lifetime.
|
||||||
|
- The last raw terminators in `src/**/*.cts` were migrated onto the seam, most notably
|
||||||
|
`src/io.cts`'s `error()`: it changed from an uncatchable `process.exit(1)` to a catchable
|
||||||
|
`throw new ExitError(1)` (stderr output is byte-identical; `runMain` projects the exit code).
|
||||||
|
`terminateNow` could not serve this site — ADR-3889 §1 makes exit codes 0 and 1
|
||||||
|
unallocatable, so `nameForExitCode(1)` throws. That control-flow change required three
|
||||||
|
interceptor fixes so an `ExitError` reaches `runMain`: `command-routing-hub`'s `dispatch()`
|
||||||
|
now rethrows it, and the profile-pipeline router's detached `.catch()` no longer calls
|
||||||
|
`error()` — it writes stderr and sets `exitCode` in place.
|
||||||
|
- **Known limits (documented and test-pinned, not endorsed):** the rule matches the literal
|
||||||
|
`process.exit(...)` shape only, with no scope/flow analysis. It does not catch
|
||||||
|
`process['exit'](0)` (computed member access), `const e = process.exit; e(1)` (aliasing to a
|
||||||
|
local binding before calling), or `process.exit.call(...)`/`.apply(...)` (indirect invocation).
|
||||||
|
Catching these needs binding/scope-aware analysis, out of scope for this issue; pinning tests
|
||||||
|
in `tests/eslint-rules.test.cjs` assert today's non-detection so a future widening is a visible
|
||||||
|
choice, not a silent one.
|
||||||
|
|
||||||
|
See [Resolve a raw-terminator finding](../how-to/resolve-a-raw-terminator-finding.md) for what to
|
||||||
|
do when this rule fires, and [ADR-3889](../adr/3889-process-exit-contract.md) for the exit-code
|
||||||
|
registry the seam is layered over.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
### 3911. Hooks Declare Their Crash Policy
|
### 3911. Hooks Declare Their Crash Policy
|
||||||
|
|
||||||
**Purpose:** Give every shipped enforcement hook (`hooks/*.js`, `hooks/*.sh`) a
|
**Purpose:** Give every shipped enforcement hook (`hooks/*.js`, `hooks/*.sh`) a
|
||||||
|
|||||||
@@ -35,6 +35,7 @@ Language versions: [English](README.md) · [Português (pt-BR)](pt-BR/README.md)
|
|||||||
- [Resolve a skipped capability probe](how-to/resolve-a-skipped-capability-probe.md) — act on a coverage gate that held your phase for an unestablished scope, or a planning checkpoint that reported `skipped` instead of a verdict
|
- [Resolve a skipped capability probe](how-to/resolve-a-skipped-capability-probe.md) — act on a coverage gate that held your phase for an unestablished scope, or a planning checkpoint that reported `skipped` instead of a verdict
|
||||||
- [Diagnose which gsd-tools is running](how-to/diagnose-a-foreign-gsd-tools.md) — tell this package's tool apart from the predecessor's colliding binary and from a gsd-core too old to identify itself
|
- [Diagnose which gsd-tools is running](how-to/diagnose-a-foreign-gsd-tools.md) — tell this package's tool apart from the predecessor's colliding binary and from a gsd-core too old to identify itself
|
||||||
- [Resolve an ESLint glob-coverage finding](how-to/resolve-eslint-coverage-findings.md) — bring a source file that matches no lint rule under coverage, or record a reasoned exemption
|
- [Resolve an ESLint glob-coverage finding](how-to/resolve-eslint-coverage-findings.md) — bring a source file that matches no lint rule under coverage, or record a reasoned exemption
|
||||||
|
- [Resolve a raw-terminator finding](how-to/resolve-a-raw-terminator-finding.md) — pick `runMain`/`ExitError`, `terminateNow`, or `process.exitCode` for a `local/require-registered-exit` finding, and know the two allowlist entries and the rule's documented evasions
|
||||||
- [Read the statusline freshness marker](how-to/read-the-statusline-freshness-marker.md) — turn on `state ~N commits back`, and tell "STATE.md is fresh" apart from "freshness could not be established"
|
- [Read the statusline freshness marker](how-to/read-the-statusline-freshness-marker.md) — turn on `state ~N commits back`, and tell "STATE.md is fresh" apart from "freshness could not be established"
|
||||||
- [Consume the planning snapshot](how-to/consume-the-planning-snapshot.md) — read `planning inspect` from a dashboard or harness, and tell "nothing to report" apart from "could not look"
|
- [Consume the planning snapshot](how-to/consume-the-planning-snapshot.md) — read `planning inspect` from a dashboard or harness, and tell "nothing to report" apart from "could not look"
|
||||||
- [Consume the state contract](how-to/consume-the-state-contract.md) — read `.planning/state.json` from a workbench or editor extension, gate on the contract version, and tell "nothing to show" apart from "could not look"
|
- [Consume the state contract](how-to/consume-the-state-contract.md) — read `.planning/state.json` from a workbench or editor extension, gate on the contract version, and tell "nothing to show" apart from "could not look"
|
||||||
|
|||||||
51
docs/features/raw-terminator-banned-by-construction.md
Normal file
51
docs/features/raw-terminator-banned-by-construction.md
Normal file
@@ -0,0 +1,51 @@
|
|||||||
|
---
|
||||||
|
id: 3910
|
||||||
|
title: The Raw Terminator Is Banned by Construction
|
||||||
|
group: v1.7.0 Features
|
||||||
|
---
|
||||||
|
|
||||||
|
**Purpose:** Make a bare `process.exit(...)` a lint error everywhere it matters, so the
|
||||||
|
"nothing fails with success" defect class ADR-3889 exists to close cannot silently reopen
|
||||||
|
through a new call site.
|
||||||
|
|
||||||
|
**What changed (ADR-3889 Phase 6, #3910):**
|
||||||
|
|
||||||
|
- New rule `local/require-registered-exit` (`eslint-rules/require-registered-exit.cjs`) flags
|
||||||
|
any `CallExpression` shaped exactly like `process.exit(...)`. It does **not** flag
|
||||||
|
`process.exitCode = N` — that assignment is the correct drain-then-exit pattern `runMain`
|
||||||
|
itself uses, and the two are structurally distinct (an assignment target is never a
|
||||||
|
`CallExpression`).
|
||||||
|
- Registered on four globs: `src/**/*.cts`, `scripts/**/*.cjs`, `hooks/**/*.js`,
|
||||||
|
`gsd-core/bin/**/*.cjs` (`eslint.config.mjs:420-426,545-547,574-576,601`). Registering on
|
||||||
|
`src/**/*.cts` — not only the emitted `gsd-core/bin/lib/*.cjs` mirrors, which are globally
|
||||||
|
eslint-ignored (ADR-457) — is load-bearing: a rule registered only on the emitted surface is
|
||||||
|
blind to the real sources, the same way `n/no-process-exit` went invisible (#3496).
|
||||||
|
- The dead `n/no-process-exit: 'off'` carve-out for `hooks/**` is deleted: Phase 7 (#3911)
|
||||||
|
migrated every enforcement hook onto `terminateNow`, so it protected nothing.
|
||||||
|
- Exactly two allowlist entries, repo-wide:
|
||||||
|
1. The body of `terminateNow` in `src/cli-exit.cts` — detected **structurally** (any
|
||||||
|
`process.exit()` lexically nested inside a function named `terminateNow`, *and* the file's
|
||||||
|
basename is `cli-exit.cts`), not by path+line, so it does not rot when the function moves.
|
||||||
|
2. `gsd-core/bin/gsd-tools.cjs`'s `ensureRuntimeBuild` bootstrap-failure path, via an inline
|
||||||
|
`// eslint-disable-next-line local/require-registered-exit` with a stated reason — it runs
|
||||||
|
*before* `./lib/cli-exit.cjs` is even required, so the registered-exit seam does not exist
|
||||||
|
yet at that point in the process's lifetime.
|
||||||
|
- The last raw terminators in `src/**/*.cts` were migrated onto the seam, most notably
|
||||||
|
`src/io.cts`'s `error()`: it changed from an uncatchable `process.exit(1)` to a catchable
|
||||||
|
`throw new ExitError(1)` (stderr output is byte-identical; `runMain` projects the exit code).
|
||||||
|
`terminateNow` could not serve this site — ADR-3889 §1 makes exit codes 0 and 1
|
||||||
|
unallocatable, so `nameForExitCode(1)` throws. That control-flow change required three
|
||||||
|
interceptor fixes so an `ExitError` reaches `runMain`: `command-routing-hub`'s `dispatch()`
|
||||||
|
now rethrows it, and the profile-pipeline router's detached `.catch()` no longer calls
|
||||||
|
`error()` — it writes stderr and sets `exitCode` in place.
|
||||||
|
- **Known limits (documented and test-pinned, not endorsed):** the rule matches the literal
|
||||||
|
`process.exit(...)` shape only, with no scope/flow analysis. It does not catch
|
||||||
|
`process['exit'](0)` (computed member access), `const e = process.exit; e(1)` (aliasing to a
|
||||||
|
local binding before calling), or `process.exit.call(...)`/`.apply(...)` (indirect invocation).
|
||||||
|
Catching these needs binding/scope-aware analysis, out of scope for this issue; pinning tests
|
||||||
|
in `tests/eslint-rules.test.cjs` assert today's non-detection so a future widening is a visible
|
||||||
|
choice, not a silent one.
|
||||||
|
|
||||||
|
See [Resolve a raw-terminator finding](../how-to/resolve-a-raw-terminator-finding.md) for what to
|
||||||
|
do when this rule fires, and [ADR-3889](../adr/3889-process-exit-contract.md) for the exit-code
|
||||||
|
registry the seam is layered over.
|
||||||
127
docs/how-to/resolve-a-raw-terminator-finding.md
Normal file
127
docs/how-to/resolve-a-raw-terminator-finding.md
Normal file
@@ -0,0 +1,127 @@
|
|||||||
|
# How to resolve a raw-terminator finding
|
||||||
|
|
||||||
|
`npm run lint` (or `npx eslint .`) reported `local/require-registered-exit`. That rule bans a
|
||||||
|
bare `process.exit(...)` call everywhere it matters — the seam it protects is the whole point of
|
||||||
|
[ADR-3889](../adr/3889-process-exit-contract.md): every process termination is projected through
|
||||||
|
one of two registered terminators, so "nothing fails with success" cannot reopen through a new
|
||||||
|
call site that bypasses them.
|
||||||
|
|
||||||
|
This page covers what the rule reports, which of the three replacements applies to your surface,
|
||||||
|
the two existing allowlist entries and why a third should not be added casually, and the
|
||||||
|
documented evasions the rule cannot catch today.
|
||||||
|
|
||||||
|
## Read a finding
|
||||||
|
|
||||||
|
```
|
||||||
|
error 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. local/require-registered-exit
|
||||||
|
```
|
||||||
|
|
||||||
|
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 flag `process.exitCode = N`: that is an assignment, never a `CallExpression`, and is
|
||||||
|
the correct pattern (see below).
|
||||||
|
|
||||||
|
## Pick the right replacement
|
||||||
|
|
||||||
|
Three outcomes exist. Pick by asking what the surrounding code actually needs, not by pattern-
|
||||||
|
matching on which file you happen to be in.
|
||||||
|
|
||||||
|
### 1. A CLI entrypoint — throw `ExitError`, let `runMain` project the code
|
||||||
|
|
||||||
|
If the call is deep inside a command's execution path and needs to unwind the stack and stop,
|
||||||
|
throw instead of exiting directly:
|
||||||
|
|
||||||
|
```js
|
||||||
|
throw new ExitError(1, 'a short reason');
|
||||||
|
```
|
||||||
|
|
||||||
|
`runMain` (`src/cli-exit.cts`) is the single place that catches an `ExitError` and turns it into
|
||||||
|
the process's actual exit code — it wraps every CLI entrypoint, so the throw always has somewhere
|
||||||
|
to land. This is exactly the migration `src/io.cts`'s `error()` went through: it used to call
|
||||||
|
`process.exit(1)` directly (uncatchable, stderr output unchanged), and now throws `ExitError(1)`
|
||||||
|
instead — stderr is byte-identical, only the control-flow shape changed.
|
||||||
|
|
||||||
|
**A throw only reaches `runMain` if nothing between the throw site and `runMain` swallows it.**
|
||||||
|
This branch's own migration needed three interceptor fixes for exactly that reason:
|
||||||
|
`command-routing-hub`'s `dispatch()` now rethrows an `ExitError` instead of catching it as a
|
||||||
|
generic failure, and the profile-pipeline router's detached `.catch()` no longer calls `error()`
|
||||||
|
(which would throw again from inside a `.catch()`, going nowhere) — it writes stderr and sets
|
||||||
|
`exitCode` in place instead. If you introduce a new `try`/`catch` or `.catch()` between your throw
|
||||||
|
site and `runMain`, check that it rethrows `ExitError` rather than absorbing it.
|
||||||
|
|
||||||
|
### 2. A hook that must write-then-terminate immediately — `terminateNow`
|
||||||
|
|
||||||
|
Enforcement hooks (`hooks/**/*.js`) run once per invocation and need to write their JSON response
|
||||||
|
and stop in the same breath — there is no `runMain` wrapper to unwind into. Use `terminateNow`
|
||||||
|
from `src/cli-exit.cts` (or its generated hook-side copy, `hooks/lib/cli-exit.js`). It is the
|
||||||
|
**only** sanctioned direct terminator in the codebase, and the only place exit code 2 (the
|
||||||
|
hook-protocol deny) may be produced (ADR-3889 §3).
|
||||||
|
|
||||||
|
If you are declaring a hook's fail-open/fail-closed policy rather than calling `terminateNow`
|
||||||
|
directly, see [Declare a hook's crash policy](declare-a-hook-crash-policy.md) — `allow()`/
|
||||||
|
`deny()`/`crash()` in `hooks/lib/hook-exit.js` are the higher-level vocabulary built on top of
|
||||||
|
this seam.
|
||||||
|
|
||||||
|
### 3. Nothing needs an immediate hard exit — `process.exitCode`
|
||||||
|
|
||||||
|
If the process should simply drain and exit non-zero once its event loop empties — no forced
|
||||||
|
unwind, no immediate write-then-die — set `process.exitCode` and return normally:
|
||||||
|
|
||||||
|
```js
|
||||||
|
process.exitCode = 1;
|
||||||
|
return;
|
||||||
|
```
|
||||||
|
|
||||||
|
This is never flagged: it is an assignment (`MemberExpression` target), never a `CallExpression`,
|
||||||
|
so the rule's `CallExpression`-only selector excludes it structurally. It is also the pattern
|
||||||
|
`runMain` itself uses once an `ExitError` is caught — projecting the code onto `process.exitCode`
|
||||||
|
rather than calling `process.exit()` a second time.
|
||||||
|
|
||||||
|
## The two allowlist entries — and why a third needs a real reason
|
||||||
|
|
||||||
|
Exactly two call sites in the repo are exempt, both for structural reasons, not convenience:
|
||||||
|
|
||||||
|
1. **`terminateNow`'s own body**, in `src/cli-exit.cts` — detected structurally: any
|
||||||
|
`process.exit()` call lexically nested inside a function declaration or expression named
|
||||||
|
`terminateNow`, *and* the file's basename is `cli-exit.cts`. The basename check matters on its
|
||||||
|
own: without it, any function named `terminateNow` anywhere in the repo would silently inherit
|
||||||
|
the allowlist.
|
||||||
|
2. **`gsd-core/bin/gsd-tools.cjs`'s `ensureRuntimeBuild` bootstrap-failure path**, via an inline
|
||||||
|
`// eslint-disable-next-line local/require-registered-exit` carrying a reason. This one call
|
||||||
|
runs *before* `./lib/cli-exit.cjs` is even required — the registered-exit seam has not been
|
||||||
|
loaded yet at that point in the process's lifetime, so there is nothing to route through.
|
||||||
|
|
||||||
|
Do not add a third entry to make an inconvenient finding go away. If you believe you have a
|
||||||
|
genuine third case — code that runs before any exit seam is loadable, the same way
|
||||||
|
`ensureRuntimeBuild` does — that is a structural claim about your file's position in the process
|
||||||
|
lifecycle, not a style preference, and it belongs in chat as a blocking question before you land
|
||||||
|
an `eslint-disable` comment.
|
||||||
|
|
||||||
|
## Known evasions — using one is a review finding, not a fix
|
||||||
|
|
||||||
|
The rule matches the literal `process.exit(...)` shape with no scope or flow analysis, so three
|
||||||
|
shapes are not caught today (and are pinned by tests in `tests/eslint-rules.test.cjs` so a future
|
||||||
|
widening is a visible decision, not a silent one):
|
||||||
|
|
||||||
|
- `process['exit'](0)` — computed member access defeats the property-name check.
|
||||||
|
- `const e = process.exit; e(1);` — aliasing the function to a local binding before calling it;
|
||||||
|
by the call site, the callee is a plain identifier, not a `MemberExpression` on `process`.
|
||||||
|
- `process.exit.call(null, 1)` / `process.exit.apply(null, [1])` — the outer call's callee is
|
||||||
|
`process.exit.call`, not `process.exit` itself.
|
||||||
|
|
||||||
|
These are documented gaps, not sanctioned escape hatches. Writing code in one of these shapes to
|
||||||
|
route around the rule reopens exactly the defect class ADR-3889 exists to close, and is a review
|
||||||
|
finding — fix the underlying call the same way any other raw terminator would be fixed, do not
|
||||||
|
rely on the lint being unable to see it.
|
||||||
|
|
||||||
|
## Related
|
||||||
|
|
||||||
|
- [ADR-3889](../adr/3889-process-exit-contract.md) — the exit-code registry and the terminator
|
||||||
|
contract this rule enforces
|
||||||
|
- [Declare a hook's crash policy](declare-a-hook-crash-policy.md) — the higher-level
|
||||||
|
`allow()`/`deny()`/`crash()` vocabulary hooks use on top of `terminateNow`
|
||||||
|
- [Resolve ESLint coverage findings](resolve-eslint-coverage-findings.md) — sibling "the lint gate
|
||||||
|
surfaced something, here is what to do with it" page
|
||||||
138
eslint-rules/require-registered-exit.cjs
Normal file
138
eslint-rules/require-registered-exit.cjs
Normal file
@@ -0,0 +1,138 @@
|
|||||||
|
'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;
|
||||||
@@ -31,6 +31,7 @@ import noDuplicateFoldMarker from './eslint-rules/no-duplicate-fold-marker.cjs';
|
|||||||
import requireSubprocessTimeout from './eslint-rules/require-subprocess-timeout.cjs';
|
import requireSubprocessTimeout from './eslint-rules/require-subprocess-timeout.cjs';
|
||||||
import noExternalRequireInBin from './eslint-rules/no-external-require-in-bin.cjs';
|
import noExternalRequireInBin from './eslint-rules/no-external-require-in-bin.cjs';
|
||||||
import noPrivateBinaryResolution from './eslint-rules/no-private-binary-resolution.cjs';
|
import noPrivateBinaryResolution from './eslint-rules/no-private-binary-resolution.cjs';
|
||||||
|
import requireRegisteredExit from './eslint-rules/require-registered-exit.cjs';
|
||||||
|
|
||||||
const localPlugin = {
|
const localPlugin = {
|
||||||
rules: {
|
rules: {
|
||||||
@@ -56,6 +57,7 @@ const localPlugin = {
|
|||||||
'require-subprocess-timeout': requireSubprocessTimeout,
|
'require-subprocess-timeout': requireSubprocessTimeout,
|
||||||
'no-external-require-in-bin': noExternalRequireInBin,
|
'no-external-require-in-bin': noExternalRequireInBin,
|
||||||
'no-private-binary-resolution': noPrivateBinaryResolution,
|
'no-private-binary-resolution': noPrivateBinaryResolution,
|
||||||
|
'require-registered-exit': requireRegisteredExit,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -415,6 +417,13 @@ export default tseslint.config(
|
|||||||
// the platform seam (src/shell-command-projection.cts, exempt by path).
|
// the platform seam (src/shell-command-projection.cts, exempt by path).
|
||||||
// See .gsd/phase/chore-3619-no-bare-binary-spawn/40-design.md.
|
// See .gsd/phase/chore-3619-no-bare-binary-spawn/40-design.md.
|
||||||
'local/no-private-binary-resolution': 'error',
|
'local/no-private-binary-resolution': 'error',
|
||||||
|
// #3910 (epic #3889 Phase 6): ban raw process.exit() outside
|
||||||
|
// terminateNow — the only sanctioned terminator (src/cli-exit.cts).
|
||||||
|
// Load-bearing that this is registered HERE, not only on the emitted
|
||||||
|
// .cjs globs: the compiled gsd-core/bin/lib/*.cjs mirrors are globally
|
||||||
|
// eslint-ignored (ADR-457), so a rule registered only on the emitted
|
||||||
|
// surface never sees the real .cts sources (#3496).
|
||||||
|
'local/require-registered-exit': 'error',
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|
||||||
@@ -533,6 +542,8 @@ export default tseslint.config(
|
|||||||
'local/no-external-require-in-bin': 'error',
|
'local/no-external-require-in-bin': 'error',
|
||||||
// #3619 (epic #3411 Phase 3): see the src/**/*.cts block above for detail.
|
// #3619 (epic #3411 Phase 3): see the src/**/*.cts block above for detail.
|
||||||
'local/no-private-binary-resolution': 'error',
|
'local/no-private-binary-resolution': 'error',
|
||||||
|
// #3910 (epic #3889 Phase 6): see the src/**/*.cts block above for detail.
|
||||||
|
'local/require-registered-exit': 'error',
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|
||||||
@@ -560,6 +571,8 @@ export default tseslint.config(
|
|||||||
rules: {
|
rules: {
|
||||||
// #3619 (epic #3411 Phase 3): see the src/**/*.cts block above for detail.
|
// #3619 (epic #3411 Phase 3): see the src/**/*.cts block above for detail.
|
||||||
'local/no-private-binary-resolution': 'error',
|
'local/no-private-binary-resolution': 'error',
|
||||||
|
// #3910 (epic #3889 Phase 6): see the src/**/*.cts block above for detail.
|
||||||
|
'local/require-registered-exit': 'error',
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|
||||||
@@ -580,26 +593,12 @@ export default tseslint.config(
|
|||||||
'local/no-adhoc-regex-escape': 'error',
|
'local/no-adhoc-regex-escape': 'error',
|
||||||
// #3619 (epic #3411 Phase 3): see the src/**/*.cts block above for detail.
|
// #3619 (epic #3411 Phase 3): see the src/**/*.cts block above for detail.
|
||||||
'local/no-private-binary-resolution': 'error',
|
'local/no-private-binary-resolution': 'error',
|
||||||
// n/no-process-exit is deliberately OFF for hooks ONLY.
|
// #3910 (epic #3889 Phase 6): Phase 7 (#3911) migrated every enforcement
|
||||||
//
|
// hook onto terminateNow's write-then-terminate seam (hooks/lib/cli-exit.js),
|
||||||
// A hook is a standalone process whose ENTIRE contract is its exit code: the
|
// so the raw-process.exit escape hatch this block used to grant hooks
|
||||||
// harness reads exit 2 as "deny". `process.exitCode = N; return;` is not
|
// (n/no-process-exit: 'off') is now dead — see the src/**/*.cts block
|
||||||
// equivalent — it lets execution continue past the denial, and several exits
|
// above for detail on the rule itself.
|
||||||
// here are load-bearing in a way that makes that a behavior change, not a
|
'local/require-registered-exit': 'error',
|
||||||
// refactor:
|
|
||||||
// - stdin-timeout guards (e.g. hooks/gsd-read-guard.js, gsd-cursor-subagent-stop.js)
|
|
||||||
// fire from a setTimeout where NOTHING else terminates the process if stdin
|
|
||||||
// never closes;
|
|
||||||
// - hooks/gsd-worktree-path-guard.js exits from a nested `if` whose fallthrough
|
|
||||||
// would otherwise reach a different unconditional exit;
|
|
||||||
// - hooks/gsd-write-guard.js:159-175 documents that pipe writes are async on
|
|
||||||
// Windows, so it deliberately does fs.writeSync(1/2, ...) BEFORE process.exit(2)
|
|
||||||
// to avoid truncation.
|
|
||||||
// ADR-0012 and ADR-0174 scope the "never calls process.exit" convention to the
|
|
||||||
// Command Routing Hub (src/command-routing-hub.cts), not to hooks. Rewriting 89
|
|
||||||
// call sites in enforcement hooks to satisfy a rule aimed at libraries would trade
|
|
||||||
// a real behavior risk for a cosmetic win. See .gsd/phase/chore-3059-eslint-glob-coverage-guard/40-design.md.
|
|
||||||
'n/no-process-exit': 'off',
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|
||||||
|
|||||||
@@ -249,7 +249,12 @@ try {
|
|||||||
process.stderr.write((bootErr && bootErr.message ? bootErr.message : String(bootErr)) + '\n');
|
process.stderr.write((bootErr && bootErr.message ? bootErr.message : String(bootErr)) + '\n');
|
||||||
// Fatal bootstrap failure before the CLI's ExitError/runMain machinery (which
|
// Fatal bootstrap failure before the CLI's ExitError/runMain machinery (which
|
||||||
// lives in ./lib) is available to load, so a direct exit is the only option.
|
// lives in ./lib) is available to load, so a direct exit is the only option.
|
||||||
// eslint-disable-next-line n/no-process-exit
|
// #3910: this call runs BEFORE ./lib/cli-exit.cjs is even required, so the
|
||||||
|
// registered-exit seam (runMain/ExitError/terminateNow) does not exist yet
|
||||||
|
// at this point in the process's lifetime — there is nothing to route
|
||||||
|
// through. This is the second (and only other) sanctioned allowlist entry
|
||||||
|
// for local/require-registered-exit, alongside terminateNow's own body.
|
||||||
|
// eslint-disable-next-line n/no-process-exit, local/require-registered-exit
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2773,9 +2778,17 @@ function dispatchOverlayCapabilityCommand({ command, args, cwd, raw, error, load
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
// ADR-3889: error() now throws ExitError instead of calling
|
||||||
|
// process.exit(1) directly, so an ExitError raised by error() INSIDE
|
||||||
|
// this try (e.g. the "Unknown windows subcommand" call above, or one
|
||||||
|
// inside cmdWindowsStatus/Append/Waive/MarkFixed) lands HERE instead of
|
||||||
|
// terminating uncatchably. It must be re-thrown unconditionally, before
|
||||||
|
// the WindowsError name check below, or it falls through to the
|
||||||
|
// generic branch and gets re-wrapped with a wrong message/reason,
|
||||||
|
// discarding the original exit code.
|
||||||
|
if (e instanceof ExitError) throw e;
|
||||||
// WindowsError carries a REASON code; surface it through the structured
|
// WindowsError carries a REASON code; surface it through the structured
|
||||||
// error path so tests can assert on the typed reason. `error()` calls
|
// error path so tests can assert on the typed reason.
|
||||||
// process.exit(1) internally so we never reach the fall-through.
|
|
||||||
if (e && e.name === 'WindowsError' && typeof e.reason === 'string') {
|
if (e && e.name === 'WindowsError' && typeof e.reason === 'string') {
|
||||||
error(e.message || 'broken-windows error', e.reason);
|
error(e.message || 'broken-windows error', e.reason);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,12 +13,55 @@
|
|||||||
* Async note: cmdExtractMessages and cmdProfileSample are async functions.
|
* Async note: cmdExtractMessages and cmdProfileSample are async functions.
|
||||||
* dispatchCapabilityCommand (gsd-tools.cjs:366-371) explicitly errors if a
|
* dispatchCapabilityCommand (gsd-tools.cjs:366-371) explicitly errors if a
|
||||||
* router returns a Promise. Therefore these router functions call the async
|
* router returns a Promise. Therefore these router functions call the async
|
||||||
* function WITHOUT await and WITHOUT returning the Promise. The async functions
|
* function WITHOUT await and WITHOUT returning the Promise; the event loop
|
||||||
* end with output() or process.exit() so the process terminates correctly once
|
* drains once the returned promise settles. Since ADR-3889 (#3910), the
|
||||||
* the event loop drains. Unhandled rejections are caught by the .catch() wrapper
|
* pipeline functions terminate by THROWING ExitError (never process.exit()
|
||||||
* to surface errors via the error() callback.
|
* directly), so a rejection surfacing here can carry either a genuine error
|
||||||
|
* OR a declared ExitError termination — the `.catch()` below must
|
||||||
|
* distinguish them: an ExitError sets process.exitCode directly (mirroring
|
||||||
|
* cli-exit.cjs's own runMain, the only other place ExitError is caught),
|
||||||
|
* while any other rejection is surfaced via the `error()` callback exactly
|
||||||
|
* as before. Calling `error(exitErr.message)` for an ExitError would be
|
||||||
|
* wrong on two counts: it discards the real exit code (error() always
|
||||||
|
* terminates at 1) and it re-derives a message from ExitError's generic
|
||||||
|
* "process exit N" constructor default rather than the (already emitted, or
|
||||||
|
* intentionally absent) stderr output the throwing call site controls.
|
||||||
*/
|
*/
|
||||||
const { ERROR_REASON } = require('./io.cjs');
|
const { ERROR_REASON, getJsonErrorMode } = require('./io.cjs');
|
||||||
|
const { ExitError } = require('./cli-exit.cjs');
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Interpret a rejection from a fire-and-forget async pipeline call: an
|
||||||
|
* ExitError sets process.exitCode (and, for a non-zero code carrying a user
|
||||||
|
* message, writes it to stderr) exactly like runMain does; anything else
|
||||||
|
* reproduces io.cjs's error() stderr output byte-for-byte and sets
|
||||||
|
* process.exitCode directly instead of calling error() itself.
|
||||||
|
*
|
||||||
|
* error() (src/io.cts) is `never`-typed: it always throws ExitError(1) after
|
||||||
|
* writing to stderr. Calling it from inside this `.catch()` callback would
|
||||||
|
* throw from a detached promise chain that nothing awaits or re-catches —
|
||||||
|
* an unhandled promise rejection that Node (>=15, this repo's
|
||||||
|
* engines.node >= 24 default is --unhandled-rejections=throw) dumps as a
|
||||||
|
* raw stack trace on top of the clean line error() already wrote. Writing
|
||||||
|
* the same bytes directly and setting process.exitCode = 1 in place gets
|
||||||
|
* the identical observable stderr + exit code without ever throwing here.
|
||||||
|
*/
|
||||||
|
function _handlePipelineRejection(e, error) {
|
||||||
|
void error;
|
||||||
|
if (e instanceof ExitError) {
|
||||||
|
if (e.hasUserMessage && e.code !== 0) process.stderr.write(`${e.message}\n`);
|
||||||
|
process.exitCode = e.code;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const message = e && e.message ? e.message : String(e);
|
||||||
|
if (getJsonErrorMode()) {
|
||||||
|
const payload = JSON.stringify({ ok: false, reason: ERROR_REASON.UNKNOWN, message }) + '\n';
|
||||||
|
process.stderr.write(payload);
|
||||||
|
} else {
|
||||||
|
process.stderr.write('Error: ' + message + '\n');
|
||||||
|
}
|
||||||
|
process.exitCode = 1;
|
||||||
|
}
|
||||||
|
|
||||||
// ─── Pipeline phase commands ───────────────────────────────────────────────────
|
// ─── Pipeline phase commands ───────────────────────────────────────────────────
|
||||||
|
|
||||||
@@ -51,7 +94,7 @@ function routeExtractMessages({ args, cwd, raw, error, _pipeline }) {
|
|||||||
// The function ends with output() or process.exit(); the event loop will drain.
|
// The function ends with output() or process.exit(); the event loop will drain.
|
||||||
void cwd;
|
void cwd;
|
||||||
p.cmdExtractMessages(projectArg, { sessionId, limit }, raw, sessionsPath)
|
p.cmdExtractMessages(projectArg, { sessionId, limit }, raw, sessionsPath)
|
||||||
.catch(e => { error(e && e.message ? e.message : String(e)); });
|
.catch(e => { _handlePipelineRejection(e, error); });
|
||||||
}
|
}
|
||||||
|
|
||||||
function routeProfileSample({ args, cwd, raw, error, _pipeline }) {
|
function routeProfileSample({ args, cwd, raw, error, _pipeline }) {
|
||||||
@@ -67,7 +110,7 @@ function routeProfileSample({ args, cwd, raw, error, _pipeline }) {
|
|||||||
const maxChars = maxCharsIdx !== -1 ? parseInt(args[maxCharsIdx + 1], 10) : 500;
|
const maxChars = maxCharsIdx !== -1 ? parseInt(args[maxCharsIdx + 1], 10) : 500;
|
||||||
// cmdProfileSample is async — do NOT return the Promise.
|
// cmdProfileSample is async — do NOT return the Promise.
|
||||||
p.cmdProfileSample(sessionsPath, { limit, maxPerProject, maxChars }, raw)
|
p.cmdProfileSample(sessionsPath, { limit, maxPerProject, maxChars }, raw)
|
||||||
.catch(e => { error(e && e.message ? e.message : String(e)); });
|
.catch(e => { _handlePipelineRejection(e, error); });
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── Output phase commands ─────────────────────────────────────────────────────
|
// ─── Output phase commands ─────────────────────────────────────────────────────
|
||||||
|
|||||||
@@ -11,6 +11,9 @@ import fs from 'node:fs';
|
|||||||
import path from 'node:path';
|
import path from 'node:path';
|
||||||
import { requireSafePath } from './security.cjs';
|
import { requireSafePath } from './security.cjs';
|
||||||
import { collectSections } from './markdown-sectionizer.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']);
|
const STATUS_REJECT_SET = new Set(['superseded', 'rejected', 'deprecated']);
|
||||||
|
|
||||||
@@ -462,12 +465,15 @@ function main(argv: string[]): void {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (require.main === module) {
|
if (require.main === module) {
|
||||||
|
runMain(() => {
|
||||||
try {
|
try {
|
||||||
main(process.argv.slice(2));
|
main(process.argv.slice(2));
|
||||||
} catch (error) {
|
} catch (err) {
|
||||||
process.stderr.write(`Error: ${(error as Error).message}\n`);
|
// ExitError with a message so runMain's catch writes it verbatim
|
||||||
process.exit(1);
|
// (byte-identical to the prior `Error: ${message}\n` process.exit(1)).
|
||||||
|
throw new ExitError(1, `Error: ${(err as Error).message}`);
|
||||||
}
|
}
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export = {
|
export = {
|
||||||
|
|||||||
@@ -20,8 +20,16 @@
|
|||||||
* Invariants:
|
* Invariants:
|
||||||
* - Hub always routes through CJS handlers. There is no SDK path (#175).
|
* - Hub always routes through CJS handlers. There is no SDK path (#175).
|
||||||
* - Hub never prints to stdout/stderr, never calls process.exit.
|
* - Hub never prints to stdout/stderr, never calls process.exit.
|
||||||
* - Hub never throws — all internal throws are caught and converted to
|
* - Hub never throws for an ordinary handler exception — those are caught
|
||||||
* { ok: false, kind: 'HandlerFailure', message, cause }.
|
* 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.
|
* - The kind taxonomy is closed. Callers switch on ERROR_KINDS values.
|
||||||
* - Each error variant carries ONLY its own typed payload (#176).
|
* - Each error variant carries ONLY its own typed payload (#176).
|
||||||
* No cross-variant `message`/`details` escape hatches.
|
* 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
|
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||||
import observabilityLogger = require('./observability/logger.cjs');
|
import observabilityLogger = require('./observability/logger.cjs');
|
||||||
const { createNoOpLogger } = observabilityLogger;
|
const { createNoOpLogger } = observabilityLogger;
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||||
|
import cliExitModule = require('./cli-exit.cjs');
|
||||||
|
const { ExitError } = cliExitModule;
|
||||||
|
|
||||||
// ─── Error kind constants ─────────────────────────────────────────────────────
|
// ─── Error kind constants ─────────────────────────────────────────────────────
|
||||||
|
|
||||||
@@ -325,6 +336,24 @@ function createHub({ cjsRegistry, manifest, logger }: HubOptions = {}): { dispat
|
|||||||
try {
|
try {
|
||||||
result = _dispatch(req);
|
result = _dispatch(req);
|
||||||
} catch (err) {
|
} 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) {
|
if (err instanceof Error) {
|
||||||
result = makeHandlerFailure(err.message, err);
|
result = makeHandlerFailure(err.message, err);
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -13,6 +13,9 @@ import os from 'node:os';
|
|||||||
import io = require('./io.cjs');
|
import io = require('./io.cjs');
|
||||||
const { output, error, ERROR_REASON } = io;
|
const { output, error, ERROR_REASON } = io;
|
||||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
// 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');
|
import configLoader = require('./config-loader.cjs');
|
||||||
const { CONFIG_DEFAULTS } = configLoader;
|
const { CONFIG_DEFAULTS } = configLoader;
|
||||||
import { platformWriteSync, platformEnsureDir } from './shell-command-projection.cjs';
|
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);
|
error('No config.json found at ' + configPath, ERROR_REASON.CONFIG_NO_FILE);
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} 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;
|
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);
|
error('Failed to read config.json: ' + (err as Error).message, ERROR_REASON.CONFIG_PARSE_FAILED);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -28,6 +28,9 @@ import {
|
|||||||
analyzeCoverage as coreAnalyzeCoverage,
|
analyzeCoverage as coreAnalyzeCoverage,
|
||||||
runProbeCli,
|
runProbeCli,
|
||||||
} from './probe-core.cjs';
|
} 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. */
|
/** The five data/behavior shapes a requirement can exhibit. */
|
||||||
export type Shape = 'numeric-range' | 'collection' | 'text' | 'stateful' | 'io';
|
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.
|
* `require.main === module` so it runs only when the compiled `.cjs` is executed directly.
|
||||||
*/
|
*/
|
||||||
if (require.main === module) {
|
if (require.main === module) {
|
||||||
|
// 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(
|
runProbeCli(
|
||||||
(requirements, resolutions) =>
|
(requirements, resolutions) =>
|
||||||
analyzeCoverage(requirements as Requirement[], resolutions as Resolution<EdgeVerification>[]),
|
analyzeCoverage(requirements as Requirement[], resolutions as Resolution<EdgeVerification>[]),
|
||||||
{ usage: 'edge-probe.cjs <requirements.json> [resolutions.json]' },
|
{ usage: 'edge-probe.cjs <requirements.json> [resolutions.json]' },
|
||||||
);
|
);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ import path from 'node:path';
|
|||||||
import { platformWriteSync, platformEnsureDir } from './shell-command-projection.cjs';
|
import { platformWriteSync, platformEnsureDir } from './shell-command-projection.cjs';
|
||||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||||
import cliExitModule = require('./cli-exit.cjs');
|
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()) ──────────────────────────────────
|
// ─── Temp-file helpers (needed by output()) ──────────────────────────────────
|
||||||
|
|
||||||
@@ -281,7 +281,10 @@ function error(message: string, reason: ErrorReasonValue = ERROR_REASON.UNKNOWN,
|
|||||||
} else {
|
} else {
|
||||||
writeAllSync(2, 'Error: ' + message + '\n');
|
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 = {
|
export = {
|
||||||
|
|||||||
@@ -29,6 +29,9 @@ const { resolveQuickTaskSummaryFile } = auditMod;
|
|||||||
import ioMod = require('./io.cjs');
|
import ioMod = require('./io.cjs');
|
||||||
const { output, error } = ioMod;
|
const { output, error } = ioMod;
|
||||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
// 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');
|
import stateContract = require('./state-contract.cjs');
|
||||||
const { publishStateContract } = stateContract;
|
const { publishStateContract } = stateContract;
|
||||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||||
@@ -739,6 +742,12 @@ function cmdMilestoneComplete(cwd: string, version: string, options: MilestoneCo
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} 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.
|
// If the error came from our guard, re-throw it; otherwise skip silently.
|
||||||
const message = e instanceof Error ? e.message : String(e);
|
const message = e instanceof Error ? e.message : String(e);
|
||||||
if (message && message.startsWith('Cannot mark milestone complete:')) throw e;
|
if (message && message.startsWith('Cannot mark milestone complete:')) throw e;
|
||||||
|
|||||||
@@ -27,6 +27,9 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import fs from 'node:fs';
|
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. */
|
/** Resolution lifecycle — shared across every probe adapter. */
|
||||||
export type Status = 'resolved' | 'dismissed' | 'unresolved';
|
export type Status = 'resolved' | 'dismissed' | 'unresolved';
|
||||||
@@ -692,7 +695,7 @@ export function runProbeCli(
|
|||||||
const readFile = options.readFile ?? ((p: string) => fs.readFileSync(p, 'utf8'));
|
const readFile = options.readFile ?? ((p: string) => fs.readFileSync(p, 'utf8'));
|
||||||
const write = options.write ?? ((s: string) => { process.stdout.write(s); });
|
const write = options.write ?? ((s: string) => { process.stdout.write(s); });
|
||||||
const writeErr = options.writeErr ?? ((s: string) => { process.stderr.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 reqPath: string | undefined = argv[2];
|
||||||
const resPath: string | undefined = argv[3];
|
const resPath: string | undefined = argv[3];
|
||||||
|
|||||||
@@ -19,6 +19,9 @@ import readline from 'node:readline';
|
|||||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||||
import ioModule = require('./io.cjs');
|
import ioModule = require('./io.cjs');
|
||||||
const { output, error, reapStaleTempFiles, ensureGsdTempDir, GSD_TEMP_DIR } = ioModule;
|
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 ────────────────────────────────────────────────────────────────────
|
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
@@ -321,7 +324,7 @@ function cmdScanSessions(overridePath: string | null | undefined, options: { jso
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
process.stdout.write(`\nTotal: ${projects.length} projects\n`);
|
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) {
|
if (sessionsSkipped > 0 && sessionsProcessed > 0) {
|
||||||
process.stdout.write(JSON.stringify(result, null, 2));
|
process.stdout.write(JSON.stringify(result, null, 2));
|
||||||
process.exit(2);
|
throw new ExitError(2);
|
||||||
} else if (sessionsProcessed === 0 && sessionsSkipped > 0) {
|
} else if (sessionsProcessed === 0 && sessionsSkipped > 0) {
|
||||||
process.stdout.write(JSON.stringify(result, null, 2));
|
process.stdout.write(JSON.stringify(result, null, 2));
|
||||||
process.exit(1);
|
throw new ExitError(1);
|
||||||
} else {
|
} else {
|
||||||
output(result, raw, undefined);
|
output(result, raw, undefined);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -19,6 +19,9 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import fs from 'node:fs';
|
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. */
|
/** The logical SPEC sections the spec-less probe fallback cares about. */
|
||||||
export type SpecSectionKey = 'edges' | 'prohibitions';
|
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
|
// 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.
|
// the compiled `.cjs` is executed directly, never when imported by tests.
|
||||||
if (require.main === module) {
|
if (require.main === module) {
|
||||||
|
runMain(() => {
|
||||||
const specFile = process.argv[2];
|
const specFile = process.argv[2];
|
||||||
const key = process.argv[3] as SpecSectionKey | undefined;
|
const key = process.argv[3] as SpecSectionKey | undefined;
|
||||||
if (!specFile || !key || !VALID_KEYS.includes(key)) {
|
if (!specFile || !key || !VALID_KEYS.includes(key)) {
|
||||||
process.stderr.write('usage: spec-section.cjs <specFile> <edges|prohibitions>\n');
|
process.stderr.write('usage: spec-section.cjs <specFile> <edges|prohibitions>\n');
|
||||||
process.exit(2);
|
throw new ExitError(2);
|
||||||
}
|
}
|
||||||
process.stdout.write(JSON.stringify(specSectionStatus(specFile, key)) + '\n');
|
process.stdout.write(JSON.stringify(specSectionStatus(specFile, key)) + '\n');
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,6 +13,9 @@ import { escapeRegex } from './pattern.cjs';
|
|||||||
import ioMod = require('./io.cjs');
|
import ioMod = require('./io.cjs');
|
||||||
const { output, error } = ioMod;
|
const { output, error } = ioMod;
|
||||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
// 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');
|
import stateContract = require('./state-contract.cjs');
|
||||||
const { publishStateContract } = stateContract;
|
const { publishStateContract } = stateContract;
|
||||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||||
@@ -541,7 +544,7 @@ function cmdStateLoad(cwd: string, raw: boolean): void {
|
|||||||
`state_exists=${stateExists}`,
|
`state_exists=${stateExists}`,
|
||||||
];
|
];
|
||||||
process.stdout.write(lines.join('\n'));
|
process.stdout.write(lines.join('\n'));
|
||||||
process.exit(0);
|
throw new ExitError(0);
|
||||||
}
|
}
|
||||||
|
|
||||||
output(result, false, undefined);
|
output(result, false, undefined);
|
||||||
|
|||||||
@@ -28,6 +28,9 @@
|
|||||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||||
import ioMod = require('./io.cjs');
|
import ioMod = require('./io.cjs');
|
||||||
const { output: coreOutput } = ioMod;
|
const { output: coreOutput } = ioMod;
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||||
|
import cliExitModule = require('./cli-exit.cjs');
|
||||||
|
const { ExitError } = cliExitModule;
|
||||||
|
|
||||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
@@ -85,7 +88,7 @@ export function cmdTeamsStatus(cwd: string, opts: { active?: boolean }): void {
|
|||||||
|
|
||||||
if (opts.active) {
|
if (opts.active) {
|
||||||
// --active mode: no output, exit code encodes the boolean
|
// --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
|
// Default: emit JSON to stdout via io.output, exit 0
|
||||||
|
|||||||
@@ -31,6 +31,9 @@ import {
|
|||||||
analyzeCoverage as coreAnalyzeCoverage,
|
analyzeCoverage as coreAnalyzeCoverage,
|
||||||
runProbeCli,
|
runProbeCli,
|
||||||
} from './probe-core.cjs';
|
} 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). */
|
/** The six UI element kinds a described component can be (the closed relevance axis, D-03). */
|
||||||
export type UIElementKind =
|
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.
|
* so it runs only when the compiled `.cjs` is executed directly.
|
||||||
*/
|
*/
|
||||||
if (require.main === module) {
|
if (require.main === module) {
|
||||||
|
// 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(
|
runProbeCli(
|
||||||
(elements, resolutions) =>
|
(elements, resolutions) =>
|
||||||
analyzeCoverage(elements as Element[], resolutions as Resolution<UIVerification>[]),
|
analyzeCoverage(elements as Element[], resolutions as Resolution<UIVerification>[]),
|
||||||
{ usage: 'ui-consideration-probe.cjs <elements.json> [resolutions.json]' },
|
{ usage: 'ui-consideration-probe.cjs <elements.json> [resolutions.json]' },
|
||||||
);
|
);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -853,6 +853,7 @@ const commands = require('../gsd-core/bin/lib/commands.cjs');
|
|||||||
const configCli = require('../gsd-core/bin/lib/config.cjs');
|
const configCli = require('../gsd-core/bin/lib/config.cjs');
|
||||||
const { loadConfigResolved, CONFIG_DEFAULTS } = require('../gsd-core/bin/lib/config-loader.cjs');
|
const { loadConfigResolved, CONFIG_DEFAULTS } = require('../gsd-core/bin/lib/config-loader.cjs');
|
||||||
const io = require('../gsd-core/bin/lib/io.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 { PHASE_NUMBER_TOKEN_SOURCE } = require('../gsd-core/bin/lib/phase-id.cjs');
|
||||||
const { DYNAMIC_KEY_PATTERNS } = require('../gsd-core/bin/lib/config-schema.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);
|
return JSON.parse(out);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Drives cmdConfigSet in-process, sentinel-exit style (mirrors
|
/** Drives cmdConfigSet in-process (mirrors tests/config-get-default.test.cjs's
|
||||||
* tests/config-get-default.test.cjs's runExpectError) for the one negative
|
* runExpectError) for the one negative (A4) case that must exercise error()'s
|
||||||
* (A4) case that must exercise error()'s process.exit(1) path. */
|
* ExitError-throwing path (ADR-3889 — error() throws ExitError directly, it
|
||||||
|
* no longer calls process.exit()). */
|
||||||
function runConfigSetExpectError(tmpDir, keyPath, value) {
|
function runConfigSetExpectError(tmpDir, keyPath, value) {
|
||||||
const origExit = process.exit;
|
|
||||||
const origWriteSync = fs.writeSync;
|
const origWriteSync = fs.writeSync;
|
||||||
io.setJsonErrorMode(true);
|
io.setJsonErrorMode(true);
|
||||||
let stderr = '';
|
let stderr = '';
|
||||||
@@ -923,14 +924,12 @@ function runConfigSetExpectError(tmpDir, keyPath, value) {
|
|||||||
stderr += chunk;
|
stderr += chunk;
|
||||||
return Buffer.byteLength(chunk);
|
return Buffer.byteLength(chunk);
|
||||||
};
|
};
|
||||||
class _ExitSignal extends Error {}
|
|
||||||
process.exit = () => { throw new _ExitSignal('exit'); };
|
|
||||||
try {
|
try {
|
||||||
configCli.cmdConfigSet(tmpDir, keyPath, value, true);
|
configCli.cmdConfigSet(tmpDir, keyPath, value, true);
|
||||||
|
assert.fail('expected cmdConfigSet to throw ExitError');
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
if (!(e instanceof _ExitSignal)) throw e;
|
if (!(e instanceof ExitError)) throw e;
|
||||||
} finally {
|
} finally {
|
||||||
process.exit = origExit;
|
|
||||||
fs.writeSync = origWriteSync;
|
fs.writeSync = origWriteSync;
|
||||||
io.setJsonErrorMode(false);
|
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
|
// 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.
|
// 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'));
|
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)
|
* cmdConfigGet's error() path (gsd-core/bin/lib/io.cjs) now throws ExitError
|
||||||
* directly (it predates the ExitError/runMain seam used by the CLI
|
* directly (ADR-3889) instead of calling process.exit(1). The harnesses below
|
||||||
* entrypoint's non-error paths). Intercepting process.exit with a throwable
|
* catch that ExitError directly — no process.exit mock / throwable sentinel
|
||||||
* sentinel lets the error path be exercised in-process without killing the
|
* is needed anymore.
|
||||||
* test worker.
|
|
||||||
*
|
*
|
||||||
* The sentinel carries the ORIGINAL error message (not a generic "process.exit(1)").
|
* cmdConfigGet's "no config.json" branch sits inside a try/catch that used to
|
||||||
* That matters for cmdConfigGet's "no config.json" branch, whose `error()` sits inside
|
* reclassify any throw NOT starting with "No config.json" as a parse failure.
|
||||||
* a try/catch that reclassifies any throw NOT starting with "No config.json" as a parse
|
* Because an ExitError carries no message (`.message` defaults to
|
||||||
* failure (a guard that is dead in production, where process.exit terminates first, but
|
* "process exit 1"), that message-sniffing check could never match it — a
|
||||||
* becomes live once process.exit is a throwing seam). Carrying the real message makes
|
* real production bug this PR also fixes at src/config.cts (an unconditional
|
||||||
* that guard re-throw — modeling the single, faithful production termination instead of
|
* `instanceof ExitError` re-throw now guards it). The `writeCount === 1`
|
||||||
* a spurious second error() call with the wrong reason.
|
* 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)
|
* 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) {
|
function runExpectError(...args) {
|
||||||
const { keyPath, raw, defaultValue } = parseConfigGetArgs(args);
|
const { keyPath, raw, defaultValue } = parseConfigGetArgs(args);
|
||||||
const origExit = process.exit;
|
|
||||||
const origWriteSync = fs.writeSync;
|
const origWriteSync = fs.writeSync;
|
||||||
io.setJsonErrorMode(true); // structured stderr line lets the sentinel carry the message + assert reason
|
io.setJsonErrorMode(true); // structured stderr line lets the payload carry the reason
|
||||||
let exitCount = 0;
|
let writeCount = 0;
|
||||||
let exitCode;
|
|
||||||
let stderr = '';
|
let stderr = '';
|
||||||
fs.writeSync = (fd, ...rest) => {
|
fs.writeSync = (fd, ...rest) => {
|
||||||
if (fd !== 2) return origWriteSync.call(fs, fd, ...rest);
|
if (fd !== 2) return origWriteSync.call(fs, fd, ...rest);
|
||||||
|
writeCount++;
|
||||||
const [data, offset = 0, length] = rest;
|
const [data, offset = 0, length] = rest;
|
||||||
const chunk = Buffer.isBuffer(data)
|
const chunk = Buffer.isBuffer(data)
|
||||||
? data.subarray(offset, offset + (length ?? data.length - offset)).toString('utf8')
|
? 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);
|
const parts = stderr.split('\n').filter(Boolean);
|
||||||
try { return JSON.parse(parts[parts.length - 1]); } catch { return {}; }
|
try { return JSON.parse(parts[parts.length - 1]); } catch { return {}; }
|
||||||
};
|
};
|
||||||
process.exit = (code) => {
|
// ADR-3889: error() now throws ExitError directly (rather than calling
|
||||||
exitCount++;
|
// process.exit()), so the real termination contract is caught here
|
||||||
exitCode = code;
|
// instead of via a process.exit mock.
|
||||||
// Carry the just-emitted error message so cmdConfigGet's seam guard re-throws
|
let exitCode;
|
||||||
// (single, faithful fire) instead of catching + reclassifying into a 2nd error().
|
|
||||||
throw new _ExitSignal(code, lastError().message);
|
|
||||||
};
|
|
||||||
try {
|
try {
|
||||||
config.cmdConfigGet(tmpDir, keyPath, raw, defaultValue);
|
config.cmdConfigGet(tmpDir, keyPath, raw, defaultValue);
|
||||||
|
assert.fail('expected cmdConfigGet to throw ExitError');
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
if (!(e instanceof _ExitSignal)) throw e;
|
if (!(e instanceof ExitError)) throw e;
|
||||||
|
exitCode = e.code;
|
||||||
} finally {
|
} finally {
|
||||||
process.exit = origExit;
|
|
||||||
fs.writeSync = origWriteSync;
|
fs.writeSync = origWriteSync;
|
||||||
io.setJsonErrorMode(false);
|
io.setJsonErrorMode(false);
|
||||||
}
|
}
|
||||||
assert.ok(exitCode !== 0 && exitCode !== undefined, 'Expected non-zero exit code');
|
assert.ok(exitCode !== 0 && exitCode !== undefined, 'Expected non-zero exit code');
|
||||||
// Faithfulness guard: production process.exit terminates, so error() fires exactly
|
// Faithfulness guard: error() must fire exactly once. A count of 2 means
|
||||||
// once. A count of 2 means the throwing-exit seam was caught + reclassified (the bug
|
// the guard's ExitError was caught by a message-sniffing catch and
|
||||||
// this harness redesign fixes) — fail loudly rather than report a wrong reason.
|
// reclassified into a 2nd error() call (the exact Part-2 defect class —
|
||||||
assert.equal(exitCount, 1, 'error() must fire exactly once (production process.exit terminates)');
|
// 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();
|
const payload = lastError();
|
||||||
return { status: exitCode, reason: payload.reason, message: payload.message, stderr };
|
return { status: exitCode, reason: payload.reason, message: payload.message, stderr };
|
||||||
}
|
}
|
||||||
@@ -277,14 +276,13 @@ describe('config-get --default flag (#1893)', () => {
|
|||||||
|
|
||||||
function runExpectError(...args) {
|
function runExpectError(...args) {
|
||||||
const { keyPath, raw, defaultValue } = parseConfigGetArgs(args);
|
const { keyPath, raw, defaultValue } = parseConfigGetArgs(args);
|
||||||
const origExit = process.exit;
|
|
||||||
const origWriteSync = fs.writeSync;
|
const origWriteSync = fs.writeSync;
|
||||||
io.setJsonErrorMode(true);
|
io.setJsonErrorMode(true);
|
||||||
let exitCount = 0;
|
let writeCount = 0;
|
||||||
let exitCode;
|
|
||||||
let stderr = '';
|
let stderr = '';
|
||||||
fs.writeSync = (fd, ...rest) => {
|
fs.writeSync = (fd, ...rest) => {
|
||||||
if (fd !== 2) return origWriteSync.call(fs, fd, ...rest);
|
if (fd !== 2) return origWriteSync.call(fs, fd, ...rest);
|
||||||
|
writeCount++;
|
||||||
const [data, offset = 0, length] = rest;
|
const [data, offset = 0, length] = rest;
|
||||||
const chunk = Buffer.isBuffer(data)
|
const chunk = Buffer.isBuffer(data)
|
||||||
? data.subarray(offset, offset + (length ?? data.length - offset)).toString('utf8')
|
? 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);
|
const parts = stderr.split('\n').filter(Boolean);
|
||||||
try { return JSON.parse(parts[parts.length - 1]); } catch { return {}; }
|
try { return JSON.parse(parts[parts.length - 1]); } catch { return {}; }
|
||||||
};
|
};
|
||||||
process.exit = (code) => {
|
// ADR-3889: error() throws ExitError directly; catch it here rather
|
||||||
exitCount++;
|
// than mocking process.exit.
|
||||||
exitCode = code;
|
let exitCode;
|
||||||
throw new _ExitSignal(code, lastError().message);
|
|
||||||
};
|
|
||||||
try {
|
try {
|
||||||
config.cmdConfigGet(tmpDir, keyPath, raw, defaultValue);
|
config.cmdConfigGet(tmpDir, keyPath, raw, defaultValue);
|
||||||
|
assert.fail('expected cmdConfigGet to throw ExitError');
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
if (!(e instanceof _ExitSignal)) throw e;
|
if (!(e instanceof ExitError)) throw e;
|
||||||
|
exitCode = e.code;
|
||||||
} finally {
|
} finally {
|
||||||
process.exit = origExit;
|
|
||||||
fs.writeSync = origWriteSync;
|
fs.writeSync = origWriteSync;
|
||||||
io.setJsonErrorMode(false);
|
io.setJsonErrorMode(false);
|
||||||
}
|
}
|
||||||
assert.ok(exitCode !== 0 && exitCode !== undefined, 'Expected non-zero exit code');
|
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();
|
const payload = lastError();
|
||||||
return { status: exitCode, reason: payload.reason, message: payload.message, stderr };
|
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
|
// fresh for every fc run (unique mkdtemp per run body, cleaned up in a
|
||||||
// finally — no shared/leaked state across runs).
|
// finally — no shared/leaked state across runs).
|
||||||
function runInProcessAt(dir, keyPath) {
|
function runInProcessAt(dir, keyPath) {
|
||||||
const origExit = process.exit;
|
|
||||||
const origWriteSync = fs.writeSync;
|
const origWriteSync = fs.writeSync;
|
||||||
io.setJsonErrorMode(true);
|
io.setJsonErrorMode(true);
|
||||||
let stdout = '';
|
let stdout = '';
|
||||||
@@ -507,17 +503,15 @@ describe('config-get --default flag (#1893)', () => {
|
|||||||
else if (fd === 2) stderr += chunk;
|
else if (fd === 2) stderr += chunk;
|
||||||
return Buffer.byteLength(chunk);
|
return Buffer.byteLength(chunk);
|
||||||
};
|
};
|
||||||
process.exit = (code) => {
|
// ADR-3889: error() throws ExitError directly; catch it here rather
|
||||||
exited = true;
|
// than mocking process.exit.
|
||||||
exitCode = code;
|
|
||||||
throw new _ExitSignal(code, '');
|
|
||||||
};
|
|
||||||
try {
|
try {
|
||||||
config.cmdConfigGet(dir, keyPath, true, undefined);
|
config.cmdConfigGet(dir, keyPath, true, undefined);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
if (!(e instanceof _ExitSignal)) throw e;
|
if (!(e instanceof ExitError)) throw e;
|
||||||
|
exited = true;
|
||||||
|
exitCode = e.code;
|
||||||
} finally {
|
} finally {
|
||||||
process.exit = origExit;
|
|
||||||
fs.writeSync = origWriteSync;
|
fs.writeSync = origWriteSync;
|
||||||
io.setJsonErrorMode(false);
|
io.setJsonErrorMode(false);
|
||||||
}
|
}
|
||||||
@@ -1415,23 +1409,24 @@ describe('#2702: workstream config-get inherits from root config', () => {
|
|||||||
const { keyPath, raw, defaultValue } = parseConfigGetArgs(args);
|
const { keyPath, raw, defaultValue } = parseConfigGetArgs(args);
|
||||||
const saved = process.env.GSD_WORKSTREAM;
|
const saved = process.env.GSD_WORKSTREAM;
|
||||||
process.env.GSD_WORKSTREAM = 'alpha';
|
process.env.GSD_WORKSTREAM = 'alpha';
|
||||||
const origExit = process.exit;
|
|
||||||
const origWriteSync = fs.writeSync;
|
const origWriteSync = fs.writeSync;
|
||||||
io.setJsonErrorMode(true);
|
io.setJsonErrorMode(true);
|
||||||
let exitCode;
|
|
||||||
let stderr = '';
|
let stderr = '';
|
||||||
fs.writeSync = (fd, ...rest) => {
|
fs.writeSync = (fd, ...rest) => {
|
||||||
if (fd !== 2) return origWriteSync.call(fs, fd, ...rest);
|
if (fd !== 2) return origWriteSync.call(fs, fd, ...rest);
|
||||||
stderr += String(rest[0]);
|
stderr += String(rest[0]);
|
||||||
return Buffer.byteLength(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 {
|
try {
|
||||||
config.cmdConfigGet(tmpDir, keyPath, raw, defaultValue);
|
config.cmdConfigGet(tmpDir, keyPath, raw, defaultValue);
|
||||||
|
assert.fail('expected cmdConfigGet to throw ExitError');
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
if (!(e instanceof _ExitSignal)) throw e;
|
if (!(e instanceof ExitError)) throw e;
|
||||||
|
exitCode = e.code;
|
||||||
} finally {
|
} finally {
|
||||||
process.exit = origExit;
|
|
||||||
fs.writeSync = origWriteSync;
|
fs.writeSync = origWriteSync;
|
||||||
io.setJsonErrorMode(false);
|
io.setJsonErrorMode(false);
|
||||||
if (saved === undefined) delete process.env.GSD_WORKSTREAM;
|
if (saved === undefined) delete process.env.GSD_WORKSTREAM;
|
||||||
|
|||||||
@@ -14,6 +14,7 @@
|
|||||||
* - local/no-raw-rmsync-in-tests
|
* - local/no-raw-rmsync-in-tests
|
||||||
* - local/no-adhoc-markdown-parsing
|
* - local/no-adhoc-markdown-parsing
|
||||||
* - local/require-subprocess-timeout
|
* - local/require-subprocess-timeout
|
||||||
|
* - local/require-registered-exit
|
||||||
*/
|
*/
|
||||||
|
|
||||||
const { test, describe } = require('node:test');
|
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 noAdhocMarkdownParsing = require('../eslint-rules/no-adhoc-markdown-parsing.cjs');
|
||||||
const noDuplicateFoldMarker = require('../eslint-rules/no-duplicate-fold-marker.cjs');
|
const noDuplicateFoldMarker = require('../eslint-rules/no-duplicate-fold-marker.cjs');
|
||||||
const requireSubprocessTimeout = require('../eslint-rules/require-subprocess-timeout.cjs');
|
const requireSubprocessTimeout = require('../eslint-rules/require-subprocess-timeout.cjs');
|
||||||
|
const requireRegisteredExit = require('../eslint-rules/require-registered-exit.cjs');
|
||||||
|
|
||||||
const ruleTester = new RuleTester({
|
const ruleTester = new RuleTester({
|
||||||
languageOptions: {
|
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
|
// H1 below can assert a typed `reason`, mirroring tests/config-get-default.test.cjs's
|
||||||
// established in-process CLI-error-path pattern.
|
// established in-process CLI-error-path pattern.
|
||||||
const io = require('../gsd-core/bin/lib/io.cjs');
|
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. */
|
/** 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 }) {
|
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
|
// cross-platform IO-failure-injection rule) already used in
|
||||||
// tests/phase-locator.test.cjs for `listAllPhaseDirs`'s own unreadable case.
|
// tests/phase-locator.test.cjs for `listAllPhaseDirs`'s own unreadable case.
|
||||||
describe('unreadable phases directory refuses calibration (#3882, ADR-3473 §8.5)', () => {
|
describe('unreadable phases directory refuses calibration (#3882, ADR-3473 §8.5)', () => {
|
||||||
class _ExitSignal extends Error {
|
/** Runs cmdEstimateCalibrate in-process, catching the ExitError error()
|
||||||
constructor(code, message) {
|
* throws (ADR-3889 — error() no longer calls process.exit() directly) with
|
||||||
super(message ?? `process.exit(${code})`);
|
* stderr(fd 2) captured. */
|
||||||
this.code = code;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Runs cmdEstimateCalibrate in-process with process.exit + stderr(fd 2) captured. */
|
|
||||||
function runCalibrateExpectError(tmpDir) {
|
function runCalibrateExpectError(tmpDir) {
|
||||||
const origExit = process.exit;
|
|
||||||
const origWriteSync = fs.writeSync;
|
const origWriteSync = fs.writeSync;
|
||||||
io.setJsonErrorMode(true);
|
io.setJsonErrorMode(true);
|
||||||
let exitCount = 0;
|
let writeCount = 0;
|
||||||
let exitCode;
|
|
||||||
let stderr = '';
|
let stderr = '';
|
||||||
fs.writeSync = (fd, ...rest) => {
|
fs.writeSync = (fd, ...rest) => {
|
||||||
if (fd !== 2) return origWriteSync.call(fs, fd, ...rest);
|
if (fd !== 2) return origWriteSync.call(fs, fd, ...rest);
|
||||||
|
writeCount++;
|
||||||
const [data, offset = 0, length] = rest;
|
const [data, offset = 0, length] = rest;
|
||||||
const chunk = Buffer.isBuffer(data)
|
const chunk = Buffer.isBuffer(data)
|
||||||
? data.subarray(offset, offset + (length ?? data.length - offset)).toString('utf8')
|
? 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);
|
const parts = stderr.split('\n').filter(Boolean);
|
||||||
try { return JSON.parse(parts[parts.length - 1]); } catch { return {}; }
|
try { return JSON.parse(parts[parts.length - 1]); } catch { return {}; }
|
||||||
};
|
};
|
||||||
process.exit = (code) => {
|
let exitCode;
|
||||||
exitCount++;
|
|
||||||
exitCode = code;
|
|
||||||
throw new _ExitSignal(code, lastError().message);
|
|
||||||
};
|
|
||||||
try {
|
try {
|
||||||
estimateCli.cmdEstimateCalibrate(tmpDir, [], false);
|
estimateCli.cmdEstimateCalibrate(tmpDir, [], false);
|
||||||
|
assert.fail('expected cmdEstimateCalibrate to throw ExitError');
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
if (!(e instanceof _ExitSignal)) throw e;
|
if (!(e instanceof ExitError)) throw e;
|
||||||
|
exitCode = e.code;
|
||||||
} finally {
|
} finally {
|
||||||
process.exit = origExit;
|
|
||||||
fs.writeSync = origWriteSync;
|
fs.writeSync = origWriteSync;
|
||||||
io.setJsonErrorMode(false);
|
io.setJsonErrorMode(false);
|
||||||
}
|
}
|
||||||
assert.ok(exitCode !== 0 && exitCode !== undefined, 'expected a non-zero exit code');
|
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() };
|
return { status: exitCode, ...lastError() };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ const os = require('node:os');
|
|||||||
const fs = require('node:fs');
|
const fs = require('node:fs');
|
||||||
|
|
||||||
const io = require('../gsd-core/bin/lib/io.cjs');
|
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 { runNode } = require('./helpers/process-seam.cjs');
|
||||||
const { toLegacyResult } = require('./helpers/git-fixture.cjs');
|
const { toLegacyResult } = require('./helpers/git-fixture.cjs');
|
||||||
const { PROBE_TIMEOUT_MS } = require('./helpers/timeouts.cjs');
|
const { PROBE_TIMEOUT_MS } = require('./helpers/timeouts.cjs');
|
||||||
@@ -186,12 +187,25 @@ describe('output()', () => {
|
|||||||
|
|
||||||
describe('error()', () => {
|
describe('error()', () => {
|
||||||
const ioPath = path.resolve(__dirname, '../gsd-core/bin/lib/io.cjs');
|
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', () => {
|
test('plain-text mode: writes "Error: <msg>" to stderr and exits 1', () => {
|
||||||
const script = `
|
const script = `
|
||||||
const io = require(${JSON.stringify(ioPath)});
|
const io = require(${JSON.stringify(ioPath)});
|
||||||
|
const { runMain } = require(${JSON.stringify(cliExitPath)});
|
||||||
io.setJsonErrorMode(false);
|
io.setJsonErrorMode(false);
|
||||||
io.error('something went wrong');
|
runMain(() => { io.error('something went wrong'); });
|
||||||
`;
|
`;
|
||||||
const result = runScript(script);
|
const result = runScript(script);
|
||||||
assert.strictEqual(result.status, 1);
|
assert.strictEqual(result.status, 1);
|
||||||
@@ -202,8 +216,9 @@ describe('error()', () => {
|
|||||||
test('plain-text mode: default reason does not appear in stderr text', () => {
|
test('plain-text mode: default reason does not appear in stderr text', () => {
|
||||||
const script = `
|
const script = `
|
||||||
const io = require(${JSON.stringify(ioPath)});
|
const io = require(${JSON.stringify(ioPath)});
|
||||||
|
const { runMain } = require(${JSON.stringify(cliExitPath)});
|
||||||
io.setJsonErrorMode(false);
|
io.setJsonErrorMode(false);
|
||||||
io.error('no reason code expected');
|
runMain(() => { io.error('no reason code expected'); });
|
||||||
`;
|
`;
|
||||||
const result = runScript(script);
|
const result = runScript(script);
|
||||||
assert.strictEqual(result.status, 1);
|
assert.strictEqual(result.status, 1);
|
||||||
@@ -214,8 +229,9 @@ describe('error()', () => {
|
|||||||
test('JSON-error mode: writes structured JSON to stderr and exits 1', () => {
|
test('JSON-error mode: writes structured JSON to stderr and exits 1', () => {
|
||||||
const script = `
|
const script = `
|
||||||
const io = require(${JSON.stringify(ioPath)});
|
const io = require(${JSON.stringify(ioPath)});
|
||||||
|
const { runMain } = require(${JSON.stringify(cliExitPath)});
|
||||||
io.setJsonErrorMode(true);
|
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);
|
const result = runScript(script);
|
||||||
assert.strictEqual(result.status, 1);
|
assert.strictEqual(result.status, 1);
|
||||||
@@ -229,8 +245,9 @@ describe('error()', () => {
|
|||||||
test('JSON-error mode: defaults reason to UNKNOWN when not supplied', () => {
|
test('JSON-error mode: defaults reason to UNKNOWN when not supplied', () => {
|
||||||
const script = `
|
const script = `
|
||||||
const io = require(${JSON.stringify(ioPath)});
|
const io = require(${JSON.stringify(ioPath)});
|
||||||
|
const { runMain } = require(${JSON.stringify(cliExitPath)});
|
||||||
io.setJsonErrorMode(true);
|
io.setJsonErrorMode(true);
|
||||||
io.error('no reason given');
|
runMain(() => { io.error('no reason given'); });
|
||||||
`;
|
`;
|
||||||
const result = runScript(script);
|
const result = runScript(script);
|
||||||
assert.strictEqual(result.status, 1);
|
assert.strictEqual(result.status, 1);
|
||||||
@@ -249,8 +266,9 @@ describe('error()', () => {
|
|||||||
for (const [expected, key] of cases) {
|
for (const [expected, key] of cases) {
|
||||||
const script = `
|
const script = `
|
||||||
const io = require(${JSON.stringify(ioPath)});
|
const io = require(${JSON.stringify(ioPath)});
|
||||||
|
const { runMain } = require(${JSON.stringify(cliExitPath)});
|
||||||
io.setJsonErrorMode(true);
|
io.setJsonErrorMode(true);
|
||||||
io.error('test', io.ERROR_REASON.${key});
|
runMain(() => { io.error('test', io.ERROR_REASON.${key}); });
|
||||||
`;
|
`;
|
||||||
const result = runScript(script);
|
const result = runScript(script);
|
||||||
assert.strictEqual(result.status, 1, `key=${key}`);
|
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', () => {
|
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 = [];
|
const written = [];
|
||||||
let calls = 0;
|
let calls = 0;
|
||||||
let exitCode = null;
|
const restore = fs.writeSync;
|
||||||
t.mock.method(process, 'exit', (code) => { exitCode = code; }); // neutralize the hard exit
|
fs.writeSync = (fd, data, offset, length) => {
|
||||||
t.mock.method(fs, 'writeSync', (fd, data, offset, length) => {
|
|
||||||
calls += 1;
|
calls += 1;
|
||||||
if (calls === 1) throw bug1008WriteError('EAGAIN', -11);
|
if (calls === 1) throw bug1008WriteError('EAGAIN', -11);
|
||||||
assert.equal(fd, 2, 'error() must write to stderr');
|
assert.equal(fd, 2, 'error() must write to stderr');
|
||||||
const chunk = bug1008ChunkOf(data, offset, length);
|
const chunk = bug1008ChunkOf(data, offset, length);
|
||||||
written.push(chunk);
|
written.push(chunk);
|
||||||
return Buffer.byteLength(chunk, 'utf8');
|
return Buffer.byteLength(chunk, 'utf8');
|
||||||
});
|
};
|
||||||
|
try {
|
||||||
assert.doesNotThrow(() => io.error('boom', io.ERROR_REASON.UNKNOWN));
|
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.ok(calls >= 2, 'error() should retry after EAGAIN');
|
||||||
assert.equal(written.join(''), 'Error: boom\n');
|
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