* test(#3055): add the process seam and route runGsdTools through it Adds tests/helpers/process-seam.cjs — runNode/runGit/runHook over spawnSync, each returning a typed discriminated union { outcome, exitCode, stdout, stderr, timedOut, signal, killed, code }. Every call is timeout-bounded; there is no unbounded path. runGsdTools becomes an adapter over the seam. Its legacy { success, output, error, exitCode } shape and retry-once-on-kill behaviour are preserved byte-identically, so none of its 136 caller files change. Outcome discrimination was corrected against probed runtime behaviour rather than assumption: a timeout and a maxBuffer overflow are identical on both status (null) and signal (SIGTERM), and differ only by code (ETIMEDOUT vs ENOBUFS). Overflow is therefore classified before timeout. This fixes a live defect — the previous isKilled() treated an overflow as a kill, retried it for a second full 60s run, and then reported "host OOM or scheduler contention" for a child that had merely printed too much. Also widens the ESLint tests glob from tests/**/*.test.cjs to tests/**/*.cjs, which brought 31 previously unlinted shared helpers under the same rules their sibling test files already obey, and fixes the 5 violations that surfaced — including a bare npm invocation without shell:true in tests/helpers/emitted-runtime.cjs (DEFECT.WINDOWS-TEST-PORTABILITY), now routed through the existing portable runNpm helper. Refs #3051 Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * test(#3055): migrate every local spawn wrapper onto the process seam Replaces the spawn body of all 25 local runHook/runGuard/runGate definitions with a call to tests/helpers/process-seam.cjs. Each wrapper keeps its name, parameter list, return shape and post-processing (JSON parse, ANSI strip, env sanitising, field extraction) — only the spawn mechanism changes, so no test assertion moves. The 4 bash-driven wrappers use the seam's explicit `interpreter` option rather than a fourth primitive; it is explicit rather than inferred from the file extension, because guessing an interpreter from a path fails silently when a script's name does not match its shebang. Seven wrappers were previously unbounded and now carry an explicit timeout sized to what each actually runs, not the seam default. Two of those seven (gsd-write-guard, lint-docs-command-form) were absent from the issue's inventory entirely and were found by scanning after the migration. Adds the CONTEXT.md `### Process seam` glossary entry and a CONTRIBUTING.md reference section covering the three primitives, the discriminated union, and the two rules the seam enforces. Scope disclosure recorded in the phase design notes: the issue scoped three identifier names. A scan for local helpers that spawn AND return the spawn result finds 113 across 82 names, 71 of them unbounded, plus 122 unbounded direct git call sites. This change bounds 25 of those. The remaining surface is the same defect class and is NOT closed by this PR. Refs #3051 Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(#3055): classify an externally-killed child as KILLED, not EXITED Blocker found in this branch's own diff, independently confirmed by an isolated reviewer. A child killed by an external signal — a genuine bench OOM kill — makes spawnSync return { status: null, signal: 'SIGKILL' } with NO .error field. The seam's "no error implies EXITED" rule therefore classified it as a clean exit, and runGsdTools returned { success: false, exitCode: 1 } without retrying. That silently defeated the #969 kill-discrimination for precisely the case it was built for: the old isKilled() fired on `signal != null`, retried once, then threw a labelled resource-starvation error. A real OOM would have been reported as an ordinary assertion failure. Adds a fifth outcome, KILLED, for "no error but a signal is set", and makes the adapter retry on TIMED_OUT or KILLED — reproducing the old `killed || signal != null || code === 'ETIMEDOUT'` condition exactly. SPAWN_FAILED still does not retry (matching the old behaviour, where signal was null). BUFFER_OVERFLOW still does not retry, which remains a deliberate divergence: the old code retried it because signal was SIGTERM, burning a second 60s run on a child that had merely printed too much. All five outcomes verified against the live runtime rather than assumed: SIGKILL -> killed, exit 0/7 -> exited, timeout -> timed_out (ETIMEDOUT), >1MB stdout -> buffer_overflow (ENOBUFS). Refs #3051 Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(#3055): address standards-review findings on this branch Three findings from the standards axis of the review, all in this branch's own diff. The CONTEXT.md glossary entry this branch introduced was already stale on the branch's own last commit: it enumerated a 4-member OUTCOME while the code had 5, because the KILLED fix did not update it. That is precisely the drift the "module changes update Domain-terms" gate exists to catch, so the entry now lists all five and explains KILLED. api-coverage-gate-e2e compared an outcome against the raw string 'exited' rather than OUTCOME.EXITED, the only such outlier; the enum is now imported and used. A sweep for the other four outcome literals found no further comparison sites. Three call sites hand the literal bash flag '-c' to the seam's first parameter, which the JSDoc described as an absolute script path. Rather than add a fourth primitive, the contract is corrected to match reality: the parameter is renamed `target` and documented as the first argv element handed to the interpreter — normally a script path, but for an interpreter invoked with an inline program it may be that interpreter's own flag. No behaviour change. Refs #3051 Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * test(#3055): assert the cross-platform timeout contract, not the macOS one The remote runner failed on both Linux lanes (node 22 and node 24, identical) while the same tests passed locally on macOS. Two assertions encoded a platform-specific behaviour as a cross-platform guarantee. When spawnSync times out, macOS preserves the child's partial stdout/stderr; Linux discards it and returns empty strings. Verified on node v26.5.1 both ways. The seam passes through whatever spawnSync hands it and cannot manufacture output that was discarded, so the production code was correct — the tests were wrong. Both tests now assert the guarantee the seam actually makes on every platform: outcome TIMED_OUT, timedOut true, and stdout/stderr always being strings rather than undefined or a Buffer. The partial-content assertions are retained behind an explicit process.platform === 'darwin' guard so the macOS coverage is not lost, and the first test is renamed to say what it now guarantees. This is the failure mode the remote matrix exists to catch: local macOS verification would have shipped it. Refs #3051 Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(#3055): classify a failed spawn as SPAWN_FAILED, not a timeout Windows CI caught two defects the Linux matrix could not. tests/context-predicates-query.test.cjs passes a 32K-char argv value. On Windows that exceeds the argv limit and spawnSync fails with code ENAMETOOLONG, signal null, status null. The seam's fallback rule — "otherwise, status === null implies TIMED_OUT" — swallowed it, so the adapter retried a spawn that can never succeed and then threw the resource-starvation error. The old isKilled() returned false for that shape and returned an ordinary failure result. TIMED_OUT is now identified positively: code === 'ETIMEDOUT' OR signal is set. Anything else carrying an error is SPAWN_FAILED, which covers ENAMETOOLONG, E2BIG, EACCES and ENOENT alike. The signal clause is what keeps a platform whose timeout errno differs classified correctly, so the greedy catch-all is no longer needed. The second defect is a contract regression I introduced and had claimed otherwise. That same test asserts `typeof r.exitCode === 'number'`, and toLegacyShape was returning null for BUFFER_OVERFLOW and SPAWN_FAILED, so the assertion failed on type. The old code returned `err.status ?? 1` on every non-retried failure path. The adapter now returns 1 again for both, and the comment claiming "never coerced to exitCode:1, unlike the pre-seam helper" is retracted: the seam keeps the richer truth (exitCode null plus a distinct outcome), the legacy adapter keeps the old numeric contract its callers actually depend on. Verified on this host: a 4MB argv yields E2BIG -> SPAWN_FAILED; ENOENT -> SPAWN_FAILED; timeout -> TIMED_OUT; >1MB stdout -> BUFFER_OVERFLOW; SIGKILL -> KILLED; clean exit -> EXITED. Refs #3051 Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> --------- Co-authored-by: sim <sim@local> Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
227 lines
10 KiB
JavaScript
227 lines
10 KiB
JavaScript
'use strict';
|
|
|
|
/**
|
|
* Process seam — the single spawnSync-based primitive test helpers use to
|
|
* run a subprocess and get back a typed, discriminated-union result.
|
|
*
|
|
* Design contract: .gsd/phase/test-3055-process-seam-module/40-design.md
|
|
* Test matrix: .gsd/phase/test-3055-process-seam-module/50-test-matrix.md
|
|
*
|
|
* Scope (Phase 1, #3055): this module and the `runGsdTools` adapter in
|
|
* tests/helpers.cjs. The 23 local wrapper helpers are migrated in a later
|
|
* wave — they are not touched here.
|
|
*
|
|
* Why spawnSync (not execFileSync): execFileSync throws on any non-zero
|
|
* exit or spawn error, forcing every caller through try/catch to recover
|
|
* `stdout`/`stderr`/`status`. spawnSync returns all of that as data, which
|
|
* is what lets this module express a single discriminated-union return
|
|
* shape instead of a throw-shaped side channel.
|
|
*
|
|
* OUTCOME discrimination (verified empirically against this Node runtime's
|
|
* spawnSync — see PR discussion for the probe transcripts, since the
|
|
* design doc's stated error-code assumptions do not match observed
|
|
* behavior on this platform/Node version):
|
|
*
|
|
* - No `result.error` and `signal === null` -> EXITED (a clean or
|
|
* non-zero exit with no signal involved).
|
|
* - No `result.error` but `signal !== null` -> KILLED. A child terminated
|
|
* by a signal nobody in this seam sent (e.g. an external OOM killer, or
|
|
* `process.kill(pid, 'SIGKILL')` from outside) does NOT populate
|
|
* `result.error` on this runtime — verified empirically: `spawnSync`
|
|
* returns `{status: null, signal: 'SIGKILL', error: undefined}` for an
|
|
* externally-killed child. Treating that as EXITED would report
|
|
* `exitCode: null` under an EXITED outcome, an incoherent shape, and
|
|
* would silently drop the #969 kill-discrimination retry for the exact
|
|
* case it exists to catch. KILLED is reported as its own outcome so the
|
|
* `runGsdTools` adapter can retry it exactly like TIMED_OUT.
|
|
* - `result.error.code` is a buffer-overflow code (`ENOBUFS` on this
|
|
* runtime, or the `ERR_CHILD_PROCESS_STDIO_MAXBUFFER` code documented
|
|
* for the async exec()/execFile() family, accepted defensively in case
|
|
* a different Node version/platform surfaces it here) -> BUFFER_OVERFLOW.
|
|
* - `result.error.code === 'ETIMEDOUT'` OR `signal !== null` -> TIMED_OUT.
|
|
* A timeout is identified POSITIVELY now, not by elimination: on this
|
|
* runtime spawnSync's own timeout kill reports `ETIMEDOUT`, and on a
|
|
* platform whose timeout errno differs, the child is still killed by a
|
|
* signal on the way out, so `signal !== null` still catches it. This
|
|
* replaces an earlier `status === null` catch-all that was too greedy —
|
|
* it also matched a spawn that never started at all (e.g. Windows
|
|
* `ENAMETOOLONG` from an oversized argv: `status: null, signal: null`),
|
|
* misclassifying a non-retryable spawn failure as a retryable timeout
|
|
* and driving the adapter into a retry loop that could never succeed.
|
|
* - Any other populated `result.error` -> SPAWN_FAILED. This subsumes the
|
|
* `ENOENT` case (binary not found) along with every other spawn-time
|
|
* errno (`ENAMETOOLONG`, `E2BIG`, `EACCES`, `EPERM`, …) — none of them
|
|
* carry a timeout errno or a signal, so none of them satisfy the
|
|
* TIMED_OUT branch above. A dedicated `ENOENT`-only branch was dropped
|
|
* since it produced the exact same outcome as this fallback; keeping it
|
|
* would have implied ENOENT gets special handling it does not need.
|
|
*/
|
|
|
|
const { spawnSync } = require('child_process');
|
|
|
|
const DEFAULT_TIMEOUT_MS = 60000;
|
|
|
|
const OUTCOME = Object.freeze({
|
|
EXITED: 'exited',
|
|
KILLED: 'killed',
|
|
TIMED_OUT: 'timed_out',
|
|
BUFFER_OVERFLOW: 'buffer_overflow',
|
|
SPAWN_FAILED: 'spawn_failed',
|
|
});
|
|
|
|
const BUFFER_OVERFLOW_CODES = new Set(['ENOBUFS', 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER']);
|
|
|
|
/**
|
|
* Resolve and validate `timeoutMs`. `undefined` means "use the bounded
|
|
* default" and is the only valid way to get an unspecified timeout — there
|
|
* is no code path in this module that spawns without one.
|
|
*/
|
|
function resolveTimeoutMs(timeoutMs) {
|
|
if (timeoutMs === undefined) return DEFAULT_TIMEOUT_MS;
|
|
if (typeof timeoutMs !== 'number' || !Number.isFinite(timeoutMs) || timeoutMs <= 0) {
|
|
throw new TypeError(
|
|
`process-seam: timeoutMs must be a finite positive number, or omitted for the ` +
|
|
`${DEFAULT_TIMEOUT_MS}ms default; received ${String(timeoutMs)}`
|
|
);
|
|
}
|
|
return timeoutMs;
|
|
}
|
|
|
|
/**
|
|
* Classify a raw spawnSync() result into the seam's discriminated union.
|
|
*/
|
|
function toSeamResult(result) {
|
|
const { error, status, signal } = result;
|
|
const stdout = typeof result.stdout === 'string' ? result.stdout : '';
|
|
const stderr = typeof result.stderr === 'string' ? result.stderr : '';
|
|
const errorCode = error ? (error.code ?? null) : null;
|
|
|
|
let outcome;
|
|
if (!error) {
|
|
outcome = signal === null ? OUTCOME.EXITED : OUTCOME.KILLED;
|
|
} else if (BUFFER_OVERFLOW_CODES.has(errorCode)) {
|
|
outcome = OUTCOME.BUFFER_OVERFLOW;
|
|
} else if (errorCode === 'ETIMEDOUT' || signal !== null) {
|
|
outcome = OUTCOME.TIMED_OUT;
|
|
} else {
|
|
// Any other populated `result.error` — ENOENT, ENAMETOOLONG, E2BIG,
|
|
// EACCES, EPERM, etc. — is a spawn failure: the process never started
|
|
// (or started and errored in a way that carries neither a timeout
|
|
// errno nor a signal), so retrying can never succeed.
|
|
outcome = OUTCOME.SPAWN_FAILED;
|
|
}
|
|
|
|
const timedOut = outcome === OUTCOME.TIMED_OUT;
|
|
// KILLED always has signal !== null by construction (see the branch
|
|
// above), so this single check also satisfies "killed is true for both
|
|
// KILLED and TIMED_OUT" without narrowing existing behavior for the other
|
|
// outcomes (e.g. a signaled BUFFER_OVERFLOW kill).
|
|
const killed = timedOut || signal !== null;
|
|
|
|
return {
|
|
outcome,
|
|
exitCode: status,
|
|
stdout,
|
|
stderr,
|
|
timedOut,
|
|
signal: signal ?? null,
|
|
killed,
|
|
code: errorCode,
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Core seam primitive: spawn `command` with argv `args` and return the
|
|
* typed OUTCOME-discriminated result. Never throws on a child's exit code,
|
|
* a timeout, a buffer overflow, or a spawn failure — those are all data.
|
|
* Throws (TypeError) only for a seam-contract violation: a non-array
|
|
* `args`, or an invalid `timeoutMs`.
|
|
*
|
|
* @param {string} command - binary to spawn (never shell-interpreted).
|
|
* @param {string[]} args - argv array. No shell-string parsing.
|
|
* @param {object} [options]
|
|
* @param {string} [options.cwd]
|
|
* @param {object} [options.env]
|
|
* @param {string} [options.input] - stdin payload. Omit entirely to leave
|
|
* stdin unwritten-then-closed; passing `''` is a different, deliberate
|
|
* choice callers may still make, but it is never implied by omission.
|
|
* @param {number} [options.timeoutMs] - bounded; see resolveTimeoutMs.
|
|
* @param {string} [options.killSignal] - forwarded to spawnSync verbatim;
|
|
* the seam asserts nothing about which signal is used.
|
|
* @returns {{outcome:string, exitCode:number|null, stdout:string,
|
|
* stderr:string, timedOut:boolean, signal:string|null, killed:boolean,
|
|
* code:string|null}}
|
|
*/
|
|
function spawnSeam(command, args, options = {}) {
|
|
if (!Array.isArray(args)) {
|
|
throw new TypeError('process-seam: args must be an argv array, not a shell string');
|
|
}
|
|
const timeoutMs = resolveTimeoutMs(options.timeoutMs);
|
|
|
|
const spawnOptions = {
|
|
encoding: 'utf-8', // Never caller-controlled — the seam always forces string output.
|
|
timeout: timeoutMs,
|
|
};
|
|
if (options.cwd !== undefined) spawnOptions.cwd = options.cwd;
|
|
if (options.env !== undefined) spawnOptions.env = options.env;
|
|
if (options.input !== undefined) spawnOptions.input = options.input;
|
|
if (options.killSignal !== undefined) spawnOptions.killSignal = options.killSignal;
|
|
|
|
const result = spawnSync(command, args, spawnOptions);
|
|
return toSeamResult(result);
|
|
}
|
|
|
|
/**
|
|
* Run a Node script/module via the current interpreter (`process.execPath`).
|
|
* @param {string[]} args - argv passed to the spawned Node process.
|
|
* @param {object} [options] - see spawnSeam.
|
|
*/
|
|
function runNode(args, options = {}) {
|
|
return spawnSeam(process.execPath, args, options);
|
|
}
|
|
|
|
/**
|
|
* Run `git`.
|
|
* @param {string[]} args - argv passed to git.
|
|
* @param {object} [options] - see spawnSeam.
|
|
*/
|
|
function runGit(args, options = {}) {
|
|
return spawnSeam('git', args, options);
|
|
}
|
|
|
|
/**
|
|
* Run a hook script, matching how tests/read-guard.test.cjs and
|
|
* tests/workflow-guard.test.cjs invoke hooks/*.js today:
|
|
* `execFileSync(process.execPath, [HOOK_PATH, ...args], ...)`.
|
|
*
|
|
* The hook surface this seam replaces is not node-only: 4 of the 23 local
|
|
* wrappers being migrated drive `bash` guard/gate scripts directly
|
|
* (tests/execute-phase-worktree-guard.test.cjs:59,
|
|
* tests/graphify-auto-update.slow.test.cjs:248,
|
|
* tests/worktree-cleanup.test.cjs:1549, tests/worktree-safety.test.cjs:4641).
|
|
* Rather than add a fourth spawn primitive for one more binary, the target
|
|
* interpreter is a parameter here. It is EXPLICIT, never inferred from
|
|
* `target`'s extension — guessing an interpreter from a path fails silently
|
|
* on a script whose name does not match its shebang.
|
|
*
|
|
* @param {string} target - the first argv element handed to the
|
|
* interpreter. Normally an absolute path to the hook/guard/gate script
|
|
* being run. But for an interpreter invoked with an inline program (e.g.
|
|
* `bash -c '<script text>'`), this is that interpreter's own flag —
|
|
* `'-c'` — with the actual program text supplied as the first element of
|
|
* `args`, not as `target` itself.
|
|
* @param {string[]} [args] - extra argv for the hook. When `target` is an
|
|
* interpreter flag like `'-c'`, this is where the inline program text and
|
|
* its own argv go.
|
|
* @param {object} [options] - see spawnSeam.
|
|
* @param {string} [options.interpreter] - binary used to run `target`.
|
|
* Defaults to `process.execPath` (matching read-guard/workflow-guard
|
|
* today); pass `'bash'` to run a shell script instead.
|
|
*/
|
|
function runHook(target, args = [], options = {}) {
|
|
const { interpreter = process.execPath, ...spawnOptions } = options;
|
|
return spawnSeam(interpreter, [target, ...args], spawnOptions);
|
|
}
|
|
|
|
module.exports = { runNode, runGit, runHook, OUTCOME };
|