* 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>
This commit is contained in:
@@ -7,6 +7,7 @@ const fs = require('fs');
|
||||
const os = require('os');
|
||||
const path = require('path');
|
||||
const { createFixture } = require('./fixtures/index.cjs');
|
||||
const processSeam = require('./helpers/process-seam.cjs');
|
||||
|
||||
const TOOLS_PATH = path.join(__dirname, '..', 'gsd-core', 'bin', 'gsd-tools.cjs');
|
||||
const TEST_ENV_BASE = {
|
||||
@@ -44,72 +45,150 @@ function runGsdTools(args, cwd = process.cwd(), env = {}) {
|
||||
: (args.match(/(?:[^\s"']+|"[^"]*"|'[^']*')+/g) || [])
|
||||
.map(t => t.replace(/"([^"]*)"/g, '$1').replace(/'([^']*)'/g, '$1'));
|
||||
|
||||
// Adapter over tests/helpers/process-seam.cjs (#3055). The seam returns a
|
||||
// typed { outcome, exitCode, stdout, stderr, timedOut, signal, killed, code }
|
||||
// result — never throws for a kill/timeout/buffer-overflow/spawn-failure.
|
||||
// This adapter is the ONLY place that retries and the ONLY place that
|
||||
// reconstructs runGsdTools's legacy { success, output, error, exitCode }
|
||||
// shape, so all 136 callers keep their existing contract byte-identically.
|
||||
//
|
||||
// `processSeam.runNode` is looked up on the module object (not destructured
|
||||
// at require time) so tests can `mock.method(processSeam, 'runNode', fn)`
|
||||
// to inject TIMED_OUT / BUFFER_OVERFLOW / SPAWN_FAILED without waiting on
|
||||
// real subprocess timers.
|
||||
function attempt() {
|
||||
// Split shell-style string into argv, stripping surrounding quotes, so we
|
||||
// can invoke execFileSync with process.execPath instead of relying on
|
||||
// `node` being on PATH (it isn't in Claude Code shell sessions).
|
||||
// Apply shell-style quote removal: strip surrounding quotes from quoted
|
||||
// sequences anywhere in a token (handles both "foo bar" and --"foo bar").
|
||||
return execFileSync(process.execPath, [TOOLS_PATH, ...argv], {
|
||||
return processSeam.runNode([TOOLS_PATH, ...argv], {
|
||||
cwd,
|
||||
encoding: 'utf-8',
|
||||
stdio: ['pipe', 'pipe', 'pipe'],
|
||||
env: childEnv,
|
||||
timeout: 60000,
|
||||
timeoutMs: 60000,
|
||||
});
|
||||
}
|
||||
|
||||
// isKilled: true when the subprocess was terminated by a signal or timed out.
|
||||
// This indicates host resource starvation (OOM, scheduler contention), NOT a
|
||||
// product assertion failure.
|
||||
function isKilled(err) {
|
||||
return err.killed || err.signal != null || err.code === 'ETIMEDOUT';
|
||||
}
|
||||
|
||||
function throwResourceStarvation(err) {
|
||||
function throwResourceStarvation(result) {
|
||||
throw new Error(
|
||||
`[runGsdTools: resource-starvation / subprocess-kill after retry] ` +
|
||||
`gsd-tools was killed before completion ` +
|
||||
`(signal=${err.signal}, code=${err.code}, killed=${err.killed}). ` +
|
||||
`(signal=${result.signal}, code=${result.code}, killed=${result.killed}). ` +
|
||||
`This indicates host OOM or scheduler contention, not a product bug. ` +
|
||||
`stdout=${err.stdout?.toString().trim() || ''} ` +
|
||||
`stderr=${err.stderr?.toString().trim() || ''}`
|
||||
`stdout=${(result.stdout || '').trim()} ` +
|
||||
`stderr=${(result.stderr || '').trim()}`
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
const result = attempt();
|
||||
return { success: true, output: result.trim(), exitCode: 0 };
|
||||
} catch (firstErr) {
|
||||
// Kill-signal discrimination (#969): transient OOM/contention usually
|
||||
// succeeds on retry; retry ONCE before surfacing the labeled error.
|
||||
if (isKilled(firstErr)) {
|
||||
try {
|
||||
const result = attempt();
|
||||
return { success: true, output: result.trim(), exitCode: 0 };
|
||||
} catch (retryErr) {
|
||||
// Still killed after retry — persistent resource starvation, throw.
|
||||
throwResourceStarvation(retryErr);
|
||||
function toLegacyShape(result) {
|
||||
if (result.outcome === processSeam.OUTCOME.EXITED) {
|
||||
if (result.exitCode === 0) {
|
||||
return { success: true, output: (result.stdout || '').trim(), exitCode: 0 };
|
||||
}
|
||||
// Clean non-zero exit (real command error, no kill signal, no spawn
|
||||
// failure): return normally. No retry, no throw — preserves existing
|
||||
// test behavior that asserts on error shape.
|
||||
const stderrRaw = (result.stderr || '').trim();
|
||||
// Prefer actual stderr content; fall back to the same "Command failed:
|
||||
// <argv0> <args...>" message Node's execFileSync used to synthesize
|
||||
// for a clean non-zero exit with no stderr (verified against this
|
||||
// runtime's child_process internals: checkExecSyncError() only builds
|
||||
// that message when `ret.error` is absent and `ret.status !== 0`, and
|
||||
// never appends stderr when it is empty). If stderr is empty, append a
|
||||
// note so CI logs show "stderr: (empty)" rather than silently losing
|
||||
// the fact that the child process produced no error output — empty
|
||||
// stderr with a non-zero exit code is a signal of OS-level crash (OOM
|
||||
// kill, worker thread fatal error) rather than a gsd-tools application
|
||||
// error.
|
||||
const commandLine = [process.execPath, TOOLS_PATH, ...argv].join(' ');
|
||||
const error = stderrRaw
|
||||
|| `Command failed: ${commandLine} [stderr: (empty) exit:${result.exitCode ?? 1}]`;
|
||||
return {
|
||||
success: false,
|
||||
output: (result.stdout || '').trim(),
|
||||
error,
|
||||
exitCode: result.exitCode ?? 1,
|
||||
};
|
||||
}
|
||||
// Clean non-zero exit (real command error, no kill signal): return normally.
|
||||
// No retry, no throw — preserves existing test behavior that asserts on
|
||||
// error shape.
|
||||
const stderrRaw = firstErr.stderr?.toString().trim() || '';
|
||||
// Prefer actual stderr content; fall back to err.message (which contains
|
||||
// the command invocation). If stderr is empty, append a note so CI logs
|
||||
// show "stderr: (empty)" rather than silently losing the fact that the
|
||||
// child process produced no error output — empty stderr with a non-zero
|
||||
// exit code is a signal of OS-level crash (OOM kill, worker thread fatal
|
||||
// error) rather than a gsd-tools application error.
|
||||
const error = stderrRaw || `${firstErr.message} [stderr: (empty) exit:${firstErr.status ?? 1}]`;
|
||||
if (result.outcome === processSeam.OUTCOME.BUFFER_OVERFLOW) {
|
||||
// Never retried. This is a DELIBERATE divergence from the old
|
||||
// execFileSync-based helper, not an oversight: the old code saw a
|
||||
// maxBuffer overflow as `err.signal === 'SIGTERM'`, which made the old
|
||||
// `isKilled(err)` true and triggered a retry. The new seam classifies
|
||||
// overflow as its own BUFFER_OVERFLOW outcome specifically so it stops
|
||||
// being conflated with a kill — the child ran fine and produced too
|
||||
// much output, so retrying wastes 60s and fails identically every
|
||||
// time.
|
||||
//
|
||||
// exitCode is coerced to 1 here — RETRACTED claim from an earlier
|
||||
// revision of this comment that it was "never coerced to exitCode:1,
|
||||
// unlike the pre-seam helper": that was wrong. A real caller
|
||||
// (tests/context-predicates-query.test.cjs) asserts
|
||||
// `typeof r.exitCode === 'number'`, matching the old code's
|
||||
// `err.status ?? 1` on every non-retried failure path. The SEAM layer
|
||||
// still reports `exitCode: null` (see toSeamResult) — that typed
|
||||
// result is where the "no numeric exit code exists" information
|
||||
// lives, discriminated via `outcome`. This LEGACY adapter's job is to
|
||||
// preserve the old numeric contract for existing callers, so it
|
||||
// coerces null to 1 here rather than propagating the seam's null.
|
||||
return {
|
||||
success: false,
|
||||
output: (result.stdout || '').trim(),
|
||||
error: `gsd-tools output exceeded the subprocess buffer limit (code=${result.code})`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
if (result.outcome === processSeam.OUTCOME.KILLED) {
|
||||
// Defensive only: the retry loop below always retries KILLED once and
|
||||
// throws throwResourceStarvation() if it is still KILLED afterward, so
|
||||
// this function is never actually invoked with a KILLED result that
|
||||
// has not already survived a retry. It is handled explicitly (instead
|
||||
// of falling into the SPAWN_FAILED catch-all below, whose message
|
||||
// would be misleading) so a KILLED result can never silently render as
|
||||
// a generic {success:false, exitCode:1}-shaped spawn failure.
|
||||
return {
|
||||
success: false,
|
||||
output: (result.stdout || '').trim(),
|
||||
error: `gsd-tools was killed by signal (signal=${result.signal}, code=${result.code})`,
|
||||
exitCode: null,
|
||||
};
|
||||
}
|
||||
// SPAWN_FAILED: the process never started (matches old behavior — ENOENT
|
||||
// and friends carry no signal, so the old `isKilled(err)` was false).
|
||||
// Never retried — retrying is pointless.
|
||||
//
|
||||
// exitCode is coerced to 1 here — same retraction as the BUFFER_OVERFLOW
|
||||
// branch above: this was previously described as "never coerced to
|
||||
// exitCode:1," which was wrong for the ADAPTER path. The old
|
||||
// execFileSync-based helper returned `err.status ?? 1` on every
|
||||
// non-retried failure, i.e. always `1` for a spawn failure, and a real
|
||||
// caller depends on `typeof exitCode === 'number'`. The SEAM's own
|
||||
// `toSeamResult` still reports `exitCode: null` for SPAWN_FAILED — that
|
||||
// typed layer is where "no numeric exit code exists" is expressed via
|
||||
// `outcome`; this legacy adapter re-applies the old numeric contract on
|
||||
// top of it.
|
||||
return {
|
||||
success: false,
|
||||
output: firstErr.stdout?.toString().trim() || '',
|
||||
error,
|
||||
exitCode: firstErr.status ?? 1,
|
||||
output: (result.stdout || '').trim(),
|
||||
error: `gsd-tools failed to spawn (code=${result.code})`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
// Kill-signal discrimination (#969): transient OOM/contention usually
|
||||
// succeeds on retry; retry ONCE before surfacing the labeled error.
|
||||
// TIMED_OUT and KILLED are retried — together they reproduce the OLD
|
||||
// execFileSync-based `isKilled(err)` semantics exactly:
|
||||
// old = err.killed || err.signal != null || err.code === 'ETIMEDOUT'
|
||||
// TIMED_OUT covers the timeout case; KILLED covers a child terminated by a
|
||||
// signal nobody in the seam sent (e.g. an external OOM kill) — the exact
|
||||
// #969 case this retry exists for. BUFFER_OVERFLOW and SPAWN_FAILED are
|
||||
// not kills and are never retried (see their branches in toLegacyShape).
|
||||
const first = attempt();
|
||||
if (first.outcome === processSeam.OUTCOME.TIMED_OUT || first.outcome === processSeam.OUTCOME.KILLED) {
|
||||
const retry = attempt();
|
||||
if (retry.outcome === processSeam.OUTCOME.TIMED_OUT || retry.outcome === processSeam.OUTCOME.KILLED) {
|
||||
// Still killed after retry — persistent resource starvation, throw.
|
||||
throwResourceStarvation(retry);
|
||||
}
|
||||
return toLegacyShape(retry);
|
||||
}
|
||||
return toLegacyShape(first);
|
||||
}
|
||||
|
||||
// Create a bare temp directory (no .planning/ structure)
|
||||
@@ -333,7 +412,11 @@ function captureConsole(fn) {
|
||||
console.error = origError;
|
||||
}
|
||||
if (threw) throw threw;
|
||||
const strip = (s) => s.replace(/\x1b\[[0-9;]*m/g, '');
|
||||
// Built via String.fromCharCode (not a literal control character in a
|
||||
// regex, which `no-control-regex` rejects) so the ESC byte itself is
|
||||
// matched at runtime — this strips real ANSI color codes, not a decoy.
|
||||
const ansiPattern = new RegExp(`${String.fromCharCode(0x1b)}\\[[0-9;]*m`, 'g');
|
||||
const strip = (s) => s.replace(ansiPattern, '');
|
||||
return {
|
||||
stdout: stdout.map(strip).join('\n'),
|
||||
stderr: stderr.map(strip).join('\n'),
|
||||
|
||||
Reference in New Issue
Block a user