* fix(#2587): resolve cursor hook workspace from workspace_roots, not cwd gsd-cursor-session-start.js and gsd-cursor-stop.js both resolved the project as path.join(process.cwd(), '.planning', 'STATE.md'). Under the cursor-agent CLI, hooks are invoked with cwd set to the Cursor config dir (~/.cursor), not the workspace — so the lookup always missed. sessionStart could only ever emit the "no .planning/ workflow found" nudge and stop's verify-work reminder could never fire, even with .planning/STATE.md sitting in the workspace. Slash commands were unaffected, which is why only the hook layer looked blind. Both hooks already buffered stdin into `raw` and never parsed it; the payload's workspace_roots carries the real path. Multi-root was left open in the report ("first root vs any root"). Resolved forward: prefer the first root that actually carries .planning/STATE.md, so a workspace whose GSD project is not the first root still resolves — strictly better than first-root-only and identical to it in the single-root CLI case. Falls back to roots[0], then to cwd, keeping IDE behavior unchanged if the IDE ever invokes hooks from the workspace. The resolver is duplicated verbatim across the two scripts rather than shared via hooks/lib/: these hooks ship standalone, and a new hooks/lib/ file must be registered in the GENERATED installer's GSD_HOOK_LIB_FILES allowlist — the installer-omits-shipped-file class that yields MODULE_NOT_FOUND at runtime. Per CLAUDE.md "Generative Fix Divergence", the duplication carries a parity assertion so the copies cannot drift. Failing-first, demonstrated by direct invocation with cwd != workspace: pre-fix sessionStart -> "no .planning/ workflow found" stop -> {} post-fix sessionStart -> ".planning/STATE.md is present" stop -> reminder tests/fix-2587-cursor-hook-workspace-roots.test.cjs spawns the real scripts as child processes with a cwd lacking .planning/ and workspace_roots pointing at it. Boundary coverage on the roots array (0 / 1 / 2 entries), plus malformed-JSON fail-open, junk-entry filtering, the parity assertion, and a guard that neither script resolves .planning from cwd again. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_015TCwhbMuY37DzRMCfzTABJ * fix(#2587): extend workspace_roots fix to subagentStart; keep cwd a candidate Three findings from the isolated review, all fixed. 1. MISSED SITE (high). gsd-cursor-subagent-start.js carried the identical defect at line 43 — its own header documents workspace_roots in the input schema, but it resolved .planning/ from process.cwd() anyway. Under the cursor-agent CLI that meant every Cursor subagent (planner, executor, verifier) started with "no .planning/ workflow found" and no phase context. The report named only sessionStart and stop; the defect class was wider. Verified pre-fix vs post-fix by direct invocation with cwd != workspace. 2. SEMANTIC NARROWING (medium). The first cut searched only workspace_roots and fell back to cwd solely when the array was EMPTY. So when roots were supplied but none carried .planning/ while cwd did, the hook reported absent — where the pre-fix code, which always used cwd, reported present. That contradicted the fallback's own stated intent of preserving IDE behavior. cwd is now a CANDIDATE in the search (`[...roots, process.cwd()]`), so the fix is a strict superset of both the old behavior and the CLI fix, never a narrowing. 3. STALE GOLDEN FIXTURES (high, would have failed CI). The golden-install-parity fixtures store a content hash per installed file; these three hooks appear in 13 of the 19 runtime fixtures. Regenerated via `npm run gen:golden` — the diff is exactly the three hook hashes in exactly those 13 runtimes. Tests extended: subagentStart resolution via workspace_roots; the stop hook's absent branch (previously only session-start's was covered); an explicit regression guard that a project at cwd is still found when roots miss; parity now asserts all THREE copies byte-identical; and the cwd guard sweeps the whole RESOLVING_HOOKS list so a future hook in this family cannot be left on cwd. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_015TCwhbMuY37DzRMCfzTABJ * refactor(#2587): extract cursor workspace resolution to a shared hooks/lib module The duplicate-plus-parity-test approach was the wrong call. The reported issue named two hooks; a third (subagentStart) had the identical defect. That is the signature of a systemic problem, and three copies of a resolver guarded by a parity assertion is a divergence risk maintained by hand rather than a fix. hooks/lib/cursor-workspace.js is now the single implementation. All three Cursor hooks require it; none defines a local copy. Divergence is prevented structurally instead of by asserting three copies stay byte-identical. The reason duplication looked necessary was real, and is fixed properly here rather than worked around: Cursor sets hostBehaviors.skipSharedHooksInstall (#2089), so it never reaches the installer's bulk hooks/lib copy — it was the ONE runtime shipping these hooks WITHOUT hooks/lib (verified against all 19 golden fixtures: cursor had the hook scripts, no lib). A naive require would have thrown MODULE_NOT_FOUND at load, BEFORE each hook's own try/catch, wedging every session on precisely the runtime this bug is about. writeCursorHooksJson (src/runtime-hooks-surface.cts) now stages the hooks/lib helpers the staged scripts actually require, discovered by scanning their require('./lib/…') calls rather than a hardcoded name — so a future helper cannot be silently omitted. This is narrower than flipping skipSharedHooksInstall, which would wrongly pull in every shared hook. cursor-workspace.js is also added to GSD_HOOK_LIB_FILES so uninstall and the manifest manage it for the runtimes that do receive hooks/lib. Verified against a REAL install (runMinimalInstall, cursor/global): the helper is staged, and all three INSTALLED hooks resolve the workspace end-to-end from a cwd that is not the project. Also closes the review gap that the stop hook was excluded from the cwd-candidate regression loop — it now sweeps RESOLVING_HOOKS. The byte-parity test is replaced by a structural guard (every hook requires the shared module, none redefines it) plus a new install test asserting the helper is staged and the installed hook actually loads against it. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_015TCwhbMuY37DzRMCfzTABJ * fix(#2587): fail loud on a missing hook lib source; drop unsubstituted version marker Two findings from the installer-focused review. H1 — the staging step's `if (!fs.existsSync(libSrc)) continue;` silently defeated the very guarantee it was added for. Reproduced: delete hooks/lib/cursor-workspace.js from source, run the cursor install — it exits 0, prints "Done!", and ships the three hook scripts with an EMPTY hooks/lib/. The installed hook then throws `Cannot find module './lib/cursor-workspace.js'` at load, before its own try/catch, wedging every session — and nothing surfaces until a user hits it. The scan protected against a required-but-UNLISTED helper while leaving required-but-MISSING wide open (typo, bad rebase, an accidental delete). It now throws: a missing helper source is a packaging bug and aborts the install. M1 — hooks/lib/cursor-workspace.js carried a `gsd-hook-version: <placeholder>` marker that NOTHING substitutes: copyLibDir stamps .sh files only, and writeCursorHooksJson's staging applies just the colon-to-dash rewrite. Verified the literal was reaching disk on both the bulk (--claude) and Cursor (--cursor) paths. hooks/lib/git-cmd.js — the only pre-existing hooks/lib/*.js — carries no such marker, so this was newly introduced, not inherited. Marker removed, matching that precedent, with a note on why. (The explanatory comment deliberately does not spell the token out, or it would reintroduce the literal.) M2 — the require-scan regex demanded the exact compact form, so `require( "./lib/x.js" )` would silently fail to stage its helper and compound H1. Now tolerant of interior whitespace and either quote style. Regression test added for H1 — the reviewer confirmed the invariant had zero coverage repo-wide: a source tree carrying the hooks but no hooks/lib/ must make writeCursorHooksJson throw rather than produce a broken install. Re-verified end to end: the missing-source case throws, no unsubstituted literal ships, and the installed hook still resolves the workspace from a foreign cwd. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_015TCwhbMuY37DzRMCfzTABJ * chore(#2587): backfill changeset pr number (#2680) --------- Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
361 lines
14 KiB
JavaScript
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 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 stdout = execFileSync(process.execPath, [script], {
|
|
cwd,
|
|
input: typeof payload === 'string' ? payload : JSON.stringify(payload),
|
|
encoding: 'utf8',
|
|
timeout: 20000,
|
|
});
|
|
return JSON.parse(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)`,
|
|
);
|
|
}
|
|
});
|
|
});
|