* 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>
143 lines
4.7 KiB
JavaScript
143 lines
4.7 KiB
JavaScript
/**
|
|
* Tests for gsd-workflow-guard.js PreToolUse hook.
|
|
*
|
|
* #2304 — Kimi tool vocabulary engages the guard: Kimi CLI registers this
|
|
* guard with matcher 'Shell|WriteFile|StrReplaceFile' and forwards its own
|
|
* tool vocabulary (tool_name 'Shell', possibly module-qualified). kimi-cli's
|
|
* Shell.Params names its field `command` (src/kimi_cli/tools/shell/
|
|
* __init__.py), same as Claude's Bash, so only the tool name needs
|
|
* normalization. Pre-fix the guard's Bash branch never matched on Kimi and
|
|
* the force-add block was silently dormant.
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
process.env.GSD_TEST_MODE = '1';
|
|
|
|
const { test, describe, before, after } = require('node:test');
|
|
const assert = require('node:assert/strict');
|
|
const { execFileSync, execSync } = require('node:child_process');
|
|
const fs = require('node:fs');
|
|
const os = require('node:os');
|
|
const path = require('node:path');
|
|
|
|
const { cleanup } = require('./helpers.cjs');
|
|
|
|
const HOOK_PATH = path.join(__dirname, '..', 'hooks', 'gsd-workflow-guard.js');
|
|
|
|
function runHook(payload, timeoutMs = 5000) {
|
|
const input = JSON.stringify(payload);
|
|
try {
|
|
const stdout = execFileSync(process.execPath, [HOOK_PATH], {
|
|
input,
|
|
encoding: 'utf-8',
|
|
timeout: timeoutMs,
|
|
stdio: ['pipe', 'pipe', 'pipe'],
|
|
});
|
|
return { exitCode: 0, stdout: stdout.trim(), stderr: '' };
|
|
} catch (err) {
|
|
return {
|
|
exitCode: err.status ?? 1,
|
|
stdout: (err.stdout || '').toString().trim(),
|
|
stderr: (err.stderr || '').toString().trim(),
|
|
};
|
|
}
|
|
}
|
|
|
|
describe('#2304: Kimi tool vocabulary engages the workflow guard', () => {
|
|
// A repo on a worktree-agent-* branch with the guard enabled: the one
|
|
// state where the Bash branch produces an observable block, so a dormant
|
|
// guard (silent exit 0) is distinguishable from a working one (exit 2).
|
|
let repoDir;
|
|
|
|
before(() => {
|
|
repoDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-workflow-guard-'));
|
|
execSync(
|
|
'git init -q -b worktree-agent-test && git config user.email t@t && git config user.name t',
|
|
{ cwd: repoDir, stdio: 'ignore' }
|
|
);
|
|
fs.mkdirSync(path.join(repoDir, '.planning'));
|
|
fs.writeFileSync(
|
|
path.join(repoDir, '.planning', 'config.json'),
|
|
JSON.stringify({ hooks: { workflow_guard: true } })
|
|
);
|
|
});
|
|
|
|
after(() => {
|
|
cleanup(repoDir);
|
|
});
|
|
|
|
test('Shell force-add on a worktree-agent branch is blocked like Bash', () => {
|
|
const r = runHook({
|
|
tool_name: 'Shell',
|
|
tool_input: { command: 'git add -f secrets.env' },
|
|
cwd: repoDir,
|
|
});
|
|
assert.equal(r.exitCode, 2, 'Kimi Shell should reach the Bash branch and block');
|
|
const output = JSON.parse(r.stdout);
|
|
assert.equal(
|
|
output.code,
|
|
'WORKTREE_AGENT_FORCE_ADD_FORBIDDEN',
|
|
'block payload should carry the force-add code'
|
|
);
|
|
assert.ok(
|
|
r.stderr.includes('must not run git add -f'),
|
|
'reason must reach stderr — that is what Kimi feeds back to the model on exit 2'
|
|
);
|
|
});
|
|
|
|
test('module-qualified kimi_cli.tools.shell:Shell is recognized', () => {
|
|
const r = runHook({
|
|
tool_name: 'kimi_cli.tools.shell:Shell',
|
|
tool_input: { command: 'git add --force secrets.env' },
|
|
cwd: repoDir,
|
|
});
|
|
assert.equal(r.exitCode, 2);
|
|
assert.equal(JSON.parse(r.stdout).code, 'WORKTREE_AGENT_FORCE_ADD_FORBIDDEN');
|
|
});
|
|
|
|
test('benign Shell command passes through', () => {
|
|
const r = runHook({
|
|
tool_name: 'Shell',
|
|
tool_input: { command: 'git status' },
|
|
cwd: repoDir,
|
|
});
|
|
assert.equal(r.exitCode, 0);
|
|
assert.equal(r.stdout, '');
|
|
});
|
|
|
|
test('Bash (Claude vocabulary) still blocks — normalization is additive', () => {
|
|
const r = runHook({
|
|
tool_name: 'Bash',
|
|
tool_input: { command: 'git add -f secrets.env' },
|
|
cwd: repoDir,
|
|
});
|
|
assert.equal(r.exitCode, 2);
|
|
assert.equal(JSON.parse(r.stdout).code, 'WORKTREE_AGENT_FORCE_ADD_FORBIDDEN');
|
|
});
|
|
|
|
test('WriteFile outside .planning/ gets the workflow advisory like Write', () => {
|
|
const r = runHook({
|
|
tool_name: 'WriteFile',
|
|
tool_input: { path: path.join(repoDir, 'src', 'app.js'), content: 'x' },
|
|
cwd: repoDir,
|
|
});
|
|
assert.equal(r.exitCode, 0);
|
|
const output = JSON.parse(r.stdout);
|
|
assert.ok(
|
|
output.hookSpecificOutput?.additionalContext?.includes('WORKFLOW ADVISORY'),
|
|
'Kimi WriteFile should reach the write branch and emit the advisory'
|
|
);
|
|
});
|
|
|
|
test('StrReplaceFile editing .planning/ passes silently', () => {
|
|
const r = runHook({
|
|
tool_name: 'StrReplaceFile',
|
|
tool_input: { path: path.join(repoDir, '.planning', 'notes.md'), edit: { old: 'a', new: 'b' } },
|
|
cwd: repoDir,
|
|
});
|
|
assert.equal(r.exitCode, 0);
|
|
assert.equal(r.stdout, '');
|
|
});
|
|
});
|