* feat(#770): register Claude Code lifecycle hooks (SubagentStop/Stop/PreCompact/FileChanged) Wire three new context-tracking events (SubagentStop, Stop, PreCompact) to gsd-context-monitor so context-headroom warnings surface at model-stop and subagent-finalisation moments — not just on PostToolUse. Add a new FileChanged hook (gsd-config-reload.js) that hot-reloads .planning/config.json context mid-session when the user edits it, injecting a config summary as hookSpecificOutput.additionalContext. Updates plugin manifest hooks.json, managed-hooks-registry, installer-migration-report allowlist, and shell-command-projection cleanup tables. Tests: 21 new assertions in enh-770-claude-hook-events.test.cjs; enh-788 and issue-766 test suites updated. Closes #770 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * docs(#770): document newly-registered Claude Code lifecycle hooks Add a Hook coverage table to the Claude Code npm installer section of docs/how-to/install-on-your-runtime.md describing SubagentStop, Stop, PreCompact, and the new FileChanged (gsd-config-reload.js) hook that hot-reloads .planning/config.json mid-session. Also fixes the changeset frontmatter (adds type: Added + pr: 821) so docs-lint can consume the fragment. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * fix(#770): add gsd-config-reload.js to INVENTORY.md and regenerate manifest The feat commit added hooks/gsd-config-reload.js but did not bump the Hooks count in docs/INVENTORY.md (14→15) or add the new row, and did not regenerate docs/INVENTORY-MANIFEST.json. Both inventory-counts and inventory-manifest-sync tests failed across the full CI matrix. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * fix(#770): make lifecycle-hook tests deterministic on scoped runner Replace the shared hooks/dist/ ensemble setup (ensureHooksDist / teardownHooksDist) in the Claude hook tests with per-test isolation: pre-populate each test's own tmpDir/.claude/hooks/ with stub files and pass installerMigrations:[] to install() so the first-time-baseline migration does not remove the stubs before the copy step can run. Root cause: hooks/dist/ is gitignored and absent on a fresh npm ci. ensureHooksDist() created it and teardownHooksDist() deleted it, but with --test-concurrency=4 both test files ran concurrently as separate Node.js worker processes sharing the same filesystem. One file's afterEach teardown deleted hooks/dist/ while the other file's install() was copying from it, producing an ENOENT (reproduced 2/10 runs locally). The additional issue: even with pre-placed stubs surviving the copy race, the 000-first-time-baseline migration classified hooks/gsd-*.js as bundled-gsd-hook artifacts, auto-removed them, and the copy step never re-ran (hooks/dist/ absent) — leaving contextMonitorFile missing and all hook registrations silently skipped (the 'got: []' symptom). Fix: pre-populate targetDir/hooks/ per-test (isolated temp dir) AND pass installerMigrations:[] so the baseline scan is skipped. The Qwen suites already used this pattern correctly; the Claude suites are aligned to it. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * fix(#770): ship gsd-config-reload.js by adding it to build-hooks HOOKS_TO_COPY The #770 feature added hooks/gsd-config-reload.js and registered it in MANAGED_HOOKS, the installer, INVENTORY, and the test EXPECTED_ALL_HOOKS list — but never added it to scripts/build-hooks.js HOOKS_TO_COPY. As a result the hook was never copied into hooks/dist/ during the build, so: - the hook would never ship to users (real production bug — the FileChanged config-reload feature was dead-on-arrival), and - install-minimal-hooks.test.cjs #1755 ("all expected hooks are copied from hooks/dist/ to target", ".js hooks are executable after copy", "manifest contains .js hook entries") failed on any environment with a clean checkout (no pre-existing hooks/dist/): coverage, full test macos-22/macos-24, test ubuntu-24. The failures were masked locally only by a stale hooks/dist/ left from a prior build (build-hooks copies into dist without clearing it). On CI's fresh `npm ci` there is no dist, so the omission surfaced. Fix: add 'gsd-config-reload.js' to HOOKS_TO_COPY so build-hooks stages it into hooks/dist/ alongside the other JS hooks. Verified by removing hooks/dist/ and rerunning the full suite green (0 fail). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * fix(#770): make config prototype-pollution beforeEach deterministic on scoped runner Root cause: the #663 and alert-#26 prototype-pollution describe blocks seeded .planning/config.json in beforeEach via a bare runGsdTools('config-ensure-section') whose result was discarded. That command runs in a spawned gsd-tools child; on the scoped CI lane (--test-concurrency=4, config.test.cjs scheduled alongside the heavy install/tarball suites that #770 pulled into the targeted set) the child can be transiently killed under resource pressure (non-zero exit, empty stderr — an OS-level kill, not an app error). The swallowed failure left config.json absent, so the first subtest's readConfig() threw ENOENT opening <tmp>/.planning/config.json. Only 1 of 4 subtests failed, confirming a per-invocation transient, not a deterministic miss; the full suite schedules files differently so config.test.cjs did not collide with those heavy neighbors → passed there. Fix: add ensureConfigReady(tmpDir) which retries config-ensure-section on ANY failure or missing file and throws a clear diagnostic if it still cannot create config.json, then use it in both prototype-pollution beforeEach blocks. Setup is now deterministic under load; the #663/alert-#26 security assertions are unchanged. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
218 lines
7.8 KiB
JavaScript
218 lines
7.8 KiB
JavaScript
'use strict';
|
|
|
|
/**
|
|
* Shared helpers and constants for install test suite.
|
|
* Used by install.test.cjs, install-runtime-artifacts.test.cjs,
|
|
* and install-minimal-hooks.test.cjs.
|
|
*/
|
|
|
|
const fs = require('node:fs');
|
|
const path = require('node:path');
|
|
const os = require('node:os');
|
|
const { spawnSync } = require('node:child_process');
|
|
const assert = require('node:assert/strict');
|
|
|
|
const INSTALL_SCRIPT = path.join(__dirname, '..', '..', 'bin', 'install.js');
|
|
const MANIFEST_NAME = 'gsd-file-manifest.json';
|
|
|
|
const BUILD_SCRIPT = path.join(__dirname, '..', '..', 'scripts', 'build-hooks.js');
|
|
const HOOKS_DIST = path.join(__dirname, '..', '..', 'hooks', 'dist');
|
|
|
|
const EXPECTED_SH_HOOKS = [
|
|
'gsd-session-state.sh',
|
|
'gsd-validate-commit.sh',
|
|
'gsd-phase-boundary.sh',
|
|
];
|
|
|
|
const EXPECTED_ALL_HOOKS = [
|
|
'gsd-check-update.js',
|
|
'gsd-config-reload.js',
|
|
'gsd-context-monitor.js',
|
|
'gsd-prompt-guard.js',
|
|
'gsd-read-guard.js',
|
|
'gsd-read-injection-scanner.js',
|
|
'gsd-statusline.js',
|
|
'gsd-workflow-guard.js',
|
|
...EXPECTED_SH_HOOKS,
|
|
];
|
|
|
|
// ─── Runtime metadata table ───────────────────────────────────────────────────
|
|
|
|
const RUNTIME_META = {
|
|
claude: { localDir: '.claude', globalSuffix: '.claude' },
|
|
antigravity: { localDir: '.agent', globalSuffix: path.join('.gemini', 'antigravity') },
|
|
augment: { localDir: '.augment', globalSuffix: '.augment' },
|
|
cline: { localDir: '.cline', globalSuffix: '.cline' },
|
|
codebuddy: { localDir: '.codebuddy', globalSuffix: '.codebuddy' },
|
|
codex: { localDir: '.codex', globalSuffix: '.codex' },
|
|
copilot: { localDir: '.github', globalSuffix: '.copilot' },
|
|
cursor: { localDir: '.cursor', globalSuffix: '.cursor' },
|
|
gemini: { localDir: '.gemini', globalSuffix: '.gemini' },
|
|
hermes: { localDir: '.hermes', globalSuffix: '.hermes' },
|
|
kilo: { localDir: '.kilo', globalSuffix: path.join('.config', 'kilo') },
|
|
opencode: { localDir: '.opencode', globalSuffix: path.join('.config', 'opencode') },
|
|
qwen: { localDir: '.qwen', globalSuffix: '.qwen' },
|
|
trae: { localDir: '.trae', globalSuffix: '.trae' },
|
|
windsurf: { localDir: '.windsurf', globalSuffix: path.join('.codeium', 'windsurf') },
|
|
};
|
|
|
|
// Runtimes that emit per-skill files under skills/ (not rules-based or commands-based)
|
|
const SKILL_RUNTIMES = [
|
|
'claude', 'opencode', 'gemini', 'kilo', 'codex', 'copilot', 'antigravity',
|
|
'cursor', 'windsurf', 'augment', 'trae', 'qwen', 'codebuddy',
|
|
];
|
|
|
|
// ─── Helper functions ─────────────────────────────────────────────────────────
|
|
|
|
function stripAnsi(str) {
|
|
|
|
return str.replace(/\x1b\[[0-9;]*m/g, '');
|
|
}
|
|
|
|
function walk(dir) {
|
|
const results = [];
|
|
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
const full = path.join(dir, entry.name);
|
|
if (entry.isDirectory()) results.push(...walk(full));
|
|
else results.push(full);
|
|
}
|
|
return results;
|
|
}
|
|
|
|
function simulateHookCopy(hooksSrc, hooksDest) {
|
|
fs.mkdirSync(hooksDest, { recursive: true });
|
|
for (const entry of fs.readdirSync(hooksSrc)) {
|
|
const srcFile = path.join(hooksSrc, entry);
|
|
if (!fs.statSync(srcFile).isFile()) continue;
|
|
const destFile = path.join(hooksDest, entry);
|
|
if (entry.endsWith('.js')) {
|
|
fs.writeFileSync(destFile, fs.readFileSync(srcFile, 'utf8'));
|
|
try { fs.chmodSync(destFile, 0o755); } catch { /* Windows */ }
|
|
} else {
|
|
fs.copyFileSync(srcFile, destFile);
|
|
if (entry.endsWith('.sh')) {
|
|
try { fs.chmodSync(destFile, 0o755); } catch { /* Windows */ }
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/** Build a clean env for spawned installer processes.
|
|
* Must strip GSD_TEST_MODE so the child runs the real install, not the no-op guard. */
|
|
function installerEnv(overrides = {}) {
|
|
const env = { ...process.env, ...overrides };
|
|
delete env.GSD_TEST_MODE;
|
|
return env;
|
|
}
|
|
|
|
function runMinimalInstall({ runtime, scope, extraArgs = [] }) {
|
|
const root = fs.mkdtempSync(path.join(os.tmpdir(), `gsd-${runtime}-${scope}-`));
|
|
try {
|
|
const LOCAL_DIR_NAME = {
|
|
claude: '.claude', opencode: '.opencode', gemini: '.gemini', kilo: '.kilo',
|
|
codex: '.codex', copilot: '.github', antigravity: '.agent', cursor: '.cursor',
|
|
windsurf: '.windsurf', augment: '.augment', trae: '.trae', qwen: '.qwen',
|
|
codebuddy: '.codebuddy', cline: '.',
|
|
};
|
|
let configDir;
|
|
let cwd = process.cwd();
|
|
const args = [INSTALL_SCRIPT, `--${runtime}`];
|
|
if (scope === 'global') {
|
|
args.push('--global', '--config-dir', root);
|
|
configDir = root;
|
|
} else {
|
|
args.push('--local');
|
|
cwd = root;
|
|
configDir = runtime === 'cline' ? root : path.join(root, LOCAL_DIR_NAME[runtime]);
|
|
}
|
|
args.push(...extraArgs);
|
|
const result = spawnSync(process.execPath, args, {
|
|
cwd, encoding: 'utf8',
|
|
env: installerEnv({ HOME: root, USERPROFILE: root }),
|
|
});
|
|
assert.strictEqual(result.status, 0,
|
|
`installer exited with status ${result.status} for ${runtime} --${scope}\nstdout: ${result.stdout}\nstderr: ${result.stderr}`);
|
|
const manifestPath = path.join(configDir, MANIFEST_NAME);
|
|
const manifest = fs.existsSync(manifestPath)
|
|
? JSON.parse(fs.readFileSync(manifestPath, 'utf8'))
|
|
: null;
|
|
return { manifest, configDir, root, stdout: result.stdout, stderr: result.stderr };
|
|
} catch (err) {
|
|
fs.rmSync(root, { recursive: true, force: true });
|
|
throw err;
|
|
}
|
|
}
|
|
|
|
function manifestSkillSet(manifest) {
|
|
if (!manifest || !manifest.files) return new Set();
|
|
const out = new Set();
|
|
for (const key of Object.keys(manifest.files)) {
|
|
if (key.startsWith('skills/')) {
|
|
const seg = key.split('/')[1].replace(/^gsd-/, '').replace(/\.md$/, '');
|
|
out.add(seg);
|
|
} else if (key.startsWith('command/')) {
|
|
const file = key.split('/')[1];
|
|
out.add(file.replace(/^gsd-/, '').replace(/\.md$/, ''));
|
|
} else if (key.startsWith('commands/gsd/')) {
|
|
const file = key.split('/')[2];
|
|
out.add(file.replace(/\.(md|toml)$/, ''));
|
|
}
|
|
}
|
|
return out;
|
|
}
|
|
|
|
function manifestAgentCount(manifest) {
|
|
if (!manifest || !manifest.files) return 0;
|
|
return Object.keys(manifest.files).filter((k) => k.startsWith('agents/')).length;
|
|
}
|
|
|
|
function collectSkillBasenamesOnDisk(configDir) {
|
|
const out = new Set();
|
|
const skillsDir = path.join(configDir, 'skills');
|
|
if (fs.existsSync(skillsDir)) {
|
|
for (const entry of fs.readdirSync(skillsDir, { withFileTypes: true })) {
|
|
if (entry.isDirectory() && entry.name.startsWith('gsd-')) {
|
|
out.add(entry.name.replace(/^gsd-/, ''));
|
|
} else if (entry.isFile() && entry.name.startsWith('gsd-') && entry.name.endsWith('.md')) {
|
|
out.add(entry.name.replace(/^gsd-/, '').replace(/\.md$/, ''));
|
|
}
|
|
}
|
|
}
|
|
const commandDir = path.join(configDir, 'command');
|
|
if (fs.existsSync(commandDir)) {
|
|
for (const file of fs.readdirSync(commandDir)) {
|
|
if (file.startsWith('gsd-') && file.endsWith('.md')) {
|
|
out.add(file.replace(/^gsd-/, '').replace(/\.md$/, ''));
|
|
}
|
|
}
|
|
}
|
|
const commandsGsdDir = path.join(configDir, 'commands', 'gsd');
|
|
if (fs.existsSync(commandsGsdDir)) {
|
|
for (const file of fs.readdirSync(commandsGsdDir)) {
|
|
if (file.endsWith('.md') || file.endsWith('.toml')) {
|
|
out.add(file.replace(/\.(md|toml)$/, ''));
|
|
}
|
|
}
|
|
}
|
|
return out;
|
|
}
|
|
|
|
module.exports = {
|
|
INSTALL_SCRIPT,
|
|
MANIFEST_NAME,
|
|
BUILD_SCRIPT,
|
|
HOOKS_DIST,
|
|
EXPECTED_SH_HOOKS,
|
|
EXPECTED_ALL_HOOKS,
|
|
RUNTIME_META,
|
|
SKILL_RUNTIMES,
|
|
stripAnsi,
|
|
walk,
|
|
simulateHookCopy,
|
|
installerEnv,
|
|
runMinimalInstall,
|
|
manifestSkillSet,
|
|
manifestAgentCount,
|
|
collectSkillBasenamesOnDisk,
|
|
};
|