Files
msd-core/tests/fix-2587-cursor-hook-workspace-roots.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

361 lines
14 KiB
JavaScript

/**
* #2587 — Cursor sessionStart/stop hooks resolved .planning/ from process.cwd().
*
* Under the cursor-agent CLI, hooks are invoked with cwd set to the Cursor
* config dir (~/.cursor), NOT the workspace. Both hooks did:
*
* path.join(process.cwd(), '.planning', 'STATE.md')
*
* so the lookup always missed: gsd-cursor-session-start.js could only ever emit
* the "no .planning/ workflow found" nudge, and gsd-cursor-stop.js's verify-work
* reminder could never fire — even with .planning/STATE.md right there in the
* workspace. Both hooks already buffered stdin into `raw` but never parsed it;
* the payload's `workspace_roots` carries the real path.
*
* These are BEHAVIORAL tests: each spawns the real hook script as a child
* process with a cwd that does NOT contain .planning/ and a stdin payload whose
* workspace_roots does — exactly the CLI invocation shape from the report — and
* asserts on the emitted JSON contract. They fail against the pre-fix scripts.
*/
// allow-test-rule: source-text-is-the-product #2587 — the parity check (T8) compares the shared
// resolver text across the two standalone hook scripts, which is what Cursor loads.
'use strict';
process.env.GSD_TEST_MODE = '1';
const { test, describe } = 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 { 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');
const STOP = path.join(HOOKS, 'gsd-cursor-stop.js');
// subagentStart carried the identical defect — it was not named in the report
// but its cwd lookup meant every Cursor subagent (planner, executor, verifier)
// started without phase context under the CLI.
const SUBAGENT_START = path.join(HOOKS, 'gsd-cursor-subagent-start.js');
// Every cursor hook that resolves .planning/ from the payload. Kept as one list
// so a future hook added to this family is not silently left on the old path.
const RESOLVING_HOOKS = [SESSION_START, STOP, SUBAGENT_START];
const MSG_PRESENT_FRAGMENT = '.planning/STATE.md is present';
const MSG_ABSENT_FRAGMENT = 'no .planning/ workflow found';
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 r = runHookSeam(script, [], {
cwd,
input: typeof payload === 'string' ? payload : JSON.stringify(payload),
timeoutMs: 20000,
});
return JSON.parse(r.stdout || '{}');
}
/** A directory containing .planning/STATE.md. */
function makeWorkspace(withPlanning) {
const dir = createTempDir('gsd-2587-');
if (withPlanning) {
fs.mkdirSync(path.join(dir, '.planning'), { recursive: true });
fs.writeFileSync(path.join(dir, '.planning', 'STATE.md'), '# Project State\n');
}
return dir;
}
describe('#2587: cursor hooks resolve the workspace from workspace_roots, not cwd', () => {
test('sessionStart: cwd is the Cursor config dir, workspace_roots carries the project', () => {
const workspace = makeWorkspace(true);
const cursorConfigDir = makeWorkspace(false); // stands in for ~/.cursor
try {
const out = runHook(SESSION_START, {
cwd: cursorConfigDir,
payload: {
hook_event_name: 'sessionStart',
cursor_version: '2026.07.23-e383d2b',
is_background_agent: false,
workspace_roots: [workspace],
transcript_path: null,
},
});
assert.match(
out.additional_context || '',
new RegExp(MSG_PRESENT_FRAGMENT.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')),
'must report STATE.md present when workspace_roots points at the project',
);
} finally {
cleanup(workspace);
cleanup(cursorConfigDir);
}
});
test('stop: verify-work reminder fires when workspace_roots carries the project', () => {
const workspace = makeWorkspace(true);
const cursorConfigDir = makeWorkspace(false);
try {
const out = runHook(STOP, {
cwd: cursorConfigDir,
payload: { hook_event_name: 'stop', workspace_roots: [workspace] },
});
assert.ok(
(out.additional_context || '').includes(STOP_REMINDER_FRAGMENT),
'stop hook must emit its verify-work reminder for the real workspace',
);
} finally {
cleanup(workspace);
cleanup(cursorConfigDir);
}
});
// Boundary coverage on the workspace_roots array: 0, 1, and 2 entries.
test('zero roots: falls back to cwd (preserves IDE behavior)', () => {
const workspace = makeWorkspace(true);
try {
const out = runHook(SESSION_START, {
cwd: workspace,
payload: { hook_event_name: 'sessionStart', workspace_roots: [] },
});
assert.ok(
(out.additional_context || '').includes(MSG_PRESENT_FRAGMENT),
'an empty workspace_roots must fall back to cwd, not break the IDE path',
);
} finally {
cleanup(workspace);
}
});
test('one root, no .planning anywhere: reports absent', () => {
const workspace = makeWorkspace(false);
const cursorConfigDir = makeWorkspace(false);
try {
const out = runHook(SESSION_START, {
cwd: cursorConfigDir,
payload: { hook_event_name: 'sessionStart', workspace_roots: [workspace] },
});
assert.ok(
(out.additional_context || '').includes(MSG_ABSENT_FRAGMENT),
'a genuinely project-less workspace must still nudge toward new-project',
);
} finally {
cleanup(workspace);
cleanup(cursorConfigDir);
}
});
test('two roots: resolves the one that actually carries .planning/', () => {
const plain = makeWorkspace(false);
const withPlanning = makeWorkspace(true);
const cursorConfigDir = makeWorkspace(false);
try {
const out = runHook(SESSION_START, {
cwd: cursorConfigDir,
// GSD project is NOT the first root — first-root-only would miss it.
payload: { hook_event_name: 'sessionStart', workspace_roots: [plain, withPlanning] },
});
assert.ok(
(out.additional_context || '').includes(MSG_PRESENT_FRAGMENT),
'multi-root: the root carrying .planning/ must win over mere ordering',
);
} finally {
cleanup(plain);
cleanup(withPlanning);
cleanup(cursorConfigDir);
}
});
test('malformed stdin JSON: fails open to cwd instead of crashing', () => {
const workspace = makeWorkspace(true);
try {
const out = runHook(SESSION_START, { cwd: workspace, payload: '{not valid json' });
assert.ok(
(out.additional_context || '').includes(MSG_PRESENT_FRAGMENT),
'a malformed payload must degrade to cwd, never wedge the session',
);
} finally {
cleanup(workspace);
}
});
test('non-string and empty root entries are ignored', () => {
const workspace = makeWorkspace(true);
const cursorConfigDir = makeWorkspace(false);
try {
const out = runHook(SESSION_START, {
cwd: cursorConfigDir,
payload: {
hook_event_name: 'sessionStart',
workspace_roots: [null, '', 42, workspace],
},
});
assert.ok(
(out.additional_context || '').includes(MSG_PRESENT_FRAGMENT),
'junk entries must be filtered rather than resolved as paths',
);
} finally {
cleanup(workspace);
cleanup(cursorConfigDir);
}
});
test('subagentStart: reminder resolves via workspace_roots (missed site)', () => {
const workspace = makeWorkspace(true);
const cursorConfigDir = makeWorkspace(false);
try {
const out = runHook(SUBAGENT_START, {
cwd: cursorConfigDir,
payload: { hook_event_name: 'subagentStart', workspace_roots: [workspace] },
});
assert.match(
out.additional_context || '',
/review \.planning\/STATE\.md/,
'subagents must receive phase context, not the absent nudge',
);
} finally {
cleanup(workspace);
cleanup(cursorConfigDir);
}
});
test('stop: absent branch still emits {} when no root and no cwd has .planning', () => {
const workspace = makeWorkspace(false);
const cursorConfigDir = makeWorkspace(false);
try {
const out = runHook(STOP, {
cwd: cursorConfigDir,
payload: { hook_event_name: 'stop', workspace_roots: [workspace] },
});
assert.deepEqual(
out,
{},
'stop must stay silent when there is genuinely no GSD project',
);
} finally {
cleanup(workspace);
cleanup(cursorConfigDir);
}
});
test('cwd is a candidate, not just the empty-roots fallback', () => {
// Regression guard: resolving ONLY over workspace_roots would report absent
// whenever roots are supplied but the project actually sits at cwd — a
// NARROWING versus the pre-fix behavior, which always consulted cwd.
const projectAtCwd = makeWorkspace(true);
const unrelatedRoot = makeWorkspace(false);
try {
for (const hook of RESOLVING_HOOKS) {
const out = runHook(hook, {
cwd: projectAtCwd,
payload: { hook_event_name: 'sessionStart', workspace_roots: [unrelatedRoot] },
});
// stop's present-branch is its verify-work reminder, not a STATE.md phrase.
const ctx = out.additional_context || '';
assert.ok(
/STATE\.md is present|review \.planning\/STATE\.md|Agent stopping/.test(ctx),
`${path.basename(hook)}: a project at cwd must still be found when roots miss`,
);
}
} finally {
cleanup(projectAtCwd);
cleanup(unrelatedRoot);
}
});
test('single source: every hook requires the shared resolver, none redefines it', () => {
// The resolver lives in hooks/lib/cursor-workspace.js. Divergence is
// prevented structurally (one implementation) rather than by a parity
// assertion over copies, so this guards the structure: no hook may grow a
// local copy back.
for (const file of RESOLVING_HOOKS) {
const src = fs.readFileSync(file, 'utf8');
assert.ok(
src.includes("require('./lib/cursor-workspace.js')"),
`${path.basename(file)} must use the shared resolver`,
);
assert.ok(
!src.includes('function resolveWorkspaceRoot('),
`${path.basename(file)} must not redefine resolveWorkspaceRoot locally`,
);
}
});
test('staging fails loudly if a required lib source is missing', () => {
// Previously this path did `continue`, so a helper missing from source
// (typo, bad rebase, accidental delete) produced an install that exits 0 and
// ships hooks whose top-level require() throws MODULE_NOT_FOUND at load —
// before their own try/catch — wedging every session, with nothing to
// indicate why. Packaging bugs must surface at install, not at the user.
const hooksSurface = require('../gsd-core/bin/lib/runtime-hooks-surface.cjs');
const fakeSrc = createTempDir('gsd-2587-src-');
const target = createTempDir('gsd-2587-tgt-');
try {
// A source tree with the hook scripts but NO hooks/lib/ backing them.
const srcHooks = path.join(fakeSrc, 'hooks');
fs.mkdirSync(srcHooks, { recursive: true });
for (const hook of RESOLVING_HOOKS) {
fs.copyFileSync(hook, path.join(srcHooks, path.basename(hook)));
}
assert.throws(
() => hooksSurface.writeCursorHooksJson(target, fakeSrc, {}),
/cursor-workspace\.js.*missing|missing.*cursor-workspace\.js/s,
'a missing lib source must abort the install, not ship a broken hook',
);
} finally {
cleanup(fakeSrc);
cleanup(target);
}
});
test('the shared resolver is staged next to the hooks that require it', () => {
// The MODULE_NOT_FOUND guard. Cursor sets skipSharedHooksInstall, so it
// never reaches the installer's bulk hooks/lib copy — every other runtime
// that ships these hooks does. If writeCursorHooksJson stopped staging the
// helper, each hook would throw at require time, BEFORE its own try/catch,
// and wedge every Cursor session on the one runtime this fix exists for.
const { runMinimalInstall } = require('./helpers/install-shared.cjs');
const { configDir, root } = runMinimalInstall({ runtime: 'cursor', scope: 'global' });
try {
const staged = path.join(configDir, 'hooks', 'lib', 'cursor-workspace.js');
assert.ok(
fs.existsSync(staged),
'cursor install must stage hooks/lib/cursor-workspace.js next to the hook scripts',
);
// And the staged hook must actually load against it.
const hook = path.join(configDir, 'hooks', 'gsd-cursor-session-start.js');
assert.ok(fs.existsSync(hook), 'cursor install must stage the sessionStart hook');
const ws = makeWorkspace(true);
try {
const out = JSON.parse(execFileSync(process.execPath, [hook], {
cwd: root,
input: JSON.stringify({ workspace_roots: [ws] }),
encoding: 'utf8',
timeout: 20000,
}) || '{}');
assert.ok(
(out.additional_context || '').includes('STATE.md is present'),
'the INSTALLED hook must resolve the workspace, not crash on a missing helper',
);
} finally {
cleanup(ws);
}
} finally {
cleanup(root);
}
});
test('no cursor hook resolves .planning from process.cwd() directly', () => {
for (const file of RESOLVING_HOOKS) {
const src = fs.readFileSync(file, 'utf8');
assert.ok(
!/path\.join\(\s*process\.cwd\(\)\s*,\s*'\.planning'/.test(src),
`${path.basename(file)}: must not resolve .planning from cwd (#2587)`,
);
}
});
});