* fix(#2304): normalize Kimi tool vocabulary in PreToolUse guard payload checks
The Kimi [[hooks]] registrations translate the matcher to Kimi's tool
vocabulary (WriteFile|StrReplaceFile) but the guard scripts early-exit
unless the payload's tool_name is a Claude name (Write/Edit/MultiEdit),
so every guard was dormant on Kimi: the matcher fired, the script saw
WriteFile, and exit(0)'d.
Normalize the payload's tool_name at the top of each guard
(WriteFile -> Write, StrReplaceFile -> Edit; bare or module-qualified
kimi_cli.tools.file:* forms) before the check. Inlined per guard rather
than a hooks/lib/ helper because hook scripts are staged as standalone
files on every hook surface, and a sibling require is a staging
dependency that can fail silently.
Regression tests pipe Kimi-vocabulary payloads at each guard and assert
it engages (typed fields: exit status, decision, hookSpecificOutput) —
verified red against the pre-fix scripts, green after.
* fix(#2304): normalize Kimi tool_input fields and route block reasons to stderr
Cross-AI review of the initial fix, verified against kimi-cli source,
found the tool_name normalization alone leaves the guards dormant on a
real Kimi runtime: kimi-cli forwards tool_input verbatim
(src/kimi_cli/hooks/events.py), and its tool schemas
(src/kimi_cli/tools/file/{write,replace}.py) use path/content and
edit.old/edit.new (single Edit or list) — not Claude's
file_path/old_string/new_string. The guards read file_path, got '',
and exited 0 past the now-open tool_name gate.
Extend the per-guard normalization to the payload fields
(path -> file_path, edit -> old_string/new_string with list flattening),
and write the worktree guard's block reason to stderr as well as the
stdout JSON — Kimi feeds stderr, not stdout, back to the model on
exit 2 (docs/en/customization/hooks.md exit-code table).
Regression tests rewritten to Kimi's actual payload shapes (plus an
edit-list case and a stderr-reason assertion) — verified red against
the name-only fix, green after.
* fix(#2304): join all edit[] entries into old_string, matching new_string
Review nit on #2326: old_string took only edits[0].old while new_string
joined the whole list. Symmetric join removes the latent trap for any
future consumer sizing before/after content (e.g. the #2255 write guard).
* fix(#2304): normalize Kimi ReadFile vocabulary in read-injection scanner
Review Major 2 on #2326: gsd-read-injection-scanner.js had the identical
dormancy — its Kimi matcher fires on 'ReadFile' but the SCANNED_TOOLS
check only knew 'Read', so injected content in read files was never
flagged on Kimi installs.
Folds the same inlined normalization block into the scanner and extends
the shared KIMI_TOOL_NAMES map with ReadFile:'Read' in all four copies so
they stay byte-identical. Harmless in the three write guards: a
normalized 'Read' falls out of their Write/Edit allowlist exactly as the
unmapped name did. Field mapping verified against kimi-cli upstream
(src/kimi_cli/tools/file/read.py Params.path); the existing
path->file_path copy covers the scanner's file_path read.
* test(#2304): parity test binding the four inlined Kimi normalization copies
Review Major 1 on #2326: KIMI_TOOL_NAMES + normalizeKimiPayload is
deliberately inlined in four hook scripts (staging-dependency rationale,
unchanged), with the inverse table in bin/install.js — five
hand-maintained surfaces and nothing binding them.
Static binding, zero runtime coupling:
- the four inlined blocks must be byte-identical;
- each guard-map entry must be the value-inverse of
convertKimiToolName() for its Claude name;
- every guard-relevant Claude tool (Write/Edit/MultiEdit/Read) must have
a reverse entry — a vocabulary rename or extension that updates the
installer without updating the guards now fails in CI instead of
leaving a guard silently dormant (the #2304 recurrence door).
Negative-controlled: diverging one copy or dropping a map entry fails
the suite against the fixed code.
* test(#2304): regenerate golden parity fixtures for guard hook changes
CI red on #2326: all 10 golden-parity failures were the staged guard
hooks drifting from their fixtures. Regenerated with npm run gen:golden
(after npm run build) under throwaway HOME/CLAUDE_CONFIG_DIR; diff
verified to change exactly the four PR-touched guard entries per
surface, nothing else.
* test(#2304): regression tests for Kimi ReadFile engaging the scanner
Mirrors the per-guard Kimi vocabulary tests the PR added for the three
write guards: bare and module-qualified ReadFile produce the advisory,
path exclusions still apply post-normalization, unknown Kimi names stay
fail-open. Negative-controlled against the pre-fold scanner (the two
positive cases fail there; exclusion/fall-through correctly pass on
both sides).
* fix(#2304): normalize Kimi Shell vocabulary in workflow guard
Withdraws the disclosed out-of-scope split: verification showed the
Bash->Shell case needs NO different mapping — kimi-cli's Shell.Params
names its field `command` (src/kimi_cli/tools/shell/__init__.py), same
as Claude's Bash — and the guard's write branch (Write/Edit/MultiEdit
allowlist) was ALSO dormant on Kimi under its Shell|WriteFile|
StrReplaceFile matcher. Same defect class as the other four hooks.
Folds the identical inlined block into gsd-workflow-guard.js and
extends the shared map with Shell:'Bash' in all five copies (harmless
outside the workflow guard: a normalized Bash falls out of the other
guards' checks as before). Parity test now binds five copies and adds
Bash to the dormancy alarm. New workflow-guard test file exercises the
observable block (force-add on a worktree-agent branch): Shell bare and
module-qualified block with WORKTREE_AGENT_FORCE_ADD_FORBIDDEN, benign
Shell passes, Claude Bash unchanged — negative-controlled against the
pre-fold guard (the two Kimi cases fail there). Golden parity fixtures
regenerated; diff verified to change exactly the five guard entries per
surface.
* fix(#2304): map Kimi tool_output and route workflow-guard block to stderr
Third-party review (cross-AI verifier) caught two gaps in the revision:
1. Kimi PostToolUse events carry `tool_output`, not `tool_response`
(kimi-cli src/kimi_cli/hooks/events.py post_tool_use()), so the
read-injection scanner — which reads data.tool_response — was STILL
dormant on real Kimi payloads; the earlier tests passed because they
sent Claude-shaped payloads. The shared normalization block now maps
tool_output -> tool_response (inert in PreToolUse guards, where the
field is absent), and the scanner's Kimi tests send the real shape.
2. The workflow guard's force-add block wrote its reason to stdout only.
Kimi's exit-2 protocol feeds stderr back to the model — the exact
fix this PR already applied to the other blocking guard — so the
newly-awakened block would have been a silent denial. Reason now
also routed to stderr, asserted in the test.
Also: the scanner's "unknown name" test now uses a genuinely unmapped
name (FetchURL) — Shell stopped qualifying when it entered the map —
and the workflow guard's write branch (WriteFile advisory,
StrReplaceFile .planning pass) gains behavioral coverage. All five
copies stay byte-identical (parity test green); golden fixtures
regenerated, diff verified to the five guard entries per surface.
Negative-controlled: 3 new assertions fail against the pre-fix hooks.
* docs(#2304): update changeset to cover the full five-guard fix
Review round 2 (2026-07-18) flagged the changeset as stale: it was
written for the first commit and still described only the three guards
named in the issue. The shipped diff grew to five guards plus two
payload dimensions the original body never mentioned. The body now
names gsd-read-injection-scanner and gsd-workflow-guard, the ReadFile
and Shell vocabulary entries, the tool_output -> tool_response mapping,
and the workflow guard's stderr block-reason routing.
* test(#2304): regenerate kilo golden fixture after #2305 landed on next
The branch's fixture sweep predates 50efae13 (fix(#2305), PR #2327),
which made Kilo ship the five shared guard hooks. Rebased onto next and
re-ran the full generator sweep (gen:golden, size:baseline, and the
four registry/contract generators); the only delta across all of them
is kilo.json's five guard-hook hashes, matching this PR's hook edits.
* fix(#2304): fold Kimi normalization into the two shell hooks
The 2026-07-19 review found the last two guards with the #2304 dormancy:
- hooks/gsd-graphify-update.sh gated on tool_name == "Bash" but is
registered on Kimi with matcher 'Shell' — Gate 1 never matched and the
auto-rebuild was silently dormant. kimi-cli's Shell.Params names its
field `command` (src/kimi_cli/tools/shell/__init__.py), same as Claude
Bash, so only the name needs mapping: strip the module-path prefix,
map Shell -> Bash.
- hooks/gsd-phase-boundary.sh read only tool_input.file_path, but Kimi's
file tools name the field `path` (src/kimi_cli/tools/file/write.py +
replace.py) — the hook read '' and .planning/ writes went undetected.
Falls back to tool_input.path when file_path is absent, mirroring
normalizeKimiPayload's precedence in the JS guards.
The normalization is reimplemented in shell — a byte-identity assertion
cannot span the JS<->shell boundary, so the parity test gains a
shell-guard vocabulary block that pins both scripts' mapping facts to
convertKimiToolName's live vocabulary instead of faking a byte binding.
Behavior is covered by negative-controlled tests beside each hook's
existing suite (verified red against the pre-fix scripts): Kimi Shell
dispatch (bare + module-qualified) with a WriteFile negative control in
graphify-auto-update.slow.test.cjs, and Kimi path detection, file_path
precedence, and a non-.planning negative control in hooks-opt-in.test.cjs.
Changeset updated to name all seven guards; golden install-parity
fixtures regenerated (diff is exactly the two hook entries per runtime;
size baselines unchanged).
* fix(#2304): use a Map for KIMI_TOOL_NAMES so prototype keys cannot pass the guard fall-through
A bare bracket lookup on an object literal resolves 'constructor',
'__proto__', 'toString', 'valueOf' and 'hasOwnProperty' through
Object.prototype to truthy functions/objects, so `if (!mapped)` failed
to short-circuit and data.tool_name was assigned a non-string. Map.get
returns undefined for those keys — the same shape the repo already uses
in canonicalizeRuntimeName (src/runtime-name-policy.cts). Applied
identically to all five inlined copies (review M1, PR #2326).
No new bypass class: unrecognized strings already fail open by design;
this fixes the lookup being wrong, not the posture.
* test(#2304): enumerate normalized guards by scanning hooks/, not a hardcoded list
The parity test's file list was a literal five-entry array — a sixth guard
with its own copy-pasted normalization block would be silently uncovered,
the exact divergence mode the test exists to prevent (review M2). Now the
list is a scan of hooks/*.js for the KIMI_TOOL_NAMES marker, with a floor
assertion so a scan that finds nothing fails instead of passing vacuously.
Also parses the Map declaration introduced by the M1 fix, and carries the
allow-test-rule annotation documenting the source-text scanning (review m4).
* test(#2304): parse hook JSON output instead of substring-matching raw stdout
workflow-guard.test.cjs asserted on unparsed stdout while read-guard.test.cjs
in the same PR parses the JSON envelope first — match the better pattern at
all four assertion sites (review m5).
* test(#2304): regenerate golden parity fixtures after Map conversion in the five guards
* docs(#2304): reset changeset pr:0 placeholder for Phase 0 PR (#2507)
The closed PR #2326's changeset carried pr:2326. Phase 0 of epic #2505
re-lands this fix on a fresh branch; the pr: field will be backfilled
to the real Phase 0 PR number immediately after gh pr create returns.
* docs(changeset): backfill PR #2518 for Phase 0 (#2507)
---------
Co-authored-by: 0xdhx <darkhawkx@gmail.com>
560 lines
22 KiB
JavaScript
560 lines
22 KiB
JavaScript
// Migrated to typed-IR (#2974): the gsd-session-state.sh and
|
|
// gsd-phase-boundary.sh hooks now emit Claude Code SessionStart/PostToolUse
|
|
// JSON envelopes ({ hookSpecificOutput: { hookEventName, additionalContext,
|
|
// state_present, config_mode | planning_modified, file_path } }) instead of
|
|
// plain text. gsd-validate-commit.sh already emitted JSON ({ decision,
|
|
// reason }). Tests parse the JSON and assert on typed fields.
|
|
|
|
/**
|
|
* GSD Tools Tests - Community Hooks (opt-in)
|
|
*
|
|
* Tests for feat/hooks-opt-in-1473d:
|
|
* - Hook file existence and permissions
|
|
* - Installer hook registration in install.js
|
|
* - Hook execution with opt-in enabled and disabled
|
|
* - Negative security tests for hooks
|
|
*/
|
|
|
|
const { test, describe, beforeEach, afterEach } = require('node:test');
|
|
const assert = require('node:assert/strict');
|
|
const fs = require('fs');
|
|
const path = require('path');
|
|
const os = require('os');
|
|
const { spawnSync } = require('child_process');
|
|
|
|
const HOOKS_DIR = path.join(__dirname, '..', 'hooks');
|
|
const isWindows = process.platform === 'win32';
|
|
|
|
// Ensure the running node binary is on PATH so bash hooks can call `node`
|
|
// (Claude Code shell sessions do not have `node` on PATH).
|
|
const hookEnv = {
|
|
...process.env,
|
|
PATH: `${path.dirname(process.execPath)}:${process.env.PATH || '/usr/local/bin:/usr/bin:/bin'}`,
|
|
};
|
|
|
|
// Wrapper that always injects hookEnv so bash hooks can find `node`.
|
|
function spawnHook(hookPath, options) {
|
|
return spawnSync('bash', [hookPath], { ...options, env: hookEnv });
|
|
}
|
|
|
|
// ─── Helpers ────────────────────────────────────────────────────────────────
|
|
|
|
function createTempProject(prefix = 'gsd-hook-test-') {
|
|
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
|
|
fs.mkdirSync(path.join(tmpDir, '.planning', 'phases'), { recursive: true });
|
|
return tmpDir;
|
|
}
|
|
|
|
function cleanup(tmpDir) {
|
|
// eslint-disable-next-line local/no-raw-rmsync-in-tests -- this IS the local teardown helper; wrapping helpers.cjs cleanup would create a circular dependency
|
|
try { fs.rmSync(tmpDir, { recursive: true, force: true }); } catch {}
|
|
}
|
|
|
|
function writeConfigWithHooks(tmpDir, enabled) {
|
|
fs.writeFileSync(
|
|
path.join(tmpDir, '.planning', 'config.json'),
|
|
JSON.stringify({
|
|
model_profile: 'balanced',
|
|
hooks: { community: enabled }
|
|
}, null, 2)
|
|
);
|
|
}
|
|
|
|
function writeMinimalStateMd(tmpDir, content) {
|
|
const defaultContent = content || '# Session State\n\n**Current Phase:** 01\n**Status:** Active\n';
|
|
fs.writeFileSync(
|
|
path.join(tmpDir, '.planning', 'STATE.md'),
|
|
defaultContent
|
|
);
|
|
}
|
|
|
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
// 1. Hook file existence and permissions
|
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
|
|
describe('hook file validation', () => {
|
|
test('gsd-session-state.sh exists', () => {
|
|
const hookPath = path.join(HOOKS_DIR, 'gsd-session-state.sh');
|
|
assert.ok(fs.existsSync(hookPath), 'gsd-session-state.sh should exist');
|
|
});
|
|
|
|
test('gsd-validate-commit.sh exists', () => {
|
|
const hookPath = path.join(HOOKS_DIR, 'gsd-validate-commit.sh');
|
|
assert.ok(fs.existsSync(hookPath), 'gsd-validate-commit.sh should exist');
|
|
});
|
|
|
|
test('gsd-phase-boundary.sh exists', () => {
|
|
const hookPath = path.join(HOOKS_DIR, 'gsd-phase-boundary.sh');
|
|
assert.ok(fs.existsSync(hookPath), 'gsd-phase-boundary.sh should exist');
|
|
});
|
|
|
|
test('gsd-session-state.sh is executable', { skip: isWindows ? 'Windows has no POSIX file permissions' : false }, () => {
|
|
const hookPath = path.join(HOOKS_DIR, 'gsd-session-state.sh');
|
|
const stat = fs.statSync(hookPath);
|
|
assert.ok((stat.mode & 0o111) !== 0, 'gsd-session-state.sh should be executable');
|
|
});
|
|
|
|
test('gsd-validate-commit.sh is executable', { skip: isWindows ? 'Windows has no POSIX file permissions' : false }, () => {
|
|
const hookPath = path.join(HOOKS_DIR, 'gsd-validate-commit.sh');
|
|
const stat = fs.statSync(hookPath);
|
|
assert.ok((stat.mode & 0o111) !== 0, 'gsd-validate-commit.sh should be executable');
|
|
});
|
|
|
|
test('gsd-phase-boundary.sh is executable', { skip: isWindows ? 'Windows has no POSIX file permissions' : false }, () => {
|
|
const hookPath = path.join(HOOKS_DIR, 'gsd-phase-boundary.sh');
|
|
const stat = fs.statSync(hookPath);
|
|
assert.ok((stat.mode & 0o111) !== 0, 'gsd-phase-boundary.sh should be executable');
|
|
});
|
|
});
|
|
|
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
// 2. Installer hook registration
|
|
// Migrated (#455): uses typed exports from bin/install.js instead of
|
|
// source-grep assertions (retiring pending-migration-to-typed-ir token).
|
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
|
|
// Typed import — no source-grep needed (#455)
|
|
const { GSD_UNINSTALL_HOOKS, buildHookCommand } = require(
|
|
path.join(__dirname, '..', 'bin', 'install.js')
|
|
);
|
|
|
|
describe('installer hook registration', () => {
|
|
test('GSD_UNINSTALL_HOOKS includes all 3 opt-in bash hooks', () => {
|
|
assert.ok(Array.isArray(GSD_UNINSTALL_HOOKS), 'GSD_UNINSTALL_HOOKS must be an array');
|
|
assert.ok(
|
|
GSD_UNINSTALL_HOOKS.includes('gsd-validate-commit.sh'),
|
|
'GSD_UNINSTALL_HOOKS must include gsd-validate-commit.sh'
|
|
);
|
|
assert.ok(
|
|
GSD_UNINSTALL_HOOKS.includes('gsd-session-state.sh'),
|
|
'GSD_UNINSTALL_HOOKS must include gsd-session-state.sh'
|
|
);
|
|
assert.ok(
|
|
GSD_UNINSTALL_HOOKS.includes('gsd-phase-boundary.sh'),
|
|
'GSD_UNINSTALL_HOOKS must include gsd-phase-boundary.sh'
|
|
);
|
|
});
|
|
|
|
test('GSD_UNINSTALL_HOOKS includes all core JS hooks', () => {
|
|
const requiredJsHooks = [
|
|
'gsd-statusline.js',
|
|
'gsd-check-update.js',
|
|
'gsd-context-monitor.js',
|
|
];
|
|
for (const hook of requiredJsHooks) {
|
|
assert.ok(
|
|
GSD_UNINSTALL_HOOKS.includes(hook),
|
|
`GSD_UNINSTALL_HOOKS must include ${hook}`
|
|
);
|
|
}
|
|
});
|
|
|
|
test('buildHookCommand generates a command string for gsd-validate-commit.sh', () => {
|
|
// buildHookCommand(configDir, hookName, opts) returns a non-null string command
|
|
// or null when the platform cannot run the hook. On non-Windows unix, .sh hooks
|
|
// always produce a command string.
|
|
const tmpConfigDir = os.tmpdir();
|
|
const cmd = buildHookCommand(tmpConfigDir, 'gsd-validate-commit.sh', { platform: 'linux' });
|
|
// On Linux, .sh hooks should always resolve to a non-null string
|
|
assert.ok(
|
|
cmd === null || (typeof cmd === 'string' && cmd.length > 0),
|
|
`buildHookCommand must return null or a non-empty string, got: ${JSON.stringify(cmd)}`
|
|
);
|
|
if (cmd !== null) {
|
|
assert.ok(
|
|
cmd.includes('gsd-validate-commit.sh'),
|
|
`buildHookCommand result must reference the hook filename, got: ${cmd}`
|
|
);
|
|
}
|
|
});
|
|
});
|
|
|
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
// 3. Opt-in gating behavior
|
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
|
|
describe('opt-in gating behavior', { skip: isWindows ? 'bash hooks require unix shell' : false }, () => {
|
|
let tmpDir;
|
|
|
|
beforeEach(() => {
|
|
tmpDir = createTempProject();
|
|
});
|
|
|
|
afterEach(() => {
|
|
cleanup(tmpDir);
|
|
});
|
|
|
|
test('validate-commit is a no-op when hooks.community is false', () => {
|
|
writeConfigWithHooks(tmpDir, false);
|
|
const hookPath = path.join(HOOKS_DIR, 'gsd-validate-commit.sh');
|
|
const input = JSON.stringify({
|
|
tool_input: { command: 'git commit -m "WIP save"' }
|
|
});
|
|
|
|
const result = spawnHook(hookPath, {
|
|
input,
|
|
encoding: 'utf-8',
|
|
cwd: tmpDir,
|
|
});
|
|
|
|
// Should exit 0 (no-op) even with a bad commit message
|
|
assert.strictEqual(result.status, 0, `Should be no-op when disabled, got ${result.status}`);
|
|
});
|
|
|
|
test('validate-commit is a no-op when config.json is absent', (t) => {
|
|
// No config.json at all
|
|
const bareDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-hook-bare-'));
|
|
t.after(() => { cleanup(bareDir); });
|
|
const hookPath = path.join(HOOKS_DIR, 'gsd-validate-commit.sh');
|
|
const input = JSON.stringify({
|
|
tool_input: { command: 'git commit -m "WIP save"' }
|
|
});
|
|
|
|
const result = spawnHook(hookPath, {
|
|
input,
|
|
encoding: 'utf-8',
|
|
cwd: bareDir,
|
|
});
|
|
|
|
assert.strictEqual(result.status, 0, `Should be no-op without config.json, got ${result.status}`);
|
|
});
|
|
|
|
test('session-state is a no-op when hooks.community is false', () => {
|
|
writeConfigWithHooks(tmpDir, false);
|
|
writeMinimalStateMd(tmpDir);
|
|
const hookPath = path.join(HOOKS_DIR, 'gsd-session-state.sh');
|
|
|
|
const result = spawnHook(hookPath, {
|
|
input: '',
|
|
encoding: 'utf-8',
|
|
cwd: tmpDir,
|
|
});
|
|
|
|
assert.strictEqual(result.status, 0, `Should exit 0: ${result.stderr}`);
|
|
// Migrated #2974: typed assertion that stdout is empty (no JSON envelope
|
|
// emitted when the hook is a no-op). The previous shape grepped for
|
|
// "Project State Reminder" prose; now the contract is "no output".
|
|
assert.equal(result.stdout.trim(), '',
|
|
`Should produce no output when disabled: ${JSON.stringify(result.stdout)}`);
|
|
});
|
|
|
|
test('phase-boundary is a no-op when hooks.community is false', () => {
|
|
writeConfigWithHooks(tmpDir, false);
|
|
const hookPath = path.join(HOOKS_DIR, 'gsd-phase-boundary.sh');
|
|
const input = JSON.stringify({
|
|
tool_input: { file_path: '.planning/STATE.md' }
|
|
});
|
|
|
|
const result = spawnHook(hookPath, {
|
|
input,
|
|
encoding: 'utf-8',
|
|
cwd: tmpDir,
|
|
});
|
|
|
|
assert.strictEqual(result.status, 0, `Should exit 0: ${result.stderr}`);
|
|
// Migrated #2974: typed empty-stdout assertion (#2974).
|
|
assert.equal(result.stdout.trim(), '',
|
|
`Should produce no output when disabled: ${JSON.stringify(result.stdout)}`);
|
|
});
|
|
});
|
|
|
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
// 4. Hook execution when enabled
|
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
|
|
describe('hook execution when enabled', { skip: isWindows ? 'bash hooks require unix shell' : false }, () => {
|
|
let tmpDir;
|
|
|
|
beforeEach(() => {
|
|
tmpDir = createTempProject();
|
|
writeConfigWithHooks(tmpDir, true);
|
|
});
|
|
|
|
afterEach(() => {
|
|
cleanup(tmpDir);
|
|
});
|
|
|
|
test('validate-commit allows valid conventional commit', () => {
|
|
const hookPath = path.join(HOOKS_DIR, 'gsd-validate-commit.sh');
|
|
const input = JSON.stringify({
|
|
tool_input: { command: 'git commit -m "fix(core): add locking mechanism"' }
|
|
});
|
|
|
|
const result = spawnHook(hookPath, {
|
|
input,
|
|
encoding: 'utf-8',
|
|
cwd: tmpDir,
|
|
});
|
|
|
|
assert.strictEqual(result.status, 0, `Valid commit should exit 0, got ${result.status}. stderr: ${result.stderr}`);
|
|
});
|
|
|
|
test('validate-commit blocks non-conventional commit', () => {
|
|
const hookPath = path.join(HOOKS_DIR, 'gsd-validate-commit.sh');
|
|
const input = JSON.stringify({
|
|
tool_input: { command: 'git commit -m "WIP save"' }
|
|
});
|
|
|
|
const result = spawnHook(hookPath, {
|
|
input,
|
|
encoding: 'utf-8',
|
|
cwd: tmpDir,
|
|
});
|
|
|
|
assert.strictEqual(result.status, 2, `Non-conventional commit should exit 2, got ${result.status}`);
|
|
// Migrated #2974: parse the hook's JSON envelope and assert on typed
|
|
// fields (decision, reason). Hook protocol returns
|
|
// { decision: 'block', reason: '...' } for blocked commits.
|
|
const parsed = JSON.parse(result.stdout);
|
|
assert.strictEqual(parsed.decision, 'block',
|
|
`expected typed decision: 'block', got: ${JSON.stringify(parsed)}`);
|
|
// Assert on the typed `code` field (stable enum value), not the
|
|
// human-readable `reason` string. CR feedback (#3016): substring
|
|
// matching on `reason` is still text matching — the hook now emits
|
|
// a typed code alongside the prose so tests pin behavior, not copy.
|
|
assert.strictEqual(parsed.code, 'CONVENTIONAL_COMMITS_VIOLATION',
|
|
`expected typed code: 'CONVENTIONAL_COMMITS_VIOLATION', got: ${JSON.stringify(parsed)}`);
|
|
});
|
|
|
|
test('validate-commit allows non-commit commands', () => {
|
|
const hookPath = path.join(HOOKS_DIR, 'gsd-validate-commit.sh');
|
|
const input = JSON.stringify({
|
|
tool_input: { command: 'git push origin main' }
|
|
});
|
|
|
|
const result = spawnHook(hookPath, {
|
|
input,
|
|
encoding: 'utf-8',
|
|
cwd: tmpDir,
|
|
});
|
|
|
|
assert.strictEqual(result.status, 0, `Non-commit command should exit 0, got ${result.status}`);
|
|
});
|
|
|
|
test('session-state outputs state info when enabled', () => {
|
|
writeMinimalStateMd(tmpDir);
|
|
const hookPath = path.join(HOOKS_DIR, 'gsd-session-state.sh');
|
|
|
|
const result = spawnHook(hookPath, {
|
|
input: '',
|
|
encoding: 'utf-8',
|
|
cwd: tmpDir,
|
|
});
|
|
|
|
assert.strictEqual(result.status, 0, `Should exit 0: ${result.stderr}`);
|
|
// Migrated #2974: parse the SessionStart JSON envelope and assert on
|
|
// typed fields. The hook now emits
|
|
// { hookSpecificOutput: { hookEventName, additionalContext, state_present, config_mode } }.
|
|
const parsed = JSON.parse(result.stdout);
|
|
assert.strictEqual(parsed.hookSpecificOutput.hookEventName, 'SessionStart');
|
|
assert.strictEqual(parsed.hookSpecificOutput.state_present, true,
|
|
'state_present must reflect that STATE.md was written by writeMinimalStateMd');
|
|
});
|
|
|
|
test('session-state exits 0 without .planning/ (in enabled project)', (t) => {
|
|
// Create a dir with config but no STATE.md
|
|
const noStateDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-hook-nostate-'));
|
|
t.after(() => { cleanup(noStateDir); });
|
|
fs.mkdirSync(path.join(noStateDir, '.planning'), { recursive: true });
|
|
writeConfigWithHooks(noStateDir, true);
|
|
const hookPath = path.join(HOOKS_DIR, 'gsd-session-state.sh');
|
|
|
|
const result = spawnHook(hookPath, {
|
|
input: '',
|
|
encoding: 'utf-8',
|
|
cwd: noStateDir,
|
|
});
|
|
|
|
assert.strictEqual(result.status, 0, `Should exit 0: ${result.stderr}`);
|
|
// Migrated #2974: typed assertion on state_present field instead of
|
|
// grepping additionalContext text for "No .planning/ found".
|
|
const parsed = JSON.parse(result.stdout);
|
|
assert.strictEqual(parsed.hookSpecificOutput.state_present, false,
|
|
'state_present must be false when STATE.md is absent');
|
|
});
|
|
|
|
test('phase-boundary detects .planning/ writes when enabled', () => {
|
|
const hookPath = path.join(HOOKS_DIR, 'gsd-phase-boundary.sh');
|
|
const input = JSON.stringify({
|
|
tool_input: { file_path: '.planning/STATE.md' }
|
|
});
|
|
|
|
const result = spawnHook(hookPath, {
|
|
input,
|
|
encoding: 'utf-8',
|
|
cwd: tmpDir,
|
|
});
|
|
|
|
assert.strictEqual(result.status, 0, `Should exit 0: ${result.stderr}`);
|
|
// Migrated #2974: parse the PostToolUse JSON envelope. The hook emits
|
|
// { hookSpecificOutput: { hookEventName, additionalContext,
|
|
// planning_modified, file_path } } when a .planning/ write is detected.
|
|
const parsed = JSON.parse(result.stdout);
|
|
assert.strictEqual(parsed.hookSpecificOutput.hookEventName, 'PostToolUse');
|
|
assert.strictEqual(parsed.hookSpecificOutput.planning_modified, true);
|
|
assert.strictEqual(parsed.hookSpecificOutput.file_path, '.planning/STATE.md');
|
|
});
|
|
|
|
// #2304 — Kimi tool vocabulary engages the hook: Kimi CLI registers this
|
|
// hook with matcher 'WriteFile|StrReplaceFile' and its file tools name the
|
|
// path field `path`, not `file_path` (kimi-cli src/kimi_cli/tools/file/
|
|
// write.py + replace.py). Pre-fix, the hook read '' on Kimi payloads and
|
|
// .planning/ writes were silently undetected.
|
|
test('phase-boundary detects .planning/ writes from Kimi tool_input.path (#2304)', () => {
|
|
const hookPath = path.join(HOOKS_DIR, 'gsd-phase-boundary.sh');
|
|
const input = JSON.stringify({
|
|
tool_name: 'kimi_cli.tools.file:WriteFile',
|
|
tool_input: { path: '.planning/STATE.md', content: 'x' }
|
|
});
|
|
|
|
const result = spawnHook(hookPath, {
|
|
input,
|
|
encoding: 'utf-8',
|
|
cwd: tmpDir,
|
|
});
|
|
|
|
assert.strictEqual(result.status, 0, `Should exit 0: ${result.stderr}`);
|
|
const parsed = JSON.parse(result.stdout);
|
|
assert.strictEqual(parsed.hookSpecificOutput.planning_modified, true,
|
|
'Kimi path field must be detected — pre-fix the hook read an empty path (#2304)');
|
|
assert.strictEqual(parsed.hookSpecificOutput.file_path, '.planning/STATE.md');
|
|
});
|
|
|
|
test('phase-boundary prefers Claude file_path when both fields are present (#2304)', () => {
|
|
const hookPath = path.join(HOOKS_DIR, 'gsd-phase-boundary.sh');
|
|
const input = JSON.stringify({
|
|
tool_input: { file_path: '.planning/STATE.md', path: 'unrelated.txt' }
|
|
});
|
|
|
|
const result = spawnHook(hookPath, {
|
|
input,
|
|
encoding: 'utf-8',
|
|
cwd: tmpDir,
|
|
});
|
|
|
|
assert.strictEqual(result.status, 0, `Should exit 0: ${result.stderr}`);
|
|
const parsed = JSON.parse(result.stdout);
|
|
assert.strictEqual(parsed.hookSpecificOutput.file_path, '.planning/STATE.md',
|
|
'file_path must win over path — normalization is a fallback, not an override');
|
|
});
|
|
|
|
test('phase-boundary negative control: Kimi path outside .planning/ stays silent (#2304)', () => {
|
|
const hookPath = path.join(HOOKS_DIR, 'gsd-phase-boundary.sh');
|
|
const input = JSON.stringify({
|
|
tool_name: 'kimi_cli.tools.file:StrReplaceFile',
|
|
tool_input: { path: 'src/index.ts', edit: { old: 'a', new: 'b' } }
|
|
});
|
|
|
|
const result = spawnHook(hookPath, {
|
|
input,
|
|
encoding: 'utf-8',
|
|
cwd: tmpDir,
|
|
});
|
|
|
|
assert.strictEqual(result.status, 0, `Should exit 0: ${result.stderr}`);
|
|
assert.equal(result.stdout.trim(), '',
|
|
'non-.planning/ Kimi writes must produce no output');
|
|
});
|
|
});
|
|
|
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
// 5. Negative security tests for hooks
|
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
|
|
describe('hook security tests', { skip: isWindows ? 'bash hooks require unix shell' : false }, () => {
|
|
let tmpDir;
|
|
|
|
beforeEach(() => {
|
|
tmpDir = createTempProject();
|
|
writeConfigWithHooks(tmpDir, true);
|
|
});
|
|
|
|
afterEach(() => {
|
|
cleanup(tmpDir);
|
|
});
|
|
|
|
test('validate-commit blocks message with shell metacharacters', () => {
|
|
const hookPath = path.join(HOOKS_DIR, 'gsd-validate-commit.sh');
|
|
const input = JSON.stringify({
|
|
tool_input: { command: 'git commit -m "$(rm -rf /)"' }
|
|
});
|
|
|
|
const result = spawnHook(hookPath, {
|
|
input,
|
|
encoding: 'utf-8',
|
|
cwd: tmpDir,
|
|
});
|
|
|
|
assert.strictEqual(result.status, 2, `Shell metacharacter message should be blocked: ${result.status}`);
|
|
// Migrated #2974: typed JSON envelope assertion (parsed.decision === 'block').
|
|
assert.strictEqual(JSON.parse(result.stdout).decision, 'block');
|
|
});
|
|
|
|
test('validate-commit blocks message with backtick injection', () => {
|
|
const hookPath = path.join(HOOKS_DIR, 'gsd-validate-commit.sh');
|
|
const input = JSON.stringify({
|
|
tool_input: { command: 'git commit -m "`whoami`"' }
|
|
});
|
|
|
|
const result = spawnHook(hookPath, {
|
|
input,
|
|
encoding: 'utf-8',
|
|
cwd: tmpDir,
|
|
});
|
|
|
|
assert.strictEqual(result.status, 2, `Backtick injection should be blocked: ${result.status}`);
|
|
// Migrated #2974: typed JSON envelope assertion (parsed.decision === 'block').
|
|
assert.strictEqual(JSON.parse(result.stdout).decision, 'block');
|
|
});
|
|
|
|
test('validate-commit allows commit with scope containing special chars', () => {
|
|
const hookPath = path.join(HOOKS_DIR, 'gsd-validate-commit.sh');
|
|
const input = JSON.stringify({
|
|
tool_input: { command: 'git commit -m "fix(api/v2): handle edge case"' }
|
|
});
|
|
|
|
const result = spawnHook(hookPath, {
|
|
input,
|
|
encoding: 'utf-8',
|
|
cwd: tmpDir,
|
|
});
|
|
|
|
assert.strictEqual(result.status, 0, `Valid commit with / in scope should be allowed: ${result.status}`);
|
|
});
|
|
|
|
test('phase-boundary handles malformed JSON input gracefully', () => {
|
|
const hookPath = path.join(HOOKS_DIR, 'gsd-phase-boundary.sh');
|
|
const input = 'not json at all';
|
|
|
|
const result = spawnHook(hookPath, {
|
|
input,
|
|
encoding: 'utf-8',
|
|
cwd: tmpDir,
|
|
});
|
|
|
|
assert.strictEqual(result.status, 0, `Should not crash on malformed JSON: ${result.stderr}`);
|
|
});
|
|
|
|
test('hooks handle config.json with broken JSON gracefully', () => {
|
|
// Write malformed JSON config
|
|
fs.writeFileSync(
|
|
path.join(tmpDir, '.planning', 'config.json'),
|
|
'{ broken json'
|
|
);
|
|
|
|
const hookPath = path.join(HOOKS_DIR, 'gsd-validate-commit.sh');
|
|
const input = JSON.stringify({
|
|
tool_input: { command: 'git commit -m "WIP save"' }
|
|
});
|
|
|
|
const result = spawnHook(hookPath, {
|
|
input,
|
|
encoding: 'utf-8',
|
|
cwd: tmpDir,
|
|
});
|
|
|
|
// Should exit 0 (treat malformed config as disabled)
|
|
assert.strictEqual(result.status, 0, `Malformed config should be treated as disabled: ${result.status}`);
|
|
});
|
|
});
|