Files
msd-core/tests/io.test.cjs
Tom Boucher d98b55562c enhance(#3910): the raw terminator is banned by construction (#3980)
* enhance(#3910): move the last src/ terminators onto the seam

Phase 6 bans the raw terminator by construction, which it cannot do while
violations stand. A census found 12 sites the rule would flag; nine of the ten
unsanctioned ones were owned by no phase of the epic at all — a coverage hole
in the decomposition, since P0-P2 are infra, P3 the gate modules, P4 the
scanners, P5 the fragments, P7 the hooks, P8 io.cts, and P6 itself only adds
the rule. `src/**/*.cts` now holds exactly 2 raw exits, both inside
`terminateNow`, the single sanctioned site.

`io.cts`'s `error()` is the interesting one. It was first called substantive on
"dozens of callers, contract risk" — asserted, not measured, and the
measurement refuted it: 289 call sites, zero inside a try whose catch would
swallow a throw. The real obstacle was structural instead: `terminateNow`
cannot emit exit 1, because ADR-3889 §1 makes 0 and 1 unallocatable and
`nameForExitCode(1)` throws. So the only route is `ExitError` under `runMain`,
which sets exitCode and writes stderr only when the error carries a user
message — keeping the existing stderr write and throwing a message-less
ExitError is observably identical.

That census was still too narrow, and running the CLI proved it. It asked
whether the CALL sits in a try/catch; the two regressions that surfaced were
interceptors elsewhere on the stack:

- `command-routing-hub.cts`'s `dispatch()` swallowed the ExitError into a
  HandlerFailure, so the caller emitted a duplicated, wrong stderr line on
  every Hub-routed path. It now rethrows ExitError explicitly — the same shape
  `gsd-tools.cjs` already used at two dispatch sites, so this follows an
  established idiom rather than inventing one.
- the profile-pipeline router's deliberately un-awaited `.catch(e => error(...))`
  turned an ExitError rejection into an uncaught exception; it now mirrors
  runMain's handling.

`edge-probe` and `ui-consideration-probe` gained `runMain` wrappers because
probe-core's new throwing default would otherwise have escaped them.

A follow-up sweep of every dispatcher — 19 command routers, the Hub, the
gsd-tools dispatch seams — found no further swallowing catch. The admitted
bound: ~1260 non-rethrowing catches repo-wide were scanned structurally but not
individually classified. Both real regressions were found by execution, not by
reading, so the suite is the detector that matters here.

`gsd-tools.cjs:253` stays a raw exit deliberately: it is the ensureRuntimeBuild
bootstrap, which runs before cli-exit is required, so the seam does not yet
exist. It needs a second allowlist entry, which means #3910's "single allowlist
entry" criterion is unachievable as written.

Verification runs on the remote runner.

Refs #3910

* enhance(#3910): ban the raw terminator by construction

Adds local/require-registered-exit and registers it on all four globs:
src/**/*.cts, scripts/**/*.cjs, hooks/**/*.js, gsd-core/bin/**/*.cjs.

Registering on the .cts glob is load-bearing, not redundant — the emitted .cjs
mirrors are globally eslint-ignored, so a rule registered only on the emitted
globs is blind to the sources. That is the #3496 lesson, and it is how the
previous guard became invisible: n/no-process-exit was 'error' in one block yet
fired zero times on all three surfaces that mattered.

The dead n/no-process-exit: 'off' block for hooks is deleted in the same PR.
Phase 7 migrated every hook, so the exemption now protects nothing.

Two allowlist entries, not the one #3910 anticipated. terminateNow's body is
detected STRUCTURALLY — a process.exit lexically inside a function of that name
— rather than by a path and line number that rots. The second is
gsd-tools.cjs's ensureRuntimeBuild bootstrap, an inline disable with its reason
at the call site: it runs before ./lib/cli-exit.cjs is required, so the seam
does not exist yet and no migration is possible. #3910's 'single allowlist
entry' criterion is therefore unachievable as written, and is amended with the
measurement rather than quietly missed.

The rule is proven able to FAIL, per glob: four positive controls, one for each
registered glob. A guard that cannot be shown to fire is not a guard. Four
matching negative controls pin process.exitCode as never-flagged — conflating
it with process.exit is what inflated this epic's original census 2x. An
allowlist case and a near-miss (same shape, different function name) fix the
structural detection in place.

Verification runs on the remote runner.

Refs #3910

* fix(#3910): stop the detached catch from throwing, and scope the allowlist

Review findings, one of them a regression the previous fix introduced.

_handlePipelineRejection called error() from inside a DETACHED .catch().
error() now throws, so that throw became an unhandled promise rejection — and
on Node >=15 with --unhandled-rejections=throw, Node dumps a raw stack trace
with absolute paths on top of the clean Error: line. That was impossible before
this branch, because process.exit(1) terminated synchronously before any
rejection machinery could observe it. The handler now writes byte-identical
stderr itself, in both plain and --json-errors form, and sets exitCode in
place. This was the THIRD interceptor found, and like the first two it surfaced
by running the CLI rather than by reading code.

The rule's terminateNow allowlist had no path constraint, so any function
anywhere named terminateNow across all four globs inherited it. It now requires
the structural nesting check AND a cli-exit.cts basename — still no line
numbers to rot.

The four per-glob positive controls only varied a filename inside RuleTester,
which never resolves eslint.config.mjs. Since the rule is filename-agnostic,
all four exercised identical logic and none proved the rule was WIRED — this
epic's own failure mode. A registration test now asserts the rule resolves for
a real path in each glob, and it is proven able to fail: removing one glob's
registration flips the resolved value from [2] to undefined.

Three evasions the rule cannot catch (computed member, aliasing, .call/.apply)
are documented in its header and pinned by tests, labelled as known limits
rather than endorsed, so a future change that starts catching them is a
deliberate diff.

Refs #3910

* docs(#3910): document the raw-terminator ban

Reference and Explanation via a new docs/features fragment (FEATURES.md is
generated from it, not hand-edited). How-To:
docs/how-to/resolve-a-raw-terminator-finding.md, indexed from docs/README.md —
a contributor whose code trips the rule picks among three replacements by
surface (runMain/ExitError for a CLI path, terminateNow for a hook,
process.exitCode where the process should drain), and needs to know why
process.exitCode is correct and never flagged, since conflating the two is what
inflated this epic's original census 2x.

The page also names the three patterns the rule cannot catch and says plainly
that using one to dodge it is a review finding, not a fix — documenting them
without that sentence would read as a sanctioned workaround.

docs/INVENTORY.md deliberately untouched: eslint-rules/ is not a tracked family
in the manifest (verified — a regen produced a zero diff), so a hand-written row
would desync the table from the family it claims to belong to.

Refs #3910

* fix(#3910): a catch that sniffs the message swallows an ExitError

The remote run returned 41 failures, and one of them was a live production
regression rather than a test artifact.

`cmdMilestoneComplete`'s unstarted-phase guard re-threw only when
`e.message.startsWith('Cannot mark milestone complete:')`. `error()` used to
`process.exit(1)`, uncatchable, so the guard always fired. It now throws an
ExitError carrying no message, the string test fails, and the ExitError was
silently swallowed — the guard stopped blocking milestone completion entirely.
Proven against the real CLI: pre-fix, a milestone with an unstarted phase
archived at exit 0; post-fix it is blocked at exit 1 with the intended message.

That is a guard that silently stopped guarding, which is this epic's thesis
appearing inside the phase meant to enforce it. Worth stating plainly: an
earlier census DID examine this site, saw a `throw e`, and classified it as
rethrowing. It was wrong — the rethrow is conditional, and a conditional
rethrow on an inspected message is indistinguishable from an unconditional one
unless you read the predicate.

So the class was swept rather than patched where it was tripped over. An AST
census of every CatchClause across src/, gsd-core/bin/ and scripts/ found 38
conditional rethrows. Two more had the same defect and are fixed the same way:
`config.cts`'s `'No config.json'` sniff and `gsd-tools.cjs`'s
`e.name === 'WindowsError'`. The remaining 25 are provably unreachable — every
one wraps a bare fs, YAML, manifest-require or git-exec primitive that cannot
throw ExitError — and two were scanner false positives, both explained. Each
fix is an unconditional `instanceof ExitError` rethrow placed BEFORE any
inspection, matching the idiom command-routing-hub and gsd-tools already used.

Residual bound, stated rather than implied: zero known-reachable unfixed sites,
contingent only on error() never later being called inside one of those 25
primitive try blocks.

The remaining failures were harness artifacts, and the harnesses were corrected
to the new contract rather than the assertions weakened. Tests that mocked
`process.exit` to observe termination now catch ExitError and assert its code;
tests parsing stderr as a single JSON object still assert exactly that, with
their ad-hoc `node -e` scripts wrapped in runMain so it is true. milestone and
phase-resolution-parity needed no test change — they were correctly written
against the real bug and are what caught it.

Verification runs on the remote runner.

Refs #3910

* chore(#3910): backfill the changeset PR number

Also reframes the fragment to lead with the user-visible change — the
milestone guard blocking again — rather than the narrowest of the three fixes.

Refs #3910

---------

Co-authored-by: sim <sim@local>
2026-08-28 03:15:39 -04:00

566 lines
23 KiB
JavaScript

/**
* Tests for src/io.cts (compiled to gsd-core/bin/lib/io.cjs).
*
* Verifies behavioural contracts of the extracted CLI I/O primitives:
* - output() writes expected structure to stdout
* - error() writes expected structure to stderr and exits
* - ERROR_REASON constants have the correct wire values
* - setJsonErrorMode/getJsonErrorMode toggle behaviour
* - core.cjs re-export shims resolve to the exact same objects as io.cjs
*
* ADR-857 phase 1 / issue #859.
*/
const { test, describe, afterEach } = require('node:test');
const assert = require('node:assert/strict');
const path = require('node:path');
const os = require('node:os');
const fs = require('node:fs');
const io = require('../gsd-core/bin/lib/io.cjs');
const { ExitError } = require('../gsd-core/bin/lib/cli-exit.cjs');
const { runNode } = require('./helpers/process-seam.cjs');
const { toLegacyResult } = require('./helpers/git-fixture.cjs');
const { PROBE_TIMEOUT_MS } = require('./helpers/timeouts.cjs');
function runScript(script) {
return toLegacyResult(runNode(['-e', script], { timeoutMs: PROBE_TIMEOUT_MS }));
}
// ─── ERROR_REASON constants ───────────────────────────────────────────────────
describe('ERROR_REASON', () => {
test('is a frozen object', () => {
assert.ok(Object.isFrozen(io.ERROR_REASON));
});
test('contains expected wire values', () => {
assert.strictEqual(io.ERROR_REASON.CONFIG_KEY_NOT_FOUND, 'config_key_not_found');
assert.strictEqual(io.ERROR_REASON.CONFIG_NO_FILE, 'config_no_file');
assert.strictEqual(io.ERROR_REASON.CONFIG_PARSE_FAILED, 'config_parse_failed');
assert.strictEqual(io.ERROR_REASON.CONFIG_INVALID_KEY, 'config_invalid_key');
assert.strictEqual(io.ERROR_REASON.SDK_FAIL_FAST, 'sdk_fail_fast');
assert.strictEqual(io.ERROR_REASON.SDK_UNKNOWN_COMMAND, 'sdk_unknown_command');
assert.strictEqual(io.ERROR_REASON.SDK_MISSING_ARG, 'sdk_missing_arg');
assert.strictEqual(io.ERROR_REASON.PHASE_NOT_FOUND, 'phase_not_found');
assert.strictEqual(io.ERROR_REASON.SUMMARY_NO_PLANNING, 'summary_no_planning');
assert.strictEqual(io.ERROR_REASON.GRAPHIFY_NO_GRAPH, 'graphify_no_graph');
assert.strictEqual(io.ERROR_REASON.GRAPHIFY_INVALID_QUERY, 'graphify_invalid_query');
assert.strictEqual(io.ERROR_REASON.HOOKS_OPT_OUT, 'hooks_opt_out');
assert.strictEqual(io.ERROR_REASON.SECURITY_SCAN_FAILED, 'security_scan_failed');
assert.strictEqual(io.ERROR_REASON.USAGE, 'usage');
assert.strictEqual(io.ERROR_REASON.UNKNOWN, 'unknown');
});
});
// ─── setJsonErrorMode / getJsonErrorMode ─────────────────────────────────────
describe('setJsonErrorMode / getJsonErrorMode', () => {
// Reset to false after each test so other tests are unaffected
afterEach(() => {
io.setJsonErrorMode(false);
});
test('defaults to false', () => {
io.setJsonErrorMode(false); // ensure clean state
assert.strictEqual(io.getJsonErrorMode(), false);
});
test('setJsonErrorMode(true) enables JSON error mode', () => {
io.setJsonErrorMode(true);
assert.strictEqual(io.getJsonErrorMode(), true);
});
test('setJsonErrorMode(false) disables JSON error mode', () => {
io.setJsonErrorMode(true);
io.setJsonErrorMode(false);
assert.strictEqual(io.getJsonErrorMode(), false);
});
test('setJsonErrorMode coerces truthy values', () => {
io.setJsonErrorMode(1);
assert.strictEqual(io.getJsonErrorMode(), true);
io.setJsonErrorMode(0);
assert.strictEqual(io.getJsonErrorMode(), false);
});
test('setJsonErrorMode coerces string truthy', () => {
io.setJsonErrorMode('yes');
assert.strictEqual(io.getJsonErrorMode(), true);
io.setJsonErrorMode('');
assert.strictEqual(io.getJsonErrorMode(), false);
});
});
// ─── output() ────────────────────────────────────────────────────────────────
// output() writes directly to fd 1 and never calls process.exit, so we can
// test it by spawning a child process and capturing its stdout.
describe('output()', () => {
const ioPath = path.resolve(__dirname, '../gsd-core/bin/lib/io.cjs');
test('emits JSON-serialised result to stdout', () => {
const script = `
const io = require(${JSON.stringify(ioPath)});
io.output({ ok: true, value: 42 }, false);
`;
const result = runScript(script);
assert.strictEqual(result.status, 0, `process exited non-zero: ${result.stderr}`);
const parsed = JSON.parse(result.stdout);
assert.deepStrictEqual(parsed, { ok: true, value: 42 });
});
test('emits raw string value when raw=true and rawValue provided', () => {
const script = `
const io = require(${JSON.stringify(ioPath)});
io.output({ ignored: true }, true, 'raw-text-output');
`;
const result = runScript(script);
assert.strictEqual(result.status, 0, `process exited non-zero: ${result.stderr}`);
assert.strictEqual(result.stdout, 'raw-text-output');
});
test('falls back to JSON when raw=true but rawValue is undefined', () => {
const script = `
const io = require(${JSON.stringify(ioPath)});
io.output({ fallback: true }, true);
`;
const result = runScript(script);
assert.strictEqual(result.status, 0, `process exited non-zero: ${result.stderr}`);
const parsed = JSON.parse(result.stdout);
assert.deepStrictEqual(parsed, { fallback: true });
});
test('emits null correctly', () => {
const script = `
const io = require(${JSON.stringify(ioPath)});
io.output(null, false);
`;
const result = runScript(script);
assert.strictEqual(result.status, 0, `process exited non-zero: ${result.stderr}`);
assert.strictEqual(result.stdout, 'null');
});
test('large payload (>50000 chars) spills to @file: tempfile', (t) => {
// Build a payload whose serialized JSON exceeds 50000 chars.
// A string of 60000 'x' chars serializes to 60002 chars ("x...x").
const largeString = 'x'.repeat(60000);
const payload = { large: largeString };
const serialized = JSON.stringify(payload, null, 2);
assert.ok(serialized.length > 50000, 'precondition: payload must exceed 50000 chars');
const tmpFilesCreated = [];
t.after(() => {
for (const p of tmpFilesCreated) {
try { fs.unlinkSync(p); } catch { /* ignore */ }
}
});
const script = `
const io = require(${JSON.stringify(ioPath)});
const largeString = 'x'.repeat(60000);
io.output({ large: largeString }, false);
`;
const result = runScript(script);
assert.strictEqual(result.status, 0, `process exited non-zero: ${result.stderr}`);
const stdout = result.stdout.trim();
assert.ok(stdout.startsWith('@file:'), `expected stdout to start with "@file:", got: ${stdout.slice(0, 80)}`);
const tmpPath = stdout.slice('@file:'.length);
tmpFilesCreated.push(tmpPath);
assert.ok(fs.existsSync(tmpPath), `expected temp file to exist at: ${tmpPath}`);
const fileContents = fs.readFileSync(tmpPath, 'utf-8');
const parsed = JSON.parse(fileContents);
assert.deepStrictEqual(parsed, payload);
fs.unlinkSync(tmpPath);
tmpFilesCreated.length = 0; // already cleaned, skip t.after
});
});
// ─── error() ─────────────────────────────────────────────────────────────────
describe('error()', () => {
const ioPath = path.resolve(__dirname, '../gsd-core/bin/lib/io.cjs');
const cliExitPath = path.resolve(__dirname, '../gsd-core/bin/lib/cli-exit.cjs');
// ADR-3889: io.error() now throws ExitError instead of calling
// process.exit() directly. A bare `node -e` script that calls io.error()
// with no termination seam would let that ExitError escape as an uncaught
// exception (a stack trace on stderr, not the single "Error: <msg>" line
// error() itself already wrote). Every harness script below wraps the
// error() call in runMain — the sanctioned entrypoint seam — so the
// process terminates exactly the way a real CLI invocation would: the one
// stderr write error() performs itself, then `process.exitCode = err.code`
// with nothing further written (ExitError from error() carries no message,
// so runMain's own "hasUserMessage" stderr write is a no-op here).
test('plain-text mode: writes "Error: <msg>" to stderr and exits 1', () => {
const script = `
const io = require(${JSON.stringify(ioPath)});
const { runMain } = require(${JSON.stringify(cliExitPath)});
io.setJsonErrorMode(false);
runMain(() => { io.error('something went wrong'); });
`;
const result = runScript(script);
assert.strictEqual(result.status, 1);
assert.ok(result.stderr.includes('Error: something went wrong'), `stderr was: ${result.stderr}`);
assert.strictEqual(result.stdout, '');
});
test('plain-text mode: default reason does not appear in stderr text', () => {
const script = `
const io = require(${JSON.stringify(ioPath)});
const { runMain } = require(${JSON.stringify(cliExitPath)});
io.setJsonErrorMode(false);
runMain(() => { io.error('no reason code expected'); });
`;
const result = runScript(script);
assert.strictEqual(result.status, 1);
// plain mode does NOT include the reason field
assert.ok(!result.stderr.includes('"reason"'), `stderr unexpectedly contained reason: ${result.stderr}`);
});
test('JSON-error mode: writes structured JSON to stderr and exits 1', () => {
const script = `
const io = require(${JSON.stringify(ioPath)});
const { runMain } = require(${JSON.stringify(cliExitPath)});
io.setJsonErrorMode(true);
runMain(() => { io.error('structured error', io.ERROR_REASON.SDK_FAIL_FAST); });
`;
const result = runScript(script);
assert.strictEqual(result.status, 1);
assert.strictEqual(result.stdout, '');
const payload = JSON.parse(result.stderr.trim());
assert.strictEqual(payload.ok, false);
assert.strictEqual(payload.reason, 'sdk_fail_fast');
assert.strictEqual(payload.message, 'structured error');
});
test('JSON-error mode: defaults reason to UNKNOWN when not supplied', () => {
const script = `
const io = require(${JSON.stringify(ioPath)});
const { runMain } = require(${JSON.stringify(cliExitPath)});
io.setJsonErrorMode(true);
runMain(() => { io.error('no reason given'); });
`;
const result = runScript(script);
assert.strictEqual(result.status, 1);
const payload = JSON.parse(result.stderr.trim());
assert.strictEqual(payload.reason, 'unknown');
assert.strictEqual(payload.message, 'no reason given');
});
test('all ERROR_REASON values round-trip through JSON-error mode', () => {
// spot-check a few variants
const cases = [
['config_key_not_found', 'CONFIG_KEY_NOT_FOUND'],
['phase_not_found', 'PHASE_NOT_FOUND'],
['usage', 'USAGE'],
];
for (const [expected, key] of cases) {
const script = `
const io = require(${JSON.stringify(ioPath)});
const { runMain } = require(${JSON.stringify(cliExitPath)});
io.setJsonErrorMode(true);
runMain(() => { io.error('test', io.ERROR_REASON.${key}); });
`;
const result = runScript(script);
assert.strictEqual(result.status, 1, `key=${key}`);
const payload = JSON.parse(result.stderr.trim());
assert.strictEqual(payload.reason, expected, `key=${key}`);
}
});
});
// ─── GSD_TEMP_DIR / reapStaleTempFiles ───────────────────────────────────────
describe('GSD_TEMP_DIR', () => {
test('resolves to <tmpdir>/gsd', () => {
assert.strictEqual(io.GSD_TEMP_DIR, path.join(os.tmpdir(), 'gsd'));
});
});
describe('reapStaleTempFiles (via io)', () => {
const TEST_PREFIX = 'gsd-io-test-';
afterEach(() => {
// clean up any test files we created
try {
const entries = fs.readdirSync(io.GSD_TEMP_DIR);
for (const e of entries) {
if (e.startsWith(TEST_PREFIX)) {
const p = path.join(io.GSD_TEMP_DIR, e);
try { fs.unlinkSync(p); } catch { /* ignore */ }
}
}
} catch { /* ignore */ }
});
test('removes stale files beyond maxAgeMs', () => {
fs.mkdirSync(io.GSD_TEMP_DIR, { recursive: true });
const stalePath = path.join(io.GSD_TEMP_DIR, TEST_PREFIX + 'stale.json');
fs.writeFileSync(stalePath, '{}');
// backdate mtime so it looks older than 1ms
const old = new Date(Date.now() - 10000);
fs.utimesSync(stalePath, old, old);
io.reapStaleTempFiles(TEST_PREFIX, { maxAgeMs: 5000 });
assert.ok(!fs.existsSync(stalePath), 'stale file should have been removed');
});
test('keeps fresh files within maxAgeMs', () => {
fs.mkdirSync(io.GSD_TEMP_DIR, { recursive: true });
const freshPath = path.join(io.GSD_TEMP_DIR, TEST_PREFIX + 'fresh.json');
fs.writeFileSync(freshPath, '{}');
// mtime is just now — well within a 1-hour window
io.reapStaleTempFiles(TEST_PREFIX, { maxAgeMs: 60 * 60 * 1000 });
assert.ok(fs.existsSync(freshPath), 'fresh file should have been kept');
});
test('does not throw when GSD_TEMP_DIR does not exist yet', () => {
// reap against a non-existent prefix — must not throw
assert.doesNotThrow(() => {
io.reapStaleTempFiles('gsd-io-nonexistent-prefix-xyz-', { maxAgeMs: 0 });
});
});
// #3314 — ADR-456 in-process reachability: t.mock.timers patches the
// process-global Date, so it controls `now` inside reapStaleTempFiles with
// no production code change needed. Both sides of the comparison (mocked
// "now" and the fs.utimesSync mtime) use second-aligned epoch values to
// avoid filesystem mtime sub-second-precision truncation on filesystems
// that round mtime to the nearest second.
describe('boundary: age exactly at maxAgeMs (condition is strictly-greater)', () => {
const MTIME_MS = 1_700_000_000_000; // second-aligned
const MAX_AGE_MS = 5000;
function plantFileAtAge(t, ageMs) {
fs.mkdirSync(io.GSD_TEMP_DIR, { recursive: true });
const p = path.join(io.GSD_TEMP_DIR, TEST_PREFIX + `boundary-${ageMs}.json`);
fs.writeFileSync(p, '{}');
fs.utimesSync(p, new Date(MTIME_MS), new Date(MTIME_MS));
t.mock.timers.enable(['Date']);
t.mock.timers.setTime(MTIME_MS + ageMs);
return p;
}
test('boundary: age exactly maxAgeMs-1 is kept', (t) => {
const p = plantFileAtAge(t, MAX_AGE_MS - 1);
io.reapStaleTempFiles(TEST_PREFIX, { maxAgeMs: MAX_AGE_MS });
assert.ok(fs.existsSync(p), 'file at maxAgeMs-1 must be kept');
});
test('boundary: age exactly maxAgeMs is kept (condition is strictly-greater)', (t) => {
const p = plantFileAtAge(t, MAX_AGE_MS);
io.reapStaleTempFiles(TEST_PREFIX, { maxAgeMs: MAX_AGE_MS });
assert.ok(fs.existsSync(p), 'file at exactly maxAgeMs must be kept — condition is strictly-greater, not >=');
});
test('boundary: age exactly maxAgeMs+1 is removed', (t) => {
const p = plantFileAtAge(t, MAX_AGE_MS + 1);
io.reapStaleTempFiles(TEST_PREFIX, { maxAgeMs: MAX_AGE_MS });
assert.ok(!fs.existsSync(p), 'file at maxAgeMs+1 must be removed');
});
});
});
// ─── bug #1008: output()/error() tolerate a full / slow non-blocking pipe ─────
//
// The pre-fix bare `fs.writeSync(fd, data)` assumed it blocks until the kernel
// accepts every byte — false when fd is a non-blocking pipe (the parallel
// node:test runner on Linux): a full pipe throws EAGAIN and a partially-drained
// pipe returns a SHORT count. These behavioral tests inject fs.writeSync via
// mock.method (the approved fault-injection seam) and assert the observable
// contract (no throw, full payload, real errors still surface). They are red
// against the pre-fix io.cjs (throw / truncate).
// Normalize either writeSync call form to the chunk it emits:
// buffer form: writeSync(fd, buffer, offset, length) ← the fixed writeAllSync loop
// string form: writeSync(fd, string) ← the pre-fix bare call
function bug1008ChunkOf(data, offset, length) {
if (Buffer.isBuffer(data)) {
const start = offset ?? 0;
const end = length === undefined ? data.length : start + length;
return data.subarray(start, end).toString('utf8');
}
return String(data);
}
function bug1008WriteError(code, errno) {
const e = new Error(`${code}: write`);
e.code = code;
e.errno = errno;
e.syscall = 'write';
return e;
}
describe('bug #1008: io.output() tolerates a full / slow non-blocking pipe', () => {
test('retries on EAGAIN and emits the full payload without throwing', (t) => {
const written = [];
let calls = 0;
t.mock.method(fs, 'writeSync', (fd, data, offset, length) => {
calls += 1;
if (calls === 1) throw bug1008WriteError('EAGAIN', -11); // pipe momentarily full
const chunk = bug1008ChunkOf(data, offset, length);
written.push(chunk);
return Buffer.byteLength(chunk, 'utf8');
});
const payload = { ok: true, n: 42 };
assert.doesNotThrow(() => io.output(payload, false));
assert.ok(calls >= 2, `expected a retry after EAGAIN, got ${calls} call(s)`);
assert.equal(written.join(''), JSON.stringify(payload, null, 2), 'full payload must reach the fd');
});
test('retries on EINTR (signal-interrupted write) too', (t) => {
const written = [];
let calls = 0;
t.mock.method(fs, 'writeSync', (fd, data, offset, length) => {
calls += 1;
if (calls === 1) throw bug1008WriteError('EINTR', -4);
const chunk = bug1008ChunkOf(data, offset, length);
written.push(chunk);
return Buffer.byteLength(chunk, 'utf8');
});
assert.doesNotThrow(() => io.output('plain', true, 'PLAIN-RAW'));
assert.equal(written.join(''), 'PLAIN-RAW');
});
test('handles short (partial) writes without truncating', (t) => {
const written = [];
const CAP = 3; // each writeSync accepts at most 3 bytes, like a draining pipe
t.mock.method(fs, 'writeSync', (fd, data, offset, length) => {
const chunk = bug1008ChunkOf(data, offset, length);
const part = chunk.slice(0, CAP);
written.push(part);
return Buffer.byteLength(part, 'utf8');
});
const payload = { message: 'a reasonably long ascii payload to force many short writes' };
io.output(payload, false);
assert.equal(written.join(''), JSON.stringify(payload, null, 2), 'no bytes may be dropped on short writes');
});
test('does NOT swallow a genuine, non-transient write error (EPIPE)', (t) => {
t.mock.method(fs, 'writeSync', () => { throw bug1008WriteError('EPIPE', -32); });
assert.throws(
() => io.output({ ok: true }, false),
(err) => err.code === 'EPIPE',
'real (non-transient) errors must still surface',
);
});
});
describe('bug #1008: io.error() tolerates a full non-blocking stderr pipe', () => {
// ADR-3889: error() throws ExitError instead of calling process.exit()
// directly, so mocking process.exit and asserting doesNotThrow no longer
// matches the contract — error() now DOES throw, on purpose, and the
// termination semantics (translating that throw into a process exit code)
// belong to runMain() at the entrypoint, not to error() itself. This test
// asserts the real contract directly: catch the ExitError and check its
// `code`.
test('retries on EAGAIN, emits the full message, and throws ExitError(1)', () => {
const written = [];
let calls = 0;
const restore = fs.writeSync;
fs.writeSync = (fd, data, offset, length) => {
calls += 1;
if (calls === 1) throw bug1008WriteError('EAGAIN', -11);
assert.equal(fd, 2, 'error() must write to stderr');
const chunk = bug1008ChunkOf(data, offset, length);
written.push(chunk);
return Buffer.byteLength(chunk, 'utf8');
};
try {
assert.throws(
() => io.error('boom', io.ERROR_REASON.UNKNOWN),
(err) => err instanceof ExitError && err.code === 1,
'error() must throw ExitError(1) after a retried write',
);
} finally {
fs.writeSync = restore;
}
assert.ok(calls >= 2, 'error() should retry after EAGAIN');
assert.equal(written.join(''), 'Error: boom\n');
});
});
// ────────────────────────────────────────────────────────────────────────
// Folded from tests/bug-1891-file-resolution.test.cjs — consolidation epic #1969 (B5 #1974)
// ────────────────────────────────────────────────────────────────────────
{
const { describe: __foldDescribe } = require('node:test');
__foldDescribe("folded:bug-1891-file-resolution (consolidation epic #1969 B5 #1974)", () => {
// allow-test-rule: structural-implementation-guard (see #1891)
// gsd-tools.cjs @file: resolution is a low-level stdout interception that cannot be
// exercised end-to-end via runGsdTools without a real workflow that emits @file: output.
// These structural tests guard the interception wiring until a behavioral integration
// test suite for the full @file: path is added.
/**
* Regression tests for bug #1891
*
* gsd-tools.cjs must transparently resolve @file: references in stdout
* so that workflows never see the @file: prefix. This eliminates the
* bash-specific `if [[ "$INIT" == @file:* ]]` check that breaks on
* PowerShell and other non-bash shells.
*/
'use strict';
const { describe, test, before } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('fs');
const path = require('path');
const GSD_TOOLS_SRC = path.join(__dirname, '..', 'gsd-core', 'bin', 'gsd-tools.cjs');
describe('bug #1891: @file: resolution in gsd-tools.cjs', () => {
let src;
before(() => {
src = fs.readFileSync(GSD_TOOLS_SRC, 'utf-8');
});
test('main() intercepts stdout and resolves @file: references', () => {
// The non-pick path should have @file: resolution, just like the --pick path
assert.ok(
src.includes("captured.startsWith('@file:')") ||
src.includes('captured.startsWith(\'@file:\')'),
'main() should check for @file: prefix in captured output'
);
});
test('@file: resolution reads file content via readFileSync', () => {
// Verify the resolution reads the actual file
assert.ok(
src.includes("readFileSync(captured.slice(6)") ||
src.includes('readFileSync(captured.slice(6)'),
'@file: resolution should read file at the path after the prefix'
);
});
test('stdout interception wraps runCommand in the non-pick path', () => {
// The main function should resolve @file: output in BOTH --pick and
// non-pick paths. This can be either two inline checks or a shared helper.
const mainFunc = src.slice(src.indexOf('async function main()'));
const resolveCalls = (mainFunc.match(/resolveAtFileOutput\(/g) || []).length;
const inlineAtFileChecks = (mainFunc.match(/@file:/g) || []).length;
assert.ok(
resolveCalls >= 2 || inlineAtFileChecks >= 2,
'Both --pick and normal paths should resolve @file: references'
);
});
});
});
}