* 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>
578 lines
22 KiB
JavaScript
578 lines
22 KiB
JavaScript
// allow-test-rule: source-text-is-the-product
|
|
// Workflow .md / agent .md / command .md / reference .md files — their text
|
|
// IS what the runtime loads. Testing text content tests the deployed contract.
|
|
// Per CONTRIBUTING.md exception matrix.
|
|
|
|
/**
|
|
* Tests for gsd-read-guard.js PreToolUse hook.
|
|
*
|
|
* The read guard intercepts Write/Edit tool calls on existing files and injects
|
|
* advisory guidance telling the model to Read the file first. This prevents
|
|
* infinite retry loops when non-Claude models (e.g. MiniMax M2.5 on OpenCode)
|
|
* attempt to edit files without reading them, hitting the runtime's
|
|
* "You must read file before overwriting it" error repeatedly.
|
|
*
|
|
* The hook is advisory-only (does not block) so Claude Code behavior is unaffected.
|
|
*/
|
|
|
|
process.env.GSD_TEST_MODE = '1';
|
|
|
|
const { test, describe, beforeEach, afterEach } = 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 HOOK_PATH = path.join(__dirname, '..', 'hooks', 'gsd-read-guard.js');
|
|
|
|
/**
|
|
* Run the read guard hook with a given tool input payload.
|
|
* Returns { exitCode, stdout, stderr }.
|
|
*/
|
|
function runHook(payload, envOverrides = {}) {
|
|
const input = JSON.stringify(payload);
|
|
// Sanitize all Claude Code detection signals so positive-path tests work
|
|
// when the test runner itself is running inside Claude Code (#2344, #2520).
|
|
const env = {
|
|
...process.env,
|
|
CLAUDE_SESSION_ID: '',
|
|
CLAUDECODE: '',
|
|
CLAUDE_CODE_ENTRYPOINT: '',
|
|
CLAUDE_CODE_SSE_PORT: '',
|
|
CLAUDE_PROJECT_DIR: '',
|
|
...envOverrides,
|
|
};
|
|
try {
|
|
const stdout = execFileSync(process.execPath, [HOOK_PATH], {
|
|
input,
|
|
encoding: 'utf-8',
|
|
timeout: 5000,
|
|
stdio: ['pipe', 'pipe', 'pipe'],
|
|
env,
|
|
});
|
|
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('gsd-read-guard hook', () => {
|
|
let tmpDir;
|
|
|
|
beforeEach(() => {
|
|
tmpDir = createTempDir('gsd-read-guard-');
|
|
});
|
|
|
|
afterEach(() => {
|
|
cleanup(tmpDir);
|
|
});
|
|
|
|
// ─── Core: advisory on Write to existing file ───────────────────────────
|
|
|
|
test('injects read-first guidance when Write targets an existing file', () => {
|
|
const filePath = path.join(tmpDir, 'existing.js');
|
|
fs.writeFileSync(filePath, 'console.log("hello");\n');
|
|
|
|
const result = runHook({
|
|
tool_name: 'Write',
|
|
tool_input: { file_path: filePath, content: 'console.log("world");\n' },
|
|
});
|
|
|
|
assert.equal(result.exitCode, 0);
|
|
assert.ok(result.stdout.length > 0, 'should produce output');
|
|
|
|
const output = JSON.parse(result.stdout);
|
|
assert.ok(output.hookSpecificOutput, 'should have hookSpecificOutput');
|
|
assert.ok(output.hookSpecificOutput.additionalContext, 'should have additionalContext');
|
|
assert.ok(
|
|
output.hookSpecificOutput.additionalContext.includes('Read'),
|
|
'guidance should mention Read tool'
|
|
);
|
|
});
|
|
|
|
test('injects read-first guidance when Edit targets an existing file', () => {
|
|
const filePath = path.join(tmpDir, 'existing.js');
|
|
fs.writeFileSync(filePath, 'const x = 1;\n');
|
|
|
|
const result = runHook({
|
|
tool_name: 'Edit',
|
|
tool_input: { file_path: filePath, old_string: 'const x = 1;', new_string: 'const x = 2;' },
|
|
});
|
|
|
|
assert.equal(result.exitCode, 0);
|
|
assert.ok(result.stdout.length > 0, 'should produce output');
|
|
|
|
const output = JSON.parse(result.stdout);
|
|
assert.ok(output.hookSpecificOutput.additionalContext.includes('Read'));
|
|
});
|
|
|
|
// ─── No-op cases: should NOT inject guidance ────────────────────────────
|
|
|
|
test('does nothing for Write to a new file (file does not exist)', () => {
|
|
const filePath = path.join(tmpDir, 'brand-new.js');
|
|
// File does NOT exist
|
|
|
|
const result = runHook({
|
|
tool_name: 'Write',
|
|
tool_input: { file_path: filePath, content: 'new content' },
|
|
});
|
|
|
|
assert.equal(result.exitCode, 0);
|
|
assert.equal(result.stdout, '', 'should produce no output for new files');
|
|
});
|
|
|
|
test('does nothing for non-Write/Edit tools', () => {
|
|
const result = runHook({
|
|
tool_name: 'Bash',
|
|
tool_input: { command: 'echo hello' },
|
|
});
|
|
|
|
assert.equal(result.exitCode, 0);
|
|
assert.equal(result.stdout, '');
|
|
});
|
|
|
|
test('does nothing for Read tool', () => {
|
|
const filePath = path.join(tmpDir, 'existing.js');
|
|
fs.writeFileSync(filePath, 'content');
|
|
|
|
const result = runHook({
|
|
tool_name: 'Read',
|
|
tool_input: { file_path: filePath },
|
|
});
|
|
|
|
assert.equal(result.exitCode, 0);
|
|
assert.equal(result.stdout, '');
|
|
});
|
|
|
|
// ─── Error resilience ──────────────────────────────────────────────────
|
|
|
|
test('exits cleanly on invalid JSON input', () => {
|
|
try {
|
|
const stdout = execFileSync(process.execPath, [HOOK_PATH], {
|
|
input: 'not json',
|
|
encoding: 'utf-8',
|
|
timeout: 5000,
|
|
stdio: ['pipe', 'pipe', 'pipe'],
|
|
});
|
|
// Should exit 0 silently
|
|
assert.equal(stdout.trim(), '');
|
|
} catch (err) {
|
|
assert.equal(err.status, 0, 'should exit 0 on parse error');
|
|
}
|
|
});
|
|
|
|
test('exits cleanly when tool_input is missing', () => {
|
|
const result = runHook({ tool_name: 'Write' });
|
|
assert.equal(result.exitCode, 0);
|
|
assert.equal(result.stdout, '');
|
|
});
|
|
|
|
// ─── Guidance content quality ──────────────────────────────────────────
|
|
|
|
test('guidance message includes the filename', () => {
|
|
const filePath = path.join(tmpDir, 'myfile.ts');
|
|
fs.writeFileSync(filePath, 'export const foo = 1;\n');
|
|
|
|
const result = runHook({
|
|
tool_name: 'Write',
|
|
tool_input: { file_path: filePath, content: 'export const foo = 2;\n' },
|
|
});
|
|
|
|
const output = JSON.parse(result.stdout);
|
|
assert.ok(
|
|
output.hookSpecificOutput.additionalContext.includes('myfile.ts'),
|
|
'guidance should include the filename being edited'
|
|
);
|
|
});
|
|
|
|
test('guidance message instructs to use Read tool before editing', () => {
|
|
const filePath = path.join(tmpDir, 'target.py');
|
|
fs.writeFileSync(filePath, 'x = 1\n');
|
|
|
|
const result = runHook({
|
|
tool_name: 'Edit',
|
|
tool_input: { file_path: filePath, old_string: 'x = 1', new_string: 'x = 2' },
|
|
});
|
|
|
|
const output = JSON.parse(result.stdout);
|
|
const ctx = output.hookSpecificOutput.additionalContext;
|
|
assert.ok(ctx.includes('Read'), 'must mention Read tool');
|
|
assert.ok(
|
|
ctx.includes('before') || ctx.includes('first'),
|
|
'must indicate Read should come before the edit'
|
|
);
|
|
});
|
|
|
|
// ─── Build / install integration ───────────────────────────────────────
|
|
|
|
test('hook is registered in build-hooks.js HOOKS_TO_COPY', () => {
|
|
const buildHooksPath = path.join(__dirname, '..', 'scripts', 'build-hooks.js');
|
|
const content = fs.readFileSync(buildHooksPath, 'utf8');
|
|
assert.ok(
|
|
content.includes('gsd-read-guard.js'),
|
|
'gsd-read-guard.js must be in HOOKS_TO_COPY so it ships in hooks/dist/'
|
|
);
|
|
});
|
|
|
|
test('hook is registered in install.js uninstall hook list', () => {
|
|
const installPath = path.join(__dirname, '..', 'bin', 'install.js');
|
|
const content = fs.readFileSync(installPath, 'utf8');
|
|
assert.ok(
|
|
content.includes("'gsd-read-guard.js'"),
|
|
'gsd-read-guard.js must be in the uninstall gsdHooks list'
|
|
);
|
|
});
|
|
|
|
test('exits cleanly when tool_input.file_path is non-string', () => {
|
|
const result = runHook({
|
|
tool_name: 'Write',
|
|
tool_input: { file_path: 12345, content: 'data' },
|
|
});
|
|
// file_path is a number — || '' yields '' — hook exits silently
|
|
assert.equal(result.exitCode, 0);
|
|
assert.equal(result.stdout, '');
|
|
});
|
|
|
|
// ─── Claude Code runtime skip (#1984) ─────────────────────────────────
|
|
|
|
test('skips advisory on Claude Code runtime (CLAUDE_SESSION_ID set)', () => {
|
|
const filePath = path.join(tmpDir, 'existing.js');
|
|
fs.writeFileSync(filePath, 'const x = 1;\n');
|
|
|
|
const result = runHook(
|
|
{ tool_name: 'Edit', tool_input: { file_path: filePath, old_string: 'const x = 1;', new_string: 'const x = 2;' } },
|
|
{ CLAUDE_SESSION_ID: 'test-session-123' }
|
|
);
|
|
|
|
assert.equal(result.exitCode, 0);
|
|
assert.equal(result.stdout, '', 'should produce no output on Claude Code');
|
|
});
|
|
});
|
|
|
|
|
|
// ────────────────────────────────────────────────────────────────────────
|
|
// Folded from tests/bug-2344-read-guard-claudecode-env.test.cjs — consolidation epic #1969 (B6 #1975)
|
|
// ────────────────────────────────────────────────────────────────────────
|
|
{
|
|
const { describe: __foldDescribe } = require('node:test');
|
|
__foldDescribe("folded:bug-2344-read-guard-claudecode-env (consolidation epic #1969 B6 #1975)", () => {
|
|
/**
|
|
* Regression test for bug #2344
|
|
*
|
|
* gsd-read-guard.js checked process.env.CLAUDE_SESSION_ID to detect the
|
|
* Claude Code runtime and skip its advisory. However, Claude Code CLI exports
|
|
* CLAUDECODE=1, not CLAUDE_SESSION_ID. The skip never fired, so the
|
|
* READ-BEFORE-EDIT advisory injected on every Edit/Write call inside Claude
|
|
* Code — producing noise in long-running sessions.
|
|
*
|
|
* Fix: check CLAUDECODE (and CLAUDE_SESSION_ID for back-compat) before
|
|
* emitting the advisory.
|
|
*/
|
|
|
|
process.env.GSD_TEST_MODE = '1';
|
|
|
|
const { test, describe, beforeEach, afterEach } = 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 HOOK_PATH = path.join(__dirname, '..', 'hooks', 'gsd-read-guard.js');
|
|
|
|
function runHook(payload, envOverrides = {}) {
|
|
const input = JSON.stringify(payload);
|
|
const env = {
|
|
...process.env,
|
|
CLAUDE_SESSION_ID: '',
|
|
CLAUDECODE: '',
|
|
CLAUDE_CODE_ENTRYPOINT: '',
|
|
CLAUDE_CODE_SSE_PORT: '',
|
|
CLAUDE_PROJECT_DIR: '',
|
|
...envOverrides,
|
|
};
|
|
try {
|
|
const stdout = execFileSync(process.execPath, [HOOK_PATH], {
|
|
input,
|
|
encoding: 'utf-8',
|
|
timeout: 5000,
|
|
stdio: ['pipe', 'pipe', 'pipe'],
|
|
env,
|
|
});
|
|
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('bug #2344: read guard skips on CLAUDECODE env var', () => {
|
|
let tmpDir;
|
|
|
|
beforeEach(() => { tmpDir = createTempDir('gsd-read-guard-2344-'); });
|
|
afterEach(() => { cleanup(tmpDir); });
|
|
|
|
test('skips advisory when CLAUDECODE=1 is set (Claude Code CLI env)', () => {
|
|
const filePath = path.join(tmpDir, 'existing.js');
|
|
fs.writeFileSync(filePath, 'const x = 1;\n');
|
|
|
|
const result = runHook(
|
|
{ tool_name: 'Edit', tool_input: { file_path: filePath, old_string: 'const x = 1;', new_string: 'const x = 2;' } },
|
|
{ CLAUDECODE: '1' }
|
|
);
|
|
|
|
assert.equal(result.exitCode, 0);
|
|
assert.equal(result.stdout, '', 'advisory must not fire when CLAUDECODE=1');
|
|
});
|
|
|
|
test('skips advisory when CLAUDE_SESSION_ID is set (back-compat)', () => {
|
|
const filePath = path.join(tmpDir, 'existing.js');
|
|
fs.writeFileSync(filePath, 'const x = 1;\n');
|
|
|
|
const result = runHook(
|
|
{ tool_name: 'Edit', tool_input: { file_path: filePath, old_string: 'const x = 1;', new_string: 'const x = 2;' } },
|
|
{ CLAUDE_SESSION_ID: 'test-session-123' }
|
|
);
|
|
|
|
assert.equal(result.exitCode, 0);
|
|
assert.equal(result.stdout, '', 'advisory must not fire when CLAUDE_SESSION_ID is set');
|
|
});
|
|
|
|
test('still injects advisory when neither CLAUDECODE nor CLAUDE_SESSION_ID is set', () => {
|
|
const filePath = path.join(tmpDir, 'existing.js');
|
|
fs.writeFileSync(filePath, 'const x = 1;\n');
|
|
|
|
const result = runHook(
|
|
{ tool_name: 'Edit', tool_input: { file_path: filePath, old_string: 'const x = 1;', new_string: 'const x = 2;' } },
|
|
{ CLAUDECODE: '', CLAUDE_SESSION_ID: '' }
|
|
);
|
|
|
|
assert.equal(result.exitCode, 0);
|
|
assert.ok(result.stdout.length > 0, 'advisory should fire on non-Claude-Code runtimes');
|
|
const output = JSON.parse(result.stdout);
|
|
assert.ok(output.hookSpecificOutput?.additionalContext?.includes('Read'));
|
|
});
|
|
});
|
|
});
|
|
}
|
|
|
|
|
|
// ────────────────────────────────────────────────────────────────────────
|
|
// Folded from tests/bug-2520-read-guard-hook-subprocess-env.test.cjs — consolidation epic #1969 (B6 #1975)
|
|
// ────────────────────────────────────────────────────────────────────────
|
|
{
|
|
const { describe: __foldDescribe } = require('node:test');
|
|
__foldDescribe("folded:bug-2520-read-guard-hook-subprocess-env (consolidation epic #1969 B6 #1975)", () => {
|
|
/**
|
|
* Regression test for bug #2520
|
|
*
|
|
* The fix for #2344 added `|| process.env.CLAUDECODE` to the Claude Code
|
|
* skip check. That works in principle — CLAUDECODE=1 is propagated to Bash
|
|
* tool subprocesses — but it does NOT reach hook subprocesses on Claude Code
|
|
* v2.1.116. Claude Code applies a separate env filter when spawning
|
|
* PreToolUse hook commands; that filter drops bare CLAUDECODE and
|
|
* CLAUDE_SESSION_ID and keeps only CLAUDE_CODE_*-prefixed vars plus
|
|
* CLAUDE_PROJECT_DIR. `data.session_id` is, however, reliably delivered via
|
|
* the hook's stdin JSON payload (documented part of Claude Code's hook
|
|
* input schema).
|
|
*
|
|
* Fix: use `data.session_id` as the primary Claude Code signal, with
|
|
* CLAUDE_CODE_ENTRYPOINT / CLAUDE_CODE_SSE_PORT as env-var fallbacks, and
|
|
* keep legacy CLAUDECODE / CLAUDE_SESSION_ID for back-compat and
|
|
* future-proofing.
|
|
*/
|
|
|
|
process.env.GSD_TEST_MODE = '1';
|
|
|
|
const { test, describe, beforeEach, afterEach } = 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 HOOK_PATH = path.join(__dirname, '..', 'hooks', 'gsd-read-guard.js');
|
|
|
|
/**
|
|
* Spawn the hook with an env that mirrors the actual Claude Code hook
|
|
* subprocess env: CLAUDECODE and CLAUDE_SESSION_ID are stripped, only
|
|
* CLAUDE_CODE_*-prefixed vars (plus CLAUDE_PROJECT_DIR) remain. Extra env
|
|
* overrides can be supplied via `envOverrides`.
|
|
*/
|
|
function runHookInClaudeCodeSubprocess(payload, envOverrides = {}) {
|
|
const input = JSON.stringify(payload);
|
|
const baseEnv = { ...process.env };
|
|
// Strip env vars Claude Code does NOT propagate to hook subprocesses.
|
|
delete baseEnv.CLAUDECODE;
|
|
delete baseEnv.CLAUDE_SESSION_ID;
|
|
const env = {
|
|
...baseEnv,
|
|
// Env vars Claude Code DOES propagate to hook subprocesses (observed on
|
|
// Claude Code CLI 2.1.116).
|
|
CLAUDE_CODE_ENTRYPOINT: 'cli',
|
|
CLAUDE_CODE_SSE_PORT: '51291',
|
|
CLAUDE_PROJECT_DIR: process.cwd(),
|
|
...envOverrides,
|
|
};
|
|
try {
|
|
const stdout = execFileSync(process.execPath, [HOOK_PATH], {
|
|
input,
|
|
encoding: 'utf-8',
|
|
timeout: 5000,
|
|
stdio: ['pipe', 'pipe', 'pipe'],
|
|
env,
|
|
});
|
|
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('bug #2520: read guard detects Claude Code without relying on CLAUDECODE env', () => {
|
|
let tmpDir;
|
|
|
|
beforeEach(() => { tmpDir = createTempDir('gsd-read-guard-2520-'); });
|
|
afterEach(() => { cleanup(tmpDir); });
|
|
|
|
test('skips advisory when stdin payload includes session_id (Claude Code hook-subprocess env)', () => {
|
|
const filePath = path.join(tmpDir, 'existing.js');
|
|
fs.writeFileSync(filePath, 'const x = 1;\n');
|
|
|
|
// Isolate the stdin `session_id` signal by clearing the CLAUDE_CODE_*
|
|
// env fallbacks the helper normally provides. Without this the env
|
|
// fallback would rescue the skip even if session_id detection broke,
|
|
// hiding a regression of the primary signal.
|
|
const result = runHookInClaudeCodeSubprocess(
|
|
{
|
|
session_id: 'e7123e54-0977-45dd-848a-b9c8a45a5cd3',
|
|
tool_name: 'Edit',
|
|
tool_input: { file_path: filePath, old_string: 'const x = 1;', new_string: 'const x = 2;' },
|
|
},
|
|
{ CLAUDE_CODE_ENTRYPOINT: '', CLAUDE_CODE_SSE_PORT: '', CLAUDE_PROJECT_DIR: '' },
|
|
);
|
|
|
|
assert.equal(result.exitCode, 0);
|
|
assert.equal(
|
|
result.stdout,
|
|
'',
|
|
'advisory must not fire when session_id is present on stdin (real Claude Code hook env)',
|
|
);
|
|
});
|
|
|
|
test('skips advisory when CLAUDE_CODE_ENTRYPOINT is set (env-var fallback, no session_id on stdin)', () => {
|
|
const filePath = path.join(tmpDir, 'existing.js');
|
|
fs.writeFileSync(filePath, 'const x = 1;\n');
|
|
|
|
const result = runHookInClaudeCodeSubprocess(
|
|
{ tool_name: 'Edit', tool_input: { file_path: filePath, old_string: 'const x = 1;', new_string: 'const x = 2;' } },
|
|
{ CLAUDE_CODE_ENTRYPOINT: 'cli', CLAUDE_CODE_SSE_PORT: '' },
|
|
);
|
|
|
|
assert.equal(result.exitCode, 0);
|
|
assert.equal(result.stdout, '', 'advisory must not fire when CLAUDE_CODE_ENTRYPOINT is set');
|
|
});
|
|
|
|
test('still injects advisory when no Claude Code signal is present (non-Claude host)', () => {
|
|
const filePath = path.join(tmpDir, 'existing.js');
|
|
fs.writeFileSync(filePath, 'const x = 1;\n');
|
|
|
|
const result = runHookInClaudeCodeSubprocess(
|
|
{ tool_name: 'Edit', tool_input: { file_path: filePath, old_string: 'const x = 1;', new_string: 'const x = 2;' } },
|
|
{ CLAUDE_CODE_ENTRYPOINT: '', CLAUDE_CODE_SSE_PORT: '', CLAUDE_PROJECT_DIR: '' },
|
|
);
|
|
|
|
assert.equal(result.exitCode, 0);
|
|
assert.ok(result.stdout.length > 0, 'advisory should fire on non-Claude-Code hosts');
|
|
const output = JSON.parse(result.stdout);
|
|
assert.ok(output.hookSpecificOutput?.additionalContext?.includes('Read'));
|
|
});
|
|
});
|
|
});
|
|
}
|
|
|
|
|
|
// ────────────────────────────────────────────────────────────────────────
|
|
// #2304 — Kimi tool vocabulary engages the read guard
|
|
// ────────────────────────────────────────────────────────────────────────
|
|
|
|
describe('#2304: Kimi tool vocabulary engages the read guard', () => {
|
|
// Payload shapes mirror kimi-cli's actual tool schemas
|
|
// (src/kimi_cli/tools/file/{write,replace}.py): WriteFile takes
|
|
// `path`/`content`, StrReplaceFile takes `path` + `edit: Edit | list[Edit]`.
|
|
let tmpDir;
|
|
|
|
beforeEach(() => { tmpDir = createTempDir('gsd-read-guard-2304-'); });
|
|
afterEach(() => { cleanup(tmpDir); });
|
|
|
|
test('WriteFile on an existing file injects read-first guidance like Write', () => {
|
|
const filePath = path.join(tmpDir, 'existing.js');
|
|
fs.writeFileSync(filePath, 'console.log("hello");\n');
|
|
|
|
const result = runHook({
|
|
tool_name: 'WriteFile',
|
|
tool_input: { path: filePath, content: 'console.log("world");\n' },
|
|
});
|
|
|
|
assert.equal(result.exitCode, 0);
|
|
assert.ok(result.stdout.length > 0, 'Kimi WriteFile should produce the advisory');
|
|
const output = JSON.parse(result.stdout);
|
|
assert.ok(output.hookSpecificOutput?.additionalContext?.includes('Read'));
|
|
});
|
|
|
|
test('StrReplaceFile on an existing file injects guidance like Edit', () => {
|
|
const filePath = path.join(tmpDir, 'existing.js');
|
|
fs.writeFileSync(filePath, 'const x = 1;\n');
|
|
|
|
const result = runHook({
|
|
tool_name: 'StrReplaceFile',
|
|
tool_input: { path: filePath, edit: { old: 'const x = 1;', new: 'const x = 2;' } },
|
|
});
|
|
|
|
assert.equal(result.exitCode, 0);
|
|
assert.ok(result.stdout.length > 0, 'Kimi StrReplaceFile should produce the advisory');
|
|
const output = JSON.parse(result.stdout);
|
|
assert.ok(output.hookSpecificOutput?.additionalContext?.includes('Read'));
|
|
});
|
|
|
|
test('module-qualified kimi_cli.tools.file:WriteFile is recognized', () => {
|
|
const filePath = path.join(tmpDir, 'existing.js');
|
|
fs.writeFileSync(filePath, 'content\n');
|
|
|
|
const result = runHook({
|
|
tool_name: 'kimi_cli.tools.file:WriteFile',
|
|
tool_input: { path: filePath, content: 'replacement\n' },
|
|
});
|
|
|
|
assert.equal(result.exitCode, 0);
|
|
assert.ok(result.stdout.length > 0, 'module-qualified Kimi WriteFile should produce the advisory');
|
|
});
|
|
|
|
test('Kimi ReadFile stays out of scope (silent exit)', () => {
|
|
const filePath = path.join(tmpDir, 'existing.js');
|
|
fs.writeFileSync(filePath, 'content\n');
|
|
|
|
const result = runHook({
|
|
tool_name: 'kimi_cli.tools.file:ReadFile',
|
|
tool_input: { path: filePath },
|
|
});
|
|
|
|
assert.equal(result.exitCode, 0);
|
|
assert.equal(result.stdout, '', 'ReadFile is not a write tool — guard must stay silent');
|
|
});
|
|
});
|