* enhance(#3912): gsd-tools declares outcomes, pinned at v1 ADR-3889 §4. Phase 6 already moved error()'s terminator onto the seam, so what remained was the declaration — and the pin that makes it invisible today. The census corrected two documented figures before any code changed. ERROR_REASON has exactly 25 members (the ADR and epic were right; an earlier note of mine claiming 23 was wrong and is corrected). And output({error}) is **64 sites across 9 files, not the 60 ADR-2980 ratified** — the module shape holds but the total drifted +4: frontmatter 7 not 6, phase 4 not 2, roadmap 3 not 2. That matters because this phase's criterion demands the pin be asserted over the enumerated population rather than sampled; asserting over a stale 60 would leave four sites unpinned while claiming full coverage, which is the shape of failure this epic exists to remove. The issue does not state the fact that shapes the design: output() never touches the exit code. Confirmed by reading it — it writes fd 1 and returns. So a declared outcome for those 64 sites had nowhere to be READ. The mapping was never the work; wiring somewhere for the declaration to land was. The seam already existed twice over. cli-exit.cts holds two globalThis-Symbol cells, each because the module is emitted to three locations and a module-level `let` would let instances disagree, and runMain already maps a code returned by main(). A third cell inherits that solution. output() records DEGRADED for any {error} payload — key-order agnostic, which is exactly why the "42 sites" figure undercounts — and runMain projects the cell only when main() returns nothing, so an explicit return still wins. error() maps its reason through a table over the closed 25-member enum, leaving all 278 call sites untouched; 226 of them pass no reason at all. The version gate lives in error(), NOT in projectOutcome: registered names are version-invariant there, so mapping a reason straight through would make USAGE project to 64 under v1 and break the pin on its first line. projectOutcome is left exactly as Phase 2 shipped it, DEGRADED's 0/80 asymmetry included. Proven rather than asserted. v1 is byte-identical across three real CLI paths — config-get plain, config-get --json-errors, and an output({error}) path — matching exit code and exact bytes against the pre-change build. Under GSD_EXIT_CONTRACT=v2 the same commands now exit 66 (CONFIG_KEY_NOT_FOUND -> NO_INPUT) and 80 (DEGRADED), both looked up through the registry. An anti-vacuity test pins that v1 and v2 genuinely differ for at least one reason, because without it a mapping where everything projects to 1 under both versions would satisfy every other assertion and the declaration would be theatre. A1 iterates all 25 enum members and A3 asserts over the measured 64-site population, so a 26th reason or a 65th site fails until it is given a mapping — the drift guard this phase needs, given ADR-2980's own count had drifted +4 unnoticed. Verification runs on the remote runner. Refs #3912 * fix(#3912): the outcome cell must never lower an exit code The remote run caught a fail-open that this phase introduced, in the phase whose entire purpose is removing fail-opens. `state validate --strict` on a missing STATE.md exited **0** where it must exit 1. Mechanism: `runMain` projected the pending outcome whenever `main()` returned void, and under v1 DEGRADED projects to 0 — so a `process.exitCode` already set non-zero by the command was clobbered down to success. Confirmed live against a fixture, before and after. This refutes a review conclusion recorded earlier in this phase, that the cell was "fail-closed and can never mask a failure as success". It could, and did. Recording that plainly so the assumption is not repeated: the cell's danger was never only that it might add a failure — it was that projecting it unconditionally overwrites whatever decision came before. Projection is now guarded: it may set a code only when none is set, and an already-non-zero exit code always wins. The full precedence — explicit `main()` return, then an existing non-zero exitCode, then the declared outcome — is written at the projection site. A regression test drives a void return with a pre-set non-zero code and a pending DEGRADED, and fails against the pre-fix build. The second failure was my test encoding the wrong contract, not a code defect. It asserted `output({found:false, error: undefined})` records DEGRADED because the KEY is present. `JSON.stringify` drops undefined, so the payload the user receives is `{"found":false}` — carrying no error at all, and calling that degraded would hand back exit 80 under v2 for output that reads as clean. The discriminator is a serializable error VALUE, not key presence. The test now pins `{error: undefined}` as explicitly NOT degraded, and the design doc's wording is tightened to match. Verification runs on the remote runner. Refs #3912 * docs(#3912): the versioned exit contract, and a flag defect the docs found Diataxis pass for Phase 8, plus a real fix that only surfaced because writing the how-to meant running its own examples. The docs. ADR-2980's "Revisit if" clause asked for exactly the versioned projection this phase provides, so it gets an amendment naming #3912 / ADR-3889 section 4 as that boundary: v1 stays 0 byte-for-byte, v2 projects DEGRADED to 80. The amendment also records the count drift rather than restating a stale figure — the ADR ratified 60 output({error}) sites in 9 modules; the AST-measured population is 64 across the same 9 (frontmatter 7 not 6, phase 4 not 2, roadmap 3 not 2). The pin is asserted over the enumerated 64. json-errors.md gains the outcome-declaration reference, including the precedence order a review pass got wrong and the suite refuted: an explicit main() return, then an already-set non-zero process.exitCode, then the declared outcome. Projection may only ever set a code, never lower one. A how-to is owed here and is written, not skipped. Under v1 nothing changes, so the audience is an operator opting into v2 and needing to know what the codes mean for a CI gate — a migration, which is how-to shaped. It covers turning v2 on, the code table, why 80 is "ran and reported a condition" rather than a crash, and how to split a gate that treats any non-zero as fatal. No tutorial: there is no new entry point to learn, and under the default contract a reader would be walked through observing nothing. The defect. Running the how-to's own Step 1 example returned $ gsd-tools --exit-contract=v2 state validate --strict Error: Unknown command: --exit-contract=v2 (exit 64) while the same flag trailing the subcommand worked and exited 80. The flag half-worked, by argv position. resolveContractVersion scans argv non-destructively, so the token survived into the dispatcher, which treats argv[2] as the command name. --json-errors had already solved precisely this at gsd-tools.cjs:4455, under a comment naming the hazard verbatim: "The argv splice must happen here too, otherwise the dispatcher below sees --json-errors as an unknown command." The later flag never got the same treatment. Fixed rather than documented around: the version is resolved first — which memoizes the cell and makes an invalid value throw early — and then every --exit-contract= token is spliced out of the dispatcher's argv copy. --exit-contract is now listed in TOP_LEVEL_USAGE, where it never was. The regression test pins leading position, trailing position, agreement between the two, and a loud failure on v3 rather than a silent fall back to v1. Neither review engine would have caught this: the defect is invisible in the diff, because the diff does not touch argv handling. It surfaced only from running the documentation's own example. Writing a how-to is an execution pass. Verification runs on the remote runner. Refs #3912 * fix(#3912): the flag splice has to run before the run-with-timeout return An isolated review of the previous commit found that the fix did not deliver what it claimed, and that two of its own tests were weak. All three findings reproduced by execution before any change was made. The fix was placed below a return. main() intercepts `run-with-timeout` at gsd-tools.cjs:4436 and returns from there — above both the --json-errors block and the --exit-contract splice added in the previous commit. So the flag still died in leading position for that one command: $ gsd-tools --exit-contract=v2 run-with-timeout 5 -- node -e "..." Error: Unknown command: run-with-timeout (exit 64, child never ran) The previous commit message and the test's describe-block both claimed position-independence unconditionally. That was an overclaim, not a gap left open, and it is the part worth naming: the fix was verified by hand on the commands I happened to think of, and `run-with-timeout` returns before the code I was verifying. Both global-flag blocks now run above the interception, with a comment naming it so a later edit cannot slide them back down. Moving --json-errors up fixes the identical pre-existing bug for that flag, verified failing beforehand (exit 1, sdk_unknown_command). Fixing the sibling is deliberate: same defect, same block, and a known-broken twin next to a fixed one is not a resting state. Two tests were not pulling their weight. The invalid-value test was vacuous — it passed against the pre-fix build, because `--exit-contract=v3` already exited 1 there and already printed the resolve error lazily through error() -> getContractVersion. Both its assertions held before the fix, so it pinned nothing. The real discriminator is that the pre-fix build emits BOTH "Unknown command: --exit-contract=v3" and the resolve error, while the fixed build emits only the latter; the test now asserts that absence. The leading-position and leading==trailing tests asserted proxies — "not 64", "no Unknown command", "the two agree" — none of which pin a value, and all of which would survive both positions being identically broken. With a .planning directory and no STATE.md, state-snapshot exits exactly 80 under v2 and 0 under v1 in both positions. Those numbers are pinned now. The multi-token case the descending splice loop exists for is covered too, and run-with-timeout has regression tests for both flags. The lesson is narrower than "test more". Hand-verifying the production behavior does not verify that the test would have caught its absence. The pre-fix binary has to be run against the test's own assertions. Investigated and deliberately not changed: splicing before --cwd parsing degrades one diagnostic from "Missing value for --cwd" to "Invalid --cwd: <path>", but that is pre-existing — verified on the pre-fix build via --json-errors, which already did it. This change joins the pattern rather than creating it, and both forms exit 64 on malformed input either way. Verification runs on the remote runner. Refs #3912 * chore(#3912): backfill changeset pr numbers to 3983 * test(#3912): pin the reason-table invariant as set equality, not a count A graph-backed review flagged the unchecked lookup in expectedErrorCode3912. Investigated by execution: the drift guard DOES hold — for an unmapped reason under v2 the production error() yields 1 while the table yields undefined, so the assertion fails. Not a correctness defect, and deliberately NOT made tolerant, since a tolerant lookup would destroy the guard. Two real problems remained. The guard asserted the wrong invariant: it counted the TABLE's keys at 25 rather than checking they match the ENUM's values, so a renamed member keeps the count at 25 and slips past, and a 26th member leaves the table at 25 and slips past too. Both were then caught only indirectly, by an undefined mismatch producing 'must exit undefined'. It is now a sorted set equality, so the failure names the specific missing or extra reason. And the comment above it described a '?? FAIL' fallback that does not exist anywhere in the function. It now states what the code actually does, verified by running it rather than by reading it. Refs #3912 --------- Co-authored-by: sim <sim@local>
422 lines
19 KiB
TypeScript
422 lines
19 KiB
TypeScript
/**
|
|
* CLI I/O primitives — output(), error(), ERROR_REASON, JSON-error mode,
|
|
* and the temp-file helpers that output() depends on.
|
|
*
|
|
* Extracted from core.cts (ADR-857 rollout phase 1 / issue #859).
|
|
* The hand-written bodies are preserved byte-for-behaviour; only the module
|
|
* boundary moved. The core.cjs re-export spine was retired in epic #1267;
|
|
* callers import I/O primitives from io.cjs directly.
|
|
*/
|
|
|
|
import fs from 'node:fs';
|
|
import os from 'node:os';
|
|
import path from 'node:path';
|
|
import { platformWriteSync, platformEnsureDir } from './shell-command-projection.cjs';
|
|
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
|
import cliExitModule = require('./cli-exit.cjs');
|
|
const {
|
|
setJsonErrorMode, getJsonErrorMode, EXIT_ENVELOPE_REASON, ExitError,
|
|
setPendingOutcome, projectOutcome, getContractVersion,
|
|
} = cliExitModule;
|
|
|
|
// ─── Temp-file helpers (needed by output()) ──────────────────────────────────
|
|
|
|
/**
|
|
* Dedicated GSD temp directory: path.join(os.tmpdir(), 'gsd').
|
|
* Created on first use. Keeps GSD temp files isolated from the system
|
|
* temp directory so reap scans only GSD files (#1975).
|
|
*/
|
|
const GSD_TEMP_DIR = path.join(os.tmpdir(), 'gsd');
|
|
|
|
function ensureGsdTempDir(): void {
|
|
platformEnsureDir(GSD_TEMP_DIR);
|
|
}
|
|
|
|
interface ReapOptions {
|
|
maxAgeMs?: number;
|
|
dirsOnly?: boolean;
|
|
}
|
|
|
|
/**
|
|
* Remove stale gsd-* temp files/dirs older than maxAgeMs (default: 5 minutes).
|
|
* Runs opportunistically before each new temp file write to prevent unbounded accumulation.
|
|
* @param prefix - filename prefix to match (e.g., 'gsd-')
|
|
* @param opts
|
|
* @param opts.maxAgeMs - max age in ms before removal (default: 5 min)
|
|
* @param opts.dirsOnly - if true, only remove directories (default: false)
|
|
*/
|
|
function reapStaleTempFiles(prefix = 'gsd-', { maxAgeMs = 5 * 60 * 1000, dirsOnly = false }: ReapOptions = {}): void {
|
|
try {
|
|
ensureGsdTempDir();
|
|
const now = Date.now();
|
|
const entries = fs.readdirSync(GSD_TEMP_DIR);
|
|
for (const entry of entries) {
|
|
if (!entry.startsWith(prefix)) continue;
|
|
const fullPath = path.join(GSD_TEMP_DIR, entry);
|
|
try {
|
|
const stat = fs.statSync(fullPath);
|
|
if (now - stat.mtimeMs > maxAgeMs) {
|
|
if (stat.isDirectory()) {
|
|
fs.rmSync(fullPath, { recursive: true, force: true });
|
|
} else if (!dirsOnly) {
|
|
fs.unlinkSync(fullPath);
|
|
}
|
|
}
|
|
} catch {
|
|
// File may have been removed between readdir and stat — ignore
|
|
}
|
|
}
|
|
} catch {
|
|
// Non-critical — don't let cleanup failures break output
|
|
}
|
|
}
|
|
|
|
// ─── Output helpers ───────────────────────────────────────────────────────────
|
|
|
|
/**
|
|
* Transient write errnos. When stdout/stderr is a NON-BLOCKING pipe — as it is
|
|
* under the parallel `node --test` runner on Linux CI — a full pipe buffer makes
|
|
* `fs.writeSync` throw EAGAIN, and a signal can interrupt it with EINTR. Both
|
|
* clear on retry once the reader drains. This is the same transient class the
|
|
* STATE.md lock path already retries (ACQUIRE_LOCK_RETRY_ERRNOS, #3776); #1008.
|
|
*/
|
|
const WRITE_RETRY_ERRNOS = new Set(['EAGAIN', 'EINTR']);
|
|
|
|
// Bounded so a pathological never-draining fd cannot spin forever. Each retry
|
|
// yields the thread for ~1ms via Atomics.wait (the project's sync-sleep idiom —
|
|
// see clock.cts realClock.sleep), so the cap is ~1s of total back-pressure wait.
|
|
const WRITE_MAX_RETRIES = 1000;
|
|
const WRITE_RETRY_BACKOFF_MS = 1;
|
|
|
|
// Sleep buffer is lazily allocated on the FIRST back-pressure retry (rare — only
|
|
// when a non-blocking pipe is full) and then reused. Keeping it out of module
|
|
// load costs nothing on the overwhelmingly common no-retry path and avoids
|
|
// perturbing SharedArrayBuffer-allocation accounting in other modules (perf-316).
|
|
let _writeSleepBuf: Int32Array | null = null;
|
|
function backoffOnce(): void {
|
|
if (_writeSleepBuf === null) _writeSleepBuf = new Int32Array(new SharedArrayBuffer(4));
|
|
Atomics.wait(_writeSleepBuf, 0, 0, WRITE_RETRY_BACKOFF_MS);
|
|
}
|
|
|
|
/**
|
|
* Write the entire payload to `fd`, tolerating non-blocking-pipe back-pressure.
|
|
*
|
|
* `fs.writeSync` does NOT block on a non-blocking pipe: a full buffer throws
|
|
* EAGAIN, and a partially-drained buffer returns a SHORT count (fewer bytes than
|
|
* requested). The previous bare `fs.writeSync(fd, string)` call assumed it always
|
|
* blocked until the kernel accepted every byte — false under load, which both
|
|
* threw spurious errors and risked silently truncating output (#1008).
|
|
*
|
|
* This loops on short counts (advancing the offset) and retries EAGAIN/EINTR with
|
|
* a brief Atomics.wait backoff that yields the thread so the reader can drain.
|
|
* Non-transient errors (e.g. EPIPE) propagate unchanged.
|
|
*/
|
|
function writeAllSync(fd: number, data: string): void {
|
|
const buf = Buffer.from(data, 'utf8');
|
|
let offset = 0;
|
|
let retries = 0;
|
|
while (offset < buf.length) {
|
|
try {
|
|
offset += fs.writeSync(fd, buf, offset, buf.length - offset);
|
|
} catch (err) {
|
|
const code = (err as NodeJS.ErrnoException).code ?? '';
|
|
if (WRITE_RETRY_ERRNOS.has(code) && retries < WRITE_MAX_RETRIES) {
|
|
retries += 1;
|
|
backoffOnce();
|
|
continue;
|
|
}
|
|
throw err;
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* The wire form of a JSON result: the exact bytes `output()` emits for it.
|
|
*
|
|
* Exported because a caller that has to reason about the size of its own
|
|
* response — graphify's `--budget` accounting (#2738) — must measure the string
|
|
* this function produces rather than a second, privately-maintained
|
|
* serialization that can drift from it. One definition, so estimator and
|
|
* emitter cannot disagree about indentation or shape.
|
|
*
|
|
* The `@file:` redirection in `output()` is a transport detail, not a payload
|
|
* change: the caller still consumes these bytes, so these are the right ones to
|
|
* measure.
|
|
*/
|
|
function serializeForOutput(result: unknown): string {
|
|
return JSON.stringify(result, null, 2);
|
|
}
|
|
|
|
/**
|
|
* A payload-carried error, per ADR-2980's own definition (#3912, ADR-3889
|
|
* §4): `result` is an object carrying a SERIALIZABLE `error` property, in
|
|
* ANY key order — `{ found: false, error }` counts exactly the same as
|
|
* `{ error, found: false }`. The discriminator is a serializable error
|
|
* value, NOT mere key presence: `result.error`'s own truthiness is
|
|
* irrelevant (falsy `0`/`null`/`''` all count), and neither is `result`'s
|
|
* prototype (a plain object literal is all any call site here ever
|
|
* passes) — but `error: undefined` does NOT count, because
|
|
* `JSON.stringify` (the exact serializer `serializeForOutput` uses to
|
|
* build the payload the caller actually receives) drops an object
|
|
* property whose value is `undefined` entirely. A payload built as
|
|
* `{ found: false, error: undefined }` therefore reaches the wire as
|
|
* `{"found":false}` — no error at all — and recording DEGRADED for it
|
|
* would be a false verdict: exit 80 under v2 for output the user sees as
|
|
* clean. `hasOwnProperty` alone is not enough to answer "does this payload
|
|
* declare an error"; it must also survive `JSON.stringify`.
|
|
*/
|
|
function isPayloadCarriedError(result: unknown): boolean {
|
|
return typeof result === 'object' && result !== null
|
|
&& Object.prototype.hasOwnProperty.call(result, 'error')
|
|
&& (result as { error?: unknown }).error !== undefined;
|
|
}
|
|
|
|
function output(result: unknown, raw: boolean, rawValue?: unknown): void {
|
|
// #3912 (ADR-3889 §4): a payload-carried error declares DEGRADED into the
|
|
// pending-outcome cell runMain reads. This is the ONLY new thing output()
|
|
// does — it still just writes fd 1 and returns; the exit code stays
|
|
// whatever it already was under v1 (DEGRADED projects to 0), and nothing
|
|
// here touches process.exitCode directly.
|
|
//
|
|
// LAST-WRITE-WINS (review fix): a clean (non-error-shaped) payload CLEARS
|
|
// the cell rather than leaving a prior degraded declaration in place. A
|
|
// handler that calls output() more than once per invocation — a
|
|
// diagnostic error payload followed by a clean final payload — must have
|
|
// its LATEST declaration win, not its first: the cell reflects "is a
|
|
// degraded outcome pending right now", not "was one ever declared".
|
|
if (isPayloadCarriedError(result)) {
|
|
setPendingOutcome('DEGRADED');
|
|
} else {
|
|
setPendingOutcome(undefined);
|
|
}
|
|
let data: string;
|
|
if (raw && rawValue !== undefined) {
|
|
// eslint-disable-next-line @typescript-eslint/no-base-to-string
|
|
data = String(rawValue);
|
|
} else {
|
|
const json = serializeForOutput(result);
|
|
// Large payloads exceed Claude Code's Bash tool buffer (~50KB).
|
|
// Write to tmpfile and output the path prefixed with @file: so callers can detect it.
|
|
if (json.length > 50000) {
|
|
reapStaleTempFiles();
|
|
ensureGsdTempDir();
|
|
const tmpPath = path.join(GSD_TEMP_DIR, `gsd-${Date.now()}.json`);
|
|
platformWriteSync(tmpPath, json);
|
|
data = '@file:' + tmpPath;
|
|
} else {
|
|
data = json;
|
|
}
|
|
}
|
|
// process.stdout.write() is async when stdout is a pipe — process.exit()
|
|
// can tear down the process before the reader consumes the buffer. writeAllSync
|
|
// pushes every byte synchronously (looping short counts, retrying EAGAIN/EINTR),
|
|
// and skipping process.exit() lets the event loop drain naturally.
|
|
writeAllSync(1, data);
|
|
}
|
|
|
|
/**
|
|
* Frozen enum of typed reason codes used by error() for structured errors.
|
|
* Each subcommand contributes its own codes; the enum exists so tests can
|
|
* assert against typed values instead of grepping stderr (#2974).
|
|
*
|
|
* Adding a new code:
|
|
* - Pick a snake_case lowercase value (the JSON wire form)
|
|
* - Group by subsystem prefix (CONFIG_*, SDK_*, etc)
|
|
* - Pass it to error(msg, ERROR_REASON.NEW_CODE) at the call site
|
|
*/
|
|
const ERROR_REASON = Object.freeze({
|
|
// config-get / config-set
|
|
CONFIG_KEY_NOT_FOUND: 'config_key_not_found',
|
|
CONFIG_NO_FILE: 'config_no_file',
|
|
CONFIG_PARSE_FAILED: 'config_parse_failed',
|
|
CONFIG_INVALID_KEY: 'config_invalid_key',
|
|
// SDK / gsd-tools dispatch
|
|
SDK_FAIL_FAST: EXIT_ENVELOPE_REASON,
|
|
SDK_UNKNOWN_COMMAND: 'sdk_unknown_command',
|
|
SDK_MISSING_ARG: 'sdk_missing_arg',
|
|
// workflow / phase
|
|
PHASE_NOT_FOUND: 'phase_not_found',
|
|
PHASE_VERIFICATION_INCOMPLETE: 'phase_verification_incomplete',
|
|
PHASE_PLAN_COVERAGE_INCOMPLETE: 'phase_plan_coverage_incomplete',
|
|
SUMMARY_NO_PLANNING: 'summary_no_planning',
|
|
// #3579: workstream-mode fail-safe guards (init.progress, phase.complete) —
|
|
// distinguishes "no marker/pointer anywhere" from "a marker exists but
|
|
// didn't resolve" so a JSON-error-mode caller can branch on `reason`
|
|
// instead of regexing the human message.
|
|
WORKSTREAM_MODE_NONE_ACTIVE: 'workstream_mode_none_active',
|
|
WORKSTREAM_MODE_MARKER_UNRESOLVED: 'workstream_mode_marker_unresolved',
|
|
// graphify
|
|
GRAPHIFY_NO_GRAPH: 'graphify_no_graph',
|
|
GRAPHIFY_INVALID_QUERY: 'graphify_invalid_query',
|
|
// estimate-calibrate (#3882, ADR-3473 §8.2): the phases directory exists
|
|
// but could not be read — a NON-answer, distinct from a project that
|
|
// genuinely has zero completed phases yet.
|
|
ESTIMATE_PHASES_UNREADABLE: 'estimate_phases_unreadable',
|
|
// hooks
|
|
HOOKS_OPT_OUT: 'hooks_opt_out',
|
|
// commit-docs-guard (#3588)
|
|
COMMIT_DOCS_GUARD_NOT_A_REPO: 'commit_docs_guard_not_a_repo',
|
|
COMMIT_DOCS_GUARD_FOREIGN_HOOK: 'commit_docs_guard_foreign_hook',
|
|
COMMIT_DOCS_GUARD_HOOKS_PATH_SET: 'commit_docs_guard_hooks_path_set',
|
|
// security-scan
|
|
SECURITY_SCAN_FAILED: 'security_scan_failed',
|
|
// --pick (#3365 / #3358, ADR-3473 §8.4): an absent field or non-JSON
|
|
// command output is a failure, never a demotion to an empty answer at
|
|
// exit 0. See .gsd/phase/feat-3884-failure-is-a-value/40-design.md.
|
|
PICK_FIELD_ABSENT: 'pick_field_absent',
|
|
PICK_OUTPUT_NOT_JSON: 'pick_output_not_json',
|
|
// generic
|
|
USAGE: 'usage',
|
|
UNKNOWN: 'unknown',
|
|
});
|
|
|
|
type ErrorReasonValue = typeof ERROR_REASON[keyof typeof ERROR_REASON];
|
|
|
|
// setJsonErrorMode / getJsonErrorMode now live in cli-exit.cts (imported above)
|
|
// and are re-exported here for the callers that already import them from io.
|
|
|
|
/**
|
|
* Emit an error and exit. When the second argument is provided it must be
|
|
* a value from ERROR_REASON; tests can assert on `result.reason`. When the
|
|
* process is in JSON-error mode, stderr receives `{ ok: false, reason,
|
|
* message }` so callers can parse it; otherwise stderr keeps the plain
|
|
* text form for human operators.
|
|
*
|
|
* `extra` (optional) lets a caller attach additional structured fields
|
|
* (e.g. `{ verification_stale_check_indeterminate: true }`) onto the
|
|
* JSON-error-mode payload, spread alongside `ok`/`reason`/`message`, so a
|
|
* test can assert on the value directly instead of regexing `message`'s
|
|
* human-readable text. Ignored entirely in plain-text mode — the human
|
|
* message is the only thing an operator sees there.
|
|
*/
|
|
/**
|
|
* Render an UNTRUSTED string for embedding inside a human-readable,
|
|
* plain-text diagnostic (the `'Error: ' + message` line `error()` writes in
|
|
* non-JSON mode).
|
|
*
|
|
* WHY THIS EXISTS AND WHY `error()` DOES NOT DO IT ITSELF: `error()`
|
|
* deliberately writes its `message` argument verbatim — several callers in
|
|
* this repo intentionally emit multi-line diagnostics (e.g. the phase-gate
|
|
* messages), and `error()` has no way to distinguish a legitimate multi-line
|
|
* message from a hostile one, so it must not mangle newlines generically.
|
|
* That means any UNTRUSTED substring a caller interpolates into `message`
|
|
* (an argv token, a JSON key/value read back from a command's own output,
|
|
* etc.) can smuggle its own `\n` and forge a second `Error: ` line on
|
|
* stderr — a caller that parses stderr line-by-line would then see a second,
|
|
* attacker-authored error. Every call site that interpolates untrusted data
|
|
* into a diagnostic MUST pass that substring through this function first;
|
|
* `error()` itself stays a dumb, faithful writer.
|
|
*
|
|
* `JSON.stringify` is the primitive: it wraps the value in quotes and
|
|
* escapes control characters (`\n`, `\r`, `\t`, and the rest of the C0
|
|
* range, plus the quote character itself), so the result can never span
|
|
* more than one line or introduce an unescaped `"`. Callers embedding the
|
|
* result MUST NOT add their own surrounding quotes — that would
|
|
* double-quote it.
|
|
*/
|
|
function formatDiagnosticToken(value: string): string {
|
|
return JSON.stringify(value);
|
|
}
|
|
|
|
/**
|
|
* Map an ERROR_REASON wire value onto a declared outcome name (#3912,
|
|
* ADR-3889 §4). Closed over the 25-member enum: every reason gets an
|
|
* explicit entry below, so a 26th member added without a mapping falls
|
|
* through to the `?? 'FAIL'` default rather than silently mis-projecting —
|
|
* and tests/A1 iterates `Object.values(ERROR_REASON)`, so that default is
|
|
* exactly what makes an unmapped addition visible instead of invisible.
|
|
*
|
|
* This function's result is ONLY consulted under v2 (see `error()` below) —
|
|
* it is deliberately never routed through `projectOutcome` under v1, which
|
|
* is what keeps the v1 pin intact (`projectOutcome` treats registered names
|
|
* as version-invariant, so e.g. USAGE would otherwise become 64 today).
|
|
*
|
|
* Each non-FAIL choice below is justified inline; `UNKNOWN` and anything
|
|
* with no clearly better fit stays `FAIL` — the honest default the design
|
|
* calls for, not a guess dressed up as a specific outcome.
|
|
*/
|
|
const REASON_TO_OUTCOME: Readonly<Record<string, string>> = Object.freeze({
|
|
// Bad argv/subcommand/argument — the caller, not the run, is at fault.
|
|
[ERROR_REASON.CONFIG_INVALID_KEY]: 'USAGE',
|
|
[ERROR_REASON.SDK_UNKNOWN_COMMAND]: 'USAGE',
|
|
[ERROR_REASON.SDK_MISSING_ARG]: 'USAGE',
|
|
[ERROR_REASON.GRAPHIFY_INVALID_QUERY]: 'USAGE',
|
|
[ERROR_REASON.USAGE]: 'USAGE',
|
|
|
|
// A specific, named thing does not exist / nothing was there to find —
|
|
// genuine, known emptiness rather than a broken prerequisite.
|
|
[ERROR_REASON.CONFIG_KEY_NOT_FOUND]: 'NO_INPUT',
|
|
[ERROR_REASON.SUMMARY_NO_PLANNING]: 'NO_INPUT',
|
|
[ERROR_REASON.WORKSTREAM_MODE_NONE_ACTIVE]: 'NO_INPUT',
|
|
|
|
// A prerequisite is absent, unreadable, or otherwise not in a state the
|
|
// run could proceed from — distinct from NO_INPUT's genuine emptiness.
|
|
[ERROR_REASON.CONFIG_NO_FILE]: 'UNAVAILABLE',
|
|
[ERROR_REASON.CONFIG_PARSE_FAILED]: 'UNAVAILABLE',
|
|
[ERROR_REASON.PHASE_NOT_FOUND]: 'UNAVAILABLE',
|
|
[ERROR_REASON.PHASE_VERIFICATION_INCOMPLETE]: 'UNAVAILABLE',
|
|
[ERROR_REASON.PHASE_PLAN_COVERAGE_INCOMPLETE]: 'UNAVAILABLE',
|
|
// Its own docstring: "a marker exists but didn't resolve" — a broken
|
|
// prerequisite, not the "no marker anywhere" emptiness NONE_ACTIVE covers.
|
|
[ERROR_REASON.WORKSTREAM_MODE_MARKER_UNRESOLVED]: 'UNAVAILABLE',
|
|
[ERROR_REASON.GRAPHIFY_NO_GRAPH]: 'UNAVAILABLE',
|
|
// Its own docstring: "a NON-answer, distinct from a project that
|
|
// genuinely has zero completed phases yet" — UNAVAILABLE, not NO_INPUT.
|
|
[ERROR_REASON.ESTIMATE_PHASES_UNREADABLE]: 'UNAVAILABLE',
|
|
[ERROR_REASON.COMMIT_DOCS_GUARD_NOT_A_REPO]: 'UNAVAILABLE',
|
|
[ERROR_REASON.COMMIT_DOCS_GUARD_FOREIGN_HOOK]: 'UNAVAILABLE',
|
|
[ERROR_REASON.COMMIT_DOCS_GUARD_HOOKS_PATH_SET]: 'UNAVAILABLE',
|
|
// Its own docstring: "an absent field or non-JSON command output is a
|
|
// failure, never a demotion to an empty answer" — the field/output was
|
|
// supposed to be there and was not; a prerequisite of the query failed.
|
|
[ERROR_REASON.PICK_FIELD_ABSENT]: 'UNAVAILABLE',
|
|
[ERROR_REASON.PICK_OUTPUT_NOT_JSON]: 'UNAVAILABLE',
|
|
|
|
// Self-failure: the run itself broke, not its inputs.
|
|
[ERROR_REASON.SDK_FAIL_FAST]: 'INTERNAL',
|
|
[ERROR_REASON.SECURITY_SCAN_FAILED]: 'INTERNAL',
|
|
|
|
// No clearly better fit — the honest default, per design.
|
|
[ERROR_REASON.HOOKS_OPT_OUT]: 'FAIL',
|
|
[ERROR_REASON.UNKNOWN]: 'FAIL',
|
|
});
|
|
|
|
function outcomeForReason(reason: ErrorReasonValue): string {
|
|
return REASON_TO_OUTCOME[reason] ?? 'FAIL';
|
|
}
|
|
|
|
function error(message: string, reason: ErrorReasonValue = ERROR_REASON.UNKNOWN, extra?: Record<string, unknown>): never {
|
|
if (getJsonErrorMode()) {
|
|
const payload = JSON.stringify({ ok: false, reason, message, ...(extra || {}) }) + '\n';
|
|
writeAllSync(2, payload);
|
|
} else {
|
|
writeAllSync(2, 'Error: ' + message + '\n');
|
|
}
|
|
// #3912 (ADR-3889 §4): the declaration is version-gated HERE, not inside
|
|
// projectOutcome — registered names are version-invariant there, so
|
|
// routing every reason through it unconditionally would change v1 exit
|
|
// codes today (e.g. USAGE -> 64) and break the pin. Under v1 the exit
|
|
// stays ExitError(1) unconditionally, byte-identical to every prior
|
|
// release; only v2 projects the declared outcome through the registry.
|
|
if (getContractVersion() === 'v2') {
|
|
throw new ExitError(projectOutcome(outcomeForReason(reason), 'v2'));
|
|
}
|
|
// 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 = {
|
|
GSD_TEMP_DIR,
|
|
ensureGsdTempDir,
|
|
reapStaleTempFiles,
|
|
output,
|
|
serializeForOutput,
|
|
ERROR_REASON,
|
|
setJsonErrorMode,
|
|
getJsonErrorMode,
|
|
error,
|
|
formatDiagnosticToken,
|
|
};
|