mirror of
https://github.com/pbakaus/impeccable.git
synced 2026-09-12 14:16:28 +03:00
* docs: add PRD for design detector hook integration Plans a PostToolUse hook for Claude Code and Codex that runs the existing design detector after every relevant file write and feeds findings back to the agent as advisory system-reminder context. No implementation in this commit; covers UX, technical design, build pipeline changes, distribution, coverage tradeoffs, and rollout. Co-authored-by: Cursor <cursoragent@cursor.com> * docs: revise hook PRD with best-practices review Folds in the P0/P1/P2 findings from an online best-practices critique against the official Claude Code and Codex hook references plus 10+ 2026 community guides and similar prior-art tools (claw-hooks, claude-code-hooks-mastery). Key changes: - Exec form everywhere (Codex snippet was shell form), with Windows rationale. - Default timeout dropped from 10s to 5s. - Re-entrancy guard (CLAUDE_HOOK_DEPTH) and per-file edit counter. - Session-scoped finding dedup promoted from open question to v1. - Per-language inline-ignore syntax map (HTML/JSX/CSS/JS). - Hard-skip rules for sensitive paths and generated/lock files. - Honest framing about Claude Code lacking per-plugin hook disable. - Honest framing about Bash-written files being invisible in v1. - Codex Windows-not-supported call-out, feature flag note, trust ceremony detail. - Optional NDJSON audit log via IMPECCABLE_HOOK_LOG. - Findings cap lowered 8 → 5 with attention-budget rationale. - Versioned envelope ([impeccable@1]) on rendered template. - Expanded test plan, decision log, and stdin payload appendix. Co-authored-by: Cursor <cursoragent@cursor.com> * feat(hooks): ship the design detector hook for Claude Code and Codex Implements docs/hooks-prd.md: a PostToolUse hook that runs the impeccable design detector after every Edit/Write/MultiEdit on a UI file and pushes findings into the agent's next-turn context as a short system reminder. Silent on clean files. Never blocks an edit. Why this matters: today, design slop (side-tab borders, gradient text, purple/cyan palettes, bounce easing, etc.) only gets caught when a human notices or someone explicitly runs /impeccable audit. The hook closes the loop at the moment slop is written. What ships in v1 - skill/scripts/hook.mjs: PostToolUse entry. Reads stdin, runs the detector in-process (no `npx impeccable` cold start), emits hookSpecificOutput.additionalContext when fresh findings exist. - skill/scripts/hook-lib.mjs: extracted helpers (config, cache, filter, render, audit log, runHook orchestrator). 100% unit-testable. - skill/scripts/hook-session-start.mjs: SessionStart greeting, gated by a project-scannable probe + 30-day throttle. - skill/scripts/hook-admin.mjs: backs /impeccable hooks on/off/status/ignore-rule/ignore-file/reset. Hardening built in - Re-entrancy guard (IMPECCABLE_HOOK_DEPTH) so the hook can never recursively spawn itself. - Hard-skip regexes for sensitive paths (.env, .pem, id_rsa, secrets, credentials, .git) and generated/lock/build output. These fire before the file is even read; cannot be turned off via config. - Path-traversal check on the inbound file_path. - Session-scoped dedup keyed by (session, file, rule, line) so the same finding never lands in context twice. Prevents the ~12.5K wasted tokens per chatty session called out in the PRD. - Per-(session, file) edit counter with a one-shot suppression notice on the 7th edit, silent after. - Fail-open contract: every error path returns exit 0 with no stdout. Optional NDJSON audit log via IMPECCABLE_HOOK_LOG. Three kill switches (precedence high to low): 1. IMPECCABLE_HOOK_DISABLED env var (1/true/yes/on, case-insensitive) 2. .impeccable/hook.json `enabled: false` 3. /impeccable hooks off slash command (writes the JSON) Inline ignores are language-aware. `// impeccable: ignore <rule>` for JS/TS, `<!-- impeccable: ignore <rule> -->` for HTML/Vue/Svelte/Astro, `{/* impeccable: ignore <rule> */}` for JSX/TSX, `/* impeccable: ignore <rule> */` for CSS. `*` matches any rule. Directive applies to the next non-blank line. Same shape as ESLint, Stylelint, Biome. Build pipeline - scripts/lib/transformers/hooks.js: per-provider hooks.json builders, plus the slim .codex-plugin/plugin.json manifest. - providers.js: emitHooks: 'claude' for claude-code, emitHooks: 'codex' for codex and agents. Codex also emits emitCodexPlugin. - factory.js: emits hooks/hooks.json next to the skills tree. - build.js: syncs hooks/ into harness roots and into the slim plugin/ subtree; writes .codex-plugin/plugin.json. Build is idempotent (verified: 98 staged files unchanged across two runs). Claude Code wiring uses exec form (command + args) and the ${CLAUDE_PLUGIN_ROOT} placeholder. Matcher: Edit|Write|MultiEdit. `if:` glob filters to UI extensions before spawning Node. PostToolUse timeout 5s, SessionStart timeout 3s. Codex wiring uses ${PLUGIN_ROOT} (Codex's native placeholder), matcher Edit|Write|apply_patch, no `if:` analog (the script does the extension filter). macOS and Linux only; hooks are disabled on Windows in current Codex builds. The trust ceremony and feature flag are documented in README.md. Routing - /impeccable hooks lives outside the 23-command router table on purpose: it is plumbing, not a design skill. The hidden routing slot is added to SKILL.md alongside pin/unpin so the LLM knows to dispatch it. The 23-command count and all stale-count validators remain happy. Tests - tests/hook.test.mjs: 38 unit tests covering env parsing, config load + defaults + malformed, cache round-trip + GC, ignoreRules/minSeverity/inline ignores (all four languages), globbing with **/*/{a,b}, render template with cap + clamp + 0-line prefix drop, audit log NDJSON, payload event-name parameterization, re-entrancy, kill switches, sensitive-path + generated-path + traversal skips, allowlist filter, config ignoreFiles, edit counter cycle including the 7th-edit notice, MultiEdit and apply_patch payload shapes, detector throw swallow, malformed stdin, missing file race. - tests/hook-build.test.mjs: 18 integration tests covering hook manifest shape (matcher, timeouts, exec form, if: glob, placeholders), Codex differences (${PLUGIN_ROOT}, no if:, no SessionStart), Codex plugin manifest (no inline hooks field to avoid the duplicate-file error), routing across the hooksJsonFor table, and presence of all three committed artifacts plus the bundled detector the runtime relative-import path depends on. Full suite: 175 bun tests + 186 node tests, all green. Docs - README.md: new "Design hook" section explaining default behavior, per-project / global / inline disable paths, the JSON schema knobs, the audit log debug flag, and the slop / a11y coverage split. - HARNESSES.md: flips the `hooks` row for Codex from No -> Yes (Claude was already Yes), adds a per-harness hook-surface table with the manifest location and matcher each provider uses. Open questions from the PRD intentionally deferred to v2: Bash-write blind spot, effort-aware suppression, Stop-hook session summary, per-rule severity, async hook mode. None block v1. Co-authored-by: Cursor <cursoragent@cursor.com> * Fix Codex hook scanning: apply_patch paths and co-located stylesheets Parse file targets from Codex apply_patch command bodies, co-scan imported and sibling CSS when UI components are edited, drop the git-sweep PostToolUse group, and align Codex SessionStart manifest and trust docs with the official hooks spec. Co-authored-by: Cursor <cursoragent@cursor.com> * Gitignore hook session cache and drop local test HTML Hook dedup/throttle state in .impeccable/hook.cache.json is per-project runtime data like other .impeccable/ sidecars. Remove an untracked bad-nested-flexbox scratch page from site/public/. Co-authored-by: Cursor <cursoragent@cursor.com> * Fix Claude Code hook: drop Edit-only if filter so Write/MultiEdit fire Claude's if permission rule binds to one tool name, so Edit(*.{…}) never spawned the hook on Write or MultiEdit despite the matcher listing them. Extension filtering now lives in hook-lib on both Claude and Codex. Co-authored-by: Cursor <cursoragent@cursor.com> * Surface Cursor design findings via stop-hook followup Replace dropped postToolUse additional_context with afterFileEdit recording and a one-shot stop followup_message so anti-pattern nudges reach the agent. Co-authored-by: Cursor <cursoragent@cursor.com> * Fix design hook packaging and scans * Fix Cursor hook pending bucket fallback * Fix Sass hook scan coverage * Fix Cursor hook review findings * Fix session start dead hook normalization * Fix hook config and relative scan paths * Remove SessionStart design hook * Remove redundant afterFileEdit normalization * Fix Cursor suppression and module style scans * Fix sensitive path hook filter * Fix disabled Cursor stop hook emission * Refresh hook harness artifacts * Fix Cursor hook manifest install * Add hook ignore-value support * Ignore hook runtime files locally * Fix Codex plugin hook packaging * fix: address PR review bot findings Block numeric hook depth counters from re-entering. Avoid following stylesheet imports from traversal-looking hook targets. * fix: gate ignore-value suggestions by supported rules Only render exact ignore-value commands when the same finding can be suppressed by ignoreValues. * Package Codex plugin as hook-only * Remove Codex plugin packaging * Recover hook install probe plumbing * Remove Codex hook packaging follow-up doc * Remove extra hook docs and skill wording changes * Install real design hooks via skills CLI * Add provider hook smoke runner * Fix Cursor hook delivery with preToolUse gate * Simplify Cursor hook install to preToolUse * Clarify confirmed hook exceptions * Persist hook ignores in shared config * Guard font hook exceptions * Fix hook install after main rebase * Fix hook scan target handling * fix: address hook review findings * Address hook review feedback * Stabilize DeepSeek insert live fixture * Fix Cursor hook Python shell write bypass --------- Co-authored-by: Cursor <cursoragent@cursor.com>
473 lines
16 KiB
JavaScript
473 lines
16 KiB
JavaScript
#!/usr/bin/env node
|
|
/**
|
|
* Impeccable design hook — Cursor preToolUse write gate.
|
|
*
|
|
* Cursor's stop hook is not consistently dispatched by the headless agent, so
|
|
* this hook checks proposed Write/Edit content before it lands. It only denies
|
|
* writes when the real detector finds an issue in the proposed UI content.
|
|
*
|
|
* Contract: never break a turn accidentally. On malformed input or internal
|
|
* errors, allow the tool and exit 0.
|
|
*/
|
|
|
|
import fs from 'node:fs';
|
|
import path from 'node:path';
|
|
|
|
import {
|
|
ALLOWED_EXTS,
|
|
EDIT_COUNT_THRESHOLD,
|
|
GENERATED_PATH,
|
|
SENSITIVE_PATH,
|
|
filterFindings,
|
|
loadDetector,
|
|
matchesAnyGlob,
|
|
persistCache,
|
|
readCache,
|
|
readConfig,
|
|
renderTemplate,
|
|
resolveProjectCwd,
|
|
truthy,
|
|
writeAuditLog,
|
|
} from './hook-lib.mjs';
|
|
|
|
async function readStdin() {
|
|
if (process.stdin.isTTY) return '';
|
|
const chunks = [];
|
|
for await (const chunk of process.stdin) chunks.push(chunk);
|
|
return Buffer.concat(chunks).toString('utf-8');
|
|
}
|
|
|
|
function done(payload = null) {
|
|
if (payload) process.stdout.write(JSON.stringify(payload));
|
|
process.exit(0);
|
|
}
|
|
|
|
function allow(extra = {}, payload = {}) {
|
|
writeAuditLog(process.env, {
|
|
ts: new Date().toISOString(),
|
|
event: 'preToolUse',
|
|
...extra,
|
|
});
|
|
return done({ permission: 'allow', ...payload });
|
|
}
|
|
|
|
function deny(message, audit) {
|
|
writeAuditLog(process.env, {
|
|
ts: new Date().toISOString(),
|
|
event: 'preToolUse',
|
|
blocked: true,
|
|
...audit,
|
|
});
|
|
return done({
|
|
permission: 'deny',
|
|
user_message: message,
|
|
agent_message: message,
|
|
});
|
|
}
|
|
|
|
function toolInput(event) {
|
|
return event?.tool_input && typeof event.tool_input === 'object' ? event.tool_input : {};
|
|
}
|
|
|
|
function proposedFilePath(event, cwd) {
|
|
const input = toolInput(event);
|
|
const raw = input.file_path || input.path || input.target_file || event?.file_path;
|
|
const candidate = typeof raw === 'string' && raw.trim()
|
|
? raw
|
|
: shellWriteDestination(shellCommand(input));
|
|
if (typeof candidate !== 'string' || !candidate.trim()) return '';
|
|
return path.isAbsolute(candidate) ? candidate : path.resolve(cwd, candidate);
|
|
}
|
|
|
|
function proposedContent(event, cwd, filePath) {
|
|
const input = toolInput(event);
|
|
for (const key of ['content', 'streamContent', 'text']) {
|
|
if (typeof input[key] === 'string') return input[key];
|
|
}
|
|
|
|
const editProjection = projectedEditContent(input, filePath, cwd);
|
|
if (editProjection !== undefined) return editProjection;
|
|
|
|
if (hasFragmentEditContent(input)) {
|
|
return { skipped: 'fragment-only-edit' };
|
|
}
|
|
|
|
const command = shellCommand(input);
|
|
const pythonContent = shellPythonWriteContent(command);
|
|
if (pythonContent) return pythonContent;
|
|
const shellContent = shellHereDocContent(command);
|
|
if (shellContent) return shellContent;
|
|
const copiedContent = shellCopiedFileContent(command, cwd);
|
|
if (copiedContent) return copiedContent;
|
|
return '';
|
|
}
|
|
|
|
function hasFragmentEditContent(input) {
|
|
if (!input || typeof input !== 'object') return false;
|
|
if (typeof input.new_string === 'string' || typeof input.newString === 'string' || typeof input.new_str === 'string' || typeof input.replacement === 'string') {
|
|
return true;
|
|
}
|
|
return Array.isArray(input.edits) && input.edits.some((edit) => edit && typeof edit === 'object');
|
|
}
|
|
|
|
function projectedEditContent(input, filePath, cwd) {
|
|
if (!filePath) return undefined;
|
|
const singleOld = firstString(input, ['old_string', 'oldString', 'old_str', 'target']);
|
|
const singleNew = firstString(input, ['new_string', 'newString', 'new_str', 'replacement']);
|
|
if (singleOld !== undefined || singleNew !== undefined) {
|
|
if (singleOld === undefined || singleNew === undefined) return { skipped: 'fragment-only-edit' };
|
|
const original = readExistingProjectFile(filePath, cwd);
|
|
if (original === null) return { skipped: 'edit-original-unreadable' };
|
|
const projected = replaceOnce(original, singleOld, singleNew);
|
|
return projected === null ? { skipped: 'edit-old-string-missing' } : projected;
|
|
}
|
|
|
|
if (!Array.isArray(input.edits)) return undefined;
|
|
const original = readExistingProjectFile(filePath, cwd);
|
|
if (original === null) return { skipped: 'edit-original-unreadable' };
|
|
|
|
let projected = original;
|
|
for (const edit of input.edits) {
|
|
if (!edit || typeof edit !== 'object') return { skipped: 'fragment-only-edit' };
|
|
const oldString = firstString(edit, ['old_string', 'oldString', 'old_str', 'target']);
|
|
const newString = firstString(edit, ['new_string', 'newString', 'new_str', 'replacement']);
|
|
if (oldString === undefined || newString === undefined) return { skipped: 'fragment-only-edit' };
|
|
const next = replaceOnce(projected, oldString, newString);
|
|
if (next === null) return { skipped: 'edit-old-string-missing' };
|
|
projected = next;
|
|
}
|
|
return projected;
|
|
}
|
|
|
|
function firstString(obj, keys) {
|
|
for (const key of keys) {
|
|
if (typeof obj?.[key] === 'string') return obj[key];
|
|
}
|
|
return undefined;
|
|
}
|
|
|
|
function replaceOnce(original, oldString, newString) {
|
|
if (oldString === '') return null;
|
|
const index = original.indexOf(oldString);
|
|
if (index === -1) return null;
|
|
return `${original.slice(0, index)}${newString}${original.slice(index + oldString.length)}`;
|
|
}
|
|
|
|
function readExistingProjectFile(filePath, cwd) {
|
|
if (!isInsideProject(filePath, cwd)) return null;
|
|
if (SENSITIVE_PATH.test(filePath) || GENERATED_PATH.test(filePath)) return null;
|
|
try {
|
|
const stat = fs.statSync(filePath);
|
|
if (!stat.isFile() || stat.size > 1024 * 1024) return null;
|
|
return fs.readFileSync(filePath, 'utf-8');
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
function shellCommand(input) {
|
|
if (typeof input.command === 'string') return input.command;
|
|
if (input.args && typeof input.args.command === 'string') return input.args.command;
|
|
return '';
|
|
}
|
|
|
|
function shellRedirectPath(command) {
|
|
if (!command || typeof command !== 'string') return '';
|
|
const match = command.match(/(?:^|[\s;&|])(?:>>?|1>>?)\s*(?:"([^"]+)"|'([^']+)'|([^<>\s]+))/);
|
|
return (match?.[1] || match?.[2] || match?.[3] || '').trim();
|
|
}
|
|
|
|
function shellWriteDestination(command) {
|
|
return shellRedirectPath(command) || shellTeeDestination(command) || shellCopyPaths(command)?.dest || shellPythonWriteDestination(command) || '';
|
|
}
|
|
|
|
function shellPythonWriteDestination(command) {
|
|
if (!/\bpython(?:3)?\b/.test(command || '')) return '';
|
|
const directPath = firstMatch(command, /(?:^|[^\w.])(?:pathlib\.)?Path\(\s*(["'])(.*?)\1\s*\)\s*\.write_text\s*\(/);
|
|
if (directPath) return directPath;
|
|
|
|
const pathsByVar = new Map();
|
|
const assignmentRe = /\b([A-Za-z_]\w*)\s*=\s*(?:pathlib\.)?Path\(\s*(["'])(.*?)\2\s*\)/g;
|
|
let assignment;
|
|
while ((assignment = assignmentRe.exec(command))) {
|
|
pathsByVar.set(assignment[1], assignment[3]);
|
|
}
|
|
|
|
const writeVarRe = /\b([A-Za-z_]\w*)\.write_text\s*\(/g;
|
|
let writeVar;
|
|
while ((writeVar = writeVarRe.exec(command))) {
|
|
const candidate = pathsByVar.get(writeVar[1]);
|
|
if (candidate) return candidate;
|
|
}
|
|
|
|
return firstMatch(command, /\bopen\(\s*(["'])(.*?)\1\s*,\s*(["'])[wax](?:\+)?b?\3/);
|
|
}
|
|
|
|
function firstMatch(value, re) {
|
|
const match = String(value || '').match(re);
|
|
return (match?.[2] || '').trim();
|
|
}
|
|
|
|
function shellTeeDestination(command) {
|
|
const words = shellWords(command);
|
|
const teeIndex = words.findIndex((word) => path.basename(word) === 'tee');
|
|
if (teeIndex === -1) return '';
|
|
for (const word of words.slice(teeIndex + 1)) {
|
|
if (['&&', '||', ';', '|'].includes(word)) break;
|
|
if (word === '--') continue;
|
|
if (word.startsWith('-')) continue;
|
|
return word;
|
|
}
|
|
return '';
|
|
}
|
|
|
|
function shellCopiedFileContent(command, cwd) {
|
|
const source = shellCopyPaths(command)?.source;
|
|
if (!source) return '';
|
|
const sourcePath = path.isAbsolute(source) ? source : path.resolve(cwd, source);
|
|
if (!isInsideProject(sourcePath, cwd)) return '';
|
|
if (SENSITIVE_PATH.test(sourcePath) || GENERATED_PATH.test(sourcePath)) return '';
|
|
try {
|
|
const stat = fs.statSync(sourcePath);
|
|
if (!stat.isFile() || stat.size > 1024 * 1024) return '';
|
|
return fs.readFileSync(sourcePath, 'utf-8');
|
|
} catch {
|
|
return '';
|
|
}
|
|
}
|
|
|
|
function shellCopyPaths(command) {
|
|
const words = shellWords(command);
|
|
if (words.length < 3 || path.basename(words[0]) !== 'cp') return null;
|
|
const args = [];
|
|
for (const word of words.slice(1)) {
|
|
if (['&&', '||', ';', '|'].includes(word)) break;
|
|
if (word === '--') continue;
|
|
if (word.startsWith('-')) continue;
|
|
args.push(word);
|
|
}
|
|
if (args.length < 2) return null;
|
|
return { source: args[args.length - 2], dest: args[args.length - 1] };
|
|
}
|
|
|
|
function shellWords(command) {
|
|
if (!command || typeof command !== 'string') return [];
|
|
const words = [];
|
|
const re = /"((?:\\"|[^"])*)"|'((?:\\'|[^'])*)'|([^\s]+)/g;
|
|
let match;
|
|
while ((match = re.exec(command))) {
|
|
words.push((match[1] ?? match[2] ?? match[3] ?? '').replace(/\\(["'])/g, '$1'));
|
|
}
|
|
return words;
|
|
}
|
|
|
|
function shellHereDocContent(command) {
|
|
if (!command || typeof command !== 'string') return '';
|
|
const markerMatch = command.match(/<<-?\s*['"]?([A-Za-z0-9_.-]+)['"]?[^\r\n]*\r?\n/);
|
|
if (!markerMatch) return '';
|
|
const marker = markerMatch[1];
|
|
const start = (markerMatch.index || 0) + markerMatch[0].length;
|
|
const rest = command.slice(start);
|
|
const endRe = new RegExp(`\\r?\\n${escapeRegExp(marker)}(?:\\r?\\n|$)`);
|
|
const end = rest.search(endRe);
|
|
return end >= 0 ? rest.slice(0, end) : '';
|
|
}
|
|
|
|
function shellPythonWriteContent(command) {
|
|
if (!/\bpython(?:3)?\b/.test(command || '')) return '';
|
|
const script = shellHereDocContent(command) || command;
|
|
return pythonStringArg(script, /\.write_text\s*\(\s*/g) || pythonStringArg(script, /\.write\s*\(\s*/g);
|
|
}
|
|
|
|
function pythonStringArg(script, prefixRe) {
|
|
let prefix;
|
|
while ((prefix = prefixRe.exec(script))) {
|
|
const start = prefixRe.lastIndex;
|
|
const triple = script.slice(start, start + 3);
|
|
if (triple === "'''" || triple === '"""') {
|
|
const end = script.indexOf(triple, start + 3);
|
|
if (end !== -1) return script.slice(start + 3, end);
|
|
continue;
|
|
}
|
|
const quote = script[start];
|
|
if (quote !== '"' && quote !== "'") continue;
|
|
let out = '';
|
|
for (let i = start + 1; i < script.length; i++) {
|
|
const ch = script[i];
|
|
if (ch === '\\') {
|
|
out += script[i + 1] || '';
|
|
i += 1;
|
|
} else if (ch === quote) {
|
|
return out;
|
|
} else {
|
|
out += ch;
|
|
}
|
|
}
|
|
}
|
|
return '';
|
|
}
|
|
|
|
function escapeRegExp(value) {
|
|
return String(value).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
}
|
|
|
|
function relativePath(filePath, cwd) {
|
|
try {
|
|
const rel = path.relative(cwd, filePath);
|
|
if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) return filePath;
|
|
return rel.split(path.sep).join('/');
|
|
} catch {
|
|
return filePath;
|
|
}
|
|
}
|
|
|
|
function isInsideProject(filePath, cwd) {
|
|
try {
|
|
const rel = path.relative(cwd, filePath);
|
|
return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
function cursorBlockMessage(findings, filePath, config, cwd) {
|
|
const rendered = renderTemplate(findings, filePath, config, { cwd });
|
|
const blocked = rendered.replace(
|
|
'[impeccable@1] Required design corrections',
|
|
'[impeccable@1] Impeccable design hook blocked this write before it landed. Required design corrections',
|
|
);
|
|
return blocked.length > 4000 ? `${blocked.slice(0, 3984)}\n...(truncated)` : blocked;
|
|
}
|
|
|
|
function findingSignature(findings) {
|
|
return findings
|
|
.map((finding) => `${finding.antipattern || 'unknown'}:${finding.line || 0}`)
|
|
.sort()
|
|
.join('|');
|
|
}
|
|
|
|
function bumpCursorDenial(cache, sessionId, filePath, findings) {
|
|
const session = cache.sessions[sessionId] || { updatedAt: Date.now(), files: {} };
|
|
cache.sessions[sessionId] = session;
|
|
session.updatedAt = Date.now();
|
|
const fileEntry = session.files[filePath] || { editCount: 0, findings: [] };
|
|
session.files[filePath] = fileEntry;
|
|
const key = findingSignature(findings);
|
|
fileEntry.cursorDenials = fileEntry.cursorDenials && typeof fileEntry.cursorDenials === 'object'
|
|
? fileEntry.cursorDenials
|
|
: {};
|
|
fileEntry.cursorDenials[key] = (fileEntry.cursorDenials[key] || 0) + 1;
|
|
return { key, count: fileEntry.cursorDenials[key] };
|
|
}
|
|
|
|
async function main() {
|
|
if (truthy(process.env.IMPECCABLE_HOOK_DISABLED)) {
|
|
return allow({ skipped: 'env-disabled' });
|
|
}
|
|
|
|
let event = null;
|
|
try {
|
|
const raw = await readStdin();
|
|
if (raw) event = JSON.parse(raw);
|
|
} catch {
|
|
return allow({ skipped: 'stdin-malformed' });
|
|
}
|
|
|
|
if (!event || typeof event !== 'object') {
|
|
return allow({ skipped: 'stdin-empty' });
|
|
}
|
|
|
|
const cwd = resolveProjectCwd(event);
|
|
const started = Date.now();
|
|
const filePath = proposedFilePath(event, cwd);
|
|
const audit = {
|
|
harness: 'cursor',
|
|
tool: event.tool_name || null,
|
|
file: filePath || null,
|
|
};
|
|
|
|
if (!filePath) return allow({ ...audit, skipped: 'no-file-path', durationMs: Date.now() - started });
|
|
if (!isInsideProject(filePath, cwd)) return allow({ ...audit, skipped: 'outside-project', durationMs: Date.now() - started });
|
|
if (SENSITIVE_PATH.test(filePath)) return allow({ ...audit, skipped: 'sensitive', durationMs: Date.now() - started });
|
|
if (GENERATED_PATH.test(filePath)) return allow({ ...audit, skipped: 'generated', durationMs: Date.now() - started });
|
|
|
|
const ext = path.extname(filePath).toLowerCase();
|
|
audit.ext = ext;
|
|
if (!ALLOWED_EXTS.has(ext)) return allow({ ...audit, skipped: 'extension', durationMs: Date.now() - started });
|
|
|
|
const contentResult = proposedContent(event, cwd, filePath);
|
|
if (contentResult && typeof contentResult === 'object' && contentResult.skipped) {
|
|
return allow({ ...audit, skipped: contentResult.skipped, durationMs: Date.now() - started });
|
|
}
|
|
const content = typeof contentResult === 'string' ? contentResult : '';
|
|
if (!content) return allow({ ...audit, skipped: 'no-proposed-content', durationMs: Date.now() - started });
|
|
|
|
const config = readConfig(cwd);
|
|
if (config.enabled === false) return allow({ ...audit, skipped: 'config-disabled', durationMs: Date.now() - started });
|
|
|
|
const rel = relativePath(filePath, cwd);
|
|
if (matchesAnyGlob(rel, config.ignoreFiles) || matchesAnyGlob(filePath, config.ignoreFiles)) {
|
|
return allow({ ...audit, skipped: 'config-ignore-file', durationMs: Date.now() - started });
|
|
}
|
|
|
|
const detector = await loadDetector();
|
|
if (!detector || typeof detector.detectText !== 'function') {
|
|
return allow({ ...audit, skipped: 'detector-missing', durationMs: Date.now() - started });
|
|
}
|
|
|
|
let findings = [];
|
|
try {
|
|
findings = await detector.detectText(content, filePath);
|
|
} catch {
|
|
return allow({ ...audit, error: 'detector-threw', durationMs: Date.now() - started });
|
|
}
|
|
|
|
const filtered = filterFindings(findings || [], content, ext, config);
|
|
if (filtered.length === 0) {
|
|
return allow({
|
|
...audit,
|
|
findings: (findings || []).length,
|
|
blockedFindings: 0,
|
|
durationMs: Date.now() - started,
|
|
});
|
|
}
|
|
|
|
const message = cursorBlockMessage(filtered, filePath, config, cwd);
|
|
const sessionId = event.session_id || event.conversation_id || 'unknown';
|
|
const cache = readCache(cwd);
|
|
const denial = bumpCursorDenial(cache, sessionId, filePath, filtered);
|
|
persistCache(cwd, cache);
|
|
if (denial.count > EDIT_COUNT_THRESHOLD) {
|
|
const warning = `${message}\n\nThis is the ${denial.count}th repeated denial for the same file and finding signature, so Impeccable is allowing this write to avoid a loop. Reconsider the issue immediately after the tool runs.`;
|
|
return allow({
|
|
...audit,
|
|
findings: (findings || []).length,
|
|
blockedFindings: filtered.length,
|
|
cursorDenialKey: denial.key,
|
|
cursorDenialCount: denial.count,
|
|
downgraded: true,
|
|
chars: warning.length,
|
|
durationMs: Date.now() - started,
|
|
}, {
|
|
user_message: warning,
|
|
agent_message: warning,
|
|
});
|
|
}
|
|
return deny(message, {
|
|
...audit,
|
|
findings: (findings || []).length,
|
|
blockedFindings: filtered.length,
|
|
cursorDenialKey: denial.key,
|
|
cursorDenialCount: denial.count,
|
|
chars: message.length,
|
|
durationMs: Date.now() - started,
|
|
});
|
|
}
|
|
|
|
main().catch((err) => {
|
|
if (process.env.IMPECCABLE_HOOK_DEBUG) {
|
|
process.stderr.write(`[impeccable-hook-before-edit] ${err}\n`);
|
|
}
|
|
done({ permission: 'allow' });
|
|
});
|