Files
msd-core/tests/lint-docs-command-form.test.cjs
Tom Boucher 5fd5c81042 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>
2026-08-05 01:06:39 -04:00

224 lines
8.4 KiB
JavaScript

'use strict';
/**
* TDD tests for scripts/lint-docs-command-form.cjs (#2903).
*
* Uses spawnSync to invoke the guard script against a temporary git repo so
* we can inject fixtures without touching the real repo. Mirrors the fixture
* pattern in tests/lint-legacy-dir-name.test.cjs.
*/
const { describe, test } = require('node:test');
const assert = require('node:assert/strict');
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');
function createTempRepo() {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-lint-docs-command-form-test-'));
execFileSync('git', ['init', '--initial-branch=main'], { cwd: dir });
execFileSync('git', ['config', 'user.email', 'test@example.com'], { cwd: dir });
execFileSync('git', ['config', 'user.name', 'Test'], { cwd: dir });
// Roster source: the guard reads commands/gsd/*.md filenames as valid
// command names, regardless of tracked/staged status.
writeFile(dir, 'commands/gsd/plan-phase.md', '# plan-phase\n');
return dir;
}
function writeFile(dir, relPath, content) {
const fullPath = path.join(dir, relPath);
fs.mkdirSync(path.dirname(fullPath), { recursive: true });
fs.writeFileSync(fullPath, content, 'utf8');
}
function gitAdd(dir, relPath) {
execFileSync('git', ['add', relPath], { cwd: dir });
}
function cleanup(dir) {
// eslint-disable-next-line local/no-raw-rmsync-in-tests -- local cleanup in lint test; no helpers import available
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) {
const r = runNode([GUARD_SCRIPT], {
cwd,
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', () => {
test('exits non-zero and names the file when docs contain /gsd:<cmd>', () => {
const dir = createTempRepo();
try {
writeFile(dir, 'docs/how-to/example.md', 'Run `/gsd:plan-phase` to start.\n');
gitAdd(dir, 'commands/gsd/plan-phase.md');
gitAdd(dir, 'docs/how-to/example.md');
const result = runGuard(dir);
assert.notEqual(result.status, 0, `expected non-zero exit, got ${result.status}; stdout: ${result.stdout}`);
assert.ok(result.stderr.includes('docs/how-to/example.md'), `stderr should name the file: ${result.stderr}`);
} finally {
cleanup(dir);
}
});
});
describe('lint-docs-command-form — plugin namespace permitted', () => {
test('exits 0 when docs contain /gsd-core:<cmd>', () => {
const dir = createTempRepo();
try {
writeFile(dir, 'docs/how-to/example.md', 'Run `/gsd-core:plan-phase` to start.\n');
gitAdd(dir, 'commands/gsd/plan-phase.md');
gitAdd(dir, 'docs/how-to/example.md');
const result = runGuard(dir);
assert.equal(result.status, 0, `expected exit 0 for /gsd-core:, got ${result.status}; stderr: ${result.stderr}`);
} finally {
cleanup(dir);
}
});
});
describe('lint-docs-command-form — docs/adr exempt', () => {
test('exits 0 for a fixture under docs/adr/', () => {
const dir = createTempRepo();
try {
writeFile(dir, 'docs/adr/999-example.md', 'Historically we typed `/gsd:plan-phase`.\n');
gitAdd(dir, 'commands/gsd/plan-phase.md');
gitAdd(dir, 'docs/adr/999-example.md');
const result = runGuard(dir);
assert.equal(result.status, 0, `expected exit 0 under docs/adr/, got ${result.status}; stderr: ${result.stderr}`);
} finally {
cleanup(dir);
}
});
});
describe('lint-docs-command-form — source trees never checked', () => {
test('exits 0 for a fixture under gsd-core/workflows/ (colon form is correct there)', () => {
const dir = createTempRepo();
try {
writeFile(dir, 'gsd-core/workflows/example.md', 'Dispatch `/gsd:plan-phase`.\n');
gitAdd(dir, 'commands/gsd/plan-phase.md');
gitAdd(dir, 'gsd-core/workflows/example.md');
const result = runGuard(dir);
assert.equal(result.status, 0, `expected exit 0 under gsd-core/workflows/, got ${result.status}; stderr: ${result.stderr}`);
} finally {
cleanup(dir);
}
});
});
describe('lint-docs-command-form — bare colon form flagged', () => {
test('exits non-zero when docs contain bare gsd:<cmd>', () => {
const dir = createTempRepo();
try {
writeFile(dir, 'docs/how-to/example.md', 'The command is gsd:plan-phase.\n');
gitAdd(dir, 'commands/gsd/plan-phase.md');
gitAdd(dir, 'docs/how-to/example.md');
const result = runGuard(dir);
assert.notEqual(result.status, 0, `expected non-zero exit, got ${result.status}; stdout: ${result.stdout}`);
assert.ok(result.stderr.includes('docs/how-to/example.md'), `stderr should name the file: ${result.stderr}`);
} finally {
cleanup(dir);
}
});
});
describe('lint-docs-command-form — name: frontmatter key citation exempt', () => {
test('exits 0 when docs quote `name: gsd:next` as a source frontmatter citation', () => {
const dir = createTempRepo();
try {
writeFile(dir, 'commands/gsd/next.md', '---\nname: gsd:next\n---\n');
writeFile(
dir,
'docs/how-to/example.md',
'Frontmatter:\n- `name: gsd:next` (surfaces as `/gsd-next`)\n',
);
gitAdd(dir, 'commands/gsd/next.md');
gitAdd(dir, 'docs/how-to/example.md');
const result = runGuard(dir);
assert.equal(
result.status,
0,
`expected exit 0 for a name: frontmatter citation, got ${result.status}; stderr: ${result.stderr}`,
);
assert.ok(result.stdout.includes('0 violations'), `stdout: ${result.stdout}`);
} finally {
cleanup(dir);
}
});
});
describe('lint-docs-command-form — name: exemption is narrow, not a blanket hole', () => {
test('exits non-zero when bare gsd:next appears without a preceding name: key', () => {
const dir = createTempRepo();
try {
writeFile(dir, 'commands/gsd/next.md', '---\nname: gsd:next\n---\n');
writeFile(dir, 'docs/how-to/example.md', 'Just type gsd:next to run it.\n');
gitAdd(dir, 'commands/gsd/next.md');
gitAdd(dir, 'docs/how-to/example.md');
const result = runGuard(dir);
assert.notEqual(result.status, 0, `expected non-zero exit, got ${result.status}; stdout: ${result.stdout}`);
assert.ok(result.stderr.includes('docs/how-to/example.md'), `stderr should name the file: ${result.stderr}`);
} finally {
cleanup(dir);
}
});
});
describe('lint-docs-command-form — case-insensitive detection', () => {
test('exits non-zero when docs contain /GSD:next (mixed case)', () => {
const dir = createTempRepo();
try {
writeFile(dir, 'commands/gsd/next.md', '---\nname: gsd:next\n---\n');
writeFile(dir, 'docs/how-to/example.md', 'Run `/GSD:next` to start.\n');
gitAdd(dir, 'commands/gsd/next.md');
gitAdd(dir, 'docs/how-to/example.md');
const result = runGuard(dir);
assert.notEqual(result.status, 0, `expected non-zero exit, got ${result.status}; stdout: ${result.stdout}`);
assert.ok(result.stderr.includes('docs/how-to/example.md'), `stderr should name the file: ${result.stderr}`);
} finally {
cleanup(dir);
}
});
});
describe('lint-docs-command-form — clean docs tree', () => {
test('exits 0 on a clean fixture repo with no colon-form commands', () => {
const dir = createTempRepo();
try {
writeFile(dir, 'docs/how-to/example.md', 'Run `/gsd-plan-phase` to start.\n');
gitAdd(dir, 'commands/gsd/plan-phase.md');
gitAdd(dir, 'docs/how-to/example.md');
const result = runGuard(dir);
assert.equal(result.status, 0, `expected exit 0, got ${result.status}; stderr: ${result.stderr}`);
assert.ok(result.stdout.includes('0 violations'), `stdout: ${result.stdout}`);
} finally {
cleanup(dir);
}
});
});