test(#3055): add the process seam so a subprocess timeout is expressible as data (#3066)

* 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:
Tom Boucher
2026-08-05 01:06:39 -04:00
committed by GitHub
parent 59b74c4e7d
commit 5fd5c81042
31 changed files with 1392 additions and 254 deletions

View File

@@ -420,6 +420,9 @@ Five-axis story decomposition discipline (**S**pike, **P**aths, **I**nterfaces,
### Clock seam
An injectable time abstraction accepted as an optional parameter by production code (`{ clock = Date } = {}`). Test code substitutes `node:test` `mock.timers` to control time deterministically without waiting for real OS scheduler events. Canonical pattern established by ADR 456 (`docs/adr/456-test-rigor-architecture.md`).
### Process seam
The single subprocess-spawning primitive test code uses (`tests/helpers/process-seam.cjs`, #3055): `runNode` / `runGit` / `runHook`, each returning one discriminated union `{ outcome, exitCode, stdout, stderr, timedOut, signal, killed, code }` where `outcome` is the frozen `OUTCOME` enum (`EXITED` / `KILLED` / `TIMED_OUT` / `BUFFER_OVERFLOW` / `SPAWN_FAILED`). Every call is timeout-bounded — there is no unbounded code path — and nothing throws for a child's exit code, kill, timeout, buffer overflow, or spawn failure; all five are data. KILLED is a child terminated by a signal the seam did not send (a genuine OOM kill): `spawnSync` reports no `error` for that case, so it must be distinguished from EXITED, and the `runGsdTools` adapter retries it exactly as the pre-seam `isKilled()` did. This is what makes `timedOut` and `signal` assertable, so a fail-open guard's degraded verdict can be tested instead of merely observing that the call did not throw. Discrimination order is forced by runtime behavior: a timeout and a maxBuffer overflow are identical on both `status` (`null`) and `signal` (`SIGTERM`) and differ only by `code` (`ETIMEDOUT` vs `ENOBUFS`), so overflow is classified first. Per-suite wrappers remain and bind fixtures (cwd, env, payload); only the spawn body delegates here. Deliberately **not** a fault-injection surface — it cannot distinguish an injected timeout from a genuine bench OOM and would retry it; injection is in-process via `deps` (#3056). `runGsdTools` is an adapter over it that preserves its own legacy `{ success, output, error, exitCode }` shape and retry-once-on-kill behavior.
### Deterministic scheduler
Test-execution model in which all timing and concurrency outcomes are fully controlled by the test (via clock seam, explicit `await` ordering, or synchronous stepping) rather than by the OS thread scheduler. Opposed to real-race tests, which are non-deterministic on loaded CI runners.

View File

@@ -373,6 +373,50 @@ const { createTempProject, createTempGitProject, createTempDir, cleanup, runGsdT
| `cleanup(tmpDir)` | Removes directory recursively | Always use in `afterEach` |
| `runGsdTools(args, cwd, env?)` | Executes gsd-tools.cjs | Testing CLI commands |
### Spawning a subprocess: use the process seam
Anything that shells out goes through `tests/helpers/process-seam.cjs` — never a hand-rolled
`spawnSync`/`execFileSync` in your suite.
```javascript
const { runNode, runGit, runHook, OUTCOME } = require('./helpers/process-seam.cjs');
const r = runHook(HOOK_PATH, [], { input: JSON.stringify(payload), timeoutMs: 5000 });
assert.equal(r.outcome, OUTCOME.EXITED);
assert.equal(r.exitCode, 0);
```
| Primitive | Spawns |
|---|---|
| `runNode(argv, opts)` | `process.execPath` |
| `runGit(argv, opts)` | `git` |
| `runHook(scriptPath, argv, opts)` | `opts.interpreter` (default `process.execPath`; pass `'bash'` for a shell script) |
`opts`: `{ cwd, env, input, timeoutMs, killSignal, interpreter }`.
Every call returns the same discriminated union — `{ outcome, exitCode, stdout, stderr, timedOut,
signal, killed, code }` — and **never throws** for a child's exit code, a timeout, a buffer
overflow, or a spawn failure. All four are data, so you assert on them:
```javascript
assert.equal(r.outcome, OUTCOME.TIMED_OUT);
assert.equal(r.timedOut, true);
```
Two rules the seam enforces for you:
- **Every call is timeout-bounded.** `timeoutMs` defaults to 60s; there is no unbounded path. An
unbounded subprocess is an indefinite hang, and it is how macOS CI silently stops reporting.
- **`outcome` distinguishes cases that look identical.** A timeout and a `maxBuffer` overflow both
report `exitCode: null` and `signal: 'SIGTERM'`, differing only in `code` (`ETIMEDOUT` vs
`ENOBUFS`). Branch on `outcome`, never on `signal`.
The seam is **not** a fault-injection surface — it cannot tell an injected timeout from a genuine
bench OOM. Inject faults in-process through a module's `deps` parameter instead.
Per-suite wrappers are still expected and encouraged: bind your fixture (cwd, env, payload) in a
local helper and delegate the spawn to the seam.
### Test Structure
```javascript

View File

@@ -351,7 +351,7 @@ export default tseslint.config(
// ── tests/**/*.test.cjs ─────────────────────────────────────────────────────
{
files: ['tests/**/*.test.cjs'],
files: ['tests/**/*.cjs'],
plugins: {
'no-only-tests': noOnlyTests,
local: localPlugin,

View File

@@ -19,9 +19,9 @@ const assert = require('node:assert/strict');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const { execFileSync } = require('node:child_process');
const { cleanup } = require('./helpers.cjs');
const { runNode, OUTCOME } = require('./helpers/process-seam.cjs');
// In-process seam for the fail-closed read-injection tests at the bottom of this
// file (#2365 review): readPhaseScope is the pure phase-scope reader behind the
// gate. Those tests monkeypatch fs rather than drive a subprocess.
@@ -51,22 +51,23 @@ function runTools(args, cwd) {
? args
: (args.match(/(?:[^\s"']+|"[^"]*"|'[^']*')+/g) || [])
.map((t) => t.replace(/"([^"]*)"/g, '$1').replace(/'([^']*)'/g, '$1'));
try {
const stdout = execFileSync(process.execPath, [TOOLS_PATH, ...argv], {
cwd,
encoding: 'utf-8',
env: { ...process.env, ...TEST_ENV_BASE },
timeout: 60000,
});
return { success: true, output: stdout.trim(), exitCode: 0, error: '' };
} catch (err) {
return {
success: false,
output: err.stdout?.toString().trim() || '',
error: err.stderr?.toString().trim() || err.message,
exitCode: err.status ?? 1,
};
const r = runNode([TOOLS_PATH, ...argv], {
cwd,
env: { ...process.env, ...TEST_ENV_BASE },
timeoutMs: 60000,
});
if (r.outcome === OUTCOME.EXITED && r.exitCode === 0) {
return { success: true, output: r.stdout.trim(), exitCode: 0, error: '' };
}
return {
success: false,
output: r.stdout.trim(),
// Non-EXITED outcomes (timeout, spawn failure, buffer overflow) never
// populate stderr, so fall back to the seam's outcome label — mirroring
// execFileSync's err.message fallback when err.stderr was empty.
error: r.stderr.trim() || `process-seam: ${r.outcome}`,
exitCode: r.exitCode ?? 1,
};
}
function makeProject(workflow) {

View File

@@ -10,8 +10,9 @@ const assert = require('node:assert/strict');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const { execFileSync, spawnSync } = require('node:child_process');
const { execFileSync } = require('node:child_process');
const { cleanup } = require('./helpers.cjs');
const { runHook } = require('./helpers/process-seam.cjs');
const ROOT = path.resolve(__dirname, '..');
const WORKFLOW = path.join(ROOT, 'gsd-core', 'workflows', 'execute-phase.md');
@@ -57,13 +58,15 @@ function commitFile(dir, name, msg) {
/** Run the extracted guard in `dir`. Never throws — returns the observed result. */
function runGuard(dir) {
const res = spawnSync('bash', ['-c', guardScript()], {
// 30s: already bounded pre-migration (unchanged) — the guard runs a handful
// of git plumbing calls (rev-parse, log, status) against a small fixture repo.
const res = runHook('-c', [guardScript()], {
interpreter: 'bash',
cwd: dir,
encoding: 'utf8',
timeout: 30_000,
timeoutMs: 30_000,
env: { ...process.env, GIT_TERMINAL_PROMPT: '0' },
});
return { status: res.status, stdout: res.stdout || '', stderr: res.stderr || '' };
return { status: res.exitCode, stdout: res.stdout || '', stderr: res.stderr || '' };
}
test('#1856: refusal names the stranded commits and the dirty tree', () => {

View File

@@ -31,6 +31,7 @@ const fs = require('node:fs');
const path = require('node:path');
const { execFileSync } = require('node:child_process');
const { createTempDir, cleanup } = require('./helpers.cjs');
const { runHook: runHookSeam } = require('./helpers/process-seam.cjs');
const HOOKS = path.join(__dirname, '..', 'hooks');
const SESSION_START = path.join(HOOKS, 'gsd-cursor-session-start.js');
@@ -49,13 +50,12 @@ const STOP_REMINDER_FRAGMENT = 'Agent stopping';
/** Run a hook script with an explicit cwd and stdin payload; return parsed stdout JSON. */
function runHook(script, { cwd, payload }) {
const stdout = execFileSync(process.execPath, [script], {
const r = runHookSeam(script, [], {
cwd,
input: typeof payload === 'string' ? payload : JSON.stringify(payload),
encoding: 'utf8',
timeout: 20000,
timeoutMs: 20000,
});
return JSON.parse(stdout || '{}');
return JSON.parse(r.stdout || '{}');
}
/** A directory containing .planning/STATE.md. */

View File

@@ -14,6 +14,7 @@ const path = require('path');
const os = require('node:os');
const { execFileSync, spawnSync } = require('child_process');
const { createTempProject, cleanup, runGsdTools, delay } = require('./helpers.cjs');
const { runHook: seamRunHook } = require('./helpers/process-seam.cjs');
const {
graphifyStatus,
@@ -249,7 +250,12 @@ describe('auto-update', () => {
const PATH = pathPrepend
? `${pathPrepend}${path.delimiter}${process.env.PATH || ''}`
: process.env.PATH || '';
return spawnSync('bash', [HOOK], {
// 30000ms: already bounded pre-migration (unchanged) — this is the `slow`
// suite and the hook itself dispatches a detached graphify rebuild that
// some tests wait on separately; the hook's own synchronous return (gate
// checks + status-file write) is fast, so 30s stays generous headroom.
const r = seamRunHook(HOOK, [], {
interpreter: 'bash',
cwd: tmpDir,
input: JSON.stringify(toolPayload),
env: {
@@ -258,9 +264,9 @@ describe('auto-update', () => {
CI: '',
...env,
},
encoding: 'utf8',
timeout: 30000,
timeoutMs: 30000,
});
return { status: r.exitCode, stdout: r.stdout, stderr: r.stderr };
}
// Wait until the detached rebuild writes a terminal status, with a generous

View File

@@ -495,7 +495,7 @@ const assert = require('node:assert/strict');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const { spawnSync } = require('node:child_process');
const { runHook: seamRunHook } = require('./helpers/process-seam.cjs');
const { cleanup } = require('./helpers.cjs');
const HOOK_PATH = path.join(__dirname, '..', 'hooks', 'gsd-update-banner.js');
@@ -653,10 +653,16 @@ describe('gsd-update-banner.js end-to-end', () => {
}
function runHook(home) {
return spawnSync(process.execPath, [HOOK_PATH], {
// 10000ms: previously UNBOUNDED (no `timeout` option passed to
// spawnSync). gsd-update-banner.js only reads a small cache file from
// disk and prints JSON — no subprocess/network work — so 10s is
// generous headroom over its sub-second worst case even on a
// contended CI runner.
const r = seamRunHook(HOOK_PATH, [], {
env: { ...process.env, HOME: home, USERPROFILE: home },
encoding: 'utf8',
timeoutMs: 10_000,
});
return { status: r.exitCode, stdout: r.stdout, stderr: r.stderr };
}
function writeCache(home, contents) {

View File

@@ -609,7 +609,7 @@ describe('readGsdState', () => {
// ─── CLAUDE_CODE_AUTO_COMPACT_WINDOW context meter (#2219) ──────────────────
describe('context meter respects CLAUDE_CODE_AUTO_COMPACT_WINDOW (#2219)', () => {
const { execFileSync } = require('node:child_process');
const { runHook: runHookSeam } = require('./helpers/process-seam.cjs');
const hookPath = path.join(__dirname, '..', 'hooks', 'gsd-statusline.js');
/**
@@ -639,17 +639,8 @@ describe('context meter respects CLAUDE_CODE_AUTO_COMPACT_WINDOW (#2219)', () =>
delete env.CLAUDE_CODE_AUTO_COMPACT_WINDOW;
}
let stdout = '';
try {
stdout = execFileSync(process.execPath, [hookPath], {
input: payload,
env,
encoding: 'utf8',
timeout: 4000,
});
} catch (e) {
stdout = e.stdout || '';
}
const r = runHookSeam(hookPath, [], { input: payload, env, timeoutMs: 4000 });
const stdout = r.stdout;
// Parse normalized used% from the statusline bar output (e.g. "60%")
// Strip ANSI escape codes then extract the percentage digit(s) before "%"
@@ -1549,7 +1540,7 @@ test('config-set statusline.show_context_tokens yes → rejected', () => {
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const { execFileSync } = require('node:child_process');
const { runHook: runHookSeam } = require('./helpers/process-seam.cjs');
const { cleanup } = require('./helpers.cjs');
const { formatTokens, contextTokenSuffix } = require('../hooks/gsd-statusline.js');
const { VALID_CONFIG_KEYS } = require('../gsd-core/bin/lib/config-schema.cjs');
@@ -1639,16 +1630,9 @@ test('config-set statusline.show_context_tokens yes → rejected', () => {
},
},
});
let stdout = '';
try {
stdout = execFileSync(process.execPath, [hookPath], {
input: payload, encoding: 'utf8', timeout: 4000,
});
} catch (e) {
stdout = e.stdout || '';
}
const r = runHookSeam(hookPath, [], { input: payload, timeoutMs: 4000 });
// eslint-disable-next-line no-control-regex -- stripping ANSI SGR sequences from captured CLI output
return stdout.replace(/\x1b\[[0-9;]*m/g, '');
return r.stdout.replace(/\x1b\[[0-9;]*m/g, '');
}
test('flag=true appends the token count after the percentage', () => {
@@ -1986,6 +1970,7 @@ test('config-set statusline.show_context_tokens yes → rejected', () => {
const os = require('node:os');
const path = require('node:path');
const { execFileSync } = require('node:child_process');
const { runHook: runHookSeam } = require('./helpers/process-seam.cjs');
const { cleanup } = require('./helpers.cjs');
const statusline = require('../hooks/gsd-statusline.js');
const { parseGitStatus, buildGitSegment, readGitStatus, composeStatusline } = statusline;
@@ -2210,16 +2195,9 @@ test('config-set statusline.show_context_tokens yes → rejected', () => {
workspace: { current_dir: dir },
session_id: `test-git-${Date.now()}-${Math.random().toString(36).slice(2)}`,
});
let stdout = '';
try {
stdout = execFileSync(process.execPath, [hookPath], {
input: payload, encoding: 'utf8', timeout: 4000,
});
} catch (e) {
stdout = e.stdout || '';
}
const r = runHookSeam(hookPath, [], { input: payload, timeoutMs: 4000 });
// eslint-disable-next-line no-control-regex -- stripping ANSI SGR sequences from captured CLI output
return stdout.replace(/\x1b\[[0-9;]*m/g, '');
return r.stdout.replace(/\x1b\[[0-9;]*m/g, '');
}
test('flag=true renders the branch segment', () => {

View File

@@ -26,8 +26,8 @@ const { describe, test, before, after } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const { spawnSync } = require('node:child_process');
const { createTempDir, cleanup } = require('./helpers.cjs');
const { runHook: runHookSeam } = require('./helpers/process-seam.cjs');
const HOOK_PATH = path.join(__dirname, '..', 'hooks', 'gsd-write-guard.js');
@@ -35,16 +35,25 @@ const HOOK_PATH = path.join(__dirname, '..', 'hooks', 'gsd-write-guard.js');
* Run the hook with a given payload. The override env var is stripped by
* default so an outer environment can never leak a bypass into the tests;
* pass extraEnv to set it explicitly.
*
* Returns an object shaped like the raw spawnSync() result (status/stdout/
* stderr) because every call site in this file was written against that
* shape; the seam itself returns exitCode, not status, so it is mapped here.
* 10_000ms: gsd-write-guard.js does no subprocess work of its own (pure
* fs reads + JSON, no execFileSync/spawnSync inside the hook) — generous
* headroom over the fs-bound workload without matching the 30_000ms figure
* sibling suites use for guards that shell out to git.
*/
function runHook(payload, extraEnv = {}) {
const env = { ...process.env };
delete env.GSD_ALLOW_PLANNING_SHRINK;
Object.assign(env, extraEnv);
return spawnSync(process.execPath, [HOOK_PATH], {
const r = runHookSeam(HOOK_PATH, [], {
input: typeof payload === 'string' ? payload : JSON.stringify(payload),
encoding: 'utf8',
env,
timeoutMs: 10_000,
});
return { status: r.exitCode, stdout: r.stdout, stderr: r.stderr };
}
function lines(n, tag = 'line') {

View File

@@ -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'),

View File

@@ -40,8 +40,6 @@
const path = require('node:path');
const REPO_ROOT = path.join(__dirname, '..', '..');
const { cleanup } = require('../helpers.cjs');
const { MANIFEST_FAMILIES, runMinimalInstall, buildParityManifest } = require('./install-shared.cjs');

View File

@@ -36,7 +36,7 @@ const path = require('node:path');
const crypto = require('node:crypto');
const { execFileSync } = require('node:child_process');
const { cleanup } = require('../helpers.cjs');
const { cleanup, runNpm } = require('../helpers.cjs');
const {
MANIFEST_FAMILIES,
MINIMUM_MANIFEST_FAMILIES,
@@ -689,8 +689,8 @@ function buildBaselineAtRef(ref, { cwd = REPO_ROOT } = {}) {
fs.symlinkSync(sharedNodeModules, path.join(worktreeDir, 'node_modules'), 'dir');
}
execFileSync('npm', ['run', 'build:lib'], {
cwd: worktreeDir, encoding: 'utf8', timeout: BUILD_LIB_TIMEOUT_MS, stdio: ['ignore', 'pipe', 'pipe'],
runNpm(['run', 'build:lib'], {
cwd: worktreeDir, timeout: BUILD_LIB_TIMEOUT_MS, stdio: ['ignore', 'pipe', 'pipe'],
});
// Run `cwd`'s OWN generator (not the worktree's — see the function doc for why),

View File

@@ -205,9 +205,11 @@ const EXCLUDED_PREFIXES = ['gsd-core/bin/lib/'];
// ─── Helper functions ─────────────────────────────────────────────────────────
function stripAnsi(str) {
const ANSI_ESCAPE = String.fromCharCode(27);
const ANSI_SGR_RE = new RegExp(`${ANSI_ESCAPE}\\[[0-9;]*m`, 'g');
return str.replace(/\x1b\[[0-9;]*m/g, '');
function stripAnsi(str) {
return str.replace(ANSI_SGR_RE, '');
}
// A version string can itself contain regex metacharacters (`.`, and — via

View File

@@ -0,0 +1,226 @@
'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 };

View File

@@ -37,22 +37,13 @@ process.env.GSD_TEST_MODE = '1';
const { describe, test } = require('node:test');
const assert = require('node:assert/strict');
const path = require('node:path');
const { execFileSync } = require('node:child_process');
const { runHook: runHookSeam } = require('./helpers/process-seam.cjs');
const HOOK_PATH = path.join(__dirname, '..', 'hooks', 'gsd-prompt-guard.js');
function runHook(payload, timeoutMs = 5000) {
try {
const stdout = execFileSync(process.execPath, [HOOK_PATH], {
input: JSON.stringify(payload),
encoding: 'utf-8',
timeout: timeoutMs,
stdio: ['pipe', 'pipe', 'pipe'],
});
return { exitCode: 0, stdout: (stdout || '').trim() };
} catch (err) {
return { exitCode: err.status ?? 1, stdout: (err.stdout || '').toString().trim() };
}
const r = runHookSeam(HOOK_PATH, [], { input: JSON.stringify(payload), timeoutMs });
return { exitCode: r.exitCode ?? 1, stdout: r.stdout.trim() };
}
// The guard only scans writes landing in .planning/ (agent context files).

View File

@@ -10,10 +10,11 @@
const { describe, test } = require('node:test');
const assert = require('node:assert/strict');
const { spawnSync, execFileSync } = require('node:child_process');
const { execFileSync } = require('node:child_process');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const { runNode } = require('./helpers/process-seam.cjs');
const GUARD_SCRIPT = path.resolve(__dirname, '..', 'scripts', 'lint-docs-command-form.cjs');
@@ -43,12 +44,21 @@ function cleanup(dir) {
fs.rmSync(dir, { recursive: true, force: true });
}
/**
* Returns an object shaped like the raw spawnSync() result (status/stdout/
* stderr) because every call site in this file was written against that
* shape; the seam itself returns exitCode, not status, so it is mapped here.
* 30_000ms: matches the sibling-suite default for guard scripts that shell
* out to git (the guard runs `git ls-files` over the fixture repo), which
* is comparable workload to this script's own `git ls-files` invocation.
*/
function runGuard(cwd) {
return spawnSync(process.execPath, [GUARD_SCRIPT], {
const r = runNode([GUARD_SCRIPT], {
cwd,
encoding: 'utf8',
env: { ...process.env, GSD_LINT_DOCS_COMMAND_FORM_REPO_ROOT: cwd },
timeoutMs: 30_000,
});
return { status: r.exitCode, stdout: r.stdout, stderr: r.stderr };
}
describe('lint-docs-command-form — colon slash form flagged', () => {

View File

@@ -9,13 +9,25 @@
const { describe, test } = require('node:test');
const assert = require('node:assert/strict');
const { spawnSync, execFileSync } = require('node:child_process');
const { execFileSync } = require('node:child_process');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const { runNode } = require('./helpers/process-seam.cjs');
const GUARD_SCRIPT = path.resolve(__dirname, '..', 'scripts', 'lint-legacy-dir-name.cjs');
// The guard itself does trivial work here (git ls-files against a 1-2 file
// fixture repo, then a per-line regex scan), but it shells out to `git` as a
// real subprocess and this call previously had NO timeout at all (unbounded
// spawnSync). The seam requires an explicit bound, so pick one generous
// enough to absorb a slow/contended CI runner's process-spawn and git-init
// overhead without masking a genuine hang: 30s, matching the timeout this
// suite already uses for the sibling check-npm-integrity.cjs script
// invocation in tests/npm-integrity-gate.test.cjs (also a small-fixture,
// single-subprocess CLI script).
const GUARD_TIMEOUT_MS = 30_000;
function createTempRepo() {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-lint-legacy-test-'));
execFileSync('git', ['init', '--initial-branch=main'], { cwd: dir });
@@ -48,11 +60,12 @@ function runGuard(cwd) {
// Simpler: run as a child process with the --cwd trick is not available for
// scripts. Instead we pass the fixture dir path as an env var that the guard
// can use to override REPO_ROOT when present.
return spawnSync(process.execPath, [GUARD_SCRIPT], {
const r = runNode([GUARD_SCRIPT], {
cwd,
encoding: 'utf8',
env: { ...process.env, GSD_LINT_LEGACY_REPO_ROOT: cwd },
timeoutMs: GUARD_TIMEOUT_MS,
});
return { status: r.exitCode, stdout: r.stdout, stderr: r.stderr };
}
// ---------------------------------------------------------------------------

View File

@@ -22,6 +22,7 @@ const { describe, test } = require('node:test');
const assert = require('node:assert/strict');
const { spawnSync } = require('node:child_process');
const path = require('node:path');
const { runNode } = require('./helpers/process-seam.cjs');
const ROOT = path.resolve(__dirname, '..');
const SCRIPT = path.join(ROOT, 'scripts', 'check-npm-integrity.cjs');
@@ -36,15 +37,11 @@ const FIXTURES = path.join(__dirname, 'fixtures', 'npm-integrity');
*/
function runGate(fixtureName, extraArgs = []) {
const fixtureDir = path.join(FIXTURES, fixtureName);
const result = spawnSync(process.execPath, [SCRIPT, ...extraArgs], {
cwd: fixtureDir,
encoding: 'utf-8',
timeout: 30_000,
});
const r = runNode([SCRIPT, ...extraArgs], { cwd: fixtureDir, timeoutMs: 30_000 });
return {
status: result.status ?? 1,
stdout: result.stdout ?? '',
stderr: result.stderr ?? '',
status: r.exitCode ?? 1,
stdout: r.stdout,
stderr: r.stderr,
};
}

View File

@@ -321,6 +321,7 @@ const fs = require('node:fs');
const path = require('node:path');
const os = require('node:os');
const { spawnSync } = require('node:child_process');
const { runHook: runHookSeam } = require('./helpers/process-seam.cjs');
const { cleanup, delay } = require('./helpers.cjs');
const HOOK_PATH = path.resolve(__dirname, '..', 'hooks', 'gsd-context-monitor.js');
@@ -366,14 +367,13 @@ function runHook(sessionId, remainingPct, cwd) {
hook_event_name: 'PostToolUse',
});
const result = spawnSync(process.execPath, [HOOK_PATH], {
const result = runHookSeam(HOOK_PATH, [], {
input,
encoding: 'utf-8',
timeout: 10000,
timeoutMs: 10000,
env: { ...process.env, HOME: process.env.HOME },
});
return { exitCode: result.status, stdout: result.stdout, stderr: result.stderr };
return { exitCode: result.exitCode, stdout: result.stdout, stderr: result.stderr };
}
/**

779
tests/process-seam.test.cjs Normal file
View File

@@ -0,0 +1,779 @@
'use strict';
/**
* Tests for tests/helpers/process-seam.cjs (the spawnSync-based subprocess
* seam) and its runGsdTools adapter in tests/helpers.cjs.
*
* Contract: .gsd/phase/test-3055-process-seam-module/40-design.md
* Matrix: .gsd/phase/test-3055-process-seam-module/50-test-matrix.md
*
* Rows 1-24 exercise the seam directly. Rows 25-35 exercise the
* `runGsdTools` adapter's contract-parity guarantee for its 136 callers.
*
* Assertions are on typed fields only (outcome/exitCode/timedOut/signal/
* killed/code) or on structured JSON a fixture prints to stdout — never on
* raw stdout/stderr text via .includes()/assert.match(), per CONTRIBUTING
* "Prohibited: Raw Text Matching on Test Outputs".
*/
const { test, describe, beforeEach, afterEach } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const { spawnSync } = require('node:child_process');
const { createTempDir, cleanup, runGsdTools, TOOLS_PATH } = require('./helpers.cjs');
const processSeam = require('./helpers/process-seam.cjs');
const { runNode, runGit, runHook, OUTCOME } = processSeam;
// ---- fixture sources -------------------------------------------------
// argv: [exitCode?, stdoutPayload?, stderrPayload?]
const FIXTURE_EXIT = [
"const code = Number(process.argv[2] || '0');",
'const stdoutPayload = process.argv[3];',
'const stderrPayload = process.argv[4];',
"if (stdoutPayload) console.log(stdoutPayload);",
"if (stderrPayload) console.error(stderrPayload);",
'process.exitCode = code;',
].join('\n');
// argv: [sleepMs, stdoutMarker?, stderrMarker?] — writes markers via a
// synchronous fd write (never buffered console.log) so partial output
// survives a kill even when the child never reaches a clean exit.
const FIXTURE_SLEEPER = [
"const fs = require('fs');",
"const sleepMs = Number(process.argv[2] || '0');",
'const stdoutMarker = process.argv[3];',
'const stderrMarker = process.argv[4];',
"if (stdoutMarker) fs.writeSync(1, stdoutMarker + '\\n');",
"if (stderrMarker) fs.writeSync(2, stderrMarker + '\\n');",
'setTimeout(() => {}, sleepMs);',
].join('\n');
// Echoes received argv back as JSON — proves argv arrives literal/unmodified.
const FIXTURE_ECHO_ARGV = [
'console.log(JSON.stringify({ argv: process.argv.slice(2) }));',
].join('\n');
// Echoes stdin back as JSON.
const FIXTURE_ECHO_STDIN = [
"let data = '';",
"process.stdin.on('data', (chunk) => { data += chunk; });",
"process.stdin.on('end', () => {",
' console.log(JSON.stringify({ received: data, hadData: data.length > 0 }));',
'});',
].join('\n');
// Kills its own process with SIGKILL — simulates an external kill (OOM
// killer, `process.kill(pid, 'SIGKILL')` from outside) that spawnSync does
// NOT populate `result.error` for on this runtime.
const FIXTURE_SUICIDE = [
"process.kill(process.pid, 'SIGKILL');",
'setTimeout(() => {}, 5000);',
].join('\n');
// argv: [exitCode?] — writes well past the 1MB default maxBuffer, then
// attempts a clean exit with exitCode (which the overflow kill preempts).
const FIXTURE_OVERFLOW = [
"const exitCode = Number(process.argv[2] || '0');",
'process.exitCode = exitCode;',
'for (let i = 0; i < 300; i += 1) {',
" process.stdout.write('x'.repeat(10000));",
'}',
].join('\n');
const BUFFER_OVERFLOW_CODES = ['ENOBUFS', 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER'];
function writeFixture(dir, name, source) {
const fixturePath = path.join(dir, name);
fs.writeFileSync(fixturePath, source);
return fixturePath;
}
/**
* Monkeypatch processSeam.runNode for the duration of `block`, restoring the
* original in `finally`. Standalone helper (no test-context access), per
* CONTRIBUTING's try/finally carve-out and the CLAUDE.md IO-fault-injection
* pattern (save original, override, restore in finally).
*/
function withMockedRunNode(impl, block) {
const original = processSeam.runNode;
let callCount = 0;
processSeam.runNode = (...args) => {
callCount += 1;
return impl(callCount, ...args);
};
try {
block(() => callCount);
} finally {
processSeam.runNode = original;
}
}
describe('process-seam', () => {
let tmpDir;
beforeEach(() => {
tmpDir = createTempDir('process-seam-');
});
afterEach(() => {
cleanup(tmpDir);
});
test('exit 0 reports EXITED with the child stdout', () => {
const fixture = writeFixture(tmpDir, 'exit.cjs', FIXTURE_EXIT);
const result = runNode([fixture, '0', JSON.stringify({ ok: true })]);
assert.equal(result.outcome, OUTCOME.EXITED);
assert.equal(result.exitCode, 0);
assert.equal(result.timedOut, false);
assert.equal(result.signal, null);
assert.equal(result.killed, false);
assert.equal(result.code, null);
assert.equal(typeof result.stdout, 'string');
assert.deepStrictEqual(JSON.parse(result.stdout.trim()), { ok: true });
});
test('non-zero exit is EXITED, not a failure-to-run', () => {
const fixture = writeFixture(tmpDir, 'exit.cjs', FIXTURE_EXIT);
const result = runNode([fixture, '5', '', 'boom']);
assert.equal(result.outcome, OUTCOME.EXITED);
assert.equal(result.exitCode, 5);
assert.equal(result.timedOut, false);
assert.ok(result.stderr.length > 0);
});
test('empty stderr with non-zero exit keeps exitCode', () => {
const fixture = writeFixture(tmpDir, 'exit.cjs', FIXTURE_EXIT);
const result = runNode([fixture, '9']);
assert.equal(result.outcome, OUTCOME.EXITED);
assert.equal(result.exitCode, 9);
assert.equal(result.stderr, '');
assert.notEqual(result.code, undefined);
assert.equal(result.code, null);
});
test('a child that overruns is TIMED_OUT as data, not a throw', () => {
const fixture = writeFixture(tmpDir, 'sleeper.cjs', FIXTURE_SLEEPER);
const result = runNode([fixture, '5000'], { timeoutMs: 300 });
assert.equal(result.outcome, OUTCOME.TIMED_OUT);
assert.equal(result.timedOut, true);
assert.equal(result.killed, true);
assert.equal(result.exitCode, null);
});
test('timedOut does not depend on signal presence (Windows)', () => {
const fixture = writeFixture(tmpDir, 'sleeper.cjs', FIXTURE_SLEEPER);
const result = runNode([fixture, '5000'], { timeoutMs: 300 });
// The assertion below is intentionally the whole point of this test: it
// proves timedOut alone, without ever branching on result.signal. See
// 40-design.md row 6 — signal is null on Windows and must not be
// load-bearing for this flag.
assert.equal(result.timedOut, true);
});
test('a timeout still returns string stdout/stderr (partial content is platform-dependent)', () => {
const fixture = writeFixture(tmpDir, 'sleeper.cjs', FIXTURE_SLEEPER);
const marker = JSON.stringify({ partial: true });
const result = runNode([fixture, '5000', marker], { timeoutMs: 300 });
assert.equal(result.outcome, OUTCOME.TIMED_OUT);
assert.equal(result.timedOut, true);
assert.equal(typeof result.stdout, 'string');
assert.equal(typeof result.stderr, 'string');
// spawnSync preserves partial child output on a timeout on darwin, but discards
// it on Linux (verified on node 22 and 24). The seam passes through whatever
// spawnSync gives it, so the cross-platform contract is only that these are
// strings — the partial content itself is asserted where it is actually available.
if (process.platform === 'darwin') {
assert.ok(result.stdout.length > 0, 'darwin preserves partial stdout on timeout');
assert.deepStrictEqual(JSON.parse(result.stdout.trim()), { partial: true });
}
});
test('maxBuffer overflow is not misreported as exit 1', () => {
const fixture = writeFixture(tmpDir, 'overflow.cjs', FIXTURE_OVERFLOW);
const result = runNode([fixture, '0']);
assert.equal(result.outcome, OUTCOME.BUFFER_OVERFLOW);
assert.notEqual(result.exitCode, 1);
assert.equal(result.exitCode, null);
assert.ok(BUFFER_OVERFLOW_CODES.includes(result.code));
});
test('a missing binary is SPAWN_FAILED, not a timeout', () => {
// git exists on the test host; a nonexistent cwd makes the OS-level
// spawn itself fail with ENOENT (uv_spawn), the same failure class as a
// missing binary, without requiring the seam to expose a raw command
// parameter callers could point at an arbitrary executable name.
const result = runGit(['status'], { cwd: path.join(tmpDir, 'does-not-exist') });
assert.equal(result.outcome, OUTCOME.SPAWN_FAILED);
assert.equal(result.code, 'ENOENT');
assert.equal(result.exitCode, null);
assert.equal(result.timedOut, false);
});
// Regression for the Windows CI failure on PR #3066: a `status === null`
// catch-all previously misclassified this as TIMED_OUT (the process never
// even started), which drove the adapter into a pointless retry. An
// oversized argv errors at the OS spawn boundary before the child exists
// at all — E2BIG on Linux/macOS, ENAMETOOLONG on Windows — and must
// classify as SPAWN_FAILED regardless of which errno the platform uses.
test('an oversized argv is SPAWN_FAILED, not TIMED_OUT, cross-platform', () => {
const fixture = writeFixture(tmpDir, 'echo-argv.cjs', FIXTURE_ECHO_ARGV);
const oversizedArg = 'x'.repeat(4 * 1024 * 1024);
const result = runNode([fixture, oversizedArg]);
assert.equal(result.outcome, OUTCOME.SPAWN_FAILED);
assert.equal(result.timedOut, false);
assert.equal(typeof result.code, 'string');
assert.ok(result.code.length > 0);
});
test('omitting timeoutMs still bounds the call', () => {
const fixture = writeFixture(tmpDir, 'exit.cjs', FIXTURE_EXIT);
const withDefault = runNode([fixture, '0']);
const withExplicitDefault = runNode([fixture, '0'], { timeoutMs: 60000 });
// Omitting timeoutMs must resolve to the same bounded code path as
// explicitly passing the documented default — never a distinct
// "unbounded" branch.
assert.deepStrictEqual(
{ outcome: withDefault.outcome, exitCode: withDefault.exitCode, timedOut: withDefault.timedOut },
{ outcome: withExplicitDefault.outcome, exitCode: withExplicitDefault.exitCode, timedOut: withExplicitDefault.timedOut }
);
});
test('child finishing just under the bound is EXITED', () => {
const fixture = writeFixture(tmpDir, 'sleeper.cjs', FIXTURE_SLEEPER);
const result = runNode([fixture, '50'], { timeoutMs: 5000 });
assert.equal(result.outcome, OUTCOME.EXITED);
assert.equal(result.timedOut, false);
});
test('at-the-bound child yields one deterministic outcome', () => {
const fixture = writeFixture(tmpDir, 'sleeper.cjs', FIXTURE_SLEEPER);
const result = runNode([fixture, '300'], { timeoutMs: 300 });
// Either outcome is acceptable at the exact bound (OS/scheduler
// jitter decides which side of the race wins) — what must never happen
// is an outcome outside the pair, or fields inconsistent with whichever
// branch fired. This is the non-flaky formulation of "at the limit".
assert.ok([OUTCOME.EXITED, OUTCOME.TIMED_OUT].includes(result.outcome));
if (result.outcome === OUTCOME.EXITED) {
assert.equal(result.timedOut, false);
assert.notEqual(result.exitCode, null);
} else {
assert.equal(result.timedOut, true);
assert.equal(result.exitCode, null);
}
});
test('child overrunning the bound is TIMED_OUT', () => {
const fixture = writeFixture(tmpDir, 'sleeper.cjs', FIXTURE_SLEEPER);
const result = runNode([fixture, '5000'], { timeoutMs: 200 });
assert.equal(result.outcome, OUTCOME.TIMED_OUT);
});
test('invalid timeoutMs is rejected, not coerced to unbounded', () => {
const fixture = writeFixture(tmpDir, 'exit.cjs', FIXTURE_EXIT);
for (const invalid of [0, -5, NaN, 'abc', Infinity]) {
assert.throws(() => runNode([fixture, '0'], { timeoutMs: invalid }), TypeError);
}
});
test('input is delivered to the child on stdin', () => {
const fixture = writeFixture(tmpDir, 'echo-stdin.cjs', FIXTURE_ECHO_STDIN);
const result = runNode([fixture], { input: 'hello-stdin' });
assert.equal(result.outcome, OUTCOME.EXITED);
assert.deepStrictEqual(JSON.parse(result.stdout.trim()), {
received: 'hello-stdin',
hadData: true,
});
});
test('omitted input does not close stdin as empty string', () => {
const fixture = writeFixture(tmpDir, 'echo-stdin.cjs', FIXTURE_ECHO_STDIN);
const result = runNode([fixture]);
assert.equal(result.outcome, OUTCOME.EXITED);
assert.deepStrictEqual(JSON.parse(result.stdout.trim()), {
received: '',
hadData: false,
});
});
test('caller cannot override encoding into Buffers', () => {
const fixture = writeFixture(tmpDir, 'exit.cjs', FIXTURE_EXIT);
const result = runNode([fixture, '0', 'marker'], { encoding: 'buffer' });
assert.equal(typeof result.stdout, 'string');
assert.equal(Buffer.isBuffer(result.stdout), false);
});
test('argv metacharacters are not interpreted by a shell', () => {
const fixture = writeFixture(tmpDir, 'echo-argv.cjs', FIXTURE_ECHO_ARGV);
const hostileArgv = [';', '&&', '$(ls)', '`ls`', '| cat', '> /tmp/x'];
const result = runNode([fixture, ...hostileArgv]);
assert.equal(result.outcome, OUTCOME.EXITED);
assert.deepStrictEqual(JSON.parse(result.stdout.trim()).argv, hostileArgv);
});
test('flag-shaped argv values are not re-parsed', () => {
const fixture = writeFixture(tmpDir, 'echo-argv.cjs', FIXTURE_ECHO_ARGV);
const flagLikeArgv = ['--weird', '--timeoutMs=1', '-x'];
const result = runNode([fixture, ...flagLikeArgv]);
assert.deepStrictEqual(JSON.parse(result.stdout.trim()).argv, flagLikeArgv);
});
test('long and unicode argv survive the seam', () => {
const fixture = writeFixture(tmpDir, 'echo-argv.cjs', FIXTURE_ECHO_ARGV);
const longArgv = ['x'.repeat(5000), '日本語テスト', '🚀emoji🚀', 'café'];
const result = runNode([fixture, ...longArgv]);
assert.deepStrictEqual(JSON.parse(result.stdout.trim()).argv, longArgv);
});
test('a custom killSignal is reported, not normalized', () => {
const fixture = writeFixture(tmpDir, 'sleeper.cjs', FIXTURE_SLEEPER);
const result = runNode([fixture, '5000'], { timeoutMs: 200, killSignal: 'SIGINT' });
assert.equal(result.outcome, OUTCOME.TIMED_OUT);
if (process.platform !== 'win32') {
assert.equal(result.signal, 'SIGINT');
}
});
test('timeout with stderr reports one outcome, keeps both fields', () => {
const fixture = writeFixture(tmpDir, 'sleeper.cjs', FIXTURE_SLEEPER);
const result = runNode([fixture, '5000', '', 'err-marker'], { timeoutMs: 300 });
assert.equal(result.outcome, OUTCOME.TIMED_OUT);
assert.equal(typeof result.stdout, 'string');
assert.equal(typeof result.stderr, 'string');
// spawnSync preserves partial child output on a timeout on darwin, but discards
// it on Linux (verified on node 22 and 24). The seam passes through whatever
// spawnSync gives it, so the cross-platform contract is only that these are
// strings — the partial content itself is asserted where it is actually available.
if (process.platform === 'darwin') {
assert.ok(result.stderr.length > 0, 'darwin preserves partial stderr on timeout');
}
});
test('overflow is not masked by an exit code', () => {
const fixture = writeFixture(tmpDir, 'overflow.cjs', FIXTURE_OVERFLOW);
const result = runNode([fixture, '7']);
assert.equal(result.outcome, OUTCOME.BUFFER_OVERFLOW);
assert.equal(result.exitCode, null);
});
test('consecutive timeouts do not share state', () => {
const fixture = writeFixture(tmpDir, 'sleeper.cjs', FIXTURE_SLEEPER);
const first = runNode([fixture, '5000'], { timeoutMs: 200 });
const second = runNode([fixture, '5000'], { timeoutMs: 200 });
assert.equal(first.outcome, OUTCOME.TIMED_OUT);
assert.equal(second.outcome, OUTCOME.TIMED_OUT);
});
test('OUTCOME enum keys are locked', () => {
assert.equal(Object.isFrozen(OUTCOME), true);
assert.deepStrictEqual(Object.keys(OUTCOME).sort(), [
'BUFFER_OVERFLOW',
'EXITED',
'KILLED',
'SPAWN_FAILED',
'TIMED_OUT',
]);
assert.deepStrictEqual(OUTCOME, {
EXITED: 'exited',
KILLED: 'killed',
TIMED_OUT: 'timed_out',
BUFFER_OVERFLOW: 'buffer_overflow',
SPAWN_FAILED: 'spawn_failed',
});
assert.throws(() => {
OUTCOME.EXITED = 'nope';
}, TypeError);
});
test('a child killed by an external signal is KILLED, not EXITED', (t) => {
if (process.platform === 'win32') {
t.skip('signal semantics differ on win32 — see design doc row on Windows signals');
return;
}
const fixture = writeFixture(tmpDir, 'suicide.cjs', FIXTURE_SUICIDE);
const result = runNode([fixture], { timeoutMs: 5000 });
assert.equal(result.outcome, OUTCOME.KILLED);
assert.equal(result.killed, true);
assert.equal(result.timedOut, false);
assert.equal(result.signal, 'SIGKILL');
assert.equal(result.exitCode, null);
});
// Smoke coverage for runHook's export (matches the invocation shape used by
// tests/read-guard.test.cjs:34 and tests/workflow-guard.test.cjs:28 —
// process.execPath + [HOOK_PATH, ...args] with a JSON stdin payload).
test('runHook invokes a real hook via process.execPath', () => {
const hookPath = path.join(__dirname, '..', 'hooks', 'gsd-read-guard.js');
const payload = JSON.stringify({ tool_name: 'Read', tool_input: {} });
const env = {
...process.env,
CLAUDE_SESSION_ID: '',
CLAUDECODE: '',
CLAUDE_CODE_ENTRYPOINT: '',
CLAUDE_CODE_SSE_PORT: '',
CLAUDE_PROJECT_DIR: '',
};
const result = runHook(hookPath, [], { input: payload, env, timeoutMs: 5000 });
assert.equal(result.outcome, OUTCOME.EXITED);
assert.equal(typeof result.stdout, 'string');
});
});
describe('runHook interpreter option', () => {
let tmpDir;
beforeEach(() => {
tmpDir = createTempDir('process-seam-interpreter-');
});
afterEach(() => {
cleanup(tmpDir);
});
test('omitting interpreter still spawns via process.execPath', () => {
const hookPath = writeFixture(tmpDir, 'hook.cjs', FIXTURE_ECHO_ARGV);
const result = runHook(hookPath, ['a', 'b']);
assert.equal(result.outcome, OUTCOME.EXITED);
assert.deepStrictEqual(JSON.parse(result.stdout.trim()).argv, ['a', 'b']);
});
// bash availability is checked, never assumed — a Windows host or a
// node-only container may not have bash on PATH.
function isBashAvailable() {
if (process.platform === 'win32') return false;
const probeResult = spawnSync('bash', ['-c', 'exit 0']);
return !probeResult.error;
}
const bashAvailable = isBashAvailable();
test('interpreter: bash runs a bash script and reports EXITED', (t) => {
if (!bashAvailable) {
t.skip('bash is not available on this host');
return;
}
const scriptPath = path.join(tmpDir, 'hook.sh');
fs.writeFileSync(
scriptPath,
[
'#!/usr/bin/env bash',
'echo \'{"ok":true}\'',
'exit 0',
].join('\n')
);
const result = runHook(scriptPath, [], { interpreter: 'bash' });
assert.equal(result.outcome, OUTCOME.EXITED);
assert.equal(result.exitCode, 0);
assert.deepStrictEqual(JSON.parse(result.stdout.trim()), { ok: true });
});
test('interpreter is not forwarded into spawnSync options', () => {
const hookPath = writeFixture(tmpDir, 'hook.cjs', FIXTURE_EXIT);
// If `interpreter` leaked into spawnOptions, spawnSync would receive an
// unexpected string-valued option alongside a valid timeoutMs; the
// seam's contract-validation for timeoutMs must still pass through
// untouched and the call must complete without throwing.
const result = runHook(hookPath, ['0'], { interpreter: process.execPath, timeoutMs: 5000 });
assert.equal(result.outcome, OUTCOME.EXITED);
assert.equal(result.exitCode, 0);
});
test('interpreter: bash on a script past timeoutMs is TIMED_OUT', (t) => {
if (!bashAvailable) {
t.skip('bash is not available on this host');
return;
}
const scriptPath = path.join(tmpDir, 'sleeper.sh');
fs.writeFileSync(
scriptPath,
[
'#!/usr/bin/env bash',
'sleep 5',
].join('\n')
);
const result = runHook(scriptPath, [], { interpreter: 'bash', timeoutMs: 300 });
assert.equal(result.outcome, OUTCOME.TIMED_OUT);
assert.equal(result.timedOut, true);
assert.equal(result.exitCode, null);
});
});
describe('runGsdTools adapter (process-seam parity)', () => {
let tmpDir;
beforeEach(() => {
tmpDir = createTempDir('process-seam-adapter-');
});
afterEach(() => {
cleanup(tmpDir);
});
test('adapter returns the legacy success shape', () => {
const result = runGsdTools(['--help'], tmpDir);
assert.equal(result.success, true);
assert.equal(result.exitCode, 0);
assert.equal(typeof result.output, 'string');
});
test('adapter returns the legacy failure shape', () => {
const result = runGsdTools(['this-is-not-a-real-command'], tmpDir);
assert.equal(result.success, false);
assert.equal(typeof result.error, 'string');
assert.ok(result.error.length > 0);
assert.equal(typeof result.exitCode, 'number');
assert.notEqual(result.exitCode, 0);
});
test('adapter reproduces the empty-stderr diagnostic verbatim', () => {
withMockedRunNode(
() => ({
outcome: OUTCOME.EXITED,
exitCode: 9,
stdout: '',
stderr: '',
timedOut: false,
signal: null,
killed: false,
code: null,
}),
() => {
const result = runGsdTools(['a', 'b'], tmpDir);
const expected = `Command failed: ${process.execPath} ${TOOLS_PATH} a b [stderr: (empty) exit:9]`;
assert.equal(result.success, false);
assert.equal(result.error, expected);
assert.equal(result.exitCode, 9);
}
);
});
test('adapter still retries once on kill', () => {
withMockedRunNode(
(callCount) => (callCount === 1
? {
outcome: OUTCOME.TIMED_OUT,
exitCode: null,
stdout: '',
stderr: '',
timedOut: true,
signal: 'SIGTERM',
killed: true,
code: 'ETIMEDOUT',
}
: {
outcome: OUTCOME.EXITED,
exitCode: 0,
stdout: 'ok\n',
stderr: '',
timedOut: false,
signal: null,
killed: false,
code: null,
}),
(getCallCount) => {
const result = runGsdTools(['x'], tmpDir);
assert.equal(result.success, true);
assert.equal(result.output, 'ok');
assert.equal(getCallCount(), 2);
}
);
});
test('adapter retries once on KILLED, mirroring TIMED_OUT', () => {
withMockedRunNode(
(callCount) => (callCount === 1
? {
outcome: OUTCOME.KILLED,
exitCode: null,
stdout: '',
stderr: '',
timedOut: false,
signal: 'SIGKILL',
killed: true,
code: null,
}
: {
outcome: OUTCOME.EXITED,
exitCode: 0,
stdout: 'ok\n',
stderr: '',
timedOut: false,
signal: null,
killed: false,
code: null,
}),
(getCallCount) => {
const result = runGsdTools(['x'], tmpDir);
assert.equal(result.success, true);
assert.equal(result.output, 'ok');
assert.equal(getCallCount(), 2);
}
);
});
test('adapter throws resource-starvation when KILLED persists after retry', () => {
withMockedRunNode(
() => ({
outcome: OUTCOME.KILLED,
exitCode: null,
stdout: 'partial-out',
stderr: 'partial-err',
timedOut: false,
signal: 'SIGKILL',
killed: true,
code: null,
}),
(getCallCount) => {
const expected =
`[runGsdTools: resource-starvation / subprocess-kill after retry] ` +
`gsd-tools was killed before completion ` +
`(signal=SIGKILL, code=null, killed=true). ` +
`This indicates host OOM or scheduler contention, not a product bug. ` +
`stdout=partial-out stderr=partial-err`;
assert.throws(
() => runGsdTools(['x'], tmpDir),
(err) => err instanceof Error && err.message === expected
);
assert.equal(getCallCount(), 2);
}
);
});
test('adapter still throws resource-starvation after retry', () => {
withMockedRunNode(
() => ({
outcome: OUTCOME.TIMED_OUT,
exitCode: null,
stdout: 'partial-out',
stderr: 'partial-err',
timedOut: true,
signal: 'SIGTERM',
killed: true,
code: 'ETIMEDOUT',
}),
() => {
const expected =
`[runGsdTools: resource-starvation / subprocess-kill after retry] ` +
`gsd-tools was killed before completion ` +
`(signal=SIGTERM, code=ETIMEDOUT, killed=true). ` +
`This indicates host OOM or scheduler contention, not a product bug. ` +
`stdout=partial-out stderr=partial-err`;
assert.throws(
() => runGsdTools(['x'], tmpDir),
(err) => err instanceof Error && err.message === expected
);
}
);
});
test('adapter retries exactly once, not twice', () => {
withMockedRunNode(
() => ({
outcome: OUTCOME.TIMED_OUT,
exitCode: null,
stdout: '',
stderr: '',
timedOut: true,
signal: 'SIGTERM',
killed: true,
code: 'ETIMEDOUT',
}),
(getCallCount) => {
assert.throws(() => runGsdTools(['x'], tmpDir));
assert.equal(getCallCount(), 2);
}
);
});
test('adapter still accepts a shell-style string', () => {
const result = runGsdTools('--help', tmpDir);
assert.equal(result.success, true);
assert.equal(result.exitCode, 0);
});
test('adapter still accepts an argv array', () => {
const result = runGsdTools(['--help'], tmpDir);
assert.equal(result.success, true);
assert.equal(result.exitCode, 0);
});
test('adapter preserves env override precedence', () => {
withMockedRunNode(
(_callCount, _args, options) => {
// Capture the merged env the adapter built, then return a fast
// EXITED result — this test is about the merge, not gsd-tools.
withMockedRunNode.capturedEnv = options.env;
return {
outcome: OUTCOME.EXITED,
exitCode: 0,
stdout: '',
stderr: '',
timedOut: false,
signal: null,
killed: false,
code: null,
};
},
() => {
runGsdTools(['x'], tmpDir, { GSD_SESSION_KEY: 'override-value' });
// TEST_ENV_BASE defaults GSD_SESSION_KEY to '' — the caller's env
// argument must win over it.
assert.equal(withMockedRunNode.capturedEnv.GSD_SESSION_KEY, 'override-value');
}
);
});
// Legacy-shape contract: the SEAM reports exitCode: null for
// BUFFER_OVERFLOW (asserted above, at the seam level), but a real caller
// (tests/context-predicates-query.test.cjs) asserts
// `typeof r.exitCode === 'number'` on the ADAPTER's legacy shape, matching
// the pre-seam execFileSync helper's `err.status ?? 1`. This is the
// adapter-level contract, deliberately distinct from the seam-level one.
test('adapter does not retry a buffer overflow, and coerces exitCode to a number', () => {
withMockedRunNode(
() => ({
outcome: OUTCOME.BUFFER_OVERFLOW,
exitCode: null,
stdout: 'x'.repeat(20),
stderr: '',
timedOut: false,
signal: 'SIGTERM',
killed: true,
code: 'ENOBUFS',
}),
(getCallCount) => {
const result = runGsdTools(['x'], tmpDir);
assert.equal(getCallCount(), 1);
assert.equal(result.success, false);
assert.equal(typeof result.exitCode, 'number');
assert.equal(result.exitCode, 1);
}
);
});
// Same legacy-shape contract as the buffer-overflow test above, for
// SPAWN_FAILED (the Windows CI regression case: an oversized argv).
test('adapter does not retry a spawn failure, and coerces exitCode to a number', () => {
withMockedRunNode(
() => ({
outcome: OUTCOME.SPAWN_FAILED,
exitCode: null,
stdout: '',
stderr: '',
timedOut: false,
signal: null,
killed: false,
code: 'ENOENT',
}),
(getCallCount) => {
const result = runGsdTools(['x'], tmpDir);
assert.equal(getCallCount(), 1);
assert.equal(result.success, false);
assert.equal(typeof result.exitCode, 'number');
assert.equal(result.exitCode, 1);
}
);
});
});

View File

@@ -172,7 +172,7 @@ function crlf(text) {
* @returns {string}
*/
function bom(text) {
return `${text}`;
return `\uFEFF${text}`;
}
/**

View File

@@ -22,6 +22,7 @@ const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const { execFileSync } = require('node:child_process');
const { runHook: runHookSeam } = require('./helpers/process-seam.cjs');
const { createTempDir, cleanup } = require('./helpers.cjs');
@@ -44,22 +45,15 @@ function runHook(payload, envOverrides = {}) {
CLAUDE_PROJECT_DIR: '',
...envOverrides,
};
try {
const stdout = execFileSync(process.execPath, [HOOK_PATH], {
input,
encoding: 'utf-8',
timeout: 5000,
stdio: ['pipe', 'pipe', 'pipe'],
env,
});
return { exitCode: 0, stdout: stdout.trim(), stderr: '' };
} catch (err) {
return {
exitCode: err.status ?? 1,
stdout: (err.stdout || '').toString().trim(),
stderr: (err.stderr || '').toString().trim(),
};
const r = runHookSeam(HOOK_PATH, [], { input, env, timeoutMs: 5000 });
if (r.exitCode === 0) {
return { exitCode: 0, stdout: r.stdout.trim(), stderr: '' };
}
return {
exitCode: r.exitCode ?? 1,
stdout: r.stdout.trim(),
stderr: r.stderr.trim(),
};
}
describe('gsd-read-guard hook', () => {
@@ -281,7 +275,7 @@ const { test, describe, beforeEach, afterEach } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const { execFileSync } = require('node:child_process');
const { runHook: runHookSeam } = require('./helpers/process-seam.cjs');
const { createTempDir, cleanup } = require('./helpers.cjs');
@@ -298,22 +292,15 @@ function runHook(payload, envOverrides = {}) {
CLAUDE_PROJECT_DIR: '',
...envOverrides,
};
try {
const stdout = execFileSync(process.execPath, [HOOK_PATH], {
input,
encoding: 'utf-8',
timeout: 5000,
stdio: ['pipe', 'pipe', 'pipe'],
env,
});
return { exitCode: 0, stdout: stdout.trim(), stderr: '' };
} catch (err) {
return {
exitCode: err.status ?? 1,
stdout: (err.stdout || '').toString().trim(),
stderr: (err.stderr || '').toString().trim(),
};
const r = runHookSeam(HOOK_PATH, [], { input, env, timeoutMs: 5000 });
if (r.exitCode === 0) {
return { exitCode: 0, stdout: r.stdout.trim(), stderr: '' };
}
return {
exitCode: r.exitCode ?? 1,
stdout: r.stdout.trim(),
stderr: r.stderr.trim(),
};
}
describe('bug #2344: read guard skips on CLAUDECODE env var', () => {

View File

@@ -26,9 +26,9 @@
const { describe, test } = require('node:test');
const assert = require('node:assert/strict');
const { spawnSync } = require('node:child_process');
const path = require('node:path');
const fc = require('./helpers/fast-check-setup.cjs');
const { runHook: runHookSeam } = require('./helpers/process-seam.cjs');
const HOOK_PATH = path.join(__dirname, '..', 'hooks', 'gsd-read-injection-scanner.js');
@@ -57,16 +57,11 @@ function runHook(payload) {
return { exitCode: 0, stdout: '', skipped: true };
}
const result = spawnSync(process.execPath, [HOOK_PATH], {
input,
encoding: 'utf-8',
timeout: 30000,
stdio: ['pipe', 'pipe', 'pipe'],
});
const result = runHookSeam(HOOK_PATH, [], { input, timeoutMs: 30000 });
return {
exitCode: result.status ?? 1,
stdout: (result.stdout || '').trim(),
exitCode: result.exitCode ?? 1,
stdout: result.stdout.trim(),
signal: result.signal,
};
}

View File

@@ -22,25 +22,14 @@ process.env.GSD_TEST_MODE = '1';
const { test, describe } = require('node:test');
const assert = require('node:assert/strict');
const { execFileSync } = require('node:child_process');
const { runHook: runHookSeam } = require('./helpers/process-seam.cjs');
const HOOK_PATH = require('node:path').join(__dirname, '..', 'hooks', 'gsd-read-injection-scanner.js');
function runHook(payload, timeoutMs = 5000) {
const input = JSON.stringify(payload);
try {
const stdout = execFileSync(process.execPath, [HOOK_PATH], {
input,
encoding: 'utf-8',
timeout: timeoutMs,
stdio: ['pipe', 'pipe', 'pipe'],
});
return { exitCode: 0, stdout: stdout.trim() };
} catch (err) {
return {
exitCode: err.status ?? 1,
stdout: (err.stdout || '').toString().trim(),
};
}
const r = runHookSeam(HOOK_PATH, [], { input, timeoutMs });
return { exitCode: r.exitCode ?? 1, stdout: r.stdout.trim() };
}
function readPayload(filePath, content) {

View File

@@ -83,6 +83,7 @@ const {
cleanup,
} = require('./helpers.cjs');
const { runCli } = require('./helpers/cli-negative.cjs');
const { runHook: runHookSeam } = require('./helpers/process-seam.cjs');
const REPO_ROOT = path.resolve(__dirname, '..');
const PROMPT_GUARD_HOOK = path.join(REPO_ROOT, 'hooks', 'gsd-prompt-guard.js');
@@ -117,22 +118,18 @@ const {
* the human-readable `additionalContext` prose.
*/
function runHook(hookPath, payload, { timeoutMs = 5000 } = {}) {
const r = spawnSync(process.execPath, [hookPath], {
input: JSON.stringify(payload),
encoding: 'utf-8',
timeout: timeoutMs,
});
const stdout = typeof r.stdout === 'string' ? r.stdout : '';
const r = runHookSeam(hookPath, [], { input: JSON.stringify(payload), timeoutMs });
const stdout = r.stdout;
let parsed = null;
const trimmed = stdout.trim();
if (trimmed.startsWith('{') && trimmed.endsWith('}')) {
try { parsed = JSON.parse(trimmed); } catch { parsed = null; }
}
return {
status: r.status,
status: r.exitCode,
signal: r.signal,
stdout,
stderr: typeof r.stderr === 'string' ? r.stderr : '',
stderr: r.stderr,
parsed,
silent: trimmed.length === 0,
additionalContext: parsed?.hookSpecificOutput?.additionalContext ?? null,

View File

@@ -455,20 +455,14 @@ describe('validateFieldName', () => {
// Verify that gsd-context-monitor and gsd-statusline reject session_id values
// containing path traversal sequences before constructing temp file paths.
const { execFileSync } = require('child_process');
const { runHook: runHookSeam } = require('./helpers/process-seam.cjs');
function runHook(hookPath, inputJson) {
try {
const result = execFileSync(process.execPath, [hookPath], {
input: JSON.stringify(inputJson),
encoding: 'utf-8',
stdio: ['pipe', 'pipe', 'pipe'],
timeout: 3000,
});
return { exitCode: 0, stdout: result };
} catch (err) {
return { exitCode: err.status || 1, stdout: err.stdout || '', stderr: err.stderr || '' };
}
const result = runHookSeam(hookPath, [], {
input: JSON.stringify(inputJson),
timeoutMs: 3000,
});
return { exitCode: result.exitCode, stdout: result.stdout, stderr: result.stderr };
}
describe('gsd-context-monitor session_id path traversal', () => {

View File

@@ -44,7 +44,8 @@ const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const os = require('node:os');
const { spawnSync, execFileSync } = require('node:child_process');
const { execFileSync } = require('node:child_process');
const { runHook: runHookSeam } = require('./helpers/process-seam.cjs');
const { createTempDir, cleanup } = require('./helpers.cjs');
@@ -66,12 +67,12 @@ const PRE_COMMAND_SCRIPT = path.join(HOOKS_DIR, GSD_WINDSURF_PRE_COMMAND_HOOK_SC
function runHook(scriptPath, payload, opts = {}) {
const input = payload === undefined ? '' : (typeof payload === 'string' ? payload : JSON.stringify(payload));
return spawnSync(process.execPath, [scriptPath], {
const r = runHookSeam(scriptPath, [], {
input,
encoding: 'utf8',
timeout: 10000,
timeoutMs: 10000,
cwd: opts.cwd || os.tmpdir(),
});
return { status: r.exitCode, stdout: r.stdout, stderr: r.stderr, signal: r.signal };
}
function initGitRepo(dir) {
@@ -218,7 +219,7 @@ describe('gsd-windsurf-pre-command.js (pre_run_command guard)', () => {
test('G10: ReDoS-guard — a 200000+-char rm -rf-shaped payload is handled without catastrophic backtracking (length cap)', () => {
const payload = `rm -${'r'.repeat(200000)}!`;
// The ReDoS guard is `runHook`'s spawnSync `timeout: 10000`: catastrophic
// The ReDoS guard is `runHook`'s seam `timeoutMs: 10000`: catastrophic
// backtracking on this payload would run for minutes, so the hook is
// SIGKILL'd and returns a non-zero status — the exit-0 assertion below IS
// the ReDoS check. (The prior `elapsedMs < 1000` wall-clock assertion was

View File

@@ -16,10 +16,11 @@ process.env.GSD_TEST_MODE = '1';
const { test, describe, before, after } = require('node:test');
const assert = require('node:assert/strict');
const { execFileSync, execSync } = require('node:child_process');
const { execSync } = require('node:child_process');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const { runHook: runHookSeam } = require('./helpers/process-seam.cjs');
const { cleanup } = require('./helpers.cjs');
@@ -27,21 +28,15 @@ const HOOK_PATH = path.join(__dirname, '..', 'hooks', 'gsd-workflow-guard.js');
function runHook(payload, timeoutMs = 5000) {
const input = JSON.stringify(payload);
try {
const stdout = execFileSync(process.execPath, [HOOK_PATH], {
input,
encoding: 'utf-8',
timeout: timeoutMs,
stdio: ['pipe', 'pipe', 'pipe'],
});
return { exitCode: 0, stdout: stdout.trim(), stderr: '' };
} catch (err) {
return {
exitCode: err.status ?? 1,
stdout: (err.stdout || '').toString().trim(),
stderr: (err.stderr || '').toString().trim(),
};
const r = runHookSeam(HOOK_PATH, [], { input, timeoutMs });
if (r.exitCode === 0) {
return { exitCode: 0, stdout: r.stdout.trim(), stderr: '' };
}
return {
exitCode: r.exitCode ?? 1,
stdout: r.stdout.trim(),
stderr: r.stderr.trim(),
};
}
describe('#2304: Kimi tool vocabulary engages the workflow guard', () => {

View File

@@ -1484,6 +1484,7 @@ const fs = require('node:fs');
const path = require('node:path');
const os = require('node:os');
const { cleanup, readFileNormalized } = require('./helpers.cjs');
const { runHook } = require('./helpers/process-seam.cjs');
const REPO_ROOT = path.join(__dirname, '..');
const EXECUTE_PHASE_PATH = path.join(REPO_ROOT, 'gsd-core', 'workflows', 'execute-phase.md');
@@ -1567,11 +1568,17 @@ function extractCwdGuardBash() {
* Returns { status, stderr }.
*/
function runGuard(guardBash, cwd) {
const result = spawnSync('bash', ['-c', guardBash], {
// 30000ms: previously UNBOUNDED (no `timeout` option was passed to
// spawnSync). This is the same execute-phase.md cwd-drift guard snippet
// exercised by tests/execute-phase-worktree-guard.test.cjs, which already
// bounds the identical guard at 30s (a handful of git plumbing calls
// against a small fixture repo) — matched here for consistency.
const result = runHook('-c', [guardBash], {
interpreter: 'bash',
cwd,
encoding: 'utf-8',
timeoutMs: 30_000,
});
return { status: result.status, stderr: result.stderr || '' };
return { status: result.exitCode, stderr: result.stderr || '' };
}
// ---------------------------------------------------------------------------

View File

@@ -4301,8 +4301,9 @@ const assert = require('node:assert/strict');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const { spawnSync, execFileSync } = require('node:child_process');
const { execFileSync } = require('node:child_process');
const { cleanup } = require('./helpers.cjs');
const { runHook: seamRunHook } = require('./helpers/process-seam.cjs');
const HOOK_PATH = path.join(__dirname, '..', 'hooks', 'gsd-worktree-path-guard.js');
const INSTALL_SRC = path.join(__dirname, '..', 'bin', 'install.js');
@@ -4359,11 +4360,17 @@ function makeWorktree(mainRepo, branchName) {
* Run the hook with a given payload, returning the spawnSync result.
*/
function runHook(cwd, payload) {
return spawnSync(process.execPath, [HOOK_PATH], {
// 10000ms: previously UNBOUNDED (no `timeout` option passed to spawnSync).
// gsd-worktree-path-guard.js is a synchronous, in-process path-guard hook
// (fs/path checks against a JSON stdin payload) — no subprocess or network
// work of its own. 10s leaves generous headroom over its sub-second
// worst case even on a heavily contended CI runner.
const r = seamRunHook(HOOK_PATH, [], {
cwd,
input: JSON.stringify(payload),
encoding: 'utf8',
timeoutMs: 10_000,
});
return { status: r.exitCode, stdout: r.stdout, stderr: r.stderr };
}
// ---------------------------------------------------------------------------
@@ -5442,6 +5449,7 @@ const fs = require('fs');
const path = require('path');
const { execFileSync } = require('child_process');
const { createTempGitProject, cleanup } = require('./helpers.cjs');
const { runHook: seamRunHookGate } = require('./helpers/process-seam.cjs');
// Bash snippet extracted from execute-phase.md (the SUBMODULE_PATHS parse +
// per-plan intersection logic with normalization + bidirectional matching).
@@ -5515,11 +5523,27 @@ const GATE_SNIPPET = [
].join('\n');
function runGate(cwd, env) {
const out = execFileSync('bash', ['-c', GATE_SNIPPET], {
// 30000ms: previously UNBOUNDED (execFileSync had no `timeout` option).
// The snippet is pure shell string/array parsing plus one `git config
// --file .gitmodules` lookup against a small fixture repo — matched to the
// 30s bound already established for the other bash guard snippets in this
// suite for consistency, though it does substantially less work than those.
const r = seamRunHookGate('-c', [GATE_SNIPPET], {
interpreter: 'bash',
cwd,
encoding: 'utf-8',
timeoutMs: 30_000,
env: { ...process.env, ...env },
});
if (r.exitCode !== 0) {
// execFileSync THREW on non-zero exit; the seam does not. Reproduce that
// failure signal explicitly so a real gate-snippet failure still surfaces
// loudly instead of silently falling through to the parse below.
throw new Error(
`runGate: bash -c GATE_SNIPPET exited ${r.exitCode} (outcome=${r.outcome}). ` +
`stdout:\n${r.stdout}\nstderr:\n${r.stderr}`
);
}
const out = r.stdout;
const lines = out.trim().split('\n');
const last = lines[lines.length - 1];
const m = last.match(/^USE_WORKTREES_FOR_PLAN=(true|false)$/);