* enhance(#3911): give hooks an exit seam that needs no build ADR-3889 Phase 7 foundation. The 19 shipped enforcement hooks hold 91 of the epic's 128 terminators and cannot reach `terminateNow` today. The obvious route — requiring `gsd-core/bin/lib/cli-exit.cjs`, as gsd-agent-isolation-guard.js already does for two other modules — is rejected. That precedent carries its own warning (#3582): those files are tsc output, gitignored and absent on a raw plugin-marketplace or git-clone install, so the hook must first call ensureRuntimeBuild() to self-heal. Making the module a hook needs IN ORDER TO TERMINATE depend on a build inverts the dependency, and its failure mode is precisely the fail-open this phase exists to remove: a guard that cannot terminate cannot deny. `lint-hooks-runtime-build-seam` already encodes that concern, and Design B would have had to add an ensureRuntimeBuild() call to all 19 hooks to satisfy it. So `hooks/lib/` becomes a third emit location for cli-exit and a fifth for the registry, preserving the invariant `src/cli-exit.cts`'s own header states: it imports nothing but node:fs and its sibling registry, and the generator dual-emits that sibling alongside each copy so a relative require resolves next to whichever copy loaded it. Shipping needed no change — build-hooks.js already declares HOOKS_SUBDIRS_TO_COPY = ['lib']. Proven, not asserted: the two files are copied into an otherwise-empty tmpdir and a child process requires them and terminates — PASS exits 0, HOOK_DENY exits 2 with the payload on both stdout and stderr. That test fails the moment the hooks copy gains a require reaching outside hooks/lib/. Also fixed inline: the registry's fifth target let any `--write` test overwrite the real committed hooks/lib/exit-code-registry.js, because the test helper derived only three of the other output paths. It now redirects all five, and a regression test asserts every committed artifact is byte-identical after a redirected write. Install-tree goldens pick up the two new shipped paths across 11 runtimes — insertions only, no removals. lint:ci was green while they were stale, so this was found by regenerating rather than by a gate. Verification runs on the remote runner. Refs #3911 * enhance(#3911): declare a crash policy, and migrate the write guard Adds `hooks/lib/hook-exit.js` — the hook-facing vocabulary over `terminateNow`, hand-written because the cli-exit copy beside it is generated: allow(payload) exit 0 deny(payload, stderr?) exit 2 crash(onCrash, payload) whichever the hook DECLARED `crash()` takes the policy as a required argument with no default, which is the whole mechanism: fail-open by accident stops being expressible. A hook must name ALLOW or DENY at the call site, and an unrecognized value terminates INTERNAL rather than guessing. Fail-open stays legal; fail-open by omission does not. `gsd-write-guard.js` is the first hook migrated, all 12 sites, and it exposed a gap in the seam. `terminateNow`'s doc comment justified its fd-2 write by citing this hook's `emitBlock` — but modeled it as sending the same bytes to both streams, when `emitBlock` actually sends full JSON to stdout and only the bare `reason` string to stderr, because Kimi's hook bus feeds stderr verbatim back to the model. Migrating as written would have turned a readable sentence into a JSON blob for Kimi-backed agents. #3911 requires both "all 19 hooks terminate through terminateNow" and "no hook's effective default changes". Those are jointly satisfiable only by teaching the seam to carry a distinct stderr payload, so `terminateNow` gains an optional third argument: omitted, behavior is byte-for-byte what it was; a string is written raw, which is exactly the Kimi case. The doc comment's inaccurate claim about emitBlock is corrected in place. Proven rather than asserted: the pre-migration file is reconstructed from HEAD and driven with the same catastrophic-shrink payload as the migrated one — exit code, stdout and stderr all byte-identical. Verification runs on the remote runner. Refs #3911 * enhance(#3911): all 19 hooks terminate through the seam Migrates the remaining 18 enforcement hooks onto allow/deny/crash. An AST walk now reports zero `process.exit(` call sites across every `hooks/*.js` — down from the 91 the census measured. Each hook with an outer catch declares its policy once, at module top, with the reason that policy is right for that specific guard: a read guard that cannot scan must not block the read; a statusline that renders every prompt must degrade rather than crash; an injection scanner must not retroactively block a result already returned. Those sentences are the deliverable — they are what turns fail-open-by-accident into fail-open-on-purpose. No hook's effective default changed. Wiring exposed two defects, both fixed here rather than noted. A SECOND stdout/stderr-splitting site turned up in `gsd-workflow-guard.js`'s `emitForceAddBlock`, matching the pattern already known from the write guard — full JSON to stdout, bare reason to stderr for the Kimi bus. It uses the `stderrPayload` argument added in the previous commit, which is now carrying its second real caller rather than one special case. More seriously, `terminateNow` emitted both streams inside ONE try, so a payload that failed to serialize aborted before the stderr write ever ran. The two windsurf guards write nothing to stdout on a block and only a reason string to stderr, so `deny(undefined, reason)` exited 2 with EMPTY stderr — a deny that silently loses its reason, which is the exact "fails with success" class this epic exists to close. The streams are now emitted independently, each with its own guard, and `undefined` means "nothing to write for this stream" rather than an error. Regression tests inject a throwing write on one fd and assert the other still receives its payload; they fail against the single-try version. Byte-identity was proven per hook, not assumed: each pre-change file is reconstructed from HEAD and driven side by side with the migrated one across its normal path, its deny path, malformed stdin and empty stdin — exit code, stdout and stderr compared. Verification runs on the remote runner. Refs #3911 * enhance(#3911): harden the three shell hooks, and pin every hook's policy `gsd-phase-boundary.sh`, `gsd-session-state.sh` and `gsd-validate-commit.sh` gain `set -euo pipefail`. The expected hazard did not materialize, and that is worth recording: every intentionally-non-zero command in all three is already the condition of an `if`/`elif`, which `set -e` never fires on, and none of them reads a possibly-unset variable or pipes through a grep that may legitimately match nothing. No `|| true` guards were needed. Each hook was still checked command-by-command before the flags went in rather than after. Twenty-one before/after cases across the three hooks — disabled and enabled, planning and non-planning, missing STATE.md, malformed JSON, the Kimi payload shape, quoted and unquoted `-m`, valid and over-long Conventional Commits — all match on exit code, stdout and stderr. The hardening is shown to actually fire, not merely added: with a stubbed `node` that fails at the JSON-emit step, phase-boundary and session-state go from silently exiting 0 with empty stdout to failing visibly with the error surfaced. No such case could be constructed for `gsd-validate-commit.sh`, whose every statement already sits inside an if-condition — recorded as unproven rather than claimed. `tests/hooks-crash-policy.test.cjs` adds the per-hook coverage the issue asks for, table-driven over all 19 hooks rather than 76 hand-written cases: normal allow, deny where a deny path exists, crash-honors-the-declared-policy, and an unclosed-stdin case — the one `process.exitCode` structurally cannot serve. The deny assertions encode each hook's ACTUAL stream split rather than a uniform shape, since four of the six deliberately differ. A drift guard enumerates `hooks/*.js` and fails if a terminating hook is ever added without a row. Writing those tests surfaced two hooks that emit a block decision in their JSON body and exit 0. Both were checked rather than assumed, and neither is a fails-with-success: `gsd-read-injection-scanner.js` is PostToolUse, where the tool has already run and exit 2 has no meaning, and `gsd-cursor-subagent-start.js` follows Cursor's JSON-body protocol. They are deliberately left alone — a mechanical sweep to `deny()` would have broken exactly these two. Verification runs on the remote runner. Refs #3911 * fix(#3838): the commit validator says when it could not validate #3911 claims to subsume #3838. Measurement said otherwise, so this closes it for real rather than by assertion. `set -euo pipefail`, added earlier on this branch, does NOT fix #3838: bash exempts a command used as an `if` condition from `set -e`, and all three of the hook's swallow-and-pass sites are exactly that shape. Verified against the hardened hook with a node shim that fails only the classifier call — a non-conforming commit still exited 0 with empty stdout AND empty stderr, indistinguishable from "your commit conforms". That is the defect verbatim. All three sites named in #3838 now capture the real exit status instead of consuming it as a condition, and each distinguishes its genuine negative from "could not run": - the classifier: 0 = is a git commit, 1 = genuinely not one, anything else = could not classify. Its `node -e` now wraps the require and the call in try/catch and exits 3 on a throw, so a broken require chain can never be mistaken for `isGitSubcommand` legitimately returning false — which is the arm that matters, since `token-scanner.cjs` is a gitignored build artifact and a fresh checkout lands there. - the opt-in config read and the JSON command extraction get the same treatment. On "could not run" the hook emits a diagnostic to stderr naming which check failed and why, then exits 0. The issue confirms this is safe — it is a PreToolUse hook, so stderr does not disturb the JSON protocol — and ranks it the smallest sufficient fix. The gate still fails open, but it can no longer do so silently, which is the whole complaint: a validator that disables itself quietly costs more than one that is absent, because it is trusted. Both controls are unchanged and pinned by tests: a conforming commit still passes silently, a non-conforming one still exits 2 with its existing block payload. The defect test asserts stderr is non-empty and names the failure; it fails against the pre-fix hook. Verification runs on the remote runner. Refs #3911, #3838 * docs(#3911): document the hook crash-policy contract Reference and Explanation via a new docs/features fragment (FEATURES.md is generated from it), INVENTORY rows for the three new hooks/lib files, and an ARCHITECTURE note on the hooks section. How-To: docs/how-to/declare-a-hook-crash-policy.md, indexed from docs/README.md — a hook author now has to choose and declare a crash policy, which is more than one step and crosses into which harness protocol their hook speaks. It covers allow/deny/crash, writing an ON_CRASH reason that is actually useful, when a deny needs a distinct stderr payload, the two hooks whose harness reads a JSON-body decision and must NOT use deny(), and what to do when a check cannot run at all — with #3838 as the worked example. Refs #3911 * test(#3911): prove the seam actually ships, and stop hand-rolling temp cleanup Two review findings. The acceptance criterion 'hooks/dist/** stays in parity via the build seam (lint:hooks-runtime-build-seam)' was misstated and unmet: that lint checks something else — that a hook requiring a compiled gsd-core/bin/lib module also calls ensureRuntimeBuild(). Nothing exercised that the three new hooks/lib files reach hooks/dist/lib at all. That gap is not theoretical: #770 is a recorded ship-blocking bug where a new hook never shipped because a copy list missed it. The suite now builds dist through the repo's own ensureBuiltHooks(), byte-compares each shipped copy against its source, and spawns a child that requires the SHIPPED dist copy and denies — which is what catches a copy that exists but cannot resolve its sibling registry. gsd-validate-commit.sh hand-duplicated mktemp/run/rm three times; one idempotent trap on EXIT replaces them, guarded so cleanup cannot alter the exit status. Behavior-neutral across five cases, with temp-file counts taken before and after each run. Refs #3911 * fix(#3911): stage transitive hook lib requires, not just one level The remote run returned 7 failures across 3 real causes. The important one is a PRODUCTION bug this phase exposed rather than caused. `writeCursorHooksJson` scanned each hook script for `./lib/X` requires exactly one level deep and never re-scanned the lib files it staged for their own sibling requires. Nothing had a transitive lib dependency before, so the gap was invisible. Adding hook-exit.js -> cli-exit.js -> exit-code-registry.js made real Cursor installs ship a bundle that dies at require time with MODULE_NOT_FOUND. It now walks to a fixed point, and a real installed Cursor hook runs to completion. The staging harness in shared-hooks-dir-resolution hand-copied its fixture, so the injection scanner crashed at require time and its exit-1 was being read as a policy decision. Migrated to copyScriptWithDeps, which walks the require graph — the repo's recorded rule for this class, since adding another copyFileSync keeps it alive for the next person. The missing-lib-source test in cursor-hook-workspace-roots hardcoded which lib file it expected to be named in the abort message; the same throw now fires for a different file first. Its assertion is unchanged in substance — staging still must abort rather than ship a broken hook — only the name is no longer pinned. The last one was my own test asserting an uppercase reason code. Measured against origin/next: the pre-change hook emits the same lowercase 'config_unreadable', so the test was wrong, not the migration. Corrected to the real value rather than making the code match the test. Verification runs on the remote runner. Refs #3911 * chore(#3911): regenerate the cursor install-tree golden The staging fix means a Cursor install now correctly carries the two transitive lib files it was silently missing. Additive only — no path was removed. The golden diff is the evidence the packaging defect was real. Refs #3911 * chore(#3911): backfill the changeset PR number Refs #3911 * fix(#3911): a git probe that timed out is not a negative A macOS CI lane failed three deny cases at 2084ms, 2112ms and 2177ms — just past the 2000ms budget these hooks give their git probes. The three that passed took 72ms, 595ms and 651ms. Under shard contention `git rev-parse` overruns, the hook reads the non-zero result as "not a git repo", and allows with exit 0 and empty stdout AND empty stderr. Under load, the guards silently stop guarding. That is ADR-3889's thesis exactly, sitting inside the security hooks this phase is about. The repo had already recognized the class in one place — gsd-cursor-subagent-start.js fail-closed-denies on `git_timed_out` (#3045) — but nowhere else. `hooks/lib/git-probe.js` classifies a probe's outcome, distinguishing a real non-zero exit from ETIMEDOUT, a signal kill, and a spawn failure, rather than folding all four into `status !== 0`. Three guards route their eight git probes through it. The resolution is the same shape #3838 took, and the same one that issue endorsed as smallest-sufficient: fail open, but loudly. **No exit code changes on any path** — a developer on a loaded machine is still not blocked, which keeps #3911's declaration-pass contract intact for exit codes. What changes is that the hook now says on stderr which probe could not answer, instead of presenting silence as a clean verdict. Scope was checked across every hooks/*.js, not just the three that failed: gsd-agent-isolation-guard spawns no git; gsd-statusline's two probes gate only a cosmetic display segment, not an allow/deny decision, and are left alone. The C2 deny assertion was a real-race test — it demanded exit 2 while a slow git legitimately yields 0. It now requires the hook to either deny, or allow with a diagnostic naming the probe that could not run; a silent allow still fails, so the assertion is not vacuous. A deterministic regression stubs git on PATH to sleep past the budget rather than waiting for load to reproduce it. Verification runs on the remote runner. Refs #3911 * test(#3911): a PATH shim cannot intercept the hooks' git spawn on Windows The deterministic timeout regression stubbed git on PATH and asserted the guard reports rather than silently allows. It passes on Linux and macOS and failed on Windows in 83ms and 176ms — the stub was never invoked at all. Mechanism: the hooks call spawnSync('git', args) with no shell:true, so on Windows CreateProcess resolves git.exe only and never a PATH .cmd shim. The git.cmd branch could not have worked and is removed rather than left implying a Windows path that does. Adding shell:true to the hooks to serve a test would change product behavior and widen an injection surface, so the case is skipped on win32 only, with the mechanism written into the skip reason so a future reader does not 'fix' it that way. Linux and macOS keep the coverage, and macOS is where the underlying fail-open was actually caught. Refs #3911 --------- Co-authored-by: sim <sim@local>
370 lines
14 KiB
JavaScript
370 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 { escapeRegex } = require('../gsd-core/bin/lib/pattern.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(escapeRegex(MSG_PRESENT_FRAGMENT)),
|
|
'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)));
|
|
}
|
|
// Any one of the RESOLVING_HOOKS' required lib/ helpers is a valid trip
|
|
// wire here — this fixture supplies NONE of them, so whichever helper the
|
|
// scan discovers first is reported missing. Coupling this assertion to one
|
|
// specific filename (formerly 'cursor-workspace.js') breaks every time the
|
|
// discovery order shifts, e.g. #3911 adding an earlier './lib/hook-exit.js'
|
|
// require to these same hook scripts. The invariant under test is "some
|
|
// required lib helper missing from hooks/lib -> the install aborts", not
|
|
// "this exact helper is named first".
|
|
assert.throws(
|
|
() => hooksSurface.writeCursorHooksJson(target, fakeSrc, {}),
|
|
/hooks\/lib\/[A-Za-z0-9._-]+\.js is required by a staged Cursor hook but is missing/,
|
|
'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)`,
|
|
);
|
|
}
|
|
});
|
|
});
|