Skip to content

The design language that makes your AI harness better at design.

JavaScript

Add automatic design hook install and exceptions (#170)

Abdul Wahab672517f76ef2
diff --git a/.agents/skills/impeccable/SKILL.md b/.agents/skills/impeccable/SKILL.md
index 0d6acb28e..962a70e09 100644
--- a/.agents/skills/impeccable/SKILL.md
+++ b/.agents/skills/impeccable/SKILL.md
@@ -131,7 +131,7 @@ If someone could look at this interface and say "AI made that" without doubt, it
| `optimize [target]` | Fix | Diagnose and fix UI performance | [reference/optimize.md](reference/optimize.md) |
| `live` | Iterate | Visual variant mode: pick elements in the browser, generate alternatives | [reference/live.md](reference/live.md) |
-Plus two management commands: `pin <command>` and `unpin <command>`, detailed below.
+Plus three management commands: `pin <command>`, `unpin <command>`, and `hooks <on|off|status|...>`, detailed below.
### Routing rules
@@ -148,7 +148,7 @@ Plus two management commands: `pin <command>` and `unpin <command>`, detailed be
**If `scan.targets` is non-empty, run `node .agents/skills/impeccable/scripts/detect.mjs --json <scan.targets joined by spaces>` once** (the bundled detector over local files: no network, no npx). `scan.via` tells you what they are: `git-changes` (the markup/style files in your dirty tree, the most relevant set), `source-dir` (e.g. `src`, `app`), `html`, or `root`. Fold the hits into your picks: many quality / contrast hits → `audit` or `polish`; a specific slop family → the matching command (gradient text or eyebrows → `quieter` / `typeset`, flat or gray palette → `colorize`, and so on). It's a real, current signal that beats guessing. If detect errors or the tree is large and slow, skip it and recommend the user run `audit` themselves; never block the suggestion on it.
Keep it to 2-3 pointed picks with the exact command to type. The menu stays the fallback; the recommendation is the lede.
-2. **First word matches a command**: load its reference file and follow its instructions. Everything after the command name is the target.
+2. **First word matches a command** (table above OR `pin` / `unpin` / `hooks`): load its reference file and follow its instructions. Everything after the command name is the target.
3. **First word doesn't match, but the intent clearly maps to one command** (e.g. "fix the spacing" → `layout`, "rewrite this error message" → `clarify`, "the colors feel flat" → `colorize`): load that command's reference and proceed as if invoked. If two commands could fit, ask once which.
4. **No clear command match**: general design invocation. Apply the setup steps, the General rules, and the loaded register reference, using the full argument as context.
@@ -166,4 +166,8 @@ If the first word is `craft`, setup still runs first, but [reference/craft.md](r
node .agents/skills/impeccable/scripts/pin.mjs <pin|unpin> <command>
```
-Valid `<command>` is any command from the table above. Report the script's result concisely. Confirm the new shortcut on success, relay stderr verbatim on error.
\ No newline at end of file
+Valid `<command>` is any command from the table above. Report the script's result concisely. Confirm the new shortcut on success, relay stderr verbatim on error.
+
+## Hooks
+
+`$impeccable hooks <on|off|status|ignore-rule|ignore-file|ignore-value|reset>` manages the design detector hook for this project. The hook auto-runs the detector after direct UI file edits and surfaces findings as system reminders. Full flow is in [reference/hooks.md](reference/hooks.md); load it when the user invokes `$impeccable hooks` with any argument.
\ No newline at end of file
diff --git a/.agents/skills/impeccable/reference/hooks.md b/.agents/skills/impeccable/reference/hooks.md
new file mode 100644
index 000000000..5f288614d
--- /dev/null
+++ b/.agents/skills/impeccable/reference/hooks.md
@@ -0,0 +1,82 @@
+# $impeccable hooks
+
+Manage the **design detector hook** for the current project.
+
+The hook runs the impeccable design detector on direct file edits to design-relevant files (`.tsx`, `.jsx`, `.html`, `.vue`, `.svelte`, `.astro`, `.css`, `.scss`, `.sass`, `.less`, `.ts`, `.js`). Claude Code and Codex use `PostToolUse` and push a short system reminder into the agent's context after the edit; findings get a correction prompt, pending issues get a re-nudge, and clean UI-ish files get a short ack unless `IMPECCABLE_HOOK_QUIET=1` is set. Plain `.ts` and `.js` files are still scanned, but stay quiet unless the detector finds something. Cursor uses `preToolUse` to block bad proposed writes before they land and stays silent when it allows a clean write.
+
+This command toggles the hook **per project** by editing `.impeccable/hook.json`. Local-only ignore policy lives in `.impeccable/hook.local.json`, which is gitignored. To disable globally, set `IMPECCABLE_HOOK_DISABLED=1` in your shell environment.
+
+Supported harnesses: Claude Code (`.claude/settings.json` in the project), Codex (`.codex/hooks.json` in the project), and Cursor (`.cursor/hooks.json` in the project).
+
+On **Cursor**, `preToolUse` checks proposed Write/Edit/Shell write content and denies only when the real detector finds an issue. The denial message is visible to the agent as the tool error, so the agent can reconsider before the bad write lands.
+
+## Routing
+
+The first argument is the action. Defaults to `status`.
+
+| Action | What it does |
+|---|---|
+| `status` | Print current state, shared/local config paths, ignored rules / files / values, env override. |
+| `on` | Set `enabled: true` in `.impeccable/hook.json`. |
+| `off` | Set `enabled: false` in `.impeccable/hook.json`. |
+| `ignore-rule <id>` | Append `<id>` to `ignoreRules`; for `overused-font`, requires `--all-values`. |
+| `ignore-file <glob>` | Append `<glob>` to `ignoreFiles`. |
+| `ignore-value <id> <value> [--shared] [--reason "..."]` | Append a rule/value suppression to shared `.impeccable/hook.json`. |
+| `ignore-value <id> <value> --local [--reason "..."]` | Append a private rule/value suppression to `.impeccable/hook.local.json`. |
+| `reset` | Delete the project config, dedup cache, and Cursor pending queue. |
+
+## Flow
+
+1. Resolve the action from the user's argument. If no action was given, default to `status`.
+2. Invoke the admin script and pass the user's output through verbatim:
+
+ ```bash
+ node .agents/skills/impeccable/scripts/hook-admin.mjs <action> [args...]
+ ```
+
+3. If `<action>` is `off`, follow up with a one-line note: "Done. New edits will not trigger the design hook in this project until you run `$impeccable hooks on`."
+4. If `<action>` is `on`, follow up with: "Done. The design hook will fire after the next Edit/Write/MultiEdit on a UI file."
+5. If `<action>` is `ignore-value`, `ignore-file`, or `ignore-rule`, just print the script output. The default scope is shared `.impeccable/hook.json`; add `--local` only when the user explicitly asks for a private exception.
+6. If `<action>` is `status`, just print the script output. Do not add commentary unless the user asked a follow-up question.
+
+## Intentional findings
+
+The hook itself never writes ignore config. Persist an exception only after the user explicitly confirms the flagged issue is intentional, and always go through `hook-admin.mjs`.
+
+Prefer the narrowest exception:
+
+- If the finding line shows an exact `ignore-value` command, run that command. This writes shared `.impeccable/hook.json` by default.
+- For `overused-font`, use `ignore-value` when the user confirms a specific font. Do not use `ignore-rule overused-font` for a specific font.
+- If the finding has no value-specific command, such as `side-tab`, prefer `ignore-file <path>` for the current file.
+- Use `ignore-rule <id>` only when the user asks to suppress that whole rule across the project. For broad overused-font suppression, use `ignore-rule overused-font --all-values` only when the user asks to ignore overused fonts generally.
+- Do not add source comments such as `impeccable: ignore`; inline comments pollute code and are not a supported suppression mechanism.
+
+Example value-specific exception:
+
+```bash
+node .agents/skills/impeccable/scripts/hook-admin.mjs ignore-value overused-font Inter --shared --reason "User confirmed Inter is intentional"
+```
+
+Example whole-rule font exception:
+
+```bash
+node .agents/skills/impeccable/scripts/hook-admin.mjs ignore-rule overused-font --all-values --reason "User asked to ignore overused fonts generally"
+```
+
+Example file-scoped exception:
+
+```bash
+node .agents/skills/impeccable/scripts/hook-admin.mjs ignore-file "src/legacy/Card.tsx"
+```
+
+## Constraints
+
+- Never modify `.impeccable/hook.json` or `.impeccable/hook.local.json` by hand from this command. Always go through `hook-admin.mjs` so writes stay validated and the file shape stays consistent.
+- Do not edit the hook scripts themselves (`hook.mjs`, `hook-lib.mjs`, `hook-before-edit.mjs`) from this flow. Those are skill plumbing.
+- Cursor can block a proposed write when the detector finds a real issue. Claude Code and Codex do not block the edit; they emit a post-edit reminder instead. Disabling stops both blocking and reminders.
+- The hook is bundled with the Impeccable skill and installed through project-local manifests: `.claude/settings.json`, `.codex/hooks.json`, and `.cursor/hooks.json`. On Codex, the user must approve the hook via `/hooks` the first time. On Cursor, confirm hooks are enabled under Settings -> Hooks.
+
+## Failure modes
+
+- If `.impeccable/hook.json` or `.impeccable/hook.local.json` is unreadable or malformed, the hook ignores that file and uses the remaining valid config/defaults. `hook-admin.mjs status` will show malformed files as ignored.
+- If the user asks to "disable the hook" globally, suggest both options: `IMPECCABLE_HOOK_DISABLED=1` env var (one-shot, follows the shell), and `$impeccable hooks off` (persistent for this project, committable).
diff --git a/.agents/skills/impeccable/scripts/detector/engines/regex/detect-text.mjs b/.agents/skills/impeccable/scripts/detector/engines/regex/detect-text.mjs
index fd0d9c73f..4c0777c93 100644
--- a/.agents/skills/impeccable/scripts/detector/engines/regex/detect-text.mjs
+++ b/.agents/skills/impeccable/scripts/detector/engines/regex/detect-text.mjs
@@ -446,7 +446,7 @@ function detectText(content, filePath, options = {}) {
// Run regex matchers on the full file content (catches Tailwind classes, inline styles)
// Enable block context for CSS files where related properties span multiple lines
- const cssLike = new Set(['.css', '.scss', '.less']);
+ const cssLike = new Set(['.css', '.scss', '.sass', '.less']);
findings.push(...runRegexMatchers(lines, filePath, 0, cssLike.has(ext) || null, {
profile,
phase: 'source',
diff --git a/.agents/skills/impeccable/scripts/detector/node/file-system.mjs b/.agents/skills/impeccable/scripts/detector/node/file-system.mjs
index a80250a0e..aaa8c6df7 100644
--- a/.agents/skills/impeccable/scripts/detector/node/file-system.mjs
+++ b/.agents/skills/impeccable/scripts/detector/node/file-system.mjs
@@ -11,7 +11,7 @@ const SKIP_DIRS = new Set([
]);
const SCANNABLE_EXTENSIONS = new Set([
- '.html', '.htm', '.css', '.scss', '.less',
+ '.html', '.htm', '.css', '.scss', '.sass', '.less',
'.jsx', '.tsx', '.js', '.ts',
'.vue', '.svelte', '.astro',
]);
diff --git a/.agents/skills/impeccable/scripts/hook-admin.mjs b/.agents/skills/impeccable/scripts/hook-admin.mjs
new file mode 100644
index 000000000..86fcfa909
--- /dev/null
+++ b/.agents/skills/impeccable/scripts/hook-admin.mjs
@@ -0,0 +1,300 @@
+#!/usr/bin/env node
+/**
+ * `/impeccable hooks <on|off|status|reset>` — manage the design hook
+ * via .impeccable/hook.json and .impeccable/hook.local.json in the current
+ * project.
+ *
+ * Usage:
+ * node hook-admin.mjs status # print current state
+ * node hook-admin.mjs on # set enabled: true
+ * node hook-admin.mjs off # set enabled: false
+ * node hook-admin.mjs ignore-rule <rule-id> # append to ignoreRules
+ * node hook-admin.mjs ignore-rule overused-font --all-values
+ * node hook-admin.mjs ignore-file <glob> # append to ignoreFiles
+ * node hook-admin.mjs ignore-value <rule> <value> # append to shared ignoreValues
+ * node hook-admin.mjs ignore-value <rule> <value> --local
+ * node hook-admin.mjs reset # remove all config + cache
+ *
+ * Designed to be invoked by the LLM from the reference/hooks.md flow.
+ * Output is human-readable; the harness will pass it back to the user.
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+
+import {
+ getConfigPath,
+ getLocalConfigPath,
+ getCachePath,
+ getPendingPath,
+ readConfig,
+ DEFAULT_CONFIG,
+ ensureHookGitExcludes,
+ normalizeIgnoreValue,
+ normalizeIgnoreValueEntries,
+} from './hook-lib.mjs';
+
+const ACTIONS = new Set(['status', 'on', 'off', 'ignore-rule', 'ignore-file', 'ignore-value', 'reset']);
+
+function readRawConfigFile(filePath) {
+ if (!fs.existsSync(filePath)) return { exists: false, malformed: false, raw: null };
+ try {
+ return { exists: true, malformed: false, raw: JSON.parse(fs.readFileSync(filePath, 'utf-8')) };
+ } catch {
+ return { exists: true, malformed: true, raw: null };
+ }
+}
+
+function readRawConfig(cwd, opts = {}) {
+ const filePath = opts.local ? getLocalConfigPath(cwd) : getConfigPath(cwd);
+ return readRawConfigFile(filePath).raw;
+}
+
+function writeConfig(cwd, config, opts = {}) {
+ const filePath = opts.local ? getLocalConfigPath(cwd) : getConfigPath(cwd);
+ if (opts.local) ensureHookGitExcludes(cwd);
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
+ fs.writeFileSync(filePath, JSON.stringify(config, null, 2) + '\n');
+ return filePath;
+}
+
+function mergeConfig(existing) {
+ // Persist the full shape so /impeccable hooks edits leave a complete file
+ // for the user to see, not an unhelpful `{"enabled":false}`.
+ const base = existing && typeof existing === 'object' ? existing : {};
+ return {
+ enabled: base.enabled === false ? false : true,
+ ignoreRules: Array.isArray(base.ignoreRules) ? Array.from(new Set(base.ignoreRules.map(String))) : [],
+ ignoreFiles: Array.isArray(base.ignoreFiles) ? Array.from(new Set(base.ignoreFiles.map(String))) : [],
+ ignoreValues: normalizeIgnoreValueEntries(base.ignoreValues || []),
+ limits: {
+ maxFindings: Number.isFinite(base?.limits?.maxFindings) ? base.limits.maxFindings : DEFAULT_CONFIG.limits.maxFindings,
+ maxChars: Number.isFinite(base?.limits?.maxChars) ? base.limits.maxChars : DEFAULT_CONFIG.limits.maxChars,
+ },
+ };
+}
+
+function mergeLocalConfig(existing) {
+ const base = existing && typeof existing === 'object' ? existing : {};
+ const out = {};
+ if (Object.prototype.hasOwnProperty.call(base, 'enabled')) {
+ out.enabled = base.enabled === false ? false : true;
+ }
+ if (Array.isArray(base.ignoreRules)) {
+ out.ignoreRules = Array.from(new Set(base.ignoreRules.map(String)));
+ }
+ if (Array.isArray(base.ignoreFiles)) {
+ out.ignoreFiles = Array.from(new Set(base.ignoreFiles.map(String)));
+ }
+ out.ignoreValues = normalizeIgnoreValueEntries(base.ignoreValues || []);
+ if (base.limits && typeof base.limits === 'object') {
+ const limits = {};
+ if (Number.isFinite(base.limits.maxFindings)) limits.maxFindings = base.limits.maxFindings;
+ if (Number.isFinite(base.limits.maxChars)) limits.maxChars = base.limits.maxChars;
+ if (Object.keys(limits).length) out.limits = limits;
+ }
+ return out;
+}
+
+function statusReport(cwd) {
+ const shared = readRawConfigFile(getConfigPath(cwd));
+ const local = readRawConfigFile(getLocalConfigPath(cwd));
+ const cfg = readConfig(cwd);
+ const envKill = process.env.IMPECCABLE_HOOK_DISABLED;
+ const envState = envKill ? `IMPECCABLE_HOOK_DISABLED=${envKill}` : 'unset';
+ const cfgPath = path.relative(cwd, getConfigPath(cwd)) || '.impeccable/hook.json';
+ const localPath = path.relative(cwd, getLocalConfigPath(cwd)) || '.impeccable/hook.local.json';
+ const cachePath = path.relative(cwd, getCachePath(cwd)) || '.impeccable/hook.cache.json';
+ const fileState = (info, relPath, absent) => {
+ if (info.malformed) return `${relPath} (malformed; ignored)`;
+ if (info.exists) return relPath;
+ return `${relPath} (${absent})`;
+ };
+ const ignoreValues = cfg.ignoreValues.map((entry) => `${entry.rule}=${entry.value}`);
+
+ const lines = [
+ `Impeccable design hook`,
+ ` state: ${cfg.enabled ? 'enabled' : 'disabled'}`,
+ ` shared file: ${fileState(shared, cfgPath, 'using defaults; file not present')}`,
+ ` local file: ${fileState(local, localPath, 'not present')}`,
+ ` ignoreRules: ${cfg.ignoreRules.length ? cfg.ignoreRules.join(', ') : '(none)'}`,
+ ` ignoreFiles: ${cfg.ignoreFiles.length ? cfg.ignoreFiles.join(', ') : '(none)'}`,
+ ` ignoreValues: ${ignoreValues.length ? ignoreValues.join(', ') : '(none)'}`,
+ ` maxFindings: ${cfg.limits.maxFindings}`,
+ ` maxChars: ${cfg.limits.maxChars}`,
+ ` env override: ${envState}`,
+ ` cache file: ${fs.existsSync(getCachePath(cwd)) ? cachePath : `${cachePath} (not present)`}`,
+ ];
+ return lines.join('\n');
+}
+
+function setEnabled(cwd, value) {
+ const config = mergeConfig(readRawConfig(cwd));
+ config.enabled = value;
+ const target = writeConfig(cwd, config);
+ return `Design hook ${value ? 'enabled' : 'disabled'} for this project (wrote ${path.relative(cwd, target) || target}).`;
+}
+
+function normalizeRuleId(rule) {
+ return String(rule || '').trim().toLowerCase();
+}
+
+function parseIgnoreRuleArgs(args) {
+ const positionals = [];
+ let allValues = false;
+
+ for (let i = 0; i < args.length; i++) {
+ const arg = String(args[i] || '');
+ if (arg === '--all-values') {
+ allValues = true;
+ } else if (arg === '--reason') {
+ while (i + 1 < args.length && !String(args[i + 1]).startsWith('--')) i++;
+ } else if (arg.startsWith('--reason=')) {
+ // Accepted for command symmetry; ignoreRules stores rule ids only.
+ } else if (arg.startsWith('--')) {
+ throw new Error(`Unknown ignore-rule flag: ${arg}`);
+ } else {
+ positionals.push(arg);
+ }
+ }
+
+ return {
+ rule: normalizeRuleId(positionals[0]),
+ allValues,
+ };
+}
+
+function addIgnoreRule(cwd, args) {
+ const parsed = parseIgnoreRuleArgs(args);
+ const rule = parsed.rule;
+ if (!rule) throw new Error('Pass a rule id, e.g. /impeccable hooks ignore-rule side-tab');
+ if (rule === 'overused-font' && !parsed.allValues) {
+ throw new Error('overused-font is value-specific by default. Use /impeccable hooks ignore-value overused-font <font> for a confirmed font, or /impeccable hooks ignore-rule overused-font --all-values only when the user asked to ignore overused fonts generally.');
+ }
+ const config = mergeConfig(readRawConfig(cwd));
+ if (!config.ignoreRules.includes(rule)) config.ignoreRules.push(rule);
+ writeConfig(cwd, config);
+ return `Added "${rule}" to ignoreRules. Current: ${config.ignoreRules.join(', ')}`;
+}
+
+function addIgnoreFile(cwd, glob) {
+ if (!glob) throw new Error('Pass a glob, e.g. /impeccable hooks ignore-file "src/legacy/**"');
+ const config = mergeConfig(readRawConfig(cwd));
+ if (!config.ignoreFiles.includes(glob)) config.ignoreFiles.push(glob);
+ writeConfig(cwd, config);
+ return `Added "${glob}" to ignoreFiles. Current: ${config.ignoreFiles.join(', ')}`;
+}
+
+function parseIgnoreValueArgs(args) {
+ const positionals = [];
+ let shared = false;
+ let local = false;
+ let reason = '';
+
+ for (let i = 0; i < args.length; i++) {
+ const arg = args[i];
+ if (arg === '--shared') {
+ shared = true;
+ } else if (arg === '--local') {
+ local = true;
+ } else if (arg === '--reason') {
+ const chunks = [];
+ while (i + 1 < args.length && !String(args[i + 1]).startsWith('--')) {
+ chunks.push(args[++i]);
+ }
+ reason = chunks.join(' ').trim();
+ } else if (String(arg).startsWith('--reason=')) {
+ reason = String(arg).slice('--reason='.length).trim();
+ } else {
+ positionals.push(arg);
+ }
+ }
+
+ const [rule, ...valueParts] = positionals;
+ return {
+ rule: String(rule || '').trim().toLowerCase(),
+ value: normalizeIgnoreValue(valueParts.join(' ')),
+ shared,
+ local,
+ reason,
+ };
+}
+
+function addIgnoreValue(cwd, args) {
+ const parsed = parseIgnoreValueArgs(args);
+ if (!parsed.rule || !parsed.value) {
+ throw new Error('Pass a rule id and value, e.g. /impeccable hooks ignore-value overused-font Inter');
+ }
+
+ if (parsed.shared && parsed.local) {
+ throw new Error('Pass only one scope flag: --shared or --local');
+ }
+
+ const local = parsed.local;
+ const config = local
+ ? mergeLocalConfig(readRawConfig(cwd, { local: true }))
+ : mergeConfig(readRawConfig(cwd, { local: false }));
+ const key = `${parsed.rule}\0${parsed.value}`;
+ const existing = config.ignoreValues.find((entry) => `${entry.rule}\0${entry.value}` === key);
+
+ if (existing) {
+ if (parsed.reason) existing.reason = parsed.reason;
+ } else {
+ const entry = {
+ rule: parsed.rule,
+ value: parsed.value,
+ createdAt: new Date().toISOString(),
+ };
+ if (parsed.reason) entry.reason = parsed.reason;
+ config.ignoreValues.push(entry);
+ }
+
+ const target = writeConfig(cwd, config, { local });
+ const scope = local ? 'local ignoreValues' : 'shared ignoreValues';
+ return `Added ${parsed.rule}=${parsed.value} to ${scope} (${path.relative(cwd, target) || target}).`;
+}
+
+function reset(cwd) {
+ const removed = [];
+ for (const filePath of [getConfigPath(cwd), getLocalConfigPath(cwd), getCachePath(cwd), getPendingPath(cwd)]) {
+ try {
+ if (fs.existsSync(filePath)) {
+ fs.unlinkSync(filePath);
+ removed.push(path.relative(cwd, filePath) || filePath);
+ }
+ } catch { /* ignore */ }
+ }
+ return removed.length
+ ? `Reset design hook config and cache (removed: ${removed.join(', ')}).`
+ : 'No hook config or cache to remove. Already at defaults.';
+}
+
+function main() {
+ const [, , actionArg, ...rest] = process.argv;
+ const action = (actionArg || 'status').toLowerCase();
+ const cwd = process.cwd();
+
+ if (!ACTIONS.has(action)) {
+ process.stderr.write(`Unknown action: ${action}\nValid: ${Array.from(ACTIONS).join(', ')}\n`);
+ process.exit(1);
+ }
+
+ try {
+ let out = '';
+ switch (action) {
+ case 'status': out = statusReport(cwd); break;
+ case 'on': out = setEnabled(cwd, true); break;
+ case 'off': out = setEnabled(cwd, false); break;
+ case 'ignore-rule': out = addIgnoreRule(cwd, rest); break;
+ case 'ignore-file': out = addIgnoreFile(cwd, rest[0]); break;
+ case 'ignore-value': out = addIgnoreValue(cwd, rest); break;
+ case 'reset': out = reset(cwd); break;
+ }
+ process.stdout.write(out + '\n');
+ } catch (err) {
+ process.stderr.write(`Error: ${err.message || err}\n`);
+ process.exit(1);
+ }
+}
+
+main();
diff --git a/.agents/skills/impeccable/scripts/hook-before-edit.mjs b/.agents/skills/impeccable/scripts/hook-before-edit.mjs
new file mode 100644
index 000000000..54b2709d2
--- /dev/null
+++ b/.agents/skills/impeccable/scripts/hook-before-edit.mjs
@@ -0,0 +1,408 @@
+#!/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 shellContent = shellHereDocContent(shellCommand(input));
+ if (shellContent) return shellContent;
+ const copiedContent = shellCopiedFileContent(shellCommand(input), 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 || '';
+}
+
+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 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' });
+});
diff --git a/.agents/skills/impeccable/scripts/hook-lib.mjs b/.agents/skills/impeccable/scripts/hook-lib.mjs
new file mode 100644
index 000000000..02199f530
--- /dev/null
+++ b/.agents/skills/impeccable/scripts/hook-lib.mjs
@@ -0,0 +1,1232 @@
+/**
+ * Shared library for the Impeccable design hook.
+ *
+ * Pure-ish helpers split out from `hook.mjs` so unit tests can exercise
+ * config parsing, finding filtering, dedup, render, and cache logic without
+ * spawning a subprocess. `hook.mjs` itself is the thin stdin/stdout shim.
+ *
+ * Public surface (everything exported is part of the contract):
+ * ENVELOPE_PREFIX, ALLOWED_EXTS, ACK_EXTS, SENSITIVE_PATH, GENERATED_PATH, TRUTHY
+ * truthy(value)
+ * readConfig(cwd) / DEFAULT_CONFIG / getConfigPath(cwd) / getLocalConfigPath(cwd)
+ * normalizeIgnoreValue(value)
+ * readCache(cwd) / persistCache(cwd, cache)
+ * bumpEditCount(cache, sessionId, filePath) -> number
+ * suppressionNotice(filePath)
+ * filterFindings(findings, content, ext, config)
+ * dedupeAgainstCache(findings, cache, sessionId, filePath)
+ * renderTemplate(findings, filePath, config, opts)
+ * renderCleanAck(filePath, opts) / renderPendingAck(filePath, known, opts)
+ * shouldEmitAckForFile(filePath)
+ * writeAuditLog(env, entry)
+ * loadDetector() -> Promise<{ detectText, detectHtml }>
+ * matchesAnyGlob(filePath, globs)
+ * normalizeScanTargets(primaryTargets, projectCwd)
+ * runHook(deps) -> { exitCode, stdout, audit, reason? }
+ *
+ * Design notes:
+ * - All errors are swallowed at the runHook seam. The detector throwing must
+ * never break a turn. See PRD §5 "Failure modes".
+ * - Cache shape is JSON-friendly; we gc the oldest sessions when there are
+ * more than 8 to keep file size predictable across long-lived projects.
+ * - The detector loader looks for `detector/detect-antipatterns.mjs` next to
+ * this file first (built skill layout) and falls back to the repo root's
+ * `cli/engine/detect-antipatterns.mjs` (running from source).
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+import { pathToFileURL, fileURLToPath } from 'node:url';
+
+const __filename = fileURLToPath(import.meta.url);
+const __dirname = path.dirname(__filename);
+
+export const ENVELOPE_PREFIX = '[impeccable@1]';
+
+export const ALLOWED_EXTS = new Set([
+ '.tsx', '.jsx', '.html', '.htm', '.vue', '.svelte', '.astro',
+ '.css', '.scss', '.sass', '.less', '.ts', '.js',
+]);
+
+export const ACK_EXTS = new Set([
+ '.tsx', '.jsx', '.html', '.htm', '.vue', '.svelte', '.astro',
+ '.css', '.scss', '.sass', '.less',
+]);
+
+// Hard-skip regex for sensitive files. Cannot be turned off via config.
+// Match tokenized secret/credential filenames, not UI names such as
+// CredentialForm.tsx, SecretPage.jsx, or secretary-dashboard.vue.
+export const SENSITIVE_PATH = new RegExp([
+ String.raw`(?:^|[/\\])\.env(?:\.|$)`,
+ String.raw`(?:^|[/\\])\.git(?:[/\\]|$)`,
+ String.raw`(?:^|[/\\])id_rsa(?:$|[._-])[^/\\]*$`,
+ String.raw`(?:^|[/\\])[^/\\]*\.pem$`,
+ String.raw`(?:^|[/\\])(?:[^/\\]*[._-])?(?:secret|secrets|credential|credentials)(?=[._-])[^/\\]*\.(?:json|ya?ml|toml|ini|conf|config|env|txt|key|cert|crt|pem|js|ts)$`,
+].join('|'), 'i');
+
+// Hard-skip regex for generated, lock, minified, and build-output paths.
+export const GENERATED_PATH = /(?:\.generated\.[a-z]+$|\.d\.ts$|\.min\.[a-z]+$|[/\\]node_modules[/\\]|[/\\](?:dist|build|out|\.next|\.cache|coverage)[/\\]|[/\\]?[^/\\]+\.lock(?:\.json)?$)/i;
+
+export const TRUTHY = /^(1|true|yes|on)$/i;
+
+export const DEFAULT_CONFIG = Object.freeze({
+ enabled: true,
+ ignoreRules: [],
+ ignoreFiles: [],
+ ignoreValues: [],
+ limits: { maxFindings: 5, maxChars: 8000 },
+});
+
+export const HOOK_LOCAL_IGNORE_PATTERNS = Object.freeze([
+ '.impeccable/hook.cache.json',
+ '.impeccable/hook.pending.json',
+ '.impeccable/hook.local.json',
+]);
+
+const HOOK_IGNORE_MARKER_OPEN = '# impeccable-hook-ignore-start';
+const HOOK_IGNORE_MARKER_CLOSE = '# impeccable-hook-ignore-end';
+const CACHE_MAX_SESSIONS = 8;
+export const EDIT_COUNT_THRESHOLD = 6;
+
+export function truthy(value) {
+ return typeof value === 'string' && TRUTHY.test(value);
+}
+
+function depthIsSet(value) {
+ if (value === undefined || value === null) return false;
+ const text = String(value).trim();
+ if (!text) return false;
+ if (TRUTHY.test(text)) return true;
+ return /^\d+$/.test(text) && Number(text) > 0;
+}
+
+function safeReadJson(filePath) {
+ try {
+ return JSON.parse(fs.readFileSync(filePath, 'utf-8'));
+ } catch {
+ return null;
+ }
+}
+
+export function getConfigPath(cwd) {
+ return path.join(cwd, '.impeccable', 'hook.json');
+}
+
+export function getLocalConfigPath(cwd) {
+ return path.join(cwd, '.impeccable', 'hook.local.json');
+}
+
+export function getCachePath(cwd) {
+ return path.join(cwd, '.impeccable', 'hook.cache.json');
+}
+
+export function getPendingPath(cwd) {
+ return path.join(cwd, '.impeccable', 'hook.pending.json');
+}
+
+export function resolveProjectCwd(event, fallback = process.cwd()) {
+ return event?.cwd
+ || (Array.isArray(event?.workspace_roots) && event.workspace_roots[0])
+ || envProjectDir(fallback)
+ || fallback;
+}
+
+export function readConfig(cwd) {
+ const config = cloneDefaultConfig();
+ applyConfigSource(config, safeReadJson(getConfigPath(cwd)));
+ applyConfigSource(config, safeReadJson(getLocalConfigPath(cwd)));
+ return config;
+}
+
+function numberOr(value, fallback) {
+ return Number.isFinite(value) && value > 0 ? value : fallback;
+}
+
+function cloneDefaultConfig() {
+ return {
+ ...DEFAULT_CONFIG,
+ ignoreRules: [],
+ ignoreFiles: [],
+ ignoreValues: [],
+ limits: { ...DEFAULT_CONFIG.limits },
+ };
+}
+
+function applyConfigSource(config, raw) {
+ if (!raw || typeof raw !== 'object') return config;
+ if (Object.prototype.hasOwnProperty.call(raw, 'enabled')) {
+ config.enabled = raw.enabled === false ? false : true;
+ }
+ if (Array.isArray(raw.ignoreRules)) {
+ config.ignoreRules = uniqueStrings([...config.ignoreRules, ...raw.ignoreRules]);
+ }
+ if (Array.isArray(raw.ignoreFiles)) {
+ config.ignoreFiles = uniqueStrings([...config.ignoreFiles, ...raw.ignoreFiles]);
+ }
+ if (Array.isArray(raw.ignoreValues)) {
+ config.ignoreValues = mergeIgnoreValues(config.ignoreValues, raw.ignoreValues);
+ }
+ if (raw.limits && typeof raw.limits === 'object') {
+ config.limits = {
+ maxFindings: numberOr(raw.limits.maxFindings, config.limits.maxFindings),
+ maxChars: numberOr(raw.limits.maxChars, config.limits.maxChars),
+ };
+ }
+ return config;
+}
+
+function uniqueStrings(values) {
+ return Array.from(new Set(values.map(String)));
+}
+
+export function normalizeIgnoreValue(value) {
+ return String(value || '')
+ .trim()
+ .replace(/^["']|["']$/g, '')
+ .replace(/\+/g, ' ')
+ .replace(/\s+/g, ' ')
+ .toLowerCase();
+}
+
+function normalizeIgnoreRule(rule) {
+ return String(rule || '').trim().toLowerCase();
+}
+
+export function normalizeIgnoreValueEntries(entries) {
+ if (!Array.isArray(entries)) return [];
+ const out = [];
+ for (const entry of entries) {
+ if (!entry || typeof entry !== 'object') continue;
+ const rule = normalizeIgnoreRule(entry.rule);
+ const value = normalizeIgnoreValue(entry.value);
+ if (!rule || !value) continue;
+ const normalized = { rule, value };
+ if (typeof entry.reason === 'string' && entry.reason.trim()) {
+ normalized.reason = entry.reason.trim();
+ }
+ if (typeof entry.createdAt === 'string' && entry.createdAt.trim()) {
+ normalized.createdAt = entry.createdAt.trim();
+ }
+ out.push(normalized);
+ }
+ return out;
+}
+
+function mergeIgnoreValues(existing, incoming) {
+ const map = new Map();
+ for (const entry of normalizeIgnoreValueEntries(existing)) {
+ map.set(`${entry.rule}\0${entry.value}`, entry);
+ }
+ for (const entry of normalizeIgnoreValueEntries(incoming)) {
+ map.set(`${entry.rule}\0${entry.value}`, entry);
+ }
+ return Array.from(map.values());
+}
+
+export function readCache(cwd) {
+ const raw = safeReadJson(getCachePath(cwd));
+ if (!raw || typeof raw !== 'object' || raw.version !== 1) {
+ return { version: 1, sessions: {} };
+ }
+ return {
+ version: 1,
+ sessions: raw.sessions && typeof raw.sessions === 'object' ? raw.sessions : {},
+ };
+}
+
+export function persistCache(cwd, cache) {
+ const sessions = cache.sessions || {};
+ const ids = Object.keys(sessions);
+ if (ids.length > CACHE_MAX_SESSIONS) {
+ // Garbage-collect oldest sessions by updatedAt.
+ const ordered = ids
+ .map((id) => [id, sessions[id]?.updatedAt || 0])
+ .sort((a, b) => b[1] - a[1])
+ .slice(0, CACHE_MAX_SESSIONS);
+ const next = {};
+ for (const [id] of ordered) next[id] = sessions[id];
+ cache = { ...cache, sessions: next };
+ }
+ const target = getCachePath(cwd);
+ try {
+ ensureHookGitExcludes(cwd);
+ fs.mkdirSync(path.dirname(target), { recursive: true });
+ fs.writeFileSync(target, JSON.stringify(cache));
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+export function ensureHookGitExcludes(cwd = process.cwd()) {
+ try {
+ const target = resolveHookGitExcludeTarget(cwd);
+ if (!target) {
+ return { mode: 'none', changed: false, patterns: [...HOOK_LOCAL_IGNORE_PATTERNS] };
+ }
+
+ const patterns = target.patternPrefix
+ ? HOOK_LOCAL_IGNORE_PATTERNS.map((pattern) => `${target.patternPrefix}/${pattern}`)
+ : [...HOOK_LOCAL_IGNORE_PATTERNS];
+ const markerSuffix = target.patternPrefix || '.';
+ const markerOpen = `${HOOK_IGNORE_MARKER_OPEN} ${markerSuffix}`;
+ const markerClose = `${HOOK_IGNORE_MARKER_CLOSE} ${markerSuffix}`;
+ const existing = fs.existsSync(target.path) ? fs.readFileSync(target.path, 'utf-8') : '';
+ const block = [markerOpen, ...patterns, markerClose].join('\n');
+ const markerRe = new RegExp(`${escapeRegExp(markerOpen)}[\\s\\S]*?${escapeRegExp(markerClose)}`);
+
+ let updated;
+ if (markerRe.test(existing)) {
+ updated = existing.replace(markerRe, block);
+ } else {
+ const prefix = existing.length === 0 ? '' : existing.endsWith('\n') ? existing : `${existing}\n`;
+ updated = `${prefix}${prefix.endsWith('\n\n') || prefix === '' ? '' : '\n'}${block}\n`;
+ }
+
+ if (updated !== existing) {
+ fs.mkdirSync(path.dirname(target.path), { recursive: true });
+ fs.writeFileSync(target.path, updated, 'utf-8');
+ }
+
+ return {
+ mode: 'git-info-exclude',
+ file: path.relative(path.resolve(cwd), target.path).split(path.sep).join('/'),
+ changed: updated !== existing,
+ patterns,
+ };
+ } catch {
+ return { mode: 'error', changed: false, patterns: [...HOOK_LOCAL_IGNORE_PATTERNS] };
+ }
+}
+
+function resolveHookGitExcludeTarget(cwd) {
+ const start = path.resolve(cwd);
+ let dir = start;
+ while (true) {
+ const dotGit = path.join(dir, '.git');
+ if (fs.existsSync(dotGit)) {
+ const gitDir = resolveGitDir(dotGit, dir);
+ if (!gitDir) return null;
+ const relPrefix = path.relative(dir, start).split(path.sep).join('/');
+ return {
+ path: path.join(gitDir, 'info', 'exclude'),
+ patternPrefix: relPrefix && relPrefix !== '.' ? relPrefix : '',
+ };
+ }
+ const parent = path.dirname(dir);
+ if (parent === dir) return null;
+ dir = parent;
+ }
+}
+
+function resolveGitDir(dotGit, worktreeDir) {
+ const stat = fs.statSync(dotGit);
+ if (stat.isDirectory()) return dotGit;
+ if (!stat.isFile()) return null;
+
+ const body = fs.readFileSync(dotGit, 'utf-8').trim();
+ const match = body.match(/^gitdir:\s*(.+)$/i);
+ if (!match) return null;
+ return path.isAbsolute(match[1]) ? match[1] : path.resolve(worktreeDir, match[1]);
+}
+
+function escapeRegExp(value) {
+ return String(value).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+}
+
+function ensureSession(cache, sessionId) {
+ if (!cache.sessions[sessionId]) {
+ cache.sessions[sessionId] = { updatedAt: Date.now(), files: {} };
+ }
+ return cache.sessions[sessionId];
+}
+
+function ensureFile(cache, sessionId, filePath) {
+ const session = ensureSession(cache, sessionId);
+ if (!session.files[filePath]) {
+ session.files[filePath] = { editCount: 0, findings: [] };
+ }
+ return session.files[filePath];
+}
+
+export function bumpEditCount(cache, sessionId, filePath) {
+ const fileEntry = ensureFile(cache, sessionId, filePath);
+ fileEntry.editCount = (fileEntry.editCount || 0) + 1;
+ ensureSession(cache, sessionId).updatedAt = Date.now();
+ return fileEntry.editCount;
+}
+
+export function suppressionNotice(filePath) {
+ return `${ENVELOPE_PREFIX} Suppressing further design hints on ${filePath}. More than ${EDIT_COUNT_THRESHOLD} edits in this session reached. Run /impeccable audit to revisit.`;
+}
+
+// Glob → RegExp. Supports `**`, `*`, `?`, and `{a,b}` alternation.
+function globToRegex(glob) {
+ let re = '^';
+ let i = 0;
+ while (i < glob.length) {
+ const c = glob[i];
+ if (c === '*') {
+ if (glob[i + 1] === '*') {
+ re += '.*';
+ i += 2;
+ if (glob[i] === '/') i += 1;
+ } else {
+ re += '[^/]*';
+ i += 1;
+ }
+ } else if (c === '?') {
+ re += '[^/]';
+ i += 1;
+ } else if (c === '{') {
+ const end = glob.indexOf('}', i);
+ if (end === -1) { re += '\\{'; i += 1; continue; }
+ const parts = glob.slice(i + 1, end).split(',').map((p) => p.replace(/[.+^$()|[\]\\]/g, '\\$&'));
+ re += `(?:${parts.join('|')})`;
+ i = end + 1;
+ } else if (/[.+^$()|[\]\\]/.test(c)) {
+ re += `\\${c}`;
+ i += 1;
+ } else {
+ re += c;
+ i += 1;
+ }
+ }
+ re += '$';
+ return new RegExp(re);
+}
+
+export function matchesAnyGlob(filePath, globs) {
+ if (!Array.isArray(globs) || globs.length === 0) return false;
+ const normalized = filePath.split(path.sep).join('/');
+ for (const glob of globs) {
+ try {
+ const re = globToRegex(String(glob));
+ if (re.test(normalized)) return true;
+ // Match against basename too for convenience: `*.generated.tsx` should
+ // catch `src/foo.generated.tsx` without requiring `**/`.
+ const base = normalized.split('/').pop();
+ if (re.test(base)) return true;
+ } catch {
+ /* malformed glob, skip */
+ }
+ }
+ return false;
+}
+
+export function filterFindings(findings, _content, _ext, config) {
+ if (!Array.isArray(findings) || findings.length === 0) return [];
+ const ignoreRules = new Set((config.ignoreRules || []).map((rule) => normalizeIgnoreRule(rule)));
+ const ignoreValues = normalizeIgnoreValueEntries(config.ignoreValues || []);
+ return findings.filter((f) => {
+ if (!f || typeof f !== 'object') return false;
+ if (ignoreRules.has(normalizeIgnoreRule(f.antipattern))) return false;
+ if (isIgnoredFindingValue(f, ignoreValues)) return false;
+ return true;
+ });
+}
+
+function isIgnoredFindingValue(finding, ignoreValues) {
+ if (!Array.isArray(ignoreValues) || ignoreValues.length === 0) return false;
+ const rule = normalizeIgnoreRule(finding.antipattern);
+ const value = extractFindingIgnoreValue(finding);
+ if (!rule || !value) return false;
+ return ignoreValues.some((entry) => entry.rule === rule && entry.value === value);
+}
+
+export function extractFindingIgnoreValue(finding) {
+ if (!finding || typeof finding !== 'object') return '';
+ const rule = normalizeIgnoreRule(finding.antipattern);
+ if (rule !== 'overused-font') return '';
+ return normalizeIgnoreValue(extractFindingIgnoreValueRaw(finding));
+}
+
+function extractFindingIgnoreValueRaw(finding) {
+ const direct = cleanIgnoreValueDisplay(finding.ignoreValue || finding.value || '');
+ if (direct) return direct;
+
+ const candidates = [finding.detail, finding.snippet].filter((v) => typeof v === 'string' && v);
+ for (const text of candidates) {
+ const primary = text.match(/Primary font:\s*([^()\n;]+)/i);
+ if (primary) return cleanIgnoreValueDisplay(primary[1]);
+
+ const family = text.match(/font-family\s*:\s*["']?([^'",;\n]+)/i);
+ if (family) return cleanIgnoreValueDisplay(family[1]);
+
+ const google = text.match(/[?&]family=([^&:;\n]+)/i);
+ if (google) {
+ try {
+ return cleanIgnoreValueDisplay(decodeURIComponent(google[1]));
+ } catch {
+ return cleanIgnoreValueDisplay(google[1]);
+ }
+ }
+ }
+
+ return '';
+}
+
+function cleanIgnoreValueDisplay(value) {
+ return String(value || '')
+ .trim()
+ .replace(/^["']|["']$/g, '')
+ .replace(/\+/g, ' ')
+ .replace(/\s+/g, ' ');
+}
+
+export function dedupeAgainstCache(findings, cache, sessionId, filePath) {
+ if (!Array.isArray(findings) || findings.length === 0) return [];
+ const fileEntry = ensureFile(cache, sessionId, filePath);
+ const known = new Set(fileEntry.findings || []);
+ const fresh = [];
+ for (const f of findings) {
+ const key = `${f.antipattern}:${f.line || 0}`;
+ if (known.has(key)) continue;
+ known.add(key);
+ fresh.push(f);
+ }
+ return fresh;
+}
+
+export function rememberFindings(cache, sessionId, filePath, findings) {
+ const fileEntry = ensureFile(cache, sessionId, filePath);
+ const known = new Set(fileEntry.findings || []);
+ for (const f of findings) known.add(`${f.antipattern}:${f.line || 0}`);
+ fileEntry.findings = Array.from(known);
+ ensureSession(cache, sessionId).updatedAt = Date.now();
+}
+
+export function renderTemplate(findings, filePath, config, opts = {}) {
+ if (!Array.isArray(findings) || findings.length === 0) return '';
+ const limits = config?.limits || DEFAULT_CONFIG.limits;
+ const cap = Math.max(1, limits.maxFindings || DEFAULT_CONFIG.limits.maxFindings);
+ const maxChars = Math.max(500, limits.maxChars || DEFAULT_CONFIG.limits.maxChars);
+
+ const cwd = opts.cwd || process.cwd();
+ const display = relativize(filePath, cwd);
+ const total = findings.length;
+ const shown = findings.slice(0, cap);
+ const remaining = total - shown.length;
+
+ const header = `${ENVELOPE_PREFIX} Required design corrections in ${display} (${total} issue(s)):`;
+ const lines = shown.map((f) => formatFindingLine(f));
+ const more = remaining > 0
+ ? `... and ${remaining} more (see /impeccable audit).`
+ : null;
+ const footer = directiveFooter(display);
+
+ const blocks = [header, ...lines];
+ if (more) blocks.push(more);
+ blocks.push('');
+ blocks.push(footer);
+ let text = blocks.join('\n');
+
+ if (text.length > maxChars) {
+ text = clampToBudget(header, lines, more, footer, maxChars);
+ }
+ return text;
+}
+
+function renderGroupedTemplate(groups, config, opts = {}) {
+ const realGroups = groups.filter((group) => Array.isArray(group.findings) && group.findings.length > 0);
+ if (realGroups.length === 0) return '';
+ if (realGroups.length === 1) {
+ const [group] = realGroups;
+ return renderTemplate(group.findings, group.filePath, config, opts);
+ }
+
+ const limits = config?.limits || DEFAULT_CONFIG.limits;
+ const cap = Math.max(1, limits.maxFindings || DEFAULT_CONFIG.limits.maxFindings);
+ const maxChars = Math.max(500, limits.maxChars || DEFAULT_CONFIG.limits.maxChars);
+ const cwd = opts.cwd || process.cwd();
+ const total = realGroups.reduce((sum, group) => sum + group.findings.length, 0);
+ const header = `${ENVELOPE_PREFIX} Required design corrections across ${realGroups.length} files (${total} issue(s)):`;
+ const lines = [];
+ let shownCount = 0;
+
+ for (const group of realGroups) {
+ const display = relativize(group.filePath, cwd);
+ lines.push(`${display} (${group.findings.length} issue(s)):`);
+ const remainingCap = Math.max(0, cap - shownCount);
+ const shown = group.findings.slice(0, remainingCap);
+ for (const finding of shown) {
+ lines.push(formatFindingLine(finding));
+ }
+ shownCount += shown.length;
+ const hidden = group.findings.length - shown.length;
+ if (hidden > 0) {
+ lines.push(`- ... ${hidden} more in ${display} (see /impeccable audit).`);
+ }
+ }
+
+ const footer = directiveFooter('the affected files', { grouped: true });
+ let text = [header, ...lines, '', footer].join('\n');
+ if (text.length > maxChars) {
+ text = clampGroupedToBudget(header, lines, footer, maxChars);
+ }
+ return text;
+}
+
+function clampGroupedToBudget(header, lines, footer, maxChars) {
+ const assemble = (linesArr, omitted) => [
+ header,
+ ...linesArr,
+ ...(omitted ? ['... and more (see /impeccable audit).'] : []),
+ '',
+ footer,
+ ].join('\n');
+
+ let working = lines.slice();
+ let omitted = false;
+ let assembled = assemble(working, omitted);
+ while (assembled.length > maxChars && working.length > 1) {
+ working.pop();
+ omitted = true;
+ assembled = assemble(working, omitted);
+ }
+ if (assembled.length > maxChars) {
+ assembled = `${assembled.slice(0, maxChars - 1)}…`;
+ }
+ return assembled;
+}
+
+function clampToBudget(header, lines, more, footer, maxChars) {
+ const assemble = (linesArr, moreText) => {
+ const blocks = [header, ...linesArr];
+ if (moreText) blocks.push(moreText);
+ blocks.push('');
+ blocks.push(footer);
+ return blocks.join('\n');
+ };
+
+ let working = lines.slice();
+ let moreText = more;
+ let assembled = assemble(working, moreText);
+ while (assembled.length > maxChars && working.length > 1) {
+ working.pop();
+ moreText = '... and more (see /impeccable audit).';
+ assembled = assemble(working, moreText);
+ }
+ if (assembled.length > maxChars) {
+ assembled = `${assembled.slice(0, maxChars - 1)}…`;
+ }
+ return assembled;
+}
+
+function formatFindingLine(f) {
+ const prefix = f.line && f.line > 0 ? `- L${f.line}` : '-';
+ const desc = (f.description || '').trim();
+ const name = (f.name || '').trim();
+ // Description from the registry already ends in punctuation; join with a
+ // single space. `name` may have a trailing period already, keep it clean.
+ const nameSegment = name ? `${name.replace(/\.+\s*$/, '')}.` : '';
+ const ignoreCommand = formatFindingIgnoreCommand(f);
+ const ignoreSegment = ignoreCommand
+ ? ` If the user explicitly confirms this value is intentional: \`${ignoreCommand}\`.`
+ : '';
+ return `${prefix} [${f.antipattern}] ${nameSegment} ${desc}${ignoreSegment}`.replace(/\s+/g, ' ').trim();
+}
+
+function formatFindingIgnoreCommand(finding) {
+ if (!finding || typeof finding !== 'object') return '';
+ const rule = normalizeIgnoreRule(finding.antipattern);
+ if (!rule) return '';
+ const normalizedValue = extractFindingIgnoreValue(finding);
+ if (!normalizedValue) return '';
+ const value = extractFindingIgnoreValueRaw(finding);
+ const valueArg = quoteCommandArg(value);
+ const reason = quoteCommandArg(`User confirmed ${value} is intentional`);
+ return `/impeccable hooks ignore-value ${rule} ${valueArg} --shared --reason ${reason}`;
+}
+
+function quoteCommandArg(value) {
+ const text = String(value || '').trim();
+ if (/^[A-Za-z0-9._:-]+$/.test(text)) return text;
+ return `"${text.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
+}
+
+function relativize(filePath, cwd) {
+ try {
+ const rel = path.relative(cwd, filePath);
+ if (!rel || rel.startsWith('..')) return filePath;
+ return rel.split(path.sep).join('/');
+ } catch {
+ return filePath;
+ }
+}
+
+// Codex `apply_patch` exposes the raw patch in `tool_input.command`, not
+// `tool_input.file_path`. Claude Code may send both; parse the patch body
+// so we can scan the file(s) the tool actually touched.
+// https://developers.openai.com/codex/hooks#posttooluse
+const APPLY_PATCH_FILE_RE = /^\*\*\* (?:Update|Add) File: (.+)$/gm;
+
+export function parseApplyPatchPaths(command, projectCwd) {
+ if (!command || typeof command !== 'string') return [];
+ const out = [];
+ for (const m of command.matchAll(APPLY_PATCH_FILE_RE)) {
+ let p = (m[1] || '').trim();
+ if (!p) continue;
+ if (!path.isAbsolute(p)) p = path.resolve(projectCwd, p);
+ out.push(p);
+ }
+ return out;
+}
+
+export function resolveTargetFiles(event, projectCwd) {
+ const ti = event?.tool_input;
+ const out = [];
+ const add = (filePath) => {
+ if (typeof filePath !== 'string' || !filePath) return;
+ if (!out.includes(filePath)) out.push(filePath);
+ };
+
+ if (event?.tool_name === 'apply_patch' && ti && typeof ti.command === 'string') {
+ for (const filePath of parseApplyPatchPaths(ti.command, projectCwd)) add(filePath);
+ }
+ if (ti && typeof ti.file_path === 'string' && ti.file_path) {
+ add(ti.file_path);
+ }
+ // Cursor Write / StrReplace use `path`, not `file_path`.
+ if (ti && typeof ti.path === 'string' && ti.path) {
+ add(ti.path);
+ }
+ if (typeof event?.file_path === 'string' && event.file_path) {
+ add(event.file_path);
+ }
+ return out;
+}
+
+export function resolveHarness(env = {}, event = null) {
+ const explicit = env?.IMPECCABLE_HOOK_HARNESS;
+ if (explicit === 'cursor') return 'cursor';
+ if (explicit === 'claude' || explicit === 'codex') return 'claude';
+ if (typeof event?.conversation_id === 'string' && event.conversation_id) return 'cursor';
+ return 'claude';
+}
+
+export function normalizeHookEvent(event, projectCwd, harness = 'claude') {
+ if (!event || typeof event !== 'object' || harness !== 'cursor') return event;
+
+ const cwd = event.cwd
+ || (Array.isArray(event.workspace_roots) && event.workspace_roots[0])
+ || envProjectDir(projectCwd)
+ || projectCwd;
+ const sessionId = event.session_id || event.conversation_id || 'unknown';
+
+ const ti = event.tool_input && typeof event.tool_input === 'object' ? event.tool_input : {};
+ const filePath = ti.file_path || ti.path || event.file_path;
+ if (filePath) {
+ return {
+ ...event,
+ cwd,
+ session_id: sessionId,
+ tool_input: { ...ti, file_path: filePath },
+ };
+ }
+
+ return { ...event, cwd, session_id: sessionId };
+}
+
+function envProjectDir(fallback) {
+ if (typeof process.env.CURSOR_PROJECT_DIR === 'string' && process.env.CURSOR_PROJECT_DIR) {
+ return process.env.CURSOR_PROJECT_DIR;
+ }
+ return fallback;
+}
+
+// UI components often keep slop in a sibling/co-located stylesheet while the
+// JSX edit is what triggered PostToolUse. Scan those styles too so an App.jsx
+// patch doesn't report "clean" while styles.css still has Inter/bounce/etc.
+const UI_CODE_EXTS = new Set(['.jsx', '.tsx', '.vue', '.svelte', '.astro']);
+const STYLE_EXTS = new Set(['.css', '.scss', '.sass', '.less']);
+const CO_SCAN_STYLE_NAMES = [
+ 'styles.css', 'styles.scss', 'styles.sass', 'styles.less',
+ 'index.css', 'index.scss', 'index.sass', 'index.less',
+ 'global.css', 'global.scss', 'global.sass', 'global.less',
+ 'globals.css', 'globals.scss', 'globals.sass', 'globals.less',
+];
+const MAX_SCAN_TARGETS = 6;
+
+const STATIC_STYLE_IMPORT_RE = /import\s+(?:[\w*{}\s,$]+\s+from\s+)?['"]([^'"]+\.(?:css|scss|sass|less))['"]/gi;
+
+function hasPathTraversal(filePath) {
+ return typeof filePath === 'string' && filePath.includes('..');
+}
+
+function isInsideProject(filePath, projectCwd) {
+ if (!filePath || !projectCwd || hasPathTraversal(filePath)) return false;
+ try {
+ const rel = path.relative(projectCwd, filePath);
+ return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));
+ } catch {
+ return false;
+ }
+}
+
+export function parseStaticStyleImports(content, fromFile, projectCwd) {
+ if (!content || typeof content !== 'string') return [];
+ const dir = path.dirname(fromFile);
+ const out = [];
+ for (const m of content.matchAll(STATIC_STYLE_IMPORT_RE)) {
+ let p = (m[1] || '').trim();
+ if (!p) continue;
+ if (p.startsWith('.')) p = path.resolve(dir, p);
+ else if (!path.isAbsolute(p)) p = path.resolve(projectCwd, p);
+ if (!isInsideProject(p, projectCwd)) continue;
+ out.push(p);
+ }
+ return out;
+}
+
+export function coLocatedStylesheets(filePath) {
+ const dir = path.dirname(filePath);
+ const base = path.basename(filePath, path.extname(filePath));
+ const candidates = new Set([
+ path.join(dir, `${base}.css`),
+ path.join(dir, `${base}.module.css`),
+ path.join(dir, `${base}.scss`),
+ path.join(dir, `${base}.module.scss`),
+ path.join(dir, `${base}.sass`),
+ path.join(dir, `${base}.module.sass`),
+ path.join(dir, `${base}.less`),
+ path.join(dir, `${base}.module.less`),
+ ]);
+ for (const name of CO_SCAN_STYLE_NAMES) {
+ candidates.add(path.join(dir, name));
+ }
+ return [...candidates].filter((p) => fs.existsSync(p));
+}
+
+export function normalizeScanTargets(primaryTargets, projectCwd) {
+ if (!Array.isArray(primaryTargets) || primaryTargets.length === 0) return [];
+ const ordered = [];
+ const seen = new Set();
+ const baseCwd = projectCwd || process.cwd();
+ const normalizeTarget = (p) => {
+ // Preserve literal `..` segments so downstream sensitive-path checks
+ // still fire. path.resolve would collapse `/foo/../etc/passwd`.
+ if (hasPathTraversal(p)) return p;
+ return path.isAbsolute(p) ? p : path.resolve(baseCwd, p);
+ };
+ const add = (p) => {
+ if (ordered.length >= MAX_SCAN_TARGETS) return;
+ const abs = normalizeTarget(p);
+ if (seen.has(abs)) return;
+ seen.add(abs);
+ ordered.push(abs);
+ return abs;
+ };
+
+ for (const p of primaryTargets) add(p);
+ return ordered;
+}
+
+export function expandScanTargets(primaryTargets, projectCwd) {
+ const ordered = normalizeScanTargets(primaryTargets, projectCwd);
+ if (ordered.length === 0) return [];
+ const seen = new Set(ordered);
+ const baseCwd = projectCwd || process.cwd();
+ const add = (p) => {
+ if (ordered.length >= MAX_SCAN_TARGETS) return;
+ const abs = hasPathTraversal(p) ? p : (path.isAbsolute(p) ? p : path.resolve(baseCwd, p));
+ if (seen.has(abs)) return;
+ seen.add(abs);
+ ordered.push(abs);
+ return abs;
+ };
+
+ const normalizedPrimaries = [];
+ for (const p of ordered) normalizedPrimaries.push(p);
+
+ for (const p of normalizedPrimaries) {
+ if (ordered.length >= MAX_SCAN_TARGETS) break;
+ if (!isInsideProject(p, baseCwd)) continue;
+ const ext = path.extname(p).toLowerCase();
+ if (STYLE_EXTS.has(ext) || !UI_CODE_EXTS.has(ext)) continue;
+
+ let content = '';
+ try { content = fs.readFileSync(p, 'utf-8'); } catch { /* unreadable primary */ }
+
+ for (const imp of parseStaticStyleImports(content, p, projectCwd)) {
+ add(imp);
+ if (ordered.length >= MAX_SCAN_TARGETS) break;
+ }
+ for (const col of coLocatedStylesheets(p)) {
+ add(col);
+ if (ordered.length >= MAX_SCAN_TARGETS) break;
+ }
+ }
+
+ return ordered;
+}
+
+export function writeAuditLog(env, entry) {
+ const target = env?.IMPECCABLE_HOOK_LOG;
+ if (!target || typeof target !== 'string') return false;
+ try {
+ const expanded = target.startsWith('~/')
+ ? path.join(process.env.HOME || process.env.USERPROFILE || '.', target.slice(2))
+ : target;
+ fs.mkdirSync(path.dirname(expanded), { recursive: true });
+ const line = JSON.stringify({ ts: new Date().toISOString(), ...entry }) + '\n';
+ fs.appendFileSync(expanded, line);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+const DETECTOR_CANDIDATES = [
+ path.join(__dirname, 'detector', 'detect-antipatterns.mjs'),
+ path.join(__dirname, '..', '..', 'cli', 'engine', 'detect-antipatterns.mjs'),
+ path.join(__dirname, '..', '..', '..', 'cli', 'engine', 'detect-antipatterns.mjs'),
+];
+
+let detectorCache = null;
+export async function loadDetector(candidates = DETECTOR_CANDIDATES) {
+ if (detectorCache) return detectorCache;
+ const found = candidates.find((c) => fs.existsSync(c));
+ if (!found) return null;
+ const mod = await import(pathToFileURL(found));
+ detectorCache = { detectText: mod.detectText, detectHtml: mod.detectHtml };
+ return detectorCache;
+}
+
+// For tests: allow injecting a detector implementation.
+export function setDetectorForTesting(impl) {
+ detectorCache = impl;
+}
+
+// ────────────────────────────────────────────────────────────────────────
+// Nudge/steer messages for the no-silent-fires policy.
+//
+// The hook is designed to be a conversational presence: every fire that
+// actually scans a file emits a developer-role message into the model's
+// next turn. Three states map to three templates:
+//
+// 1. **Fresh findings** → `renderTemplate` (existing, imperative).
+// 2. **Pending findings** → `renderPendingAck` (re-nudge for issues the
+// model was already told about in this
+// session but hasn't fixed yet).
+// 3. **Truly clean** → `renderCleanAck` (short positive nudge that
+// keeps the design discipline in context).
+//
+// All three are short (≤ ~40 tokens each) so the cumulative cost stays
+// bounded across a long active editing session. Users who explicitly want
+// silence-on-clean can set `IMPECCABLE_HOOK_QUIET=1` — runHook checks that
+// env before emitting #2 or #3.
+//
+// Why not stay silent on dedup-clean? Earlier versions did. The model
+// quickly forgets the prior reminder once tool output scrolls past it, so
+// re-nudging on the same file with a short "still pending" line keeps the
+// pressure on. The wording deliberately points back to "earlier this
+// session" so the model knows it's a re-mind, not a new finding.
+// ────────────────────────────────────────────────────────────────────────
+
+const STEER_LINE = 'Keep typography hierarchy, spacing rhythm, and color contrast intentional on the next change.';
+
+export function renderCleanAck(filePath, opts = {}) {
+ const cwd = opts.cwd || process.cwd();
+ const display = relativize(filePath, cwd);
+ return `${ENVELOPE_PREFIX} Design hook scanned ${display}. No anti-patterns. ${STEER_LINE}`;
+}
+
+export function renderPendingAck(filePath, knownFindings, opts = {}) {
+ const cwd = opts.cwd || process.cwd();
+ const display = relativize(filePath, cwd);
+ const count = knownFindings.length;
+ // `knownFindings` here are the cache strings like "side-tab:3".
+ const sample = knownFindings.slice(0, 3).join(', ');
+ const more = count > 3 ? `, +${count - 3} more` : '';
+ return `${ENVELOPE_PREFIX} Design hook scanned ${display}. Still has ${count} issue(s) flagged earlier this session (${sample}${more}). Address them before finalizing — the previous reminder still applies.`;
+}
+
+export function shouldEmitAckForFile(filePath) {
+ return ACK_EXTS.has(path.extname(String(filePath || '')).toLowerCase());
+}
+
+// The directive footer is the part of the hook output that steers model
+// behavior. Three intentional moves:
+// 1. **Imperative, not advisory.** "Fix these..." beats "Consider
+// revising..." which the model treats as a soft suggestion it can
+// override when the user asked for any kind of throwaway / demo UI.
+// 2. **Explicit exception clause.** Without it, the model will try to
+// "fix" intentional bad fixtures, anti-pattern examples in docs, or
+// test cases. Naming the exception inline beats hoping the model
+// infers it from context.
+// 3. **Acknowledgement instruction.** Hook output is injected as
+// developer-role context, not a chat turn, so the user never sees the
+// raw envelope. Asking the model to surface the fix in its reply is
+// the cheapest way to make the feedback loop visible to the user.
+function directiveFooter(display, opts = {}) {
+ const ignoreFileCommand = `/impeccable hooks ignore-file ${quoteCommandArg(display)}`;
+ const fileIgnoreGuidance = opts.grouped
+ ? 'run `/impeccable hooks ignore-file <path>` for the specific file'
+ : `run \`${ignoreFileCommand}\``;
+ return [
+ 'Fix these in your next reply before finalizing. Acknowledge what you changed so the user sees the correction.',
+ '',
+ 'Skip the fix only if the user explicitly asked for an intentionally bad UI, an anti-pattern example, a test fixture, or documentation of bad design. In that case, say so and continue.',
+ '',
+ `Do not add source comments such as \`impeccable: ignore\`; those pollute the code and do not suppress hook findings. Do not add hook ignores unless the user explicitly confirms the finding is intentional. Prefer the narrowest persisted exception: run the exact \`/impeccable hooks ignore-value ... --shared\` command shown next to a value-specific finding. For \`overused-font\`, use \`ignore-value\` for a specific font and use \`/impeccable hooks ignore-rule overused-font --all-values\` only when the user asks to ignore overused fonts generally. For file-specific findings without an ignore-value command, ${fileIgnoreGuidance}; use \`/impeccable hooks ignore-rule <id>\` only when the user asks to suppress the whole non-value-specific rule. Run /impeccable audit for the full pass.`,
+ ].join('\n');
+}
+
+/**
+ * Run the hook with explicit dependencies. Returns a result object:
+ * { exitCode, stdout, audit, reason? }
+ *
+ * Never throws. All errors are converted to `exitCode: 0` + audit entry.
+ */
+export async function runHook({ stdinJson, env = {}, cwd = process.cwd(), now = Date.now, detector } = {}) {
+ const audit = { ts: new Date(now()).toISOString(), event: 'PostToolUse' };
+ const result = (extra) => ({ exitCode: 0, stdout: '', audit: { ...audit, ...extra } });
+
+ try {
+ // Re-entrancy guard.
+ if (depthIsSet(env.IMPECCABLE_HOOK_DEPTH) || depthIsSet(env.CLAUDE_HOOK_DEPTH)) {
+ return result({ reentrant: true, durationMs: 0 });
+ }
+
+ if (truthy(env.IMPECCABLE_HOOK_DISABLED)) {
+ return result({ skipped: 'env-disabled', durationMs: 0 });
+ }
+
+ const started = Date.now();
+
+ let event;
+ try {
+ event = typeof stdinJson === 'string' ? JSON.parse(stdinJson) : stdinJson;
+ } catch {
+ return result({ skipped: 'stdin-malformed', durationMs: Date.now() - started });
+ }
+ if (!event || typeof event !== 'object') {
+ return result({ skipped: 'stdin-empty', durationMs: Date.now() - started });
+ }
+
+ const harness = resolveHarness(env, event);
+ event = normalizeHookEvent(event, cwd, harness);
+ audit.harness = harness;
+
+ const projectCwd = event.cwd || cwd;
+ const primaryFiles = normalizeScanTargets(resolveTargetFiles(event, projectCwd), projectCwd);
+ const primaryFileSet = new Set(primaryFiles);
+ const targetFiles = expandScanTargets(primaryFiles, projectCwd);
+ audit.session = event.session_id || null;
+ if (event.tool_name) audit.tool = event.tool_name;
+
+ if (targetFiles.length === 0) {
+ return result({ skipped: 'no-file-path', durationMs: Date.now() - started });
+ }
+
+ const config = readConfig(projectCwd);
+ if (config.enabled === false) {
+ return result({ skipped: 'config-disabled', durationMs: Date.now() - started });
+ }
+
+ const cache = readCache(projectCwd);
+ const sessionId = event.session_id || 'unknown';
+ const det = detector || await loadDetector();
+ if (!det || typeof det.detectText !== 'function') {
+ persistCache(projectCwd, cache);
+ return result({ skipped: 'detector-missing', durationMs: Date.now() - started });
+ }
+
+ let pendingWinner = null;
+ let cleanWinner = null;
+ const freshGroups = [];
+ let suppressionWinner = null;
+ let detectorThrewAny = false;
+ let lastSkip = 'no-scannable-file';
+ let suppressedHit = false;
+
+ for (const filePath of targetFiles) {
+ audit.file = filePath;
+
+ if (hasPathTraversal(filePath) || SENSITIVE_PATH.test(filePath)) {
+ lastSkip = 'sensitive';
+ continue;
+ }
+ if (GENERATED_PATH.test(filePath)) {
+ lastSkip = 'generated';
+ continue;
+ }
+
+ const ext = path.extname(filePath).toLowerCase();
+ audit.ext = ext;
+ if (!ALLOWED_EXTS.has(ext)) {
+ lastSkip = 'extension';
+ continue;
+ }
+
+ const relForMatch = relativize(filePath, projectCwd);
+ if (matchesAnyGlob(relForMatch, config.ignoreFiles) || matchesAnyGlob(filePath, config.ignoreFiles)) {
+ lastSkip = 'config-ignore-file';
+ continue;
+ }
+ if (!fs.existsSync(filePath)) {
+ lastSkip = 'file-missing';
+ continue;
+ }
+
+ if (primaryFileSet.has(filePath)) {
+ const editCount = bumpEditCount(cache, sessionId, filePath);
+ audit.editCount = editCount;
+
+ if (editCount > EDIT_COUNT_THRESHOLD) {
+ const wasJustCrossed = editCount === EDIT_COUNT_THRESHOLD + 1;
+ if (wasJustCrossed && !suppressionWinner) {
+ suppressionWinner = { filePath };
+ }
+ lastSkip = 'suppressed';
+ suppressedHit = true;
+ continue;
+ }
+ }
+
+ const content = fs.readFileSync(filePath, 'utf-8');
+ let findings;
+ let detectorThrew = false;
+ if ((ext === '.html' || ext === '.htm') && typeof det.detectHtml === 'function') {
+ try { findings = await det.detectHtml(filePath); } catch { findings = []; detectorThrew = true; }
+ } else {
+ try { findings = await det.detectText(content, filePath); } catch { findings = []; detectorThrew = true; }
+ }
+
+ const filtered = filterFindings(findings || [], content, ext, config);
+ const fresh = dedupeAgainstCache(filtered, cache, sessionId, filePath);
+ audit.findings = (findings || []).length;
+ audit.freshFindings = fresh.length;
+
+ if (fresh.length > 0) {
+ rememberFindings(cache, sessionId, filePath, fresh);
+ freshGroups.push({ filePath, findings: fresh });
+ continue;
+ }
+
+ if (detectorThrew) {
+ detectorThrewAny = true;
+ continue;
+ }
+
+ if (filtered.length > 0 && !pendingWinner) {
+ const known = (ensureFile(cache, sessionId, filePath).findings || []).slice();
+ pendingWinner = { filePath, known };
+ } else if (filtered.length === 0 && !cleanWinner) {
+ cleanWinner = { filePath };
+ }
+ }
+
+ persistCache(projectCwd, cache);
+
+ if (freshGroups.length > 0) {
+ const firstGroup = freshGroups[0];
+ const text = renderGroupedTemplate(freshGroups, config, { cwd: projectCwd });
+ const allFindings = freshGroups.flatMap((group) => group.findings);
+ return {
+ exitCode: 0,
+ stdout: payload(text, 'PostToolUse', harness),
+ emission: {
+ kind: 'fresh',
+ file: firstGroup.filePath,
+ findings: firstGroup.findings,
+ groups: freshGroups,
+ },
+ audit: {
+ ...audit,
+ file: firstGroup.filePath,
+ emitted: true,
+ freshFiles: freshGroups.length,
+ freshFindings: allFindings.length,
+ chars: text.length,
+ durationMs: Date.now() - started,
+ },
+ };
+ }
+
+ if (detectorThrewAny && !pendingWinner && !cleanWinner) {
+ return result({ emitted: false, error: 'detector-threw', durationMs: Date.now() - started });
+ }
+
+ if (truthy(env.IMPECCABLE_HOOK_QUIET)) {
+ return result({ emitted: false, quiet: true, durationMs: Date.now() - started });
+ }
+
+ if (pendingWinner && shouldEmitAckForFile(pendingWinner.filePath)) {
+ const text = renderPendingAck(pendingWinner.filePath, pendingWinner.known, { cwd: projectCwd });
+ return {
+ exitCode: 0,
+ stdout: payload(text, 'PostToolUse', harness),
+ emission: { kind: 'pending', file: pendingWinner.filePath, known: pendingWinner.known },
+ audit: {
+ ...audit,
+ file: pendingWinner.filePath,
+ emitted: true,
+ kind: 'pending',
+ pending: pendingWinner.known.length,
+ chars: text.length,
+ durationMs: Date.now() - started,
+ },
+ };
+ }
+
+ if (suppressionWinner) {
+ const text = suppressionNotice(relativize(suppressionWinner.filePath, projectCwd));
+ return {
+ exitCode: 0,
+ stdout: payload(text, 'PostToolUse', harness),
+ emission: { kind: 'suppression', file: suppressionWinner.filePath },
+ audit: {
+ ...audit,
+ file: suppressionWinner.filePath,
+ suppressed: true,
+ emitted: true,
+ durationMs: Date.now() - started,
+ },
+ };
+ }
+
+ if (cleanWinner && shouldEmitAckForFile(cleanWinner.filePath)) {
+ const text = renderCleanAck(cleanWinner.filePath, { cwd: projectCwd });
+ return {
+ exitCode: 0,
+ stdout: payload(text, 'PostToolUse', harness),
+ emission: { kind: 'clean', file: cleanWinner.filePath },
+ audit: {
+ ...audit,
+ file: cleanWinner.filePath,
+ emitted: true,
+ kind: 'clean',
+ chars: text.length,
+ durationMs: Date.now() - started,
+ },
+ };
+ }
+
+ if (pendingWinner || cleanWinner) {
+ return result({ emitted: false, skipped: 'non-ui-ack', durationMs: Date.now() - started });
+ }
+
+ if (suppressedHit) {
+ return result({ suppressed: true, emitted: false, durationMs: Date.now() - started });
+ }
+
+ return result({ skipped: lastSkip, durationMs: Date.now() - started });
+ } catch (err) {
+ return {
+ exitCode: 0,
+ stdout: '',
+ audit: { ...audit, error: String(err && err.message ? err.message : err) },
+ };
+ }
+}
+
+export function payload(text, eventName = 'PostToolUse', harness = 'claude') {
+ if (harness === 'cursor') {
+ return JSON.stringify({ additional_context: text });
+ }
+ return JSON.stringify({
+ hookSpecificOutput: { hookEventName: eventName, additionalContext: text },
+ });
+}
diff --git a/.agents/skills/impeccable/scripts/hook.mjs b/.agents/skills/impeccable/scripts/hook.mjs
new file mode 100644
index 000000000..b862f8033
--- /dev/null
+++ b/.agents/skills/impeccable/scripts/hook.mjs
@@ -0,0 +1,61 @@
+#!/usr/bin/env node
+/**
+ * Impeccable design hook — PostToolUse entry point.
+ *
+ * Reads the Claude Code / Codex / Cursor hook event from stdin, runs the design
+ * detector against the touched file, and emits a system reminder via
+ * `hookSpecificOutput.additionalContext` when findings exist.
+ *
+ * Contract: never break a turn. Always exit 0. Clean files emit a small ack
+ * unless quiet mode is enabled.
+ *
+ * Most logic lives in `hook-lib.mjs` so it is unit-testable without a
+ * subprocess. This file is the thin stdin/stdout adapter.
+ */
+
+import { runHook, 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');
+}
+
+async function main() {
+ // Snapshot the inherited env FIRST so the re-entrancy guard checks the
+ // parent's value, not the value we are about to export for any child
+ // processes the hook might ever spawn.
+ const inheritedEnv = { ...process.env };
+ process.env.IMPECCABLE_HOOK_DEPTH = process.env.IMPECCABLE_HOOK_DEPTH || '1';
+
+ let stdinJson = '';
+ try { stdinJson = await readStdin(); } catch { /* fall through */ }
+
+ const result = await runHook({
+ stdinJson,
+ env: inheritedEnv,
+ cwd: process.cwd(),
+ });
+
+ writeAuditLog(process.env, result.audit);
+
+ if (result.stdout) process.stdout.write(result.stdout);
+ process.exit(result.exitCode || 0);
+}
+
+main().catch((err) => {
+ // Last-ditch: never break the agent's turn even if something we did not
+ // anticipate goes wrong. Audit-log the failure if logging is enabled.
+ try {
+ writeAuditLog(process.env, {
+ ts: new Date().toISOString(),
+ event: 'PostToolUse',
+ error: String(err && err.message ? err.message : err),
+ });
+ } catch { /* swallow */ }
+ if (process.env.IMPECCABLE_HOOK_DEBUG) {
+ process.stderr.write(`[impeccable-hook] ${err}\n`);
+ }
+ process.exit(0);
+});
diff --git a/.agents/skills/impeccable/scripts/live-inject.mjs b/.agents/skills/impeccable/scripts/live-inject.mjs
index 4e5c5dc0a..69ce530c1 100644
--- a/.agents/skills/impeccable/scripts/live-inject.mjs
+++ b/.agents/skills/impeccable/scripts/live-inject.mjs
@@ -32,6 +32,8 @@ const IGNORE_MARKER_CLOSE = '# impeccable-live-ignore-end';
export const LIVE_IGNORE_PATTERNS = Object.freeze([
'.impeccable/hook.cache.json',
+ '.impeccable/hook.pending.json',
+ '.impeccable/hook.local.json',
'.impeccable/live/server.json',
'.impeccable/live/sessions/',
'.impeccable/live/previews/',
diff --git a/.claude/settings.json b/.claude/settings.json
new file mode 100644
index 000000000..aabed69a3
--- /dev/null
+++ b/.claude/settings.json
@@ -0,0 +1,18 @@
+{
+ "description": "Impeccable design detector: runs after Edit/Write/MultiEdit on UI files and surfaces findings as system reminders.",
+ "hooks": {
+ "PostToolUse": [
+ {
+ "matcher": "Edit|Write|MultiEdit",
+ "hooks": [
+ {
+ "type": "command",
+ "command": "node \"${CLAUDE_PROJECT_DIR}/.claude/skills/impeccable/scripts/hook.mjs\"",
+ "timeout": 5,
+ "statusMessage": "Scanning design"
+ }
+ ]
+ }
+ ]
+ }
+}
diff --git a/.claude/skills/impeccable/SKILL.md b/.claude/skills/impeccable/SKILL.md
index 341179949..73a27c46e 100644
--- a/.claude/skills/impeccable/SKILL.md
+++ b/.claude/skills/impeccable/SKILL.md
@@ -126,7 +126,7 @@ If someone could look at this interface and say "AI made that" without doubt, it
| `optimize [target]` | Fix | Diagnose and fix UI performance | [reference/optimize.md](reference/optimize.md) |
| `live` | Iterate | Visual variant mode: pick elements in the browser, generate alternatives | [reference/live.md](reference/live.md) |
-Plus two management commands: `pin <command>` and `unpin <command>`, detailed below.
+Plus three management commands: `pin <command>`, `unpin <command>`, and `hooks <on|off|status|...>`, detailed below.
### Routing rules
@@ -143,7 +143,7 @@ Plus two management commands: `pin <command>` and `unpin <command>`, detailed be
**If `scan.targets` is non-empty, run `node .claude/skills/impeccable/scripts/detect.mjs --json <scan.targets joined by spaces>` once** (the bundled detector over local files: no network, no npx). `scan.via` tells you what they are: `git-changes` (the markup/style files in your dirty tree, the most relevant set), `source-dir` (e.g. `src`, `app`), `html`, or `root`. Fold the hits into your picks: many quality / contrast hits → `audit` or `polish`; a specific slop family → the matching command (gradient text or eyebrows → `quieter` / `typeset`, flat or gray palette → `colorize`, and so on). It's a real, current signal that beats guessing. If detect errors or the tree is large and slow, skip it and recommend the user run `audit` themselves; never block the suggestion on it.
Keep it to 2-3 pointed picks with the exact command to type. The menu stays the fallback; the recommendation is the lede.
-2. **First word matches a command**: load its reference file and follow its instructions. Everything after the command name is the target.
+2. **First word matches a command** (table above OR `pin` / `unpin` / `hooks`): load its reference file and follow its instructions. Everything after the command name is the target.
3. **First word doesn't match, but the intent clearly maps to one command** (e.g. "fix the spacing" → `layout`, "rewrite this error message" → `clarify`, "the colors feel flat" → `colorize`): load that command's reference and proceed as if invoked. If two commands could fit, ask once which.
4. **No clear command match**: general design invocation. Apply the setup steps, the General rules, and the loaded register reference, using the full argument as context.
@@ -161,4 +161,8 @@ If the first word is `craft`, setup still runs first, but [reference/craft.md](r
node .claude/skills/impeccable/scripts/pin.mjs <pin|unpin> <command>
```
-Valid `<command>` is any command from the table above. Report the script's result concisely. Confirm the new shortcut on success, relay stderr verbatim on error.
\ No newline at end of file
+Valid `<command>` is any command from the table above. Report the script's result concisely. Confirm the new shortcut on success, relay stderr verbatim on error.
+
+## Hooks
+
+`/impeccable hooks <on|off|status|ignore-rule|ignore-file|ignore-value|reset>` manages the design detector hook for this project. The hook auto-runs the detector after direct UI file edits and surfaces findings as system reminders. Full flow is in [reference/hooks.md](reference/hooks.md); load it when the user invokes `/impeccable hooks` with any argument.
\ No newline at end of file
diff --git a/.claude/skills/impeccable/reference/hooks.md b/.claude/skills/impeccable/reference/hooks.md
new file mode 100644
index 000000000..caadaa603
--- /dev/null
+++ b/.claude/skills/impeccable/reference/hooks.md
@@ -0,0 +1,82 @@
+# /impeccable hooks
+
+Manage the **design detector hook** for the current project.
+
+The hook runs the impeccable design detector on direct file edits to design-relevant files (`.tsx`, `.jsx`, `.html`, `.vue`, `.svelte`, `.astro`, `.css`, `.scss`, `.sass`, `.less`, `.ts`, `.js`). Claude Code and Codex use `PostToolUse` and push a short system reminder into the agent's context after the edit; findings get a correction prompt, pending issues get a re-nudge, and clean UI-ish files get a short ack unless `IMPECCABLE_HOOK_QUIET=1` is set. Plain `.ts` and `.js` files are still scanned, but stay quiet unless the detector finds something. Cursor uses `preToolUse` to block bad proposed writes before they land and stays silent when it allows a clean write.
+
+This command toggles the hook **per project** by editing `.impeccable/hook.json`. Local-only ignore policy lives in `.impeccable/hook.local.json`, which is gitignored. To disable globally, set `IMPECCABLE_HOOK_DISABLED=1` in your shell environment.
+
+Supported harnesses: Claude Code (`.claude/settings.json` in the project), Codex (`.codex/hooks.json` in the project), and Cursor (`.cursor/hooks.json` in the project).
+
+On **Cursor**, `preToolUse` checks proposed Write/Edit/Shell write content and denies only when the real detector finds an issue. The denial message is visible to the agent as the tool error, so the agent can reconsider before the bad write lands.
+
+## Routing
+
+The first argument is the action. Defaults to `status`.
+
+| Action | What it does |
+|---|---|
+| `status` | Print current state, shared/local config paths, ignored rules / files / values, env override. |
+| `on` | Set `enabled: true` in `.impeccable/hook.json`. |
+| `off` | Set `enabled: false` in `.impeccable/hook.json`. |
+| `ignore-rule <id>` | Append `<id>` to `ignoreRules`; for `overused-font`, requires `--all-values`. |
+| `ignore-file <glob>` | Append `<glob>` to `ignoreFiles`. |
+| `ignore-value <id> <value> [--shared] [--reason "..."]` | Append a rule/value suppression to shared `.impeccable/hook.json`. |
+| `ignore-value <id> <value> --local [--reason "..."]` | Append a private rule/value suppression to `.impeccable/hook.local.json`. |
+| `reset` | Delete the project config, dedup cache, and Cursor pending queue. |
+
+## Flow
+
+1. Resolve the action from the user's argument. If no action was given, default to `status`.
+2. Invoke the admin script and pass the user's output through verbatim:
+
+ ```bash
+ node .claude/skills/impeccable/scripts/hook-admin.mjs <action> [args...]
+ ```
+
+3. If `<action>` is `off`, follow up with a one-line note: "Done. New edits will not trigger the design hook in this project until you run `/impeccable hooks on`."
+4. If `<action>` is `on`, follow up with: "Done. The design hook will fire after the next Edit/Write/MultiEdit on a UI file."
+5. If `<action>` is `ignore-value`, `ignore-file`, or `ignore-rule`, just print the script output. The default scope is shared `.impeccable/hook.json`; add `--local` only when the user explicitly asks for a private exception.
+6. If `<action>` is `status`, just print the script output. Do not add commentary unless the user asked a follow-up question.
+
+## Intentional findings
+
+The hook itself never writes ignore config. Persist an exception only after the user explicitly confirms the flagged issue is intentional, and always go through `hook-admin.mjs`.
+
+Prefer the narrowest exception:
+
+- If the finding line shows an exact `ignore-value` command, run that command. This writes shared `.impeccable/hook.json` by default.
+- For `overused-font`, use `ignore-value` when the user confirms a specific font. Do not use `ignore-rule overused-font` for a specific font.
+- If the finding has no value-specific command, such as `side-tab`, prefer `ignore-file <path>` for the current file.
+- Use `ignore-rule <id>` only when the user asks to suppress that whole rule across the project. For broad overused-font suppression, use `ignore-rule overused-font --all-values` only when the user asks to ignore overused fonts generally.
+- Do not add source comments such as `impeccable: ignore`; inline comments pollute code and are not a supported suppression mechanism.
+
+Example value-specific exception:
+
+```bash
+node .claude/skills/impeccable/scripts/hook-admin.mjs ignore-value overused-font Inter --shared --reason "User confirmed Inter is intentional"
+```
+
+Example whole-rule font exception:
+
+```bash
+node .claude/skills/impeccable/scripts/hook-admin.mjs ignore-rule overused-font --all-values --reason "User asked to ignore overused fonts generally"
+```
+
+Example file-scoped exception:
+
+```bash
+node .claude/skills/impeccable/scripts/hook-admin.mjs ignore-file "src/legacy/Card.tsx"
+```
+
+## Constraints
+
+- Never modify `.impeccable/hook.json` or `.impeccable/hook.local.json` by hand from this command. Always go through `hook-admin.mjs` so writes stay validated and the file shape stays consistent.
+- Do not edit the hook scripts themselves (`hook.mjs`, `hook-lib.mjs`, `hook-before-edit.mjs`) from this flow. Those are skill plumbing.
+- Cursor can block a proposed write when the detector finds a real issue. Claude Code and Codex do not block the edit; they emit a post-edit reminder instead. Disabling stops both blocking and reminders.
+- The hook is bundled with the Impeccable skill and installed through project-local manifests: `.claude/settings.json`, `.codex/hooks.json`, and `.cursor/hooks.json`. On Codex, the user must approve the hook via `/hooks` the first time. On Cursor, confirm hooks are enabled under Settings -> Hooks.
+
+## Failure modes
+
+- If `.impeccable/hook.json` or `.impeccable/hook.local.json` is unreadable or malformed, the hook ignores that file and uses the remaining valid config/defaults. `hook-admin.mjs status` will show malformed files as ignored.
+- If the user asks to "disable the hook" globally, suggest both options: `IMPECCABLE_HOOK_DISABLED=1` env var (one-shot, follows the shell), and `/impeccable hooks off` (persistent for this project, committable).
diff --git a/.claude/skills/impeccable/scripts/detector/engines/regex/detect-text.mjs b/.claude/skills/impeccable/scripts/detector/engines/regex/detect-text.mjs
index fd0d9c73f..4c0777c93 100644
--- a/.claude/skills/impeccable/scripts/detector/engines/regex/detect-text.mjs
+++ b/.claude/skills/impeccable/scripts/detector/engines/regex/detect-text.mjs
@@ -446,7 +446,7 @@ function detectText(content, filePath, options = {}) {
// Run regex matchers on the full file content (catches Tailwind classes, inline styles)
// Enable block context for CSS files where related properties span multiple lines
- const cssLike = new Set(['.css', '.scss', '.less']);
+ const cssLike = new Set(['.css', '.scss', '.sass', '.less']);
findings.push(...runRegexMatchers(lines, filePath, 0, cssLike.has(ext) || null, {
profile,
phase: 'source',
diff --git a/.claude/skills/impeccable/scripts/detector/node/file-system.mjs b/.claude/skills/impeccable/scripts/detector/node/file-system.mjs
index a80250a0e..aaa8c6df7 100644
--- a/.claude/skills/impeccable/scripts/detector/node/file-system.mjs
+++ b/.claude/skills/impeccable/scripts/detector/node/file-system.mjs
@@ -11,7 +11,7 @@ const SKIP_DIRS = new Set([
]);
const SCANNABLE_EXTENSIONS = new Set([
- '.html', '.htm', '.css', '.scss', '.less',
+ '.html', '.htm', '.css', '.scss', '.sass', '.less',
'.jsx', '.tsx', '.js', '.ts',
'.vue', '.svelte', '.astro',
]);
diff --git a/.claude/skills/impeccable/scripts/hook-admin.mjs b/.claude/skills/impeccable/scripts/hook-admin.mjs
new file mode 100644
index 000000000..86fcfa909
--- /dev/null
+++ b/.claude/skills/impeccable/scripts/hook-admin.mjs
@@ -0,0 +1,300 @@
+#!/usr/bin/env node
+/**
+ * `/impeccable hooks <on|off|status|reset>` — manage the design hook
+ * via .impeccable/hook.json and .impeccable/hook.local.json in the current
+ * project.
+ *
+ * Usage:
+ * node hook-admin.mjs status # print current state
+ * node hook-admin.mjs on # set enabled: true
+ * node hook-admin.mjs off # set enabled: false
+ * node hook-admin.mjs ignore-rule <rule-id> # append to ignoreRules
+ * node hook-admin.mjs ignore-rule overused-font --all-values
+ * node hook-admin.mjs ignore-file <glob> # append to ignoreFiles
+ * node hook-admin.mjs ignore-value <rule> <value> # append to shared ignoreValues
+ * node hook-admin.mjs ignore-value <rule> <value> --local
+ * node hook-admin.mjs reset # remove all config + cache
+ *
+ * Designed to be invoked by the LLM from the reference/hooks.md flow.
+ * Output is human-readable; the harness will pass it back to the user.
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+
+import {
+ getConfigPath,
+ getLocalConfigPath,
+ getCachePath,
+ getPendingPath,
+ readConfig,
+ DEFAULT_CONFIG,
+ ensureHookGitExcludes,
+ normalizeIgnoreValue,
+ normalizeIgnoreValueEntries,
+} from './hook-lib.mjs';
+
+const ACTIONS = new Set(['status', 'on', 'off', 'ignore-rule', 'ignore-file', 'ignore-value', 'reset']);
+
+function readRawConfigFile(filePath) {
+ if (!fs.existsSync(filePath)) return { exists: false, malformed: false, raw: null };
+ try {
+ return { exists: true, malformed: false, raw: JSON.parse(fs.readFileSync(filePath, 'utf-8')) };
+ } catch {
+ return { exists: true, malformed: true, raw: null };
+ }
+}
+
+function readRawConfig(cwd, opts = {}) {
+ const filePath = opts.local ? getLocalConfigPath(cwd) : getConfigPath(cwd);
+ return readRawConfigFile(filePath).raw;
+}
+
+function writeConfig(cwd, config, opts = {}) {
+ const filePath = opts.local ? getLocalConfigPath(cwd) : getConfigPath(cwd);
+ if (opts.local) ensureHookGitExcludes(cwd);
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
+ fs.writeFileSync(filePath, JSON.stringify(config, null, 2) + '\n');
+ return filePath;
+}
+
+function mergeConfig(existing) {
+ // Persist the full shape so /impeccable hooks edits leave a complete file
+ // for the user to see, not an unhelpful `{"enabled":false}`.
+ const base = existing && typeof existing === 'object' ? existing : {};
+ return {
+ enabled: base.enabled === false ? false : true,
+ ignoreRules: Array.isArray(base.ignoreRules) ? Array.from(new Set(base.ignoreRules.map(String))) : [],
+ ignoreFiles: Array.isArray(base.ignoreFiles) ? Array.from(new Set(base.ignoreFiles.map(String))) : [],
+ ignoreValues: normalizeIgnoreValueEntries(base.ignoreValues || []),
+ limits: {
+ maxFindings: Number.isFinite(base?.limits?.maxFindings) ? base.limits.maxFindings : DEFAULT_CONFIG.limits.maxFindings,
+ maxChars: Number.isFinite(base?.limits?.maxChars) ? base.limits.maxChars : DEFAULT_CONFIG.limits.maxChars,
+ },
+ };
+}
+
+function mergeLocalConfig(existing) {
+ const base = existing && typeof existing === 'object' ? existing : {};
+ const out = {};
+ if (Object.prototype.hasOwnProperty.call(base, 'enabled')) {
+ out.enabled = base.enabled === false ? false : true;
+ }
+ if (Array.isArray(base.ignoreRules)) {
+ out.ignoreRules = Array.from(new Set(base.ignoreRules.map(String)));
+ }
+ if (Array.isArray(base.ignoreFiles)) {
+ out.ignoreFiles = Array.from(new Set(base.ignoreFiles.map(String)));
+ }
+ out.ignoreValues = normalizeIgnoreValueEntries(base.ignoreValues || []);
+ if (base.limits && typeof base.limits === 'object') {
+ const limits = {};
+ if (Number.isFinite(base.limits.maxFindings)) limits.maxFindings = base.limits.maxFindings;
+ if (Number.isFinite(base.limits.maxChars)) limits.maxChars = base.limits.maxChars;
+ if (Object.keys(limits).length) out.limits = limits;
+ }
+ return out;
+}
+
+function statusReport(cwd) {
+ const shared = readRawConfigFile(getConfigPath(cwd));
+ const local = readRawConfigFile(getLocalConfigPath(cwd));
+ const cfg = readConfig(cwd);
+ const envKill = process.env.IMPECCABLE_HOOK_DISABLED;
+ const envState = envKill ? `IMPECCABLE_HOOK_DISABLED=${envKill}` : 'unset';
+ const cfgPath = path.relative(cwd, getConfigPath(cwd)) || '.impeccable/hook.json';
+ const localPath = path.relative(cwd, getLocalConfigPath(cwd)) || '.impeccable/hook.local.json';
+ const cachePath = path.relative(cwd, getCachePath(cwd)) || '.impeccable/hook.cache.json';
+ const fileState = (info, relPath, absent) => {
+ if (info.malformed) return `${relPath} (malformed; ignored)`;
+ if (info.exists) return relPath;
+ return `${relPath} (${absent})`;
+ };
+ const ignoreValues = cfg.ignoreValues.map((entry) => `${entry.rule}=${entry.value}`);
+
+ const lines = [
+ `Impeccable design hook`,
+ ` state: ${cfg.enabled ? 'enabled' : 'disabled'}`,
+ ` shared file: ${fileState(shared, cfgPath, 'using defaults; file not present')}`,
+ ` local file: ${fileState(local, localPath, 'not present')}`,
+ ` ignoreRules: ${cfg.ignoreRules.length ? cfg.ignoreRules.join(', ') : '(none)'}`,
+ ` ignoreFiles: ${cfg.ignoreFiles.length ? cfg.ignoreFiles.join(', ') : '(none)'}`,
+ ` ignoreValues: ${ignoreValues.length ? ignoreValues.join(', ') : '(none)'}`,
+ ` maxFindings: ${cfg.limits.maxFindings}`,
+ ` maxChars: ${cfg.limits.maxChars}`,
+ ` env override: ${envState}`,
+ ` cache file: ${fs.existsSync(getCachePath(cwd)) ? cachePath : `${cachePath} (not present)`}`,
+ ];
+ return lines.join('\n');
+}
+
+function setEnabled(cwd, value) {
+ const config = mergeConfig(readRawConfig(cwd));
+ config.enabled = value;
+ const target = writeConfig(cwd, config);
+ return `Design hook ${value ? 'enabled' : 'disabled'} for this project (wrote ${path.relative(cwd, target) || target}).`;
+}
+
+function normalizeRuleId(rule) {
+ return String(rule || '').trim().toLowerCase();
+}
+
+function parseIgnoreRuleArgs(args) {
+ const positionals = [];
+ let allValues = false;
+
+ for (let i = 0; i < args.length; i++) {
+ const arg = String(args[i] || '');
+ if (arg === '--all-values') {
+ allValues = true;
+ } else if (arg === '--reason') {
+ while (i + 1 < args.length && !String(args[i + 1]).startsWith('--')) i++;
+ } else if (arg.startsWith('--reason=')) {
+ // Accepted for command symmetry; ignoreRules stores rule ids only.
+ } else if (arg.startsWith('--')) {
+ throw new Error(`Unknown ignore-rule flag: ${arg}`);
+ } else {
+ positionals.push(arg);
+ }
+ }
+
+ return {
+ rule: normalizeRuleId(positionals[0]),
+ allValues,
+ };
+}
+
+function addIgnoreRule(cwd, args) {
+ const parsed = parseIgnoreRuleArgs(args);
+ const rule = parsed.rule;
+ if (!rule) throw new Error('Pass a rule id, e.g. /impeccable hooks ignore-rule side-tab');
+ if (rule === 'overused-font' && !parsed.allValues) {
+ throw new Error('overused-font is value-specific by default. Use /impeccable hooks ignore-value overused-font <font> for a confirmed font, or /impeccable hooks ignore-rule overused-font --all-values only when the user asked to ignore overused fonts generally.');
+ }
+ const config = mergeConfig(readRawConfig(cwd));
+ if (!config.ignoreRules.includes(rule)) config.ignoreRules.push(rule);
+ writeConfig(cwd, config);
+ return `Added "${rule}" to ignoreRules. Current: ${config.ignoreRules.join(', ')}`;
+}
+
+function addIgnoreFile(cwd, glob) {
+ if (!glob) throw new Error('Pass a glob, e.g. /impeccable hooks ignore-file "src/legacy/**"');
+ const config = mergeConfig(readRawConfig(cwd));
+ if (!config.ignoreFiles.includes(glob)) config.ignoreFiles.push(glob);
+ writeConfig(cwd, config);
+ return `Added "${glob}" to ignoreFiles. Current: ${config.ignoreFiles.join(', ')}`;
+}
+
+function parseIgnoreValueArgs(args) {
+ const positionals = [];
+ let shared = false;
+ let local = false;
+ let reason = '';
+
+ for (let i = 0; i < args.length; i++) {
+ const arg = args[i];
+ if (arg === '--shared') {
+ shared = true;
+ } else if (arg === '--local') {
+ local = true;
+ } else if (arg === '--reason') {
+ const chunks = [];
+ while (i + 1 < args.length && !String(args[i + 1]).startsWith('--')) {
+ chunks.push(args[++i]);
+ }
+ reason = chunks.join(' ').trim();
+ } else if (String(arg).startsWith('--reason=')) {
+ reason = String(arg).slice('--reason='.length).trim();
+ } else {
+ positionals.push(arg);
+ }
+ }
+
+ const [rule, ...valueParts] = positionals;
+ return {
+ rule: String(rule || '').trim().toLowerCase(),
+ value: normalizeIgnoreValue(valueParts.join(' ')),
+ shared,
+ local,
+ reason,
+ };
+}
+
+function addIgnoreValue(cwd, args) {
+ const parsed = parseIgnoreValueArgs(args);
+ if (!parsed.rule || !parsed.value) {
+ throw new Error('Pass a rule id and value, e.g. /impeccable hooks ignore-value overused-font Inter');
+ }
+
+ if (parsed.shared && parsed.local) {
+ throw new Error('Pass only one scope flag: --shared or --local');
+ }
+
+ const local = parsed.local;
+ const config = local
+ ? mergeLocalConfig(readRawConfig(cwd, { local: true }))
+ : mergeConfig(readRawConfig(cwd, { local: false }));
+ const key = `${parsed.rule}\0${parsed.value}`;
+ const existing = config.ignoreValues.find((entry) => `${entry.rule}\0${entry.value}` === key);
+
+ if (existing) {
+ if (parsed.reason) existing.reason = parsed.reason;
+ } else {
+ const entry = {
+ rule: parsed.rule,
+ value: parsed.value,
+ createdAt: new Date().toISOString(),
+ };
+ if (parsed.reason) entry.reason = parsed.reason;
+ config.ignoreValues.push(entry);
+ }
+
+ const target = writeConfig(cwd, config, { local });
+ const scope = local ? 'local ignoreValues' : 'shared ignoreValues';
+ return `Added ${parsed.rule}=${parsed.value} to ${scope} (${path.relative(cwd, target) || target}).`;
+}
+
+function reset(cwd) {
+ const removed = [];
+ for (const filePath of [getConfigPath(cwd), getLocalConfigPath(cwd), getCachePath(cwd), getPendingPath(cwd)]) {
+ try {
+ if (fs.existsSync(filePath)) {
+ fs.unlinkSync(filePath);
+ removed.push(path.relative(cwd, filePath) || filePath);
+ }
+ } catch { /* ignore */ }
+ }
+ return removed.length
+ ? `Reset design hook config and cache (removed: ${removed.join(', ')}).`
+ : 'No hook config or cache to remove. Already at defaults.';
+}
+
+function main() {
+ const [, , actionArg, ...rest] = process.argv;
+ const action = (actionArg || 'status').toLowerCase();
+ const cwd = process.cwd();
+
+ if (!ACTIONS.has(action)) {
+ process.stderr.write(`Unknown action: ${action}\nValid: ${Array.from(ACTIONS).join(', ')}\n`);
+ process.exit(1);
+ }
+
+ try {
+ let out = '';
+ switch (action) {
+ case 'status': out = statusReport(cwd); break;
+ case 'on': out = setEnabled(cwd, true); break;
+ case 'off': out = setEnabled(cwd, false); break;
+ case 'ignore-rule': out = addIgnoreRule(cwd, rest); break;
+ case 'ignore-file': out = addIgnoreFile(cwd, rest[0]); break;
+ case 'ignore-value': out = addIgnoreValue(cwd, rest); break;
+ case 'reset': out = reset(cwd); break;
+ }
+ process.stdout.write(out + '\n');
+ } catch (err) {
+ process.stderr.write(`Error: ${err.message || err}\n`);
+ process.exit(1);
+ }
+}
+
+main();
diff --git a/.claude/skills/impeccable/scripts/hook-before-edit.mjs b/.claude/skills/impeccable/scripts/hook-before-edit.mjs
new file mode 100644
index 000000000..54b2709d2
--- /dev/null
+++ b/.claude/skills/impeccable/scripts/hook-before-edit.mjs
@@ -0,0 +1,408 @@
+#!/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 shellContent = shellHereDocContent(shellCommand(input));
+ if (shellContent) return shellContent;
+ const copiedContent = shellCopiedFileContent(shellCommand(input), 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 || '';
+}
+
+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 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' });
+});
diff --git a/.claude/skills/impeccable/scripts/hook-lib.mjs b/.claude/skills/impeccable/scripts/hook-lib.mjs
new file mode 100644
index 000000000..02199f530
--- /dev/null
+++ b/.claude/skills/impeccable/scripts/hook-lib.mjs
@@ -0,0 +1,1232 @@
+/**
+ * Shared library for the Impeccable design hook.
+ *
+ * Pure-ish helpers split out from `hook.mjs` so unit tests can exercise
+ * config parsing, finding filtering, dedup, render, and cache logic without
+ * spawning a subprocess. `hook.mjs` itself is the thin stdin/stdout shim.
+ *
+ * Public surface (everything exported is part of the contract):
+ * ENVELOPE_PREFIX, ALLOWED_EXTS, ACK_EXTS, SENSITIVE_PATH, GENERATED_PATH, TRUTHY
+ * truthy(value)
+ * readConfig(cwd) / DEFAULT_CONFIG / getConfigPath(cwd) / getLocalConfigPath(cwd)
+ * normalizeIgnoreValue(value)
+ * readCache(cwd) / persistCache(cwd, cache)
+ * bumpEditCount(cache, sessionId, filePath) -> number
+ * suppressionNotice(filePath)
+ * filterFindings(findings, content, ext, config)
+ * dedupeAgainstCache(findings, cache, sessionId, filePath)
+ * renderTemplate(findings, filePath, config, opts)
+ * renderCleanAck(filePath, opts) / renderPendingAck(filePath, known, opts)
+ * shouldEmitAckForFile(filePath)
+ * writeAuditLog(env, entry)
+ * loadDetector() -> Promise<{ detectText, detectHtml }>
+ * matchesAnyGlob(filePath, globs)
+ * normalizeScanTargets(primaryTargets, projectCwd)
+ * runHook(deps) -> { exitCode, stdout, audit, reason? }
+ *
+ * Design notes:
+ * - All errors are swallowed at the runHook seam. The detector throwing must
+ * never break a turn. See PRD §5 "Failure modes".
+ * - Cache shape is JSON-friendly; we gc the oldest sessions when there are
+ * more than 8 to keep file size predictable across long-lived projects.
+ * - The detector loader looks for `detector/detect-antipatterns.mjs` next to
+ * this file first (built skill layout) and falls back to the repo root's
+ * `cli/engine/detect-antipatterns.mjs` (running from source).
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+import { pathToFileURL, fileURLToPath } from 'node:url';
+
+const __filename = fileURLToPath(import.meta.url);
+const __dirname = path.dirname(__filename);
+
+export const ENVELOPE_PREFIX = '[impeccable@1]';
+
+export const ALLOWED_EXTS = new Set([
+ '.tsx', '.jsx', '.html', '.htm', '.vue', '.svelte', '.astro',
+ '.css', '.scss', '.sass', '.less', '.ts', '.js',
+]);
+
+export const ACK_EXTS = new Set([
+ '.tsx', '.jsx', '.html', '.htm', '.vue', '.svelte', '.astro',
+ '.css', '.scss', '.sass', '.less',
+]);
+
+// Hard-skip regex for sensitive files. Cannot be turned off via config.
+// Match tokenized secret/credential filenames, not UI names such as
+// CredentialForm.tsx, SecretPage.jsx, or secretary-dashboard.vue.
+export const SENSITIVE_PATH = new RegExp([
+ String.raw`(?:^|[/\\])\.env(?:\.|$)`,
+ String.raw`(?:^|[/\\])\.git(?:[/\\]|$)`,
+ String.raw`(?:^|[/\\])id_rsa(?:$|[._-])[^/\\]*$`,
+ String.raw`(?:^|[/\\])[^/\\]*\.pem$`,
+ String.raw`(?:^|[/\\])(?:[^/\\]*[._-])?(?:secret|secrets|credential|credentials)(?=[._-])[^/\\]*\.(?:json|ya?ml|toml|ini|conf|config|env|txt|key|cert|crt|pem|js|ts)$`,
+].join('|'), 'i');
+
+// Hard-skip regex for generated, lock, minified, and build-output paths.
+export const GENERATED_PATH = /(?:\.generated\.[a-z]+$|\.d\.ts$|\.min\.[a-z]+$|[/\\]node_modules[/\\]|[/\\](?:dist|build|out|\.next|\.cache|coverage)[/\\]|[/\\]?[^/\\]+\.lock(?:\.json)?$)/i;
+
+export const TRUTHY = /^(1|true|yes|on)$/i;
+
+export const DEFAULT_CONFIG = Object.freeze({
+ enabled: true,
+ ignoreRules: [],
+ ignoreFiles: [],
+ ignoreValues: [],
+ limits: { maxFindings: 5, maxChars: 8000 },
+});
+
+export const HOOK_LOCAL_IGNORE_PATTERNS = Object.freeze([
+ '.impeccable/hook.cache.json',
+ '.impeccable/hook.pending.json',
+ '.impeccable/hook.local.json',
+]);
+
+const HOOK_IGNORE_MARKER_OPEN = '# impeccable-hook-ignore-start';
+const HOOK_IGNORE_MARKER_CLOSE = '# impeccable-hook-ignore-end';
+const CACHE_MAX_SESSIONS = 8;
+export const EDIT_COUNT_THRESHOLD = 6;
+
+export function truthy(value) {
+ return typeof value === 'string' && TRUTHY.test(value);
+}
+
+function depthIsSet(value) {
+ if (value === undefined || value === null) return false;
+ const text = String(value).trim();
+ if (!text) return false;
+ if (TRUTHY.test(text)) return true;
+ return /^\d+$/.test(text) && Number(text) > 0;
+}
+
+function safeReadJson(filePath) {
+ try {
+ return JSON.parse(fs.readFileSync(filePath, 'utf-8'));
+ } catch {
+ return null;
+ }
+}
+
+export function getConfigPath(cwd) {
+ return path.join(cwd, '.impeccable', 'hook.json');
+}
+
+export function getLocalConfigPath(cwd) {
+ return path.join(cwd, '.impeccable', 'hook.local.json');
+}
+
+export function getCachePath(cwd) {
+ return path.join(cwd, '.impeccable', 'hook.cache.json');
+}
+
+export function getPendingPath(cwd) {
+ return path.join(cwd, '.impeccable', 'hook.pending.json');
+}
+
+export function resolveProjectCwd(event, fallback = process.cwd()) {
+ return event?.cwd
+ || (Array.isArray(event?.workspace_roots) && event.workspace_roots[0])
+ || envProjectDir(fallback)
+ || fallback;
+}
+
+export function readConfig(cwd) {
+ const config = cloneDefaultConfig();
+ applyConfigSource(config, safeReadJson(getConfigPath(cwd)));
+ applyConfigSource(config, safeReadJson(getLocalConfigPath(cwd)));
+ return config;
+}
+
+function numberOr(value, fallback) {
+ return Number.isFinite(value) && value > 0 ? value : fallback;
+}
+
+function cloneDefaultConfig() {
+ return {
+ ...DEFAULT_CONFIG,
+ ignoreRules: [],
+ ignoreFiles: [],
+ ignoreValues: [],
+ limits: { ...DEFAULT_CONFIG.limits },
+ };
+}
+
+function applyConfigSource(config, raw) {
+ if (!raw || typeof raw !== 'object') return config;
+ if (Object.prototype.hasOwnProperty.call(raw, 'enabled')) {
+ config.enabled = raw.enabled === false ? false : true;
+ }
+ if (Array.isArray(raw.ignoreRules)) {
+ config.ignoreRules = uniqueStrings([...config.ignoreRules, ...raw.ignoreRules]);
+ }
+ if (Array.isArray(raw.ignoreFiles)) {
+ config.ignoreFiles = uniqueStrings([...config.ignoreFiles, ...raw.ignoreFiles]);
+ }
+ if (Array.isArray(raw.ignoreValues)) {
+ config.ignoreValues = mergeIgnoreValues(config.ignoreValues, raw.ignoreValues);
+ }
+ if (raw.limits && typeof raw.limits === 'object') {
+ config.limits = {
+ maxFindings: numberOr(raw.limits.maxFindings, config.limits.maxFindings),
+ maxChars: numberOr(raw.limits.maxChars, config.limits.maxChars),
+ };
+ }
+ return config;
+}
+
+function uniqueStrings(values) {
+ return Array.from(new Set(values.map(String)));
+}
+
+export function normalizeIgnoreValue(value) {
+ return String(value || '')
+ .trim()
+ .replace(/^["']|["']$/g, '')
+ .replace(/\+/g, ' ')
+ .replace(/\s+/g, ' ')
+ .toLowerCase();
+}
+
+function normalizeIgnoreRule(rule) {
+ return String(rule || '').trim().toLowerCase();
+}
+
+export function normalizeIgnoreValueEntries(entries) {
+ if (!Array.isArray(entries)) return [];
+ const out = [];
+ for (const entry of entries) {
+ if (!entry || typeof entry !== 'object') continue;
+ const rule = normalizeIgnoreRule(entry.rule);
+ const value = normalizeIgnoreValue(entry.value);
+ if (!rule || !value) continue;
+ const normalized = { rule, value };
+ if (typeof entry.reason === 'string' && entry.reason.trim()) {
+ normalized.reason = entry.reason.trim();
+ }
+ if (typeof entry.createdAt === 'string' && entry.createdAt.trim()) {
+ normalized.createdAt = entry.createdAt.trim();
+ }
+ out.push(normalized);
+ }
+ return out;
+}
+
+function mergeIgnoreValues(existing, incoming) {
+ const map = new Map();
+ for (const entry of normalizeIgnoreValueEntries(existing)) {
+ map.set(`${entry.rule}\0${entry.value}`, entry);
+ }
+ for (const entry of normalizeIgnoreValueEntries(incoming)) {
+ map.set(`${entry.rule}\0${entry.value}`, entry);
+ }
+ return Array.from(map.values());
+}
+
+export function readCache(cwd) {
+ const raw = safeReadJson(getCachePath(cwd));
+ if (!raw || typeof raw !== 'object' || raw.version !== 1) {
+ return { version: 1, sessions: {} };
+ }
+ return {
+ version: 1,
+ sessions: raw.sessions && typeof raw.sessions === 'object' ? raw.sessions : {},
+ };
+}
+
+export function persistCache(cwd, cache) {
+ const sessions = cache.sessions || {};
+ const ids = Object.keys(sessions);
+ if (ids.length > CACHE_MAX_SESSIONS) {
+ // Garbage-collect oldest sessions by updatedAt.
+ const ordered = ids
+ .map((id) => [id, sessions[id]?.updatedAt || 0])
+ .sort((a, b) => b[1] - a[1])
+ .slice(0, CACHE_MAX_SESSIONS);
+ const next = {};
+ for (const [id] of ordered) next[id] = sessions[id];
+ cache = { ...cache, sessions: next };
+ }
+ const target = getCachePath(cwd);
+ try {
+ ensureHookGitExcludes(cwd);
+ fs.mkdirSync(path.dirname(target), { recursive: true });
+ fs.writeFileSync(target, JSON.stringify(cache));
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+export function ensureHookGitExcludes(cwd = process.cwd()) {
+ try {
+ const target = resolveHookGitExcludeTarget(cwd);
+ if (!target) {
+ return { mode: 'none', changed: false, patterns: [...HOOK_LOCAL_IGNORE_PATTERNS] };
+ }
+
+ const patterns = target.patternPrefix
+ ? HOOK_LOCAL_IGNORE_PATTERNS.map((pattern) => `${target.patternPrefix}/${pattern}`)
+ : [...HOOK_LOCAL_IGNORE_PATTERNS];
+ const markerSuffix = target.patternPrefix || '.';
+ const markerOpen = `${HOOK_IGNORE_MARKER_OPEN} ${markerSuffix}`;
+ const markerClose = `${HOOK_IGNORE_MARKER_CLOSE} ${markerSuffix}`;
+ const existing = fs.existsSync(target.path) ? fs.readFileSync(target.path, 'utf-8') : '';
+ const block = [markerOpen, ...patterns, markerClose].join('\n');
+ const markerRe = new RegExp(`${escapeRegExp(markerOpen)}[\\s\\S]*?${escapeRegExp(markerClose)}`);
+
+ let updated;
+ if (markerRe.test(existing)) {
+ updated = existing.replace(markerRe, block);
+ } else {
+ const prefix = existing.length === 0 ? '' : existing.endsWith('\n') ? existing : `${existing}\n`;
+ updated = `${prefix}${prefix.endsWith('\n\n') || prefix === '' ? '' : '\n'}${block}\n`;
+ }
+
+ if (updated !== existing) {
+ fs.mkdirSync(path.dirname(target.path), { recursive: true });
+ fs.writeFileSync(target.path, updated, 'utf-8');
+ }
+
+ return {
+ mode: 'git-info-exclude',
+ file: path.relative(path.resolve(cwd), target.path).split(path.sep).join('/'),
+ changed: updated !== existing,
+ patterns,
+ };
+ } catch {
+ return { mode: 'error', changed: false, patterns: [...HOOK_LOCAL_IGNORE_PATTERNS] };
+ }
+}
+
+function resolveHookGitExcludeTarget(cwd) {
+ const start = path.resolve(cwd);
+ let dir = start;
+ while (true) {
+ const dotGit = path.join(dir, '.git');
+ if (fs.existsSync(dotGit)) {
+ const gitDir = resolveGitDir(dotGit, dir);
+ if (!gitDir) return null;
+ const relPrefix = path.relative(dir, start).split(path.sep).join('/');
+ return {
+ path: path.join(gitDir, 'info', 'exclude'),
+ patternPrefix: relPrefix && relPrefix !== '.' ? relPrefix : '',
+ };
+ }
+ const parent = path.dirname(dir);
+ if (parent === dir) return null;
+ dir = parent;
+ }
+}
+
+function resolveGitDir(dotGit, worktreeDir) {
+ const stat = fs.statSync(dotGit);
+ if (stat.isDirectory()) return dotGit;
+ if (!stat.isFile()) return null;
+
+ const body = fs.readFileSync(dotGit, 'utf-8').trim();
+ const match = body.match(/^gitdir:\s*(.+)$/i);
+ if (!match) return null;
+ return path.isAbsolute(match[1]) ? match[1] : path.resolve(worktreeDir, match[1]);
+}
+
+function escapeRegExp(value) {
+ return String(value).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+}
+
+function ensureSession(cache, sessionId) {
+ if (!cache.sessions[sessionId]) {
+ cache.sessions[sessionId] = { updatedAt: Date.now(), files: {} };
+ }
+ return cache.sessions[sessionId];
+}
+
+function ensureFile(cache, sessionId, filePath) {
+ const session = ensureSession(cache, sessionId);
+ if (!session.files[filePath]) {
+ session.files[filePath] = { editCount: 0, findings: [] };
+ }
+ return session.files[filePath];
+}
+
+export function bumpEditCount(cache, sessionId, filePath) {
+ const fileEntry = ensureFile(cache, sessionId, filePath);
+ fileEntry.editCount = (fileEntry.editCount || 0) + 1;
+ ensureSession(cache, sessionId).updatedAt = Date.now();
+ return fileEntry.editCount;
+}
+
+export function suppressionNotice(filePath) {
+ return `${ENVELOPE_PREFIX} Suppressing further design hints on ${filePath}. More than ${EDIT_COUNT_THRESHOLD} edits in this session reached. Run /impeccable audit to revisit.`;
+}
+
+// Glob → RegExp. Supports `**`, `*`, `?`, and `{a,b}` alternation.
+function globToRegex(glob) {
+ let re = '^';
+ let i = 0;
+ while (i < glob.length) {
+ const c = glob[i];
+ if (c === '*') {
+ if (glob[i + 1] === '*') {
+ re += '.*';
+ i += 2;
+ if (glob[i] === '/') i += 1;
+ } else {
+ re += '[^/]*';
+ i += 1;
+ }
+ } else if (c === '?') {
+ re += '[^/]';
+ i += 1;
+ } else if (c === '{') {
+ const end = glob.indexOf('}', i);
+ if (end === -1) { re += '\\{'; i += 1; continue; }
+ const parts = glob.slice(i + 1, end).split(',').map((p) => p.replace(/[.+^$()|[\]\\]/g, '\\$&'));
+ re += `(?:${parts.join('|')})`;
+ i = end + 1;
+ } else if (/[.+^$()|[\]\\]/.test(c)) {
+ re += `\\${c}`;
+ i += 1;
+ } else {
+ re += c;
+ i += 1;
+ }
+ }
+ re += '$';
+ return new RegExp(re);
+}
+
+export function matchesAnyGlob(filePath, globs) {
+ if (!Array.isArray(globs) || globs.length === 0) return false;
+ const normalized = filePath.split(path.sep).join('/');
+ for (const glob of globs) {
+ try {
+ const re = globToRegex(String(glob));
+ if (re.test(normalized)) return true;
+ // Match against basename too for convenience: `*.generated.tsx` should
+ // catch `src/foo.generated.tsx` without requiring `**/`.
+ const base = normalized.split('/').pop();
+ if (re.test(base)) return true;
+ } catch {
+ /* malformed glob, skip */
+ }
+ }
+ return false;
+}
+
+export function filterFindings(findings, _content, _ext, config) {
+ if (!Array.isArray(findings) || findings.length === 0) return [];
+ const ignoreRules = new Set((config.ignoreRules || []).map((rule) => normalizeIgnoreRule(rule)));
+ const ignoreValues = normalizeIgnoreValueEntries(config.ignoreValues || []);
+ return findings.filter((f) => {
+ if (!f || typeof f !== 'object') return false;
+ if (ignoreRules.has(normalizeIgnoreRule(f.antipattern))) return false;
+ if (isIgnoredFindingValue(f, ignoreValues)) return false;
+ return true;
+ });
+}
+
+function isIgnoredFindingValue(finding, ignoreValues) {
+ if (!Array.isArray(ignoreValues) || ignoreValues.length === 0) return false;
+ const rule = normalizeIgnoreRule(finding.antipattern);
+ const value = extractFindingIgnoreValue(finding);
+ if (!rule || !value) return false;
+ return ignoreValues.some((entry) => entry.rule === rule && entry.value === value);
+}
+
+export function extractFindingIgnoreValue(finding) {
+ if (!finding || typeof finding !== 'object') return '';
+ const rule = normalizeIgnoreRule(finding.antipattern);
+ if (rule !== 'overused-font') return '';
+ return normalizeIgnoreValue(extractFindingIgnoreValueRaw(finding));
+}
+
+function extractFindingIgnoreValueRaw(finding) {
+ const direct = cleanIgnoreValueDisplay(finding.ignoreValue || finding.value || '');
+ if (direct) return direct;
+
+ const candidates = [finding.detail, finding.snippet].filter((v) => typeof v === 'string' && v);
+ for (const text of candidates) {
+ const primary = text.match(/Primary font:\s*([^()\n;]+)/i);
+ if (primary) return cleanIgnoreValueDisplay(primary[1]);
+
+ const family = text.match(/font-family\s*:\s*["']?([^'",;\n]+)/i);
+ if (family) return cleanIgnoreValueDisplay(family[1]);
+
+ const google = text.match(/[?&]family=([^&:;\n]+)/i);
+ if (google) {
+ try {
+ return cleanIgnoreValueDisplay(decodeURIComponent(google[1]));
+ } catch {
+ return cleanIgnoreValueDisplay(google[1]);
+ }
+ }
+ }
+
+ return '';
+}
+
+function cleanIgnoreValueDisplay(value) {
+ return String(value || '')
+ .trim()
+ .replace(/^["']|["']$/g, '')
+ .replace(/\+/g, ' ')
+ .replace(/\s+/g, ' ');
+}
+
+export function dedupeAgainstCache(findings, cache, sessionId, filePath) {
+ if (!Array.isArray(findings) || findings.length === 0) return [];
+ const fileEntry = ensureFile(cache, sessionId, filePath);
+ const known = new Set(fileEntry.findings || []);
+ const fresh = [];
+ for (const f of findings) {
+ const key = `${f.antipattern}:${f.line || 0}`;
+ if (known.has(key)) continue;
+ known.add(key);
+ fresh.push(f);
+ }
+ return fresh;
+}
+
+export function rememberFindings(cache, sessionId, filePath, findings) {
+ const fileEntry = ensureFile(cache, sessionId, filePath);
+ const known = new Set(fileEntry.findings || []);
+ for (const f of findings) known.add(`${f.antipattern}:${f.line || 0}`);
+ fileEntry.findings = Array.from(known);
+ ensureSession(cache, sessionId).updatedAt = Date.now();
+}
+
+export function renderTemplate(findings, filePath, config, opts = {}) {
+ if (!Array.isArray(findings) || findings.length === 0) return '';
+ const limits = config?.limits || DEFAULT_CONFIG.limits;
+ const cap = Math.max(1, limits.maxFindings || DEFAULT_CONFIG.limits.maxFindings);
+ const maxChars = Math.max(500, limits.maxChars || DEFAULT_CONFIG.limits.maxChars);
+
+ const cwd = opts.cwd || process.cwd();
+ const display = relativize(filePath, cwd);
+ const total = findings.length;
+ const shown = findings.slice(0, cap);
+ const remaining = total - shown.length;
+
+ const header = `${ENVELOPE_PREFIX} Required design corrections in ${display} (${total} issue(s)):`;
+ const lines = shown.map((f) => formatFindingLine(f));
+ const more = remaining > 0
+ ? `... and ${remaining} more (see /impeccable audit).`
+ : null;
+ const footer = directiveFooter(display);
+
+ const blocks = [header, ...lines];
+ if (more) blocks.push(more);
+ blocks.push('');
+ blocks.push(footer);
+ let text = blocks.join('\n');
+
+ if (text.length > maxChars) {
+ text = clampToBudget(header, lines, more, footer, maxChars);
+ }
+ return text;
+}
+
+function renderGroupedTemplate(groups, config, opts = {}) {
+ const realGroups = groups.filter((group) => Array.isArray(group.findings) && group.findings.length > 0);
+ if (realGroups.length === 0) return '';
+ if (realGroups.length === 1) {
+ const [group] = realGroups;
+ return renderTemplate(group.findings, group.filePath, config, opts);
+ }
+
+ const limits = config?.limits || DEFAULT_CONFIG.limits;
+ const cap = Math.max(1, limits.maxFindings || DEFAULT_CONFIG.limits.maxFindings);
+ const maxChars = Math.max(500, limits.maxChars || DEFAULT_CONFIG.limits.maxChars);
+ const cwd = opts.cwd || process.cwd();
+ const total = realGroups.reduce((sum, group) => sum + group.findings.length, 0);
+ const header = `${ENVELOPE_PREFIX} Required design corrections across ${realGroups.length} files (${total} issue(s)):`;
+ const lines = [];
+ let shownCount = 0;
+
+ for (const group of realGroups) {
+ const display = relativize(group.filePath, cwd);
+ lines.push(`${display} (${group.findings.length} issue(s)):`);
+ const remainingCap = Math.max(0, cap - shownCount);
+ const shown = group.findings.slice(0, remainingCap);
+ for (const finding of shown) {
+ lines.push(formatFindingLine(finding));
+ }
+ shownCount += shown.length;
+ const hidden = group.findings.length - shown.length;
+ if (hidden > 0) {
+ lines.push(`- ... ${hidden} more in ${display} (see /impeccable audit).`);
+ }
+ }
+
+ const footer = directiveFooter('the affected files', { grouped: true });
+ let text = [header, ...lines, '', footer].join('\n');
+ if (text.length > maxChars) {
+ text = clampGroupedToBudget(header, lines, footer, maxChars);
+ }
+ return text;
+}
+
+function clampGroupedToBudget(header, lines, footer, maxChars) {
+ const assemble = (linesArr, omitted) => [
+ header,
+ ...linesArr,
+ ...(omitted ? ['... and more (see /impeccable audit).'] : []),
+ '',
+ footer,
+ ].join('\n');
+
+ let working = lines.slice();
+ let omitted = false;
+ let assembled = assemble(working, omitted);
+ while (assembled.length > maxChars && working.length > 1) {
+ working.pop();
+ omitted = true;
+ assembled = assemble(working, omitted);
+ }
+ if (assembled.length > maxChars) {
+ assembled = `${assembled.slice(0, maxChars - 1)}…`;
+ }
+ return assembled;
+}
+
+function clampToBudget(header, lines, more, footer, maxChars) {
+ const assemble = (linesArr, moreText) => {
+ const blocks = [header, ...linesArr];
+ if (moreText) blocks.push(moreText);
+ blocks.push('');
+ blocks.push(footer);
+ return blocks.join('\n');
+ };
+
+ let working = lines.slice();
+ let moreText = more;
+ let assembled = assemble(working, moreText);
+ while (assembled.length > maxChars && working.length > 1) {
+ working.pop();
+ moreText = '... and more (see /impeccable audit).';
+ assembled = assemble(working, moreText);
+ }
+ if (assembled.length > maxChars) {
+ assembled = `${assembled.slice(0, maxChars - 1)}…`;
+ }
+ return assembled;
+}
+
+function formatFindingLine(f) {
+ const prefix = f.line && f.line > 0 ? `- L${f.line}` : '-';
+ const desc = (f.description || '').trim();
+ const name = (f.name || '').trim();
+ // Description from the registry already ends in punctuation; join with a
+ // single space. `name` may have a trailing period already, keep it clean.
+ const nameSegment = name ? `${name.replace(/\.+\s*$/, '')}.` : '';
+ const ignoreCommand = formatFindingIgnoreCommand(f);
+ const ignoreSegment = ignoreCommand
+ ? ` If the user explicitly confirms this value is intentional: \`${ignoreCommand}\`.`
+ : '';
+ return `${prefix} [${f.antipattern}] ${nameSegment} ${desc}${ignoreSegment}`.replace(/\s+/g, ' ').trim();
+}
+
+function formatFindingIgnoreCommand(finding) {
+ if (!finding || typeof finding !== 'object') return '';
+ const rule = normalizeIgnoreRule(finding.antipattern);
+ if (!rule) return '';
+ const normalizedValue = extractFindingIgnoreValue(finding);
+ if (!normalizedValue) return '';
+ const value = extractFindingIgnoreValueRaw(finding);
+ const valueArg = quoteCommandArg(value);
+ const reason = quoteCommandArg(`User confirmed ${value} is intentional`);
+ return `/impeccable hooks ignore-value ${rule} ${valueArg} --shared --reason ${reason}`;
+}
+
+function quoteCommandArg(value) {
+ const text = String(value || '').trim();
+ if (/^[A-Za-z0-9._:-]+$/.test(text)) return text;
+ return `"${text.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
+}
+
+function relativize(filePath, cwd) {
+ try {
+ const rel = path.relative(cwd, filePath);
+ if (!rel || rel.startsWith('..')) return filePath;
+ return rel.split(path.sep).join('/');
+ } catch {
+ return filePath;
+ }
+}
+
+// Codex `apply_patch` exposes the raw patch in `tool_input.command`, not
+// `tool_input.file_path`. Claude Code may send both; parse the patch body
+// so we can scan the file(s) the tool actually touched.
+// https://developers.openai.com/codex/hooks#posttooluse
+const APPLY_PATCH_FILE_RE = /^\*\*\* (?:Update|Add) File: (.+)$/gm;
+
+export function parseApplyPatchPaths(command, projectCwd) {
+ if (!command || typeof command !== 'string') return [];
+ const out = [];
+ for (const m of command.matchAll(APPLY_PATCH_FILE_RE)) {
+ let p = (m[1] || '').trim();
+ if (!p) continue;
+ if (!path.isAbsolute(p)) p = path.resolve(projectCwd, p);
+ out.push(p);
+ }
+ return out;
+}
+
+export function resolveTargetFiles(event, projectCwd) {
+ const ti = event?.tool_input;
+ const out = [];
+ const add = (filePath) => {
+ if (typeof filePath !== 'string' || !filePath) return;
+ if (!out.includes(filePath)) out.push(filePath);
+ };
+
+ if (event?.tool_name === 'apply_patch' && ti && typeof ti.command === 'string') {
+ for (const filePath of parseApplyPatchPaths(ti.command, projectCwd)) add(filePath);
+ }
+ if (ti && typeof ti.file_path === 'string' && ti.file_path) {
+ add(ti.file_path);
+ }
+ // Cursor Write / StrReplace use `path`, not `file_path`.
+ if (ti && typeof ti.path === 'string' && ti.path) {
+ add(ti.path);
+ }
+ if (typeof event?.file_path === 'string' && event.file_path) {
+ add(event.file_path);
+ }
+ return out;
+}
+
+export function resolveHarness(env = {}, event = null) {
+ const explicit = env?.IMPECCABLE_HOOK_HARNESS;
+ if (explicit === 'cursor') return 'cursor';
+ if (explicit === 'claude' || explicit === 'codex') return 'claude';
+ if (typeof event?.conversation_id === 'string' && event.conversation_id) return 'cursor';
+ return 'claude';
+}
+
+export function normalizeHookEvent(event, projectCwd, harness = 'claude') {
+ if (!event || typeof event !== 'object' || harness !== 'cursor') return event;
+
+ const cwd = event.cwd
+ || (Array.isArray(event.workspace_roots) && event.workspace_roots[0])
+ || envProjectDir(projectCwd)
+ || projectCwd;
+ const sessionId = event.session_id || event.conversation_id || 'unknown';
+
+ const ti = event.tool_input && typeof event.tool_input === 'object' ? event.tool_input : {};
+ const filePath = ti.file_path || ti.path || event.file_path;
+ if (filePath) {
+ return {
+ ...event,
+ cwd,
+ session_id: sessionId,
+ tool_input: { ...ti, file_path: filePath },
+ };
+ }
+
+ return { ...event, cwd, session_id: sessionId };
+}
+
+function envProjectDir(fallback) {
+ if (typeof process.env.CURSOR_PROJECT_DIR === 'string' && process.env.CURSOR_PROJECT_DIR) {
+ return process.env.CURSOR_PROJECT_DIR;
+ }
+ return fallback;
+}
+
+// UI components often keep slop in a sibling/co-located stylesheet while the
+// JSX edit is what triggered PostToolUse. Scan those styles too so an App.jsx
+// patch doesn't report "clean" while styles.css still has Inter/bounce/etc.
+const UI_CODE_EXTS = new Set(['.jsx', '.tsx', '.vue', '.svelte', '.astro']);
+const STYLE_EXTS = new Set(['.css', '.scss', '.sass', '.less']);
+const CO_SCAN_STYLE_NAMES = [
+ 'styles.css', 'styles.scss', 'styles.sass', 'styles.less',
+ 'index.css', 'index.scss', 'index.sass', 'index.less',
+ 'global.css', 'global.scss', 'global.sass', 'global.less',
+ 'globals.css', 'globals.scss', 'globals.sass', 'globals.less',
+];
+const MAX_SCAN_TARGETS = 6;
+
+const STATIC_STYLE_IMPORT_RE = /import\s+(?:[\w*{}\s,$]+\s+from\s+)?['"]([^'"]+\.(?:css|scss|sass|less))['"]/gi;
+
+function hasPathTraversal(filePath) {
+ return typeof filePath === 'string' && filePath.includes('..');
+}
+
+function isInsideProject(filePath, projectCwd) {
+ if (!filePath || !projectCwd || hasPathTraversal(filePath)) return false;
+ try {
+ const rel = path.relative(projectCwd, filePath);
+ return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));
+ } catch {
+ return false;
+ }
+}
+
+export function parseStaticStyleImports(content, fromFile, projectCwd) {
+ if (!content || typeof content !== 'string') return [];
+ const dir = path.dirname(fromFile);
+ const out = [];
+ for (const m of content.matchAll(STATIC_STYLE_IMPORT_RE)) {
+ let p = (m[1] || '').trim();
+ if (!p) continue;
+ if (p.startsWith('.')) p = path.resolve(dir, p);
+ else if (!path.isAbsolute(p)) p = path.resolve(projectCwd, p);
+ if (!isInsideProject(p, projectCwd)) continue;
+ out.push(p);
+ }
+ return out;
+}
+
+export function coLocatedStylesheets(filePath) {
+ const dir = path.dirname(filePath);
+ const base = path.basename(filePath, path.extname(filePath));
+ const candidates = new Set([
+ path.join(dir, `${base}.css`),
+ path.join(dir, `${base}.module.css`),
+ path.join(dir, `${base}.scss`),
+ path.join(dir, `${base}.module.scss`),
+ path.join(dir, `${base}.sass`),
+ path.join(dir, `${base}.module.sass`),
+ path.join(dir, `${base}.less`),
+ path.join(dir, `${base}.module.less`),
+ ]);
+ for (const name of CO_SCAN_STYLE_NAMES) {
+ candidates.add(path.join(dir, name));
+ }
+ return [...candidates].filter((p) => fs.existsSync(p));
+}
+
+export function normalizeScanTargets(primaryTargets, projectCwd) {
+ if (!Array.isArray(primaryTargets) || primaryTargets.length === 0) return [];
+ const ordered = [];
+ const seen = new Set();
+ const baseCwd = projectCwd || process.cwd();
+ const normalizeTarget = (p) => {
+ // Preserve literal `..` segments so downstream sensitive-path checks
+ // still fire. path.resolve would collapse `/foo/../etc/passwd`.
+ if (hasPathTraversal(p)) return p;
+ return path.isAbsolute(p) ? p : path.resolve(baseCwd, p);
+ };
+ const add = (p) => {
+ if (ordered.length >= MAX_SCAN_TARGETS) return;
+ const abs = normalizeTarget(p);
+ if (seen.has(abs)) return;
+ seen.add(abs);
+ ordered.push(abs);
+ return abs;
+ };
+
+ for (const p of primaryTargets) add(p);
+ return ordered;
+}
+
+export function expandScanTargets(primaryTargets, projectCwd) {
+ const ordered = normalizeScanTargets(primaryTargets, projectCwd);
+ if (ordered.length === 0) return [];
+ const seen = new Set(ordered);
+ const baseCwd = projectCwd || process.cwd();
+ const add = (p) => {
+ if (ordered.length >= MAX_SCAN_TARGETS) return;
+ const abs = hasPathTraversal(p) ? p : (path.isAbsolute(p) ? p : path.resolve(baseCwd, p));
+ if (seen.has(abs)) return;
+ seen.add(abs);
+ ordered.push(abs);
+ return abs;
+ };
+
+ const normalizedPrimaries = [];
+ for (const p of ordered) normalizedPrimaries.push(p);
+
+ for (const p of normalizedPrimaries) {
+ if (ordered.length >= MAX_SCAN_TARGETS) break;
+ if (!isInsideProject(p, baseCwd)) continue;
+ const ext = path.extname(p).toLowerCase();
+ if (STYLE_EXTS.has(ext) || !UI_CODE_EXTS.has(ext)) continue;
+
+ let content = '';
+ try { content = fs.readFileSync(p, 'utf-8'); } catch { /* unreadable primary */ }
+
+ for (const imp of parseStaticStyleImports(content, p, projectCwd)) {
+ add(imp);
+ if (ordered.length >= MAX_SCAN_TARGETS) break;
+ }
+ for (const col of coLocatedStylesheets(p)) {
+ add(col);
+ if (ordered.length >= MAX_SCAN_TARGETS) break;
+ }
+ }
+
+ return ordered;
+}
+
+export function writeAuditLog(env, entry) {
+ const target = env?.IMPECCABLE_HOOK_LOG;
+ if (!target || typeof target !== 'string') return false;
+ try {
+ const expanded = target.startsWith('~/')
+ ? path.join(process.env.HOME || process.env.USERPROFILE || '.', target.slice(2))
+ : target;
+ fs.mkdirSync(path.dirname(expanded), { recursive: true });
+ const line = JSON.stringify({ ts: new Date().toISOString(), ...entry }) + '\n';
+ fs.appendFileSync(expanded, line);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+const DETECTOR_CANDIDATES = [
+ path.join(__dirname, 'detector', 'detect-antipatterns.mjs'),
+ path.join(__dirname, '..', '..', 'cli', 'engine', 'detect-antipatterns.mjs'),
+ path.join(__dirname, '..', '..', '..', 'cli', 'engine', 'detect-antipatterns.mjs'),
+];
+
+let detectorCache = null;
+export async function loadDetector(candidates = DETECTOR_CANDIDATES) {
+ if (detectorCache) return detectorCache;
+ const found = candidates.find((c) => fs.existsSync(c));
+ if (!found) return null;
+ const mod = await import(pathToFileURL(found));
+ detectorCache = { detectText: mod.detectText, detectHtml: mod.detectHtml };
+ return detectorCache;
+}
+
+// For tests: allow injecting a detector implementation.
+export function setDetectorForTesting(impl) {
+ detectorCache = impl;
+}
+
+// ────────────────────────────────────────────────────────────────────────
+// Nudge/steer messages for the no-silent-fires policy.
+//
+// The hook is designed to be a conversational presence: every fire that
+// actually scans a file emits a developer-role message into the model's
+// next turn. Three states map to three templates:
+//
+// 1. **Fresh findings** → `renderTemplate` (existing, imperative).
+// 2. **Pending findings** → `renderPendingAck` (re-nudge for issues the
+// model was already told about in this
+// session but hasn't fixed yet).
+// 3. **Truly clean** → `renderCleanAck` (short positive nudge that
+// keeps the design discipline in context).
+//
+// All three are short (≤ ~40 tokens each) so the cumulative cost stays
+// bounded across a long active editing session. Users who explicitly want
+// silence-on-clean can set `IMPECCABLE_HOOK_QUIET=1` — runHook checks that
+// env before emitting #2 or #3.
+//
+// Why not stay silent on dedup-clean? Earlier versions did. The model
+// quickly forgets the prior reminder once tool output scrolls past it, so
+// re-nudging on the same file with a short "still pending" line keeps the
+// pressure on. The wording deliberately points back to "earlier this
+// session" so the model knows it's a re-mind, not a new finding.
+// ────────────────────────────────────────────────────────────────────────
+
+const STEER_LINE = 'Keep typography hierarchy, spacing rhythm, and color contrast intentional on the next change.';
+
+export function renderCleanAck(filePath, opts = {}) {
+ const cwd = opts.cwd || process.cwd();
+ const display = relativize(filePath, cwd);
+ return `${ENVELOPE_PREFIX} Design hook scanned ${display}. No anti-patterns. ${STEER_LINE}`;
+}
+
+export function renderPendingAck(filePath, knownFindings, opts = {}) {
+ const cwd = opts.cwd || process.cwd();
+ const display = relativize(filePath, cwd);
+ const count = knownFindings.length;
+ // `knownFindings` here are the cache strings like "side-tab:3".
+ const sample = knownFindings.slice(0, 3).join(', ');
+ const more = count > 3 ? `, +${count - 3} more` : '';
+ return `${ENVELOPE_PREFIX} Design hook scanned ${display}. Still has ${count} issue(s) flagged earlier this session (${sample}${more}). Address them before finalizing — the previous reminder still applies.`;
+}
+
+export function shouldEmitAckForFile(filePath) {
+ return ACK_EXTS.has(path.extname(String(filePath || '')).toLowerCase());
+}
+
+// The directive footer is the part of the hook output that steers model
+// behavior. Three intentional moves:
+// 1. **Imperative, not advisory.** "Fix these..." beats "Consider
+// revising..." which the model treats as a soft suggestion it can
+// override when the user asked for any kind of throwaway / demo UI.
+// 2. **Explicit exception clause.** Without it, the model will try to
+// "fix" intentional bad fixtures, anti-pattern examples in docs, or
+// test cases. Naming the exception inline beats hoping the model
+// infers it from context.
+// 3. **Acknowledgement instruction.** Hook output is injected as
+// developer-role context, not a chat turn, so the user never sees the
+// raw envelope. Asking the model to surface the fix in its reply is
+// the cheapest way to make the feedback loop visible to the user.
+function directiveFooter(display, opts = {}) {
+ const ignoreFileCommand = `/impeccable hooks ignore-file ${quoteCommandArg(display)}`;
+ const fileIgnoreGuidance = opts.grouped
+ ? 'run `/impeccable hooks ignore-file <path>` for the specific file'
+ : `run \`${ignoreFileCommand}\``;
+ return [
+ 'Fix these in your next reply before finalizing. Acknowledge what you changed so the user sees the correction.',
+ '',
+ 'Skip the fix only if the user explicitly asked for an intentionally bad UI, an anti-pattern example, a test fixture, or documentation of bad design. In that case, say so and continue.',
+ '',
+ `Do not add source comments such as \`impeccable: ignore\`; those pollute the code and do not suppress hook findings. Do not add hook ignores unless the user explicitly confirms the finding is intentional. Prefer the narrowest persisted exception: run the exact \`/impeccable hooks ignore-value ... --shared\` command shown next to a value-specific finding. For \`overused-font\`, use \`ignore-value\` for a specific font and use \`/impeccable hooks ignore-rule overused-font --all-values\` only when the user asks to ignore overused fonts generally. For file-specific findings without an ignore-value command, ${fileIgnoreGuidance}; use \`/impeccable hooks ignore-rule <id>\` only when the user asks to suppress the whole non-value-specific rule. Run /impeccable audit for the full pass.`,
+ ].join('\n');
+}
+
+/**
+ * Run the hook with explicit dependencies. Returns a result object:
+ * { exitCode, stdout, audit, reason? }
+ *
+ * Never throws. All errors are converted to `exitCode: 0` + audit entry.
+ */
+export async function runHook({ stdinJson, env = {}, cwd = process.cwd(), now = Date.now, detector } = {}) {
+ const audit = { ts: new Date(now()).toISOString(), event: 'PostToolUse' };
+ const result = (extra) => ({ exitCode: 0, stdout: '', audit: { ...audit, ...extra } });
+
+ try {
+ // Re-entrancy guard.
+ if (depthIsSet(env.IMPECCABLE_HOOK_DEPTH) || depthIsSet(env.CLAUDE_HOOK_DEPTH)) {
+ return result({ reentrant: true, durationMs: 0 });
+ }
+
+ if (truthy(env.IMPECCABLE_HOOK_DISABLED)) {
+ return result({ skipped: 'env-disabled', durationMs: 0 });
+ }
+
+ const started = Date.now();
+
+ let event;
+ try {
+ event = typeof stdinJson === 'string' ? JSON.parse(stdinJson) : stdinJson;
+ } catch {
+ return result({ skipped: 'stdin-malformed', durationMs: Date.now() - started });
+ }
+ if (!event || typeof event !== 'object') {
+ return result({ skipped: 'stdin-empty', durationMs: Date.now() - started });
+ }
+
+ const harness = resolveHarness(env, event);
+ event = normalizeHookEvent(event, cwd, harness);
+ audit.harness = harness;
+
+ const projectCwd = event.cwd || cwd;
+ const primaryFiles = normalizeScanTargets(resolveTargetFiles(event, projectCwd), projectCwd);
+ const primaryFileSet = new Set(primaryFiles);
+ const targetFiles = expandScanTargets(primaryFiles, projectCwd);
+ audit.session = event.session_id || null;
+ if (event.tool_name) audit.tool = event.tool_name;
+
+ if (targetFiles.length === 0) {
+ return result({ skipped: 'no-file-path', durationMs: Date.now() - started });
+ }
+
+ const config = readConfig(projectCwd);
+ if (config.enabled === false) {
+ return result({ skipped: 'config-disabled', durationMs: Date.now() - started });
+ }
+
+ const cache = readCache(projectCwd);
+ const sessionId = event.session_id || 'unknown';
+ const det = detector || await loadDetector();
+ if (!det || typeof det.detectText !== 'function') {
+ persistCache(projectCwd, cache);
+ return result({ skipped: 'detector-missing', durationMs: Date.now() - started });
+ }
+
+ let pendingWinner = null;
+ let cleanWinner = null;
+ const freshGroups = [];
+ let suppressionWinner = null;
+ let detectorThrewAny = false;
+ let lastSkip = 'no-scannable-file';
+ let suppressedHit = false;
+
+ for (const filePath of targetFiles) {
+ audit.file = filePath;
+
+ if (hasPathTraversal(filePath) || SENSITIVE_PATH.test(filePath)) {
+ lastSkip = 'sensitive';
+ continue;
+ }
+ if (GENERATED_PATH.test(filePath)) {
+ lastSkip = 'generated';
+ continue;
+ }
+
+ const ext = path.extname(filePath).toLowerCase();
+ audit.ext = ext;
+ if (!ALLOWED_EXTS.has(ext)) {
+ lastSkip = 'extension';
+ continue;
+ }
+
+ const relForMatch = relativize(filePath, projectCwd);
+ if (matchesAnyGlob(relForMatch, config.ignoreFiles) || matchesAnyGlob(filePath, config.ignoreFiles)) {
+ lastSkip = 'config-ignore-file';
+ continue;
+ }
+ if (!fs.existsSync(filePath)) {
+ lastSkip = 'file-missing';
+ continue;
+ }
+
+ if (primaryFileSet.has(filePath)) {
+ const editCount = bumpEditCount(cache, sessionId, filePath);
+ audit.editCount = editCount;
+
+ if (editCount > EDIT_COUNT_THRESHOLD) {
+ const wasJustCrossed = editCount === EDIT_COUNT_THRESHOLD + 1;
+ if (wasJustCrossed && !suppressionWinner) {
+ suppressionWinner = { filePath };
+ }
+ lastSkip = 'suppressed';
+ suppressedHit = true;
+ continue;
+ }
+ }
+
+ const content = fs.readFileSync(filePath, 'utf-8');
+ let findings;
+ let detectorThrew = false;
+ if ((ext === '.html' || ext === '.htm') && typeof det.detectHtml === 'function') {
+ try { findings = await det.detectHtml(filePath); } catch { findings = []; detectorThrew = true; }
+ } else {
+ try { findings = await det.detectText(content, filePath); } catch { findings = []; detectorThrew = true; }
+ }
+
+ const filtered = filterFindings(findings || [], content, ext, config);
+ const fresh = dedupeAgainstCache(filtered, cache, sessionId, filePath);
+ audit.findings = (findings || []).length;
+ audit.freshFindings = fresh.length;
+
+ if (fresh.length > 0) {
+ rememberFindings(cache, sessionId, filePath, fresh);
+ freshGroups.push({ filePath, findings: fresh });
+ continue;
+ }
+
+ if (detectorThrew) {
+ detectorThrewAny = true;
+ continue;
+ }
+
+ if (filtered.length > 0 && !pendingWinner) {
+ const known = (ensureFile(cache, sessionId, filePath).findings || []).slice();
+ pendingWinner = { filePath, known };
+ } else if (filtered.length === 0 && !cleanWinner) {
+ cleanWinner = { filePath };
+ }
+ }
+
+ persistCache(projectCwd, cache);
+
+ if (freshGroups.length > 0) {
+ const firstGroup = freshGroups[0];
+ const text = renderGroupedTemplate(freshGroups, config, { cwd: projectCwd });
+ const allFindings = freshGroups.flatMap((group) => group.findings);
+ return {
+ exitCode: 0,
+ stdout: payload(text, 'PostToolUse', harness),
+ emission: {
+ kind: 'fresh',
+ file: firstGroup.filePath,
+ findings: firstGroup.findings,
+ groups: freshGroups,
+ },
+ audit: {
+ ...audit,
+ file: firstGroup.filePath,
+ emitted: true,
+ freshFiles: freshGroups.length,
+ freshFindings: allFindings.length,
+ chars: text.length,
+ durationMs: Date.now() - started,
+ },
+ };
+ }
+
+ if (detectorThrewAny && !pendingWinner && !cleanWinner) {
+ return result({ emitted: false, error: 'detector-threw', durationMs: Date.now() - started });
+ }
+
+ if (truthy(env.IMPECCABLE_HOOK_QUIET)) {
+ return result({ emitted: false, quiet: true, durationMs: Date.now() - started });
+ }
+
+ if (pendingWinner && shouldEmitAckForFile(pendingWinner.filePath)) {
+ const text = renderPendingAck(pendingWinner.filePath, pendingWinner.known, { cwd: projectCwd });
+ return {
+ exitCode: 0,
+ stdout: payload(text, 'PostToolUse', harness),
+ emission: { kind: 'pending', file: pendingWinner.filePath, known: pendingWinner.known },
+ audit: {
+ ...audit,
+ file: pendingWinner.filePath,
+ emitted: true,
+ kind: 'pending',
+ pending: pendingWinner.known.length,
+ chars: text.length,
+ durationMs: Date.now() - started,
+ },
+ };
+ }
+
+ if (suppressionWinner) {
+ const text = suppressionNotice(relativize(suppressionWinner.filePath, projectCwd));
+ return {
+ exitCode: 0,
+ stdout: payload(text, 'PostToolUse', harness),
+ emission: { kind: 'suppression', file: suppressionWinner.filePath },
+ audit: {
+ ...audit,
+ file: suppressionWinner.filePath,
+ suppressed: true,
+ emitted: true,
+ durationMs: Date.now() - started,
+ },
+ };
+ }
+
+ if (cleanWinner && shouldEmitAckForFile(cleanWinner.filePath)) {
+ const text = renderCleanAck(cleanWinner.filePath, { cwd: projectCwd });
+ return {
+ exitCode: 0,
+ stdout: payload(text, 'PostToolUse', harness),
+ emission: { kind: 'clean', file: cleanWinner.filePath },
+ audit: {
+ ...audit,
+ file: cleanWinner.filePath,
+ emitted: true,
+ kind: 'clean',
+ chars: text.length,
+ durationMs: Date.now() - started,
+ },
+ };
+ }
+
+ if (pendingWinner || cleanWinner) {
+ return result({ emitted: false, skipped: 'non-ui-ack', durationMs: Date.now() - started });
+ }
+
+ if (suppressedHit) {
+ return result({ suppressed: true, emitted: false, durationMs: Date.now() - started });
+ }
+
+ return result({ skipped: lastSkip, durationMs: Date.now() - started });
+ } catch (err) {
+ return {
+ exitCode: 0,
+ stdout: '',
+ audit: { ...audit, error: String(err && err.message ? err.message : err) },
+ };
+ }
+}
+
+export function payload(text, eventName = 'PostToolUse', harness = 'claude') {
+ if (harness === 'cursor') {
+ return JSON.stringify({ additional_context: text });
+ }
+ return JSON.stringify({
+ hookSpecificOutput: { hookEventName: eventName, additionalContext: text },
+ });
+}
diff --git a/.claude/skills/impeccable/scripts/hook.mjs b/.claude/skills/impeccable/scripts/hook.mjs
new file mode 100644
index 000000000..b862f8033
--- /dev/null
+++ b/.claude/skills/impeccable/scripts/hook.mjs
@@ -0,0 +1,61 @@
+#!/usr/bin/env node
+/**
+ * Impeccable design hook — PostToolUse entry point.
+ *
+ * Reads the Claude Code / Codex / Cursor hook event from stdin, runs the design
+ * detector against the touched file, and emits a system reminder via
+ * `hookSpecificOutput.additionalContext` when findings exist.
+ *
+ * Contract: never break a turn. Always exit 0. Clean files emit a small ack
+ * unless quiet mode is enabled.
+ *
+ * Most logic lives in `hook-lib.mjs` so it is unit-testable without a
+ * subprocess. This file is the thin stdin/stdout adapter.
+ */
+
+import { runHook, 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');
+}
+
+async function main() {
+ // Snapshot the inherited env FIRST so the re-entrancy guard checks the
+ // parent's value, not the value we are about to export for any child
+ // processes the hook might ever spawn.
+ const inheritedEnv = { ...process.env };
+ process.env.IMPECCABLE_HOOK_DEPTH = process.env.IMPECCABLE_HOOK_DEPTH || '1';
+
+ let stdinJson = '';
+ try { stdinJson = await readStdin(); } catch { /* fall through */ }
+
+ const result = await runHook({
+ stdinJson,
+ env: inheritedEnv,
+ cwd: process.cwd(),
+ });
+
+ writeAuditLog(process.env, result.audit);
+
+ if (result.stdout) process.stdout.write(result.stdout);
+ process.exit(result.exitCode || 0);
+}
+
+main().catch((err) => {
+ // Last-ditch: never break the agent's turn even if something we did not
+ // anticipate goes wrong. Audit-log the failure if logging is enabled.
+ try {
+ writeAuditLog(process.env, {
+ ts: new Date().toISOString(),
+ event: 'PostToolUse',
+ error: String(err && err.message ? err.message : err),
+ });
+ } catch { /* swallow */ }
+ if (process.env.IMPECCABLE_HOOK_DEBUG) {
+ process.stderr.write(`[impeccable-hook] ${err}\n`);
+ }
+ process.exit(0);
+});
diff --git a/.claude/skills/impeccable/scripts/live-inject.mjs b/.claude/skills/impeccable/scripts/live-inject.mjs
index 4e5c5dc0a..69ce530c1 100644
--- a/.claude/skills/impeccable/scripts/live-inject.mjs
+++ b/.claude/skills/impeccable/scripts/live-inject.mjs
@@ -32,6 +32,8 @@ const IGNORE_MARKER_CLOSE = '# impeccable-live-ignore-end';
export const LIVE_IGNORE_PATTERNS = Object.freeze([
'.impeccable/hook.cache.json',
+ '.impeccable/hook.pending.json',
+ '.impeccable/hook.local.json',
'.impeccable/live/server.json',
'.impeccable/live/sessions/',
'.impeccable/live/previews/',
diff --git a/.codex/hooks.json b/.codex/hooks.json
new file mode 100644
index 000000000..96d74229d
--- /dev/null
+++ b/.codex/hooks.json
@@ -0,0 +1,18 @@
+{
+ "description": "Impeccable design detector: runs after Edit/Write/apply_patch on UI files and surfaces findings as system reminders.",
+ "hooks": {
+ "PostToolUse": [
+ {
+ "matcher": "Edit|Write|apply_patch",
+ "hooks": [
+ {
+ "type": "command",
+ "command": "node \"$(git rev-parse --show-toplevel)/.agents/skills/impeccable/scripts/hook.mjs\"",
+ "timeout": 5,
+ "statusMessage": "Scanning design"
+ }
+ ]
+ }
+ ]
+ }
+}
diff --git a/.cursor/hooks.json b/.cursor/hooks.json
new file mode 100644
index 000000000..f57cbcb8f
--- /dev/null
+++ b/.cursor/hooks.json
@@ -0,0 +1,11 @@
+{
+ "version": 1,
+ "hooks": {
+ "preToolUse": [
+ {
+ "command": "node \".cursor/skills/impeccable/scripts/hook-before-edit.mjs\"",
+ "timeout": 5
+ }
+ ]
+ }
+}
diff --git a/.cursor/skills/impeccable/SKILL.md b/.cursor/skills/impeccable/SKILL.md
index 44bdf490d..3ec0bb2ae 100644
--- a/.cursor/skills/impeccable/SKILL.md
+++ b/.cursor/skills/impeccable/SKILL.md
@@ -122,7 +122,7 @@ If someone could look at this interface and say "AI made that" without doubt, it
| `optimize [target]` | Fix | Diagnose and fix UI performance | [reference/optimize.md](reference/optimize.md) |
| `live` | Iterate | Visual variant mode: pick elements in the browser, generate alternatives | [reference/live.md](reference/live.md) |
-Plus two management commands: `pin <command>` and `unpin <command>`, detailed below.
+Plus three management commands: `pin <command>`, `unpin <command>`, and `hooks <on|off|status|...>`, detailed below.
### Routing rules
@@ -139,7 +139,7 @@ Plus two management commands: `pin <command>` and `unpin <command>`, detailed be
**If `scan.targets` is non-empty, run `node .cursor/skills/impeccable/scripts/detect.mjs --json <scan.targets joined by spaces>` once** (the bundled detector over local files: no network, no npx). `scan.via` tells you what they are: `git-changes` (the markup/style files in your dirty tree, the most relevant set), `source-dir` (e.g. `src`, `app`), `html`, or `root`. Fold the hits into your picks: many quality / contrast hits → `audit` or `polish`; a specific slop family → the matching command (gradient text or eyebrows → `quieter` / `typeset`, flat or gray palette → `colorize`, and so on). It's a real, current signal that beats guessing. If detect errors or the tree is large and slow, skip it and recommend the user run `audit` themselves; never block the suggestion on it.
Keep it to 2-3 pointed picks with the exact command to type. The menu stays the fallback; the recommendation is the lede.
-2. **First word matches a command**: load its reference file and follow its instructions. Everything after the command name is the target.
+2. **First word matches a command** (table above OR `pin` / `unpin` / `hooks`): load its reference file and follow its instructions. Everything after the command name is the target.
3. **First word doesn't match, but the intent clearly maps to one command** (e.g. "fix the spacing" → `layout`, "rewrite this error message" → `clarify`, "the colors feel flat" → `colorize`): load that command's reference and proceed as if invoked. If two commands could fit, ask once which.
4. **No clear command match**: general design invocation. Apply the setup steps, the General rules, and the loaded register reference, using the full argument as context.
@@ -157,4 +157,8 @@ If the first word is `craft`, setup still runs first, but [reference/craft.md](r
node .cursor/skills/impeccable/scripts/pin.mjs <pin|unpin> <command>
```
-Valid `<command>` is any command from the table above. Report the script's result concisely. Confirm the new shortcut on success, relay stderr verbatim on error.
\ No newline at end of file
+Valid `<command>` is any command from the table above. Report the script's result concisely. Confirm the new shortcut on success, relay stderr verbatim on error.
+
+## Hooks
+
+`/impeccable hooks <on|off|status|ignore-rule|ignore-file|ignore-value|reset>` manages the design detector hook for this project. The hook auto-runs the detector after direct UI file edits and surfaces findings as system reminders. Full flow is in [reference/hooks.md](reference/hooks.md); load it when the user invokes `/impeccable hooks` with any argument.
\ No newline at end of file
diff --git a/.cursor/skills/impeccable/reference/hooks.md b/.cursor/skills/impeccable/reference/hooks.md
new file mode 100644
index 000000000..3e5d48e74
--- /dev/null
+++ b/.cursor/skills/impeccable/reference/hooks.md
@@ -0,0 +1,82 @@
+# /impeccable hooks
+
+Manage the **design detector hook** for the current project.
+
+The hook runs the impeccable design detector on direct file edits to design-relevant files (`.tsx`, `.jsx`, `.html`, `.vue`, `.svelte`, `.astro`, `.css`, `.scss`, `.sass`, `.less`, `.ts`, `.js`). Claude Code and Codex use `PostToolUse` and push a short system reminder into the agent's context after the edit; findings get a correction prompt, pending issues get a re-nudge, and clean UI-ish files get a short ack unless `IMPECCABLE_HOOK_QUIET=1` is set. Plain `.ts` and `.js` files are still scanned, but stay quiet unless the detector finds something. Cursor uses `preToolUse` to block bad proposed writes before they land and stays silent when it allows a clean write.
+
+This command toggles the hook **per project** by editing `.impeccable/hook.json`. Local-only ignore policy lives in `.impeccable/hook.local.json`, which is gitignored. To disable globally, set `IMPECCABLE_HOOK_DISABLED=1` in your shell environment.
+
+Supported harnesses: Claude Code (`.claude/settings.json` in the project), Codex (`.codex/hooks.json` in the project), and Cursor (`.cursor/hooks.json` in the project).
+
+On **Cursor**, `preToolUse` checks proposed Write/Edit/Shell write content and denies only when the real detector finds an issue. The denial message is visible to the agent as the tool error, so the agent can reconsider before the bad write lands.
+
+## Routing
+
+The first argument is the action. Defaults to `status`.
+
+| Action | What it does |
+|---|---|
+| `status` | Print current state, shared/local config paths, ignored rules / files / values, env override. |
+| `on` | Set `enabled: true` in `.impeccable/hook.json`. |
+| `off` | Set `enabled: false` in `.impeccable/hook.json`. |
+| `ignore-rule <id>` | Append `<id>` to `ignoreRules`; for `overused-font`, requires `--all-values`. |
+| `ignore-file <glob>` | Append `<glob>` to `ignoreFiles`. |
+| `ignore-value <id> <value> [--shared] [--reason "..."]` | Append a rule/value suppression to shared `.impeccable/hook.json`. |
+| `ignore-value <id> <value> --local [--reason "..."]` | Append a private rule/value suppression to `.impeccable/hook.local.json`. |
+| `reset` | Delete the project config, dedup cache, and Cursor pending queue. |
+
+## Flow
+
+1. Resolve the action from the user's argument. If no action was given, default to `status`.
+2. Invoke the admin script and pass the user's output through verbatim:
+
+ ```bash
+ node .cursor/skills/impeccable/scripts/hook-admin.mjs <action> [args...]
+ ```
+
+3. If `<action>` is `off`, follow up with a one-line note: "Done. New edits will not trigger the design hook in this project until you run `/impeccable hooks on`."
+4. If `<action>` is `on`, follow up with: "Done. The design hook will fire after the next Edit/Write/MultiEdit on a UI file."
+5. If `<action>` is `ignore-value`, `ignore-file`, or `ignore-rule`, just print the script output. The default scope is shared `.impeccable/hook.json`; add `--local` only when the user explicitly asks for a private exception.
+6. If `<action>` is `status`, just print the script output. Do not add commentary unless the user asked a follow-up question.
+
+## Intentional findings
+
+The hook itself never writes ignore config. Persist an exception only after the user explicitly confirms the flagged issue is intentional, and always go through `hook-admin.mjs`.
+
+Prefer the narrowest exception:
+
+- If the finding line shows an exact `ignore-value` command, run that command. This writes shared `.impeccable/hook.json` by default.
+- For `overused-font`, use `ignore-value` when the user confirms a specific font. Do not use `ignore-rule overused-font` for a specific font.
+- If the finding has no value-specific command, such as `side-tab`, prefer `ignore-file <path>` for the current file.
+- Use `ignore-rule <id>` only when the user asks to suppress that whole rule across the project. For broad overused-font suppression, use `ignore-rule overused-font --all-values` only when the user asks to ignore overused fonts generally.
+- Do not add source comments such as `impeccable: ignore`; inline comments pollute code and are not a supported suppression mechanism.
+
+Example value-specific exception:
+
+```bash
+node .cursor/skills/impeccable/scripts/hook-admin.mjs ignore-value overused-font Inter --shared --reason "User confirmed Inter is intentional"
+```
+
+Example whole-rule font exception:
+
+```bash
+node .cursor/skills/impeccable/scripts/hook-admin.mjs ignore-rule overused-font --all-values --reason "User asked to ignore overused fonts generally"
+```
+
+Example file-scoped exception:
+
+```bash
+node .cursor/skills/impeccable/scripts/hook-admin.mjs ignore-file "src/legacy/Card.tsx"
+```
+
+## Constraints
+
+- Never modify `.impeccable/hook.json` or `.impeccable/hook.local.json` by hand from this command. Always go through `hook-admin.mjs` so writes stay validated and the file shape stays consistent.
+- Do not edit the hook scripts themselves (`hook.mjs`, `hook-lib.mjs`, `hook-before-edit.mjs`) from this flow. Those are skill plumbing.
+- Cursor can block a proposed write when the detector finds a real issue. Claude Code and Codex do not block the edit; they emit a post-edit reminder instead. Disabling stops both blocking and reminders.
+- The hook is bundled with the Impeccable skill and installed through project-local manifests: `.claude/settings.json`, `.codex/hooks.json`, and `.cursor/hooks.json`. On Codex, the user must approve the hook via `/hooks` the first time. On Cursor, confirm hooks are enabled under Settings -> Hooks.
+
+## Failure modes
+
+- If `.impeccable/hook.json` or `.impeccable/hook.local.json` is unreadable or malformed, the hook ignores that file and uses the remaining valid config/defaults. `hook-admin.mjs status` will show malformed files as ignored.
+- If the user asks to "disable the hook" globally, suggest both options: `IMPECCABLE_HOOK_DISABLED=1` env var (one-shot, follows the shell), and `/impeccable hooks off` (persistent for this project, committable).
diff --git a/.cursor/skills/impeccable/scripts/detector/engines/regex/detect-text.mjs b/.cursor/skills/impeccable/scripts/detector/engines/regex/detect-text.mjs
index fd0d9c73f..4c0777c93 100644
--- a/.cursor/skills/impeccable/scripts/detector/engines/regex/detect-text.mjs
+++ b/.cursor/skills/impeccable/scripts/detector/engines/regex/detect-text.mjs
@@ -446,7 +446,7 @@ function detectText(content, filePath, options = {}) {
// Run regex matchers on the full file content (catches Tailwind classes, inline styles)
// Enable block context for CSS files where related properties span multiple lines
- const cssLike = new Set(['.css', '.scss', '.less']);
+ const cssLike = new Set(['.css', '.scss', '.sass', '.less']);
findings.push(...runRegexMatchers(lines, filePath, 0, cssLike.has(ext) || null, {
profile,
phase: 'source',
diff --git a/.cursor/skills/impeccable/scripts/detector/node/file-system.mjs b/.cursor/skills/impeccable/scripts/detector/node/file-system.mjs
index a80250a0e..aaa8c6df7 100644
--- a/.cursor/skills/impeccable/scripts/detector/node/file-system.mjs
+++ b/.cursor/skills/impeccable/scripts/detector/node/file-system.mjs
@@ -11,7 +11,7 @@ const SKIP_DIRS = new Set([
]);
const SCANNABLE_EXTENSIONS = new Set([
- '.html', '.htm', '.css', '.scss', '.less',
+ '.html', '.htm', '.css', '.scss', '.sass', '.less',
'.jsx', '.tsx', '.js', '.ts',
'.vue', '.svelte', '.astro',
]);
diff --git a/.cursor/skills/impeccable/scripts/hook-admin.mjs b/.cursor/skills/impeccable/scripts/hook-admin.mjs
new file mode 100644
index 000000000..86fcfa909
--- /dev/null
+++ b/.cursor/skills/impeccable/scripts/hook-admin.mjs
@@ -0,0 +1,300 @@
+#!/usr/bin/env node
+/**
+ * `/impeccable hooks <on|off|status|reset>` — manage the design hook
+ * via .impeccable/hook.json and .impeccable/hook.local.json in the current
+ * project.
+ *
+ * Usage:
+ * node hook-admin.mjs status # print current state
+ * node hook-admin.mjs on # set enabled: true
+ * node hook-admin.mjs off # set enabled: false
+ * node hook-admin.mjs ignore-rule <rule-id> # append to ignoreRules
+ * node hook-admin.mjs ignore-rule overused-font --all-values
+ * node hook-admin.mjs ignore-file <glob> # append to ignoreFiles
+ * node hook-admin.mjs ignore-value <rule> <value> # append to shared ignoreValues
+ * node hook-admin.mjs ignore-value <rule> <value> --local
+ * node hook-admin.mjs reset # remove all config + cache
+ *
+ * Designed to be invoked by the LLM from the reference/hooks.md flow.
+ * Output is human-readable; the harness will pass it back to the user.
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+
+import {
+ getConfigPath,
+ getLocalConfigPath,
+ getCachePath,
+ getPendingPath,
+ readConfig,
+ DEFAULT_CONFIG,
+ ensureHookGitExcludes,
+ normalizeIgnoreValue,
+ normalizeIgnoreValueEntries,
+} from './hook-lib.mjs';
+
+const ACTIONS = new Set(['status', 'on', 'off', 'ignore-rule', 'ignore-file', 'ignore-value', 'reset']);
+
+function readRawConfigFile(filePath) {
+ if (!fs.existsSync(filePath)) return { exists: false, malformed: false, raw: null };
+ try {
+ return { exists: true, malformed: false, raw: JSON.parse(fs.readFileSync(filePath, 'utf-8')) };
+ } catch {
+ return { exists: true, malformed: true, raw: null };
+ }
+}
+
+function readRawConfig(cwd, opts = {}) {
+ const filePath = opts.local ? getLocalConfigPath(cwd) : getConfigPath(cwd);
+ return readRawConfigFile(filePath).raw;
+}
+
+function writeConfig(cwd, config, opts = {}) {
+ const filePath = opts.local ? getLocalConfigPath(cwd) : getConfigPath(cwd);
+ if (opts.local) ensureHookGitExcludes(cwd);
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
+ fs.writeFileSync(filePath, JSON.stringify(config, null, 2) + '\n');
+ return filePath;
+}
+
+function mergeConfig(existing) {
+ // Persist the full shape so /impeccable hooks edits leave a complete file
+ // for the user to see, not an unhelpful `{"enabled":false}`.
+ const base = existing && typeof existing === 'object' ? existing : {};
+ return {
+ enabled: base.enabled === false ? false : true,
+ ignoreRules: Array.isArray(base.ignoreRules) ? Array.from(new Set(base.ignoreRules.map(String))) : [],
+ ignoreFiles: Array.isArray(base.ignoreFiles) ? Array.from(new Set(base.ignoreFiles.map(String))) : [],
+ ignoreValues: normalizeIgnoreValueEntries(base.ignoreValues || []),
+ limits: {
+ maxFindings: Number.isFinite(base?.limits?.maxFindings) ? base.limits.maxFindings : DEFAULT_CONFIG.limits.maxFindings,
+ maxChars: Number.isFinite(base?.limits?.maxChars) ? base.limits.maxChars : DEFAULT_CONFIG.limits.maxChars,
+ },
+ };
+}
+
+function mergeLocalConfig(existing) {
+ const base = existing && typeof existing === 'object' ? existing : {};
+ const out = {};
+ if (Object.prototype.hasOwnProperty.call(base, 'enabled')) {
+ out.enabled = base.enabled === false ? false : true;
+ }
+ if (Array.isArray(base.ignoreRules)) {
+ out.ignoreRules = Array.from(new Set(base.ignoreRules.map(String)));
+ }
+ if (Array.isArray(base.ignoreFiles)) {
+ out.ignoreFiles = Array.from(new Set(base.ignoreFiles.map(String)));
+ }
+ out.ignoreValues = normalizeIgnoreValueEntries(base.ignoreValues || []);
+ if (base.limits && typeof base.limits === 'object') {
+ const limits = {};
+ if (Number.isFinite(base.limits.maxFindings)) limits.maxFindings = base.limits.maxFindings;
+ if (Number.isFinite(base.limits.maxChars)) limits.maxChars = base.limits.maxChars;
+ if (Object.keys(limits).length) out.limits = limits;
+ }
+ return out;
+}
+
+function statusReport(cwd) {
+ const shared = readRawConfigFile(getConfigPath(cwd));
+ const local = readRawConfigFile(getLocalConfigPath(cwd));
+ const cfg = readConfig(cwd);
+ const envKill = process.env.IMPECCABLE_HOOK_DISABLED;
+ const envState = envKill ? `IMPECCABLE_HOOK_DISABLED=${envKill}` : 'unset';
+ const cfgPath = path.relative(cwd, getConfigPath(cwd)) || '.impeccable/hook.json';
+ const localPath = path.relative(cwd, getLocalConfigPath(cwd)) || '.impeccable/hook.local.json';
+ const cachePath = path.relative(cwd, getCachePath(cwd)) || '.impeccable/hook.cache.json';
+ const fileState = (info, relPath, absent) => {
+ if (info.malformed) return `${relPath} (malformed; ignored)`;
+ if (info.exists) return relPath;
+ return `${relPath} (${absent})`;
+ };
+ const ignoreValues = cfg.ignoreValues.map((entry) => `${entry.rule}=${entry.value}`);
+
+ const lines = [
+ `Impeccable design hook`,
+ ` state: ${cfg.enabled ? 'enabled' : 'disabled'}`,
+ ` shared file: ${fileState(shared, cfgPath, 'using defaults; file not present')}`,
+ ` local file: ${fileState(local, localPath, 'not present')}`,
+ ` ignoreRules: ${cfg.ignoreRules.length ? cfg.ignoreRules.join(', ') : '(none)'}`,
+ ` ignoreFiles: ${cfg.ignoreFiles.length ? cfg.ignoreFiles.join(', ') : '(none)'}`,
+ ` ignoreValues: ${ignoreValues.length ? ignoreValues.join(', ') : '(none)'}`,
+ ` maxFindings: ${cfg.limits.maxFindings}`,
+ ` maxChars: ${cfg.limits.maxChars}`,
+ ` env override: ${envState}`,
+ ` cache file: ${fs.existsSync(getCachePath(cwd)) ? cachePath : `${cachePath} (not present)`}`,
+ ];
+ return lines.join('\n');
+}
+
+function setEnabled(cwd, value) {
+ const config = mergeConfig(readRawConfig(cwd));
+ config.enabled = value;
+ const target = writeConfig(cwd, config);
+ return `Design hook ${value ? 'enabled' : 'disabled'} for this project (wrote ${path.relative(cwd, target) || target}).`;
+}
+
+function normalizeRuleId(rule) {
+ return String(rule || '').trim().toLowerCase();
+}
+
+function parseIgnoreRuleArgs(args) {
+ const positionals = [];
+ let allValues = false;
+
+ for (let i = 0; i < args.length; i++) {
+ const arg = String(args[i] || '');
+ if (arg === '--all-values') {
+ allValues = true;
+ } else if (arg === '--reason') {
+ while (i + 1 < args.length && !String(args[i + 1]).startsWith('--')) i++;
+ } else if (arg.startsWith('--reason=')) {
+ // Accepted for command symmetry; ignoreRules stores rule ids only.
+ } else if (arg.startsWith('--')) {
+ throw new Error(`Unknown ignore-rule flag: ${arg}`);
+ } else {
+ positionals.push(arg);
+ }
+ }
+
+ return {
+ rule: normalizeRuleId(positionals[0]),
+ allValues,
+ };
+}
+
+function addIgnoreRule(cwd, args) {
+ const parsed = parseIgnoreRuleArgs(args);
+ const rule = parsed.rule;
+ if (!rule) throw new Error('Pass a rule id, e.g. /impeccable hooks ignore-rule side-tab');
+ if (rule === 'overused-font' && !parsed.allValues) {
+ throw new Error('overused-font is value-specific by default. Use /impeccable hooks ignore-value overused-font <font> for a confirmed font, or /impeccable hooks ignore-rule overused-font --all-values only when the user asked to ignore overused fonts generally.');
+ }
+ const config = mergeConfig(readRawConfig(cwd));
+ if (!config.ignoreRules.includes(rule)) config.ignoreRules.push(rule);
+ writeConfig(cwd, config);
+ return `Added "${rule}" to ignoreRules. Current: ${config.ignoreRules.join(', ')}`;
+}
+
+function addIgnoreFile(cwd, glob) {
+ if (!glob) throw new Error('Pass a glob, e.g. /impeccable hooks ignore-file "src/legacy/**"');
+ const config = mergeConfig(readRawConfig(cwd));
+ if (!config.ignoreFiles.includes(glob)) config.ignoreFiles.push(glob);
+ writeConfig(cwd, config);
+ return `Added "${glob}" to ignoreFiles. Current: ${config.ignoreFiles.join(', ')}`;
+}
+
+function parseIgnoreValueArgs(args) {
+ const positionals = [];
+ let shared = false;
+ let local = false;
+ let reason = '';
+
+ for (let i = 0; i < args.length; i++) {
+ const arg = args[i];
+ if (arg === '--shared') {
+ shared = true;
+ } else if (arg === '--local') {
+ local = true;
+ } else if (arg === '--reason') {
+ const chunks = [];
+ while (i + 1 < args.length && !String(args[i + 1]).startsWith('--')) {
+ chunks.push(args[++i]);
+ }
+ reason = chunks.join(' ').trim();
+ } else if (String(arg).startsWith('--reason=')) {
+ reason = String(arg).slice('--reason='.length).trim();
+ } else {
+ positionals.push(arg);
+ }
+ }
+
+ const [rule, ...valueParts] = positionals;
+ return {
+ rule: String(rule || '').trim().toLowerCase(),
+ value: normalizeIgnoreValue(valueParts.join(' ')),
+ shared,
+ local,
+ reason,
+ };
+}
+
+function addIgnoreValue(cwd, args) {
+ const parsed = parseIgnoreValueArgs(args);
+ if (!parsed.rule || !parsed.value) {
+ throw new Error('Pass a rule id and value, e.g. /impeccable hooks ignore-value overused-font Inter');
+ }
+
+ if (parsed.shared && parsed.local) {
+ throw new Error('Pass only one scope flag: --shared or --local');
+ }
+
+ const local = parsed.local;
+ const config = local
+ ? mergeLocalConfig(readRawConfig(cwd, { local: true }))
+ : mergeConfig(readRawConfig(cwd, { local: false }));
+ const key = `${parsed.rule}\0${parsed.value}`;
+ const existing = config.ignoreValues.find((entry) => `${entry.rule}\0${entry.value}` === key);
+
+ if (existing) {
+ if (parsed.reason) existing.reason = parsed.reason;
+ } else {
+ const entry = {
+ rule: parsed.rule,
+ value: parsed.value,
+ createdAt: new Date().toISOString(),
+ };
+ if (parsed.reason) entry.reason = parsed.reason;
+ config.ignoreValues.push(entry);
+ }
+
+ const target = writeConfig(cwd, config, { local });
+ const scope = local ? 'local ignoreValues' : 'shared ignoreValues';
+ return `Added ${parsed.rule}=${parsed.value} to ${scope} (${path.relative(cwd, target) || target}).`;
+}
+
+function reset(cwd) {
+ const removed = [];
+ for (const filePath of [getConfigPath(cwd), getLocalConfigPath(cwd), getCachePath(cwd), getPendingPath(cwd)]) {
+ try {
+ if (fs.existsSync(filePath)) {
+ fs.unlinkSync(filePath);
+ removed.push(path.relative(cwd, filePath) || filePath);
+ }
+ } catch { /* ignore */ }
+ }
+ return removed.length
+ ? `Reset design hook config and cache (removed: ${removed.join(', ')}).`
+ : 'No hook config or cache to remove. Already at defaults.';
+}
+
+function main() {
+ const [, , actionArg, ...rest] = process.argv;
+ const action = (actionArg || 'status').toLowerCase();
+ const cwd = process.cwd();
+
+ if (!ACTIONS.has(action)) {
+ process.stderr.write(`Unknown action: ${action}\nValid: ${Array.from(ACTIONS).join(', ')}\n`);
+ process.exit(1);
+ }
+
+ try {
+ let out = '';
+ switch (action) {
+ case 'status': out = statusReport(cwd); break;
+ case 'on': out = setEnabled(cwd, true); break;
+ case 'off': out = setEnabled(cwd, false); break;
+ case 'ignore-rule': out = addIgnoreRule(cwd, rest); break;
+ case 'ignore-file': out = addIgnoreFile(cwd, rest[0]); break;
+ case 'ignore-value': out = addIgnoreValue(cwd, rest); break;
+ case 'reset': out = reset(cwd); break;
+ }
+ process.stdout.write(out + '\n');
+ } catch (err) {
+ process.stderr.write(`Error: ${err.message || err}\n`);
+ process.exit(1);
+ }
+}
+
+main();
diff --git a/.cursor/skills/impeccable/scripts/hook-before-edit.mjs b/.cursor/skills/impeccable/scripts/hook-before-edit.mjs
new file mode 100644
index 000000000..54b2709d2
--- /dev/null
+++ b/.cursor/skills/impeccable/scripts/hook-before-edit.mjs
@@ -0,0 +1,408 @@
+#!/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 shellContent = shellHereDocContent(shellCommand(input));
+ if (shellContent) return shellContent;
+ const copiedContent = shellCopiedFileContent(shellCommand(input), 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 || '';
+}
+
+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 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' });
+});
diff --git a/.cursor/skills/impeccable/scripts/hook-lib.mjs b/.cursor/skills/impeccable/scripts/hook-lib.mjs
new file mode 100644
index 000000000..02199f530
--- /dev/null
+++ b/.cursor/skills/impeccable/scripts/hook-lib.mjs
@@ -0,0 +1,1232 @@
+/**
+ * Shared library for the Impeccable design hook.
+ *
+ * Pure-ish helpers split out from `hook.mjs` so unit tests can exercise
+ * config parsing, finding filtering, dedup, render, and cache logic without
+ * spawning a subprocess. `hook.mjs` itself is the thin stdin/stdout shim.
+ *
+ * Public surface (everything exported is part of the contract):
+ * ENVELOPE_PREFIX, ALLOWED_EXTS, ACK_EXTS, SENSITIVE_PATH, GENERATED_PATH, TRUTHY
+ * truthy(value)
+ * readConfig(cwd) / DEFAULT_CONFIG / getConfigPath(cwd) / getLocalConfigPath(cwd)
+ * normalizeIgnoreValue(value)
+ * readCache(cwd) / persistCache(cwd, cache)
+ * bumpEditCount(cache, sessionId, filePath) -> number
+ * suppressionNotice(filePath)
+ * filterFindings(findings, content, ext, config)
+ * dedupeAgainstCache(findings, cache, sessionId, filePath)
+ * renderTemplate(findings, filePath, config, opts)
+ * renderCleanAck(filePath, opts) / renderPendingAck(filePath, known, opts)
+ * shouldEmitAckForFile(filePath)
+ * writeAuditLog(env, entry)
+ * loadDetector() -> Promise<{ detectText, detectHtml }>
+ * matchesAnyGlob(filePath, globs)
+ * normalizeScanTargets(primaryTargets, projectCwd)
+ * runHook(deps) -> { exitCode, stdout, audit, reason? }
+ *
+ * Design notes:
+ * - All errors are swallowed at the runHook seam. The detector throwing must
+ * never break a turn. See PRD §5 "Failure modes".
+ * - Cache shape is JSON-friendly; we gc the oldest sessions when there are
+ * more than 8 to keep file size predictable across long-lived projects.
+ * - The detector loader looks for `detector/detect-antipatterns.mjs` next to
+ * this file first (built skill layout) and falls back to the repo root's
+ * `cli/engine/detect-antipatterns.mjs` (running from source).
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+import { pathToFileURL, fileURLToPath } from 'node:url';
+
+const __filename = fileURLToPath(import.meta.url);
+const __dirname = path.dirname(__filename);
+
+export const ENVELOPE_PREFIX = '[impeccable@1]';
+
+export const ALLOWED_EXTS = new Set([
+ '.tsx', '.jsx', '.html', '.htm', '.vue', '.svelte', '.astro',
+ '.css', '.scss', '.sass', '.less', '.ts', '.js',
+]);
+
+export const ACK_EXTS = new Set([
+ '.tsx', '.jsx', '.html', '.htm', '.vue', '.svelte', '.astro',
+ '.css', '.scss', '.sass', '.less',
+]);
+
+// Hard-skip regex for sensitive files. Cannot be turned off via config.
+// Match tokenized secret/credential filenames, not UI names such as
+// CredentialForm.tsx, SecretPage.jsx, or secretary-dashboard.vue.
+export const SENSITIVE_PATH = new RegExp([
+ String.raw`(?:^|[/\\])\.env(?:\.|$)`,
+ String.raw`(?:^|[/\\])\.git(?:[/\\]|$)`,
+ String.raw`(?:^|[/\\])id_rsa(?:$|[._-])[^/\\]*$`,
+ String.raw`(?:^|[/\\])[^/\\]*\.pem$`,
+ String.raw`(?:^|[/\\])(?:[^/\\]*[._-])?(?:secret|secrets|credential|credentials)(?=[._-])[^/\\]*\.(?:json|ya?ml|toml|ini|conf|config|env|txt|key|cert|crt|pem|js|ts)$`,
+].join('|'), 'i');
+
+// Hard-skip regex for generated, lock, minified, and build-output paths.
+export const GENERATED_PATH = /(?:\.generated\.[a-z]+$|\.d\.ts$|\.min\.[a-z]+$|[/\\]node_modules[/\\]|[/\\](?:dist|build|out|\.next|\.cache|coverage)[/\\]|[/\\]?[^/\\]+\.lock(?:\.json)?$)/i;
+
+export const TRUTHY = /^(1|true|yes|on)$/i;
+
+export const DEFAULT_CONFIG = Object.freeze({
+ enabled: true,
+ ignoreRules: [],
+ ignoreFiles: [],
+ ignoreValues: [],
+ limits: { maxFindings: 5, maxChars: 8000 },
+});
+
+export const HOOK_LOCAL_IGNORE_PATTERNS = Object.freeze([
+ '.impeccable/hook.cache.json',
+ '.impeccable/hook.pending.json',
+ '.impeccable/hook.local.json',
+]);
+
+const HOOK_IGNORE_MARKER_OPEN = '# impeccable-hook-ignore-start';
+const HOOK_IGNORE_MARKER_CLOSE = '# impeccable-hook-ignore-end';
+const CACHE_MAX_SESSIONS = 8;
+export const EDIT_COUNT_THRESHOLD = 6;
+
+export function truthy(value) {
+ return typeof value === 'string' && TRUTHY.test(value);
+}
+
+function depthIsSet(value) {
+ if (value === undefined || value === null) return false;
+ const text = String(value).trim();
+ if (!text) return false;
+ if (TRUTHY.test(text)) return true;
+ return /^\d+$/.test(text) && Number(text) > 0;
+}
+
+function safeReadJson(filePath) {
+ try {
+ return JSON.parse(fs.readFileSync(filePath, 'utf-8'));
+ } catch {
+ return null;
+ }
+}
+
+export function getConfigPath(cwd) {
+ return path.join(cwd, '.impeccable', 'hook.json');
+}
+
+export function getLocalConfigPath(cwd) {
+ return path.join(cwd, '.impeccable', 'hook.local.json');
+}
+
+export function getCachePath(cwd) {
+ return path.join(cwd, '.impeccable', 'hook.cache.json');
+}
+
+export function getPendingPath(cwd) {
+ return path.join(cwd, '.impeccable', 'hook.pending.json');
+}
+
+export function resolveProjectCwd(event, fallback = process.cwd()) {
+ return event?.cwd
+ || (Array.isArray(event?.workspace_roots) && event.workspace_roots[0])
+ || envProjectDir(fallback)
+ || fallback;
+}
+
+export function readConfig(cwd) {
+ const config = cloneDefaultConfig();
+ applyConfigSource(config, safeReadJson(getConfigPath(cwd)));
+ applyConfigSource(config, safeReadJson(getLocalConfigPath(cwd)));
+ return config;
+}
+
+function numberOr(value, fallback) {
+ return Number.isFinite(value) && value > 0 ? value : fallback;
+}
+
+function cloneDefaultConfig() {
+ return {
+ ...DEFAULT_CONFIG,
+ ignoreRules: [],
+ ignoreFiles: [],
+ ignoreValues: [],
+ limits: { ...DEFAULT_CONFIG.limits },
+ };
+}
+
+function applyConfigSource(config, raw) {
+ if (!raw || typeof raw !== 'object') return config;
+ if (Object.prototype.hasOwnProperty.call(raw, 'enabled')) {
+ config.enabled = raw.enabled === false ? false : true;
+ }
+ if (Array.isArray(raw.ignoreRules)) {
+ config.ignoreRules = uniqueStrings([...config.ignoreRules, ...raw.ignoreRules]);
+ }
+ if (Array.isArray(raw.ignoreFiles)) {
+ config.ignoreFiles = uniqueStrings([...config.ignoreFiles, ...raw.ignoreFiles]);
+ }
+ if (Array.isArray(raw.ignoreValues)) {
+ config.ignoreValues = mergeIgnoreValues(config.ignoreValues, raw.ignoreValues);
+ }
+ if (raw.limits && typeof raw.limits === 'object') {
+ config.limits = {
+ maxFindings: numberOr(raw.limits.maxFindings, config.limits.maxFindings),
+ maxChars: numberOr(raw.limits.maxChars, config.limits.maxChars),
+ };
+ }
+ return config;
+}
+
+function uniqueStrings(values) {
+ return Array.from(new Set(values.map(String)));
+}
+
+export function normalizeIgnoreValue(value) {
+ return String(value || '')
+ .trim()
+ .replace(/^["']|["']$/g, '')
+ .replace(/\+/g, ' ')
+ .replace(/\s+/g, ' ')
+ .toLowerCase();
+}
+
+function normalizeIgnoreRule(rule) {
+ return String(rule || '').trim().toLowerCase();
+}
+
+export function normalizeIgnoreValueEntries(entries) {
+ if (!Array.isArray(entries)) return [];
+ const out = [];
+ for (const entry of entries) {
+ if (!entry || typeof entry !== 'object') continue;
+ const rule = normalizeIgnoreRule(entry.rule);
+ const value = normalizeIgnoreValue(entry.value);
+ if (!rule || !value) continue;
+ const normalized = { rule, value };
+ if (typeof entry.reason === 'string' && entry.reason.trim()) {
+ normalized.reason = entry.reason.trim();
+ }
+ if (typeof entry.createdAt === 'string' && entry.createdAt.trim()) {
+ normalized.createdAt = entry.createdAt.trim();
+ }
+ out.push(normalized);
+ }
+ return out;
+}
+
+function mergeIgnoreValues(existing, incoming) {
+ const map = new Map();
+ for (const entry of normalizeIgnoreValueEntries(existing)) {
+ map.set(`${entry.rule}\0${entry.value}`, entry);
+ }
+ for (const entry of normalizeIgnoreValueEntries(incoming)) {
+ map.set(`${entry.rule}\0${entry.value}`, entry);
+ }
+ return Array.from(map.values());
+}
+
+export function readCache(cwd) {
+ const raw = safeReadJson(getCachePath(cwd));
+ if (!raw || typeof raw !== 'object' || raw.version !== 1) {
+ return { version: 1, sessions: {} };
+ }
+ return {
+ version: 1,
+ sessions: raw.sessions && typeof raw.sessions === 'object' ? raw.sessions : {},
+ };
+}
+
+export function persistCache(cwd, cache) {
+ const sessions = cache.sessions || {};
+ const ids = Object.keys(sessions);
+ if (ids.length > CACHE_MAX_SESSIONS) {
+ // Garbage-collect oldest sessions by updatedAt.
+ const ordered = ids
+ .map((id) => [id, sessions[id]?.updatedAt || 0])
+ .sort((a, b) => b[1] - a[1])
+ .slice(0, CACHE_MAX_SESSIONS);
+ const next = {};
+ for (const [id] of ordered) next[id] = sessions[id];
+ cache = { ...cache, sessions: next };
+ }
+ const target = getCachePath(cwd);
+ try {
+ ensureHookGitExcludes(cwd);
+ fs.mkdirSync(path.dirname(target), { recursive: true });
+ fs.writeFileSync(target, JSON.stringify(cache));
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+export function ensureHookGitExcludes(cwd = process.cwd()) {
+ try {
+ const target = resolveHookGitExcludeTarget(cwd);
+ if (!target) {
+ return { mode: 'none', changed: false, patterns: [...HOOK_LOCAL_IGNORE_PATTERNS] };
+ }
+
+ const patterns = target.patternPrefix
+ ? HOOK_LOCAL_IGNORE_PATTERNS.map((pattern) => `${target.patternPrefix}/${pattern}`)
+ : [...HOOK_LOCAL_IGNORE_PATTERNS];
+ const markerSuffix = target.patternPrefix || '.';
+ const markerOpen = `${HOOK_IGNORE_MARKER_OPEN} ${markerSuffix}`;
+ const markerClose = `${HOOK_IGNORE_MARKER_CLOSE} ${markerSuffix}`;
+ const existing = fs.existsSync(target.path) ? fs.readFileSync(target.path, 'utf-8') : '';
+ const block = [markerOpen, ...patterns, markerClose].join('\n');
+ const markerRe = new RegExp(`${escapeRegExp(markerOpen)}[\\s\\S]*?${escapeRegExp(markerClose)}`);
+
+ let updated;
+ if (markerRe.test(existing)) {
+ updated = existing.replace(markerRe, block);
+ } else {
+ const prefix = existing.length === 0 ? '' : existing.endsWith('\n') ? existing : `${existing}\n`;
+ updated = `${prefix}${prefix.endsWith('\n\n') || prefix === '' ? '' : '\n'}${block}\n`;
+ }
+
+ if (updated !== existing) {
+ fs.mkdirSync(path.dirname(target.path), { recursive: true });
+ fs.writeFileSync(target.path, updated, 'utf-8');
+ }
+
+ return {
+ mode: 'git-info-exclude',
+ file: path.relative(path.resolve(cwd), target.path).split(path.sep).join('/'),
+ changed: updated !== existing,
+ patterns,
+ };
+ } catch {
+ return { mode: 'error', changed: false, patterns: [...HOOK_LOCAL_IGNORE_PATTERNS] };
+ }
+}
+
+function resolveHookGitExcludeTarget(cwd) {
+ const start = path.resolve(cwd);
+ let dir = start;
+ while (true) {
+ const dotGit = path.join(dir, '.git');
+ if (fs.existsSync(dotGit)) {
+ const gitDir = resolveGitDir(dotGit, dir);
+ if (!gitDir) return null;
+ const relPrefix = path.relative(dir, start).split(path.sep).join('/');
+ return {
+ path: path.join(gitDir, 'info', 'exclude'),
+ patternPrefix: relPrefix && relPrefix !== '.' ? relPrefix : '',
+ };
+ }
+ const parent = path.dirname(dir);
+ if (parent === dir) return null;
+ dir = parent;
+ }
+}
+
+function resolveGitDir(dotGit, worktreeDir) {
+ const stat = fs.statSync(dotGit);
+ if (stat.isDirectory()) return dotGit;
+ if (!stat.isFile()) return null;
+
+ const body = fs.readFileSync(dotGit, 'utf-8').trim();
+ const match = body.match(/^gitdir:\s*(.+)$/i);
+ if (!match) return null;
+ return path.isAbsolute(match[1]) ? match[1] : path.resolve(worktreeDir, match[1]);
+}
+
+function escapeRegExp(value) {
+ return String(value).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+}
+
+function ensureSession(cache, sessionId) {
+ if (!cache.sessions[sessionId]) {
+ cache.sessions[sessionId] = { updatedAt: Date.now(), files: {} };
+ }
+ return cache.sessions[sessionId];
+}
+
+function ensureFile(cache, sessionId, filePath) {
+ const session = ensureSession(cache, sessionId);
+ if (!session.files[filePath]) {
+ session.files[filePath] = { editCount: 0, findings: [] };
+ }
+ return session.files[filePath];
+}
+
+export function bumpEditCount(cache, sessionId, filePath) {
+ const fileEntry = ensureFile(cache, sessionId, filePath);
+ fileEntry.editCount = (fileEntry.editCount || 0) + 1;
+ ensureSession(cache, sessionId).updatedAt = Date.now();
+ return fileEntry.editCount;
+}
+
+export function suppressionNotice(filePath) {
+ return `${ENVELOPE_PREFIX} Suppressing further design hints on ${filePath}. More than ${EDIT_COUNT_THRESHOLD} edits in this session reached. Run /impeccable audit to revisit.`;
+}
+
+// Glob → RegExp. Supports `**`, `*`, `?`, and `{a,b}` alternation.
+function globToRegex(glob) {
+ let re = '^';
+ let i = 0;
+ while (i < glob.length) {
+ const c = glob[i];
+ if (c === '*') {
+ if (glob[i + 1] === '*') {
+ re += '.*';
+ i += 2;
+ if (glob[i] === '/') i += 1;
+ } else {
+ re += '[^/]*';
+ i += 1;
+ }
+ } else if (c === '?') {
+ re += '[^/]';
+ i += 1;
+ } else if (c === '{') {
+ const end = glob.indexOf('}', i);
+ if (end === -1) { re += '\\{'; i += 1; continue; }
+ const parts = glob.slice(i + 1, end).split(',').map((p) => p.replace(/[.+^$()|[\]\\]/g, '\\$&'));
+ re += `(?:${parts.join('|')})`;
+ i = end + 1;
+ } else if (/[.+^$()|[\]\\]/.test(c)) {
+ re += `\\${c}`;
+ i += 1;
+ } else {
+ re += c;
+ i += 1;
+ }
+ }
+ re += '$';
+ return new RegExp(re);
+}
+
+export function matchesAnyGlob(filePath, globs) {
+ if (!Array.isArray(globs) || globs.length === 0) return false;
+ const normalized = filePath.split(path.sep).join('/');
+ for (const glob of globs) {
+ try {
+ const re = globToRegex(String(glob));
+ if (re.test(normalized)) return true;
+ // Match against basename too for convenience: `*.generated.tsx` should
+ // catch `src/foo.generated.tsx` without requiring `**/`.
+ const base = normalized.split('/').pop();
+ if (re.test(base)) return true;
+ } catch {
+ /* malformed glob, skip */
+ }
+ }
+ return false;
+}
+
+export function filterFindings(findings, _content, _ext, config) {
+ if (!Array.isArray(findings) || findings.length === 0) return [];
+ const ignoreRules = new Set((config.ignoreRules || []).map((rule) => normalizeIgnoreRule(rule)));
+ const ignoreValues = normalizeIgnoreValueEntries(config.ignoreValues || []);
+ return findings.filter((f) => {
+ if (!f || typeof f !== 'object') return false;
+ if (ignoreRules.has(normalizeIgnoreRule(f.antipattern))) return false;
+ if (isIgnoredFindingValue(f, ignoreValues)) return false;
+ return true;
+ });
+}
+
+function isIgnoredFindingValue(finding, ignoreValues) {
+ if (!Array.isArray(ignoreValues) || ignoreValues.length === 0) return false;
+ const rule = normalizeIgnoreRule(finding.antipattern);
+ const value = extractFindingIgnoreValue(finding);
+ if (!rule || !value) return false;
+ return ignoreValues.some((entry) => entry.rule === rule && entry.value === value);
+}
+
+export function extractFindingIgnoreValue(finding) {
+ if (!finding || typeof finding !== 'object') return '';
+ const rule = normalizeIgnoreRule(finding.antipattern);
+ if (rule !== 'overused-font') return '';
+ return normalizeIgnoreValue(extractFindingIgnoreValueRaw(finding));
+}
+
+function extractFindingIgnoreValueRaw(finding) {
+ const direct = cleanIgnoreValueDisplay(finding.ignoreValue || finding.value || '');
+ if (direct) return direct;
+
+ const candidates = [finding.detail, finding.snippet].filter((v) => typeof v === 'string' && v);
+ for (const text of candidates) {
+ const primary = text.match(/Primary font:\s*([^()\n;]+)/i);
+ if (primary) return cleanIgnoreValueDisplay(primary[1]);
+
+ const family = text.match(/font-family\s*:\s*["']?([^'",;\n]+)/i);
+ if (family) return cleanIgnoreValueDisplay(family[1]);
+
+ const google = text.match(/[?&]family=([^&:;\n]+)/i);
+ if (google) {
+ try {
+ return cleanIgnoreValueDisplay(decodeURIComponent(google[1]));
+ } catch {
+ return cleanIgnoreValueDisplay(google[1]);
+ }
+ }
+ }
+
+ return '';
+}
+
+function cleanIgnoreValueDisplay(value) {
+ return String(value || '')
+ .trim()
+ .replace(/^["']|["']$/g, '')
+ .replace(/\+/g, ' ')
+ .replace(/\s+/g, ' ');
+}
+
+export function dedupeAgainstCache(findings, cache, sessionId, filePath) {
+ if (!Array.isArray(findings) || findings.length === 0) return [];
+ const fileEntry = ensureFile(cache, sessionId, filePath);
+ const known = new Set(fileEntry.findings || []);
+ const fresh = [];
+ for (const f of findings) {
+ const key = `${f.antipattern}:${f.line || 0}`;
+ if (known.has(key)) continue;
+ known.add(key);
+ fresh.push(f);
+ }
+ return fresh;
+}
+
+export function rememberFindings(cache, sessionId, filePath, findings) {
+ const fileEntry = ensureFile(cache, sessionId, filePath);
+ const known = new Set(fileEntry.findings || []);
+ for (const f of findings) known.add(`${f.antipattern}:${f.line || 0}`);
+ fileEntry.findings = Array.from(known);
+ ensureSession(cache, sessionId).updatedAt = Date.now();
+}
+
+export function renderTemplate(findings, filePath, config, opts = {}) {
+ if (!Array.isArray(findings) || findings.length === 0) return '';
+ const limits = config?.limits || DEFAULT_CONFIG.limits;
+ const cap = Math.max(1, limits.maxFindings || DEFAULT_CONFIG.limits.maxFindings);
+ const maxChars = Math.max(500, limits.maxChars || DEFAULT_CONFIG.limits.maxChars);
+
+ const cwd = opts.cwd || process.cwd();
+ const display = relativize(filePath, cwd);
+ const total = findings.length;
+ const shown = findings.slice(0, cap);
+ const remaining = total - shown.length;
+
+ const header = `${ENVELOPE_PREFIX} Required design corrections in ${display} (${total} issue(s)):`;
+ const lines = shown.map((f) => formatFindingLine(f));
+ const more = remaining > 0
+ ? `... and ${remaining} more (see /impeccable audit).`
+ : null;
+ const footer = directiveFooter(display);
+
+ const blocks = [header, ...lines];
+ if (more) blocks.push(more);
+ blocks.push('');
+ blocks.push(footer);
+ let text = blocks.join('\n');
+
+ if (text.length > maxChars) {
+ text = clampToBudget(header, lines, more, footer, maxChars);
+ }
+ return text;
+}
+
+function renderGroupedTemplate(groups, config, opts = {}) {
+ const realGroups = groups.filter((group) => Array.isArray(group.findings) && group.findings.length > 0);
+ if (realGroups.length === 0) return '';
+ if (realGroups.length === 1) {
+ const [group] = realGroups;
+ return renderTemplate(group.findings, group.filePath, config, opts);
+ }
+
+ const limits = config?.limits || DEFAULT_CONFIG.limits;
+ const cap = Math.max(1, limits.maxFindings || DEFAULT_CONFIG.limits.maxFindings);
+ const maxChars = Math.max(500, limits.maxChars || DEFAULT_CONFIG.limits.maxChars);
+ const cwd = opts.cwd || process.cwd();
+ const total = realGroups.reduce((sum, group) => sum + group.findings.length, 0);
+ const header = `${ENVELOPE_PREFIX} Required design corrections across ${realGroups.length} files (${total} issue(s)):`;
+ const lines = [];
+ let shownCount = 0;
+
+ for (const group of realGroups) {
+ const display = relativize(group.filePath, cwd);
+ lines.push(`${display} (${group.findings.length} issue(s)):`);
+ const remainingCap = Math.max(0, cap - shownCount);
+ const shown = group.findings.slice(0, remainingCap);
+ for (const finding of shown) {
+ lines.push(formatFindingLine(finding));
+ }
+ shownCount += shown.length;
+ const hidden = group.findings.length - shown.length;
+ if (hidden > 0) {
+ lines.push(`- ... ${hidden} more in ${display} (see /impeccable audit).`);
+ }
+ }
+
+ const footer = directiveFooter('the affected files', { grouped: true });
+ let text = [header, ...lines, '', footer].join('\n');
+ if (text.length > maxChars) {
+ text = clampGroupedToBudget(header, lines, footer, maxChars);
+ }
+ return text;
+}
+
+function clampGroupedToBudget(header, lines, footer, maxChars) {
+ const assemble = (linesArr, omitted) => [
+ header,
+ ...linesArr,
+ ...(omitted ? ['... and more (see /impeccable audit).'] : []),
+ '',
+ footer,
+ ].join('\n');
+
+ let working = lines.slice();
+ let omitted = false;
+ let assembled = assemble(working, omitted);
+ while (assembled.length > maxChars && working.length > 1) {
+ working.pop();
+ omitted = true;
+ assembled = assemble(working, omitted);
+ }
+ if (assembled.length > maxChars) {
+ assembled = `${assembled.slice(0, maxChars - 1)}…`;
+ }
+ return assembled;
+}
+
+function clampToBudget(header, lines, more, footer, maxChars) {
+ const assemble = (linesArr, moreText) => {
+ const blocks = [header, ...linesArr];
+ if (moreText) blocks.push(moreText);
+ blocks.push('');
+ blocks.push(footer);
+ return blocks.join('\n');
+ };
+
+ let working = lines.slice();
+ let moreText = more;
+ let assembled = assemble(working, moreText);
+ while (assembled.length > maxChars && working.length > 1) {
+ working.pop();
+ moreText = '... and more (see /impeccable audit).';
+ assembled = assemble(working, moreText);
+ }
+ if (assembled.length > maxChars) {
+ assembled = `${assembled.slice(0, maxChars - 1)}…`;
+ }
+ return assembled;
+}
+
+function formatFindingLine(f) {
+ const prefix = f.line && f.line > 0 ? `- L${f.line}` : '-';
+ const desc = (f.description || '').trim();
+ const name = (f.name || '').trim();
+ // Description from the registry already ends in punctuation; join with a
+ // single space. `name` may have a trailing period already, keep it clean.
+ const nameSegment = name ? `${name.replace(/\.+\s*$/, '')}.` : '';
+ const ignoreCommand = formatFindingIgnoreCommand(f);
+ const ignoreSegment = ignoreCommand
+ ? ` If the user explicitly confirms this value is intentional: \`${ignoreCommand}\`.`
+ : '';
+ return `${prefix} [${f.antipattern}] ${nameSegment} ${desc}${ignoreSegment}`.replace(/\s+/g, ' ').trim();
+}
+
+function formatFindingIgnoreCommand(finding) {
+ if (!finding || typeof finding !== 'object') return '';
+ const rule = normalizeIgnoreRule(finding.antipattern);
+ if (!rule) return '';
+ const normalizedValue = extractFindingIgnoreValue(finding);
+ if (!normalizedValue) return '';
+ const value = extractFindingIgnoreValueRaw(finding);
+ const valueArg = quoteCommandArg(value);
+ const reason = quoteCommandArg(`User confirmed ${value} is intentional`);
+ return `/impeccable hooks ignore-value ${rule} ${valueArg} --shared --reason ${reason}`;
+}
+
+function quoteCommandArg(value) {
+ const text = String(value || '').trim();
+ if (/^[A-Za-z0-9._:-]+$/.test(text)) return text;
+ return `"${text.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
+}
+
+function relativize(filePath, cwd) {
+ try {
+ const rel = path.relative(cwd, filePath);
+ if (!rel || rel.startsWith('..')) return filePath;
+ return rel.split(path.sep).join('/');
+ } catch {
+ return filePath;
+ }
+}
+
+// Codex `apply_patch` exposes the raw patch in `tool_input.command`, not
+// `tool_input.file_path`. Claude Code may send both; parse the patch body
+// so we can scan the file(s) the tool actually touched.
+// https://developers.openai.com/codex/hooks#posttooluse
+const APPLY_PATCH_FILE_RE = /^\*\*\* (?:Update|Add) File: (.+)$/gm;
+
+export function parseApplyPatchPaths(command, projectCwd) {
+ if (!command || typeof command !== 'string') return [];
+ const out = [];
+ for (const m of command.matchAll(APPLY_PATCH_FILE_RE)) {
+ let p = (m[1] || '').trim();
+ if (!p) continue;
+ if (!path.isAbsolute(p)) p = path.resolve(projectCwd, p);
+ out.push(p);
+ }
+ return out;
+}
+
+export function resolveTargetFiles(event, projectCwd) {
+ const ti = event?.tool_input;
+ const out = [];
+ const add = (filePath) => {
+ if (typeof filePath !== 'string' || !filePath) return;
+ if (!out.includes(filePath)) out.push(filePath);
+ };
+
+ if (event?.tool_name === 'apply_patch' && ti && typeof ti.command === 'string') {
+ for (const filePath of parseApplyPatchPaths(ti.command, projectCwd)) add(filePath);
+ }
+ if (ti && typeof ti.file_path === 'string' && ti.file_path) {
+ add(ti.file_path);
+ }
+ // Cursor Write / StrReplace use `path`, not `file_path`.
+ if (ti && typeof ti.path === 'string' && ti.path) {
+ add(ti.path);
+ }
+ if (typeof event?.file_path === 'string' && event.file_path) {
+ add(event.file_path);
+ }
+ return out;
+}
+
+export function resolveHarness(env = {}, event = null) {
+ const explicit = env?.IMPECCABLE_HOOK_HARNESS;
+ if (explicit === 'cursor') return 'cursor';
+ if (explicit === 'claude' || explicit === 'codex') return 'claude';
+ if (typeof event?.conversation_id === 'string' && event.conversation_id) return 'cursor';
+ return 'claude';
+}
+
+export function normalizeHookEvent(event, projectCwd, harness = 'claude') {
+ if (!event || typeof event !== 'object' || harness !== 'cursor') return event;
+
+ const cwd = event.cwd
+ || (Array.isArray(event.workspace_roots) && event.workspace_roots[0])
+ || envProjectDir(projectCwd)
+ || projectCwd;
+ const sessionId = event.session_id || event.conversation_id || 'unknown';
+
+ const ti = event.tool_input && typeof event.tool_input === 'object' ? event.tool_input : {};
+ const filePath = ti.file_path || ti.path || event.file_path;
+ if (filePath) {
+ return {
+ ...event,
+ cwd,
+ session_id: sessionId,
+ tool_input: { ...ti, file_path: filePath },
+ };
+ }
+
+ return { ...event, cwd, session_id: sessionId };
+}
+
+function envProjectDir(fallback) {
+ if (typeof process.env.CURSOR_PROJECT_DIR === 'string' && process.env.CURSOR_PROJECT_DIR) {
+ return process.env.CURSOR_PROJECT_DIR;
+ }
+ return fallback;
+}
+
+// UI components often keep slop in a sibling/co-located stylesheet while the
+// JSX edit is what triggered PostToolUse. Scan those styles too so an App.jsx
+// patch doesn't report "clean" while styles.css still has Inter/bounce/etc.
+const UI_CODE_EXTS = new Set(['.jsx', '.tsx', '.vue', '.svelte', '.astro']);
+const STYLE_EXTS = new Set(['.css', '.scss', '.sass', '.less']);
+const CO_SCAN_STYLE_NAMES = [
+ 'styles.css', 'styles.scss', 'styles.sass', 'styles.less',
+ 'index.css', 'index.scss', 'index.sass', 'index.less',
+ 'global.css', 'global.scss', 'global.sass', 'global.less',
+ 'globals.css', 'globals.scss', 'globals.sass', 'globals.less',
+];
+const MAX_SCAN_TARGETS = 6;
+
+const STATIC_STYLE_IMPORT_RE = /import\s+(?:[\w*{}\s,$]+\s+from\s+)?['"]([^'"]+\.(?:css|scss|sass|less))['"]/gi;
+
+function hasPathTraversal(filePath) {
+ return typeof filePath === 'string' && filePath.includes('..');
+}
+
+function isInsideProject(filePath, projectCwd) {
+ if (!filePath || !projectCwd || hasPathTraversal(filePath)) return false;
+ try {
+ const rel = path.relative(projectCwd, filePath);
+ return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));
+ } catch {
+ return false;
+ }
+}
+
+export function parseStaticStyleImports(content, fromFile, projectCwd) {
+ if (!content || typeof content !== 'string') return [];
+ const dir = path.dirname(fromFile);
+ const out = [];
+ for (const m of content.matchAll(STATIC_STYLE_IMPORT_RE)) {
+ let p = (m[1] || '').trim();
+ if (!p) continue;
+ if (p.startsWith('.')) p = path.resolve(dir, p);
+ else if (!path.isAbsolute(p)) p = path.resolve(projectCwd, p);
+ if (!isInsideProject(p, projectCwd)) continue;
+ out.push(p);
+ }
+ return out;
+}
+
+export function coLocatedStylesheets(filePath) {
+ const dir = path.dirname(filePath);
+ const base = path.basename(filePath, path.extname(filePath));
+ const candidates = new Set([
+ path.join(dir, `${base}.css`),
+ path.join(dir, `${base}.module.css`),
+ path.join(dir, `${base}.scss`),
+ path.join(dir, `${base}.module.scss`),
+ path.join(dir, `${base}.sass`),
+ path.join(dir, `${base}.module.sass`),
+ path.join(dir, `${base}.less`),
+ path.join(dir, `${base}.module.less`),
+ ]);
+ for (const name of CO_SCAN_STYLE_NAMES) {
+ candidates.add(path.join(dir, name));
+ }
+ return [...candidates].filter((p) => fs.existsSync(p));
+}
+
+export function normalizeScanTargets(primaryTargets, projectCwd) {
+ if (!Array.isArray(primaryTargets) || primaryTargets.length === 0) return [];
+ const ordered = [];
+ const seen = new Set();
+ const baseCwd = projectCwd || process.cwd();
+ const normalizeTarget = (p) => {
+ // Preserve literal `..` segments so downstream sensitive-path checks
+ // still fire. path.resolve would collapse `/foo/../etc/passwd`.
+ if (hasPathTraversal(p)) return p;
+ return path.isAbsolute(p) ? p : path.resolve(baseCwd, p);
+ };
+ const add = (p) => {
+ if (ordered.length >= MAX_SCAN_TARGETS) return;
+ const abs = normalizeTarget(p);
+ if (seen.has(abs)) return;
+ seen.add(abs);
+ ordered.push(abs);
+ return abs;
+ };
+
+ for (const p of primaryTargets) add(p);
+ return ordered;
+}
+
+export function expandScanTargets(primaryTargets, projectCwd) {
+ const ordered = normalizeScanTargets(primaryTargets, projectCwd);
+ if (ordered.length === 0) return [];
+ const seen = new Set(ordered);
+ const baseCwd = projectCwd || process.cwd();
+ const add = (p) => {
+ if (ordered.length >= MAX_SCAN_TARGETS) return;
+ const abs = hasPathTraversal(p) ? p : (path.isAbsolute(p) ? p : path.resolve(baseCwd, p));
+ if (seen.has(abs)) return;
+ seen.add(abs);
+ ordered.push(abs);
+ return abs;
+ };
+
+ const normalizedPrimaries = [];
+ for (const p of ordered) normalizedPrimaries.push(p);
+
+ for (const p of normalizedPrimaries) {
+ if (ordered.length >= MAX_SCAN_TARGETS) break;
+ if (!isInsideProject(p, baseCwd)) continue;
+ const ext = path.extname(p).toLowerCase();
+ if (STYLE_EXTS.has(ext) || !UI_CODE_EXTS.has(ext)) continue;
+
+ let content = '';
+ try { content = fs.readFileSync(p, 'utf-8'); } catch { /* unreadable primary */ }
+
+ for (const imp of parseStaticStyleImports(content, p, projectCwd)) {
+ add(imp);
+ if (ordered.length >= MAX_SCAN_TARGETS) break;
+ }
+ for (const col of coLocatedStylesheets(p)) {
+ add(col);
+ if (ordered.length >= MAX_SCAN_TARGETS) break;
+ }
+ }
+
+ return ordered;
+}
+
+export function writeAuditLog(env, entry) {
+ const target = env?.IMPECCABLE_HOOK_LOG;
+ if (!target || typeof target !== 'string') return false;
+ try {
+ const expanded = target.startsWith('~/')
+ ? path.join(process.env.HOME || process.env.USERPROFILE || '.', target.slice(2))
+ : target;
+ fs.mkdirSync(path.dirname(expanded), { recursive: true });
+ const line = JSON.stringify({ ts: new Date().toISOString(), ...entry }) + '\n';
+ fs.appendFileSync(expanded, line);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+const DETECTOR_CANDIDATES = [
+ path.join(__dirname, 'detector', 'detect-antipatterns.mjs'),
+ path.join(__dirname, '..', '..', 'cli', 'engine', 'detect-antipatterns.mjs'),
+ path.join(__dirname, '..', '..', '..', 'cli', 'engine', 'detect-antipatterns.mjs'),
+];
+
+let detectorCache = null;
+export async function loadDetector(candidates = DETECTOR_CANDIDATES) {
+ if (detectorCache) return detectorCache;
+ const found = candidates.find((c) => fs.existsSync(c));
+ if (!found) return null;
+ const mod = await import(pathToFileURL(found));
+ detectorCache = { detectText: mod.detectText, detectHtml: mod.detectHtml };
+ return detectorCache;
+}
+
+// For tests: allow injecting a detector implementation.
+export function setDetectorForTesting(impl) {
+ detectorCache = impl;
+}
+
+// ────────────────────────────────────────────────────────────────────────
+// Nudge/steer messages for the no-silent-fires policy.
+//
+// The hook is designed to be a conversational presence: every fire that
+// actually scans a file emits a developer-role message into the model's
+// next turn. Three states map to three templates:
+//
+// 1. **Fresh findings** → `renderTemplate` (existing, imperative).
+// 2. **Pending findings** → `renderPendingAck` (re-nudge for issues the
+// model was already told about in this
+// session but hasn't fixed yet).
+// 3. **Truly clean** → `renderCleanAck` (short positive nudge that
+// keeps the design discipline in context).
+//
+// All three are short (≤ ~40 tokens each) so the cumulative cost stays
+// bounded across a long active editing session. Users who explicitly want
+// silence-on-clean can set `IMPECCABLE_HOOK_QUIET=1` — runHook checks that
+// env before emitting #2 or #3.
+//
+// Why not stay silent on dedup-clean? Earlier versions did. The model
+// quickly forgets the prior reminder once tool output scrolls past it, so
+// re-nudging on the same file with a short "still pending" line keeps the
+// pressure on. The wording deliberately points back to "earlier this
+// session" so the model knows it's a re-mind, not a new finding.
+// ────────────────────────────────────────────────────────────────────────
+
+const STEER_LINE = 'Keep typography hierarchy, spacing rhythm, and color contrast intentional on the next change.';
+
+export function renderCleanAck(filePath, opts = {}) {
+ const cwd = opts.cwd || process.cwd();
+ const display = relativize(filePath, cwd);
+ return `${ENVELOPE_PREFIX} Design hook scanned ${display}. No anti-patterns. ${STEER_LINE}`;
+}
+
+export function renderPendingAck(filePath, knownFindings, opts = {}) {
+ const cwd = opts.cwd || process.cwd();
+ const display = relativize(filePath, cwd);
+ const count = knownFindings.length;
+ // `knownFindings` here are the cache strings like "side-tab:3".
+ const sample = knownFindings.slice(0, 3).join(', ');
+ const more = count > 3 ? `, +${count - 3} more` : '';
+ return `${ENVELOPE_PREFIX} Design hook scanned ${display}. Still has ${count} issue(s) flagged earlier this session (${sample}${more}). Address them before finalizing — the previous reminder still applies.`;
+}
+
+export function shouldEmitAckForFile(filePath) {
+ return ACK_EXTS.has(path.extname(String(filePath || '')).toLowerCase());
+}
+
+// The directive footer is the part of the hook output that steers model
+// behavior. Three intentional moves:
+// 1. **Imperative, not advisory.** "Fix these..." beats "Consider
+// revising..." which the model treats as a soft suggestion it can
+// override when the user asked for any kind of throwaway / demo UI.
+// 2. **Explicit exception clause.** Without it, the model will try to
+// "fix" intentional bad fixtures, anti-pattern examples in docs, or
+// test cases. Naming the exception inline beats hoping the model
+// infers it from context.
+// 3. **Acknowledgement instruction.** Hook output is injected as
+// developer-role context, not a chat turn, so the user never sees the
+// raw envelope. Asking the model to surface the fix in its reply is
+// the cheapest way to make the feedback loop visible to the user.
+function directiveFooter(display, opts = {}) {
+ const ignoreFileCommand = `/impeccable hooks ignore-file ${quoteCommandArg(display)}`;
+ const fileIgnoreGuidance = opts.grouped
+ ? 'run `/impeccable hooks ignore-file <path>` for the specific file'
+ : `run \`${ignoreFileCommand}\``;
+ return [
+ 'Fix these in your next reply before finalizing. Acknowledge what you changed so the user sees the correction.',
+ '',
+ 'Skip the fix only if the user explicitly asked for an intentionally bad UI, an anti-pattern example, a test fixture, or documentation of bad design. In that case, say so and continue.',
+ '',
+ `Do not add source comments such as \`impeccable: ignore\`; those pollute the code and do not suppress hook findings. Do not add hook ignores unless the user explicitly confirms the finding is intentional. Prefer the narrowest persisted exception: run the exact \`/impeccable hooks ignore-value ... --shared\` command shown next to a value-specific finding. For \`overused-font\`, use \`ignore-value\` for a specific font and use \`/impeccable hooks ignore-rule overused-font --all-values\` only when the user asks to ignore overused fonts generally. For file-specific findings without an ignore-value command, ${fileIgnoreGuidance}; use \`/impeccable hooks ignore-rule <id>\` only when the user asks to suppress the whole non-value-specific rule. Run /impeccable audit for the full pass.`,
+ ].join('\n');
+}
+
+/**
+ * Run the hook with explicit dependencies. Returns a result object:
+ * { exitCode, stdout, audit, reason? }
+ *
+ * Never throws. All errors are converted to `exitCode: 0` + audit entry.
+ */
+export async function runHook({ stdinJson, env = {}, cwd = process.cwd(), now = Date.now, detector } = {}) {
+ const audit = { ts: new Date(now()).toISOString(), event: 'PostToolUse' };
+ const result = (extra) => ({ exitCode: 0, stdout: '', audit: { ...audit, ...extra } });
+
+ try {
+ // Re-entrancy guard.
+ if (depthIsSet(env.IMPECCABLE_HOOK_DEPTH) || depthIsSet(env.CLAUDE_HOOK_DEPTH)) {
+ return result({ reentrant: true, durationMs: 0 });
+ }
+
+ if (truthy(env.IMPECCABLE_HOOK_DISABLED)) {
+ return result({ skipped: 'env-disabled', durationMs: 0 });
+ }
+
+ const started = Date.now();
+
+ let event;
+ try {
+ event = typeof stdinJson === 'string' ? JSON.parse(stdinJson) : stdinJson;
+ } catch {
+ return result({ skipped: 'stdin-malformed', durationMs: Date.now() - started });
+ }
+ if (!event || typeof event !== 'object') {
+ return result({ skipped: 'stdin-empty', durationMs: Date.now() - started });
+ }
+
+ const harness = resolveHarness(env, event);
+ event = normalizeHookEvent(event, cwd, harness);
+ audit.harness = harness;
+
+ const projectCwd = event.cwd || cwd;
+ const primaryFiles = normalizeScanTargets(resolveTargetFiles(event, projectCwd), projectCwd);
+ const primaryFileSet = new Set(primaryFiles);
+ const targetFiles = expandScanTargets(primaryFiles, projectCwd);
+ audit.session = event.session_id || null;
+ if (event.tool_name) audit.tool = event.tool_name;
+
+ if (targetFiles.length === 0) {
+ return result({ skipped: 'no-file-path', durationMs: Date.now() - started });
+ }
+
+ const config = readConfig(projectCwd);
+ if (config.enabled === false) {
+ return result({ skipped: 'config-disabled', durationMs: Date.now() - started });
+ }
+
+ const cache = readCache(projectCwd);
+ const sessionId = event.session_id || 'unknown';
+ const det = detector || await loadDetector();
+ if (!det || typeof det.detectText !== 'function') {
+ persistCache(projectCwd, cache);
+ return result({ skipped: 'detector-missing', durationMs: Date.now() - started });
+ }
+
+ let pendingWinner = null;
+ let cleanWinner = null;
+ const freshGroups = [];
+ let suppressionWinner = null;
+ let detectorThrewAny = false;
+ let lastSkip = 'no-scannable-file';
+ let suppressedHit = false;
+
+ for (const filePath of targetFiles) {
+ audit.file = filePath;
+
+ if (hasPathTraversal(filePath) || SENSITIVE_PATH.test(filePath)) {
+ lastSkip = 'sensitive';
+ continue;
+ }
+ if (GENERATED_PATH.test(filePath)) {
+ lastSkip = 'generated';
+ continue;
+ }
+
+ const ext = path.extname(filePath).toLowerCase();
+ audit.ext = ext;
+ if (!ALLOWED_EXTS.has(ext)) {
+ lastSkip = 'extension';
+ continue;
+ }
+
+ const relForMatch = relativize(filePath, projectCwd);
+ if (matchesAnyGlob(relForMatch, config.ignoreFiles) || matchesAnyGlob(filePath, config.ignoreFiles)) {
+ lastSkip = 'config-ignore-file';
+ continue;
+ }
+ if (!fs.existsSync(filePath)) {
+ lastSkip = 'file-missing';
+ continue;
+ }
+
+ if (primaryFileSet.has(filePath)) {
+ const editCount = bumpEditCount(cache, sessionId, filePath);
+ audit.editCount = editCount;
+
+ if (editCount > EDIT_COUNT_THRESHOLD) {
+ const wasJustCrossed = editCount === EDIT_COUNT_THRESHOLD + 1;
+ if (wasJustCrossed && !suppressionWinner) {
+ suppressionWinner = { filePath };
+ }
+ lastSkip = 'suppressed';
+ suppressedHit = true;
+ continue;
+ }
+ }
+
+ const content = fs.readFileSync(filePath, 'utf-8');
+ let findings;
+ let detectorThrew = false;
+ if ((ext === '.html' || ext === '.htm') && typeof det.detectHtml === 'function') {
+ try { findings = await det.detectHtml(filePath); } catch { findings = []; detectorThrew = true; }
+ } else {
+ try { findings = await det.detectText(content, filePath); } catch { findings = []; detectorThrew = true; }
+ }
+
+ const filtered = filterFindings(findings || [], content, ext, config);
+ const fresh = dedupeAgainstCache(filtered, cache, sessionId, filePath);
+ audit.findings = (findings || []).length;
+ audit.freshFindings = fresh.length;
+
+ if (fresh.length > 0) {
+ rememberFindings(cache, sessionId, filePath, fresh);
+ freshGroups.push({ filePath, findings: fresh });
+ continue;
+ }
+
+ if (detectorThrew) {
+ detectorThrewAny = true;
+ continue;
+ }
+
+ if (filtered.length > 0 && !pendingWinner) {
+ const known = (ensureFile(cache, sessionId, filePath).findings || []).slice();
+ pendingWinner = { filePath, known };
+ } else if (filtered.length === 0 && !cleanWinner) {
+ cleanWinner = { filePath };
+ }
+ }
+
+ persistCache(projectCwd, cache);
+
+ if (freshGroups.length > 0) {
+ const firstGroup = freshGroups[0];
+ const text = renderGroupedTemplate(freshGroups, config, { cwd: projectCwd });
+ const allFindings = freshGroups.flatMap((group) => group.findings);
+ return {
+ exitCode: 0,
+ stdout: payload(text, 'PostToolUse', harness),
+ emission: {
+ kind: 'fresh',
+ file: firstGroup.filePath,
+ findings: firstGroup.findings,
+ groups: freshGroups,
+ },
+ audit: {
+ ...audit,
+ file: firstGroup.filePath,
+ emitted: true,
+ freshFiles: freshGroups.length,
+ freshFindings: allFindings.length,
+ chars: text.length,
+ durationMs: Date.now() - started,
+ },
+ };
+ }
+
+ if (detectorThrewAny && !pendingWinner && !cleanWinner) {
+ return result({ emitted: false, error: 'detector-threw', durationMs: Date.now() - started });
+ }
+
+ if (truthy(env.IMPECCABLE_HOOK_QUIET)) {
+ return result({ emitted: false, quiet: true, durationMs: Date.now() - started });
+ }
+
+ if (pendingWinner && shouldEmitAckForFile(pendingWinner.filePath)) {
+ const text = renderPendingAck(pendingWinner.filePath, pendingWinner.known, { cwd: projectCwd });
+ return {
+ exitCode: 0,
+ stdout: payload(text, 'PostToolUse', harness),
+ emission: { kind: 'pending', file: pendingWinner.filePath, known: pendingWinner.known },
+ audit: {
+ ...audit,
+ file: pendingWinner.filePath,
+ emitted: true,
+ kind: 'pending',
+ pending: pendingWinner.known.length,
+ chars: text.length,
+ durationMs: Date.now() - started,
+ },
+ };
+ }
+
+ if (suppressionWinner) {
+ const text = suppressionNotice(relativize(suppressionWinner.filePath, projectCwd));
+ return {
+ exitCode: 0,
+ stdout: payload(text, 'PostToolUse', harness),
+ emission: { kind: 'suppression', file: suppressionWinner.filePath },
+ audit: {
+ ...audit,
+ file: suppressionWinner.filePath,
+ suppressed: true,
+ emitted: true,
+ durationMs: Date.now() - started,
+ },
+ };
+ }
+
+ if (cleanWinner && shouldEmitAckForFile(cleanWinner.filePath)) {
+ const text = renderCleanAck(cleanWinner.filePath, { cwd: projectCwd });
+ return {
+ exitCode: 0,
+ stdout: payload(text, 'PostToolUse', harness),
+ emission: { kind: 'clean', file: cleanWinner.filePath },
+ audit: {
+ ...audit,
+ file: cleanWinner.filePath,
+ emitted: true,
+ kind: 'clean',
+ chars: text.length,
+ durationMs: Date.now() - started,
+ },
+ };
+ }
+
+ if (pendingWinner || cleanWinner) {
+ return result({ emitted: false, skipped: 'non-ui-ack', durationMs: Date.now() - started });
+ }
+
+ if (suppressedHit) {
+ return result({ suppressed: true, emitted: false, durationMs: Date.now() - started });
+ }
+
+ return result({ skipped: lastSkip, durationMs: Date.now() - started });
+ } catch (err) {
+ return {
+ exitCode: 0,
+ stdout: '',
+ audit: { ...audit, error: String(err && err.message ? err.message : err) },
+ };
+ }
+}
+
+export function payload(text, eventName = 'PostToolUse', harness = 'claude') {
+ if (harness === 'cursor') {
+ return JSON.stringify({ additional_context: text });
+ }
+ return JSON.stringify({
+ hookSpecificOutput: { hookEventName: eventName, additionalContext: text },
+ });
+}
diff --git a/.cursor/skills/impeccable/scripts/hook.mjs b/.cursor/skills/impeccable/scripts/hook.mjs
new file mode 100644
index 000000000..b862f8033
--- /dev/null
+++ b/.cursor/skills/impeccable/scripts/hook.mjs
@@ -0,0 +1,61 @@
+#!/usr/bin/env node
+/**
+ * Impeccable design hook — PostToolUse entry point.
+ *
+ * Reads the Claude Code / Codex / Cursor hook event from stdin, runs the design
+ * detector against the touched file, and emits a system reminder via
+ * `hookSpecificOutput.additionalContext` when findings exist.
+ *
+ * Contract: never break a turn. Always exit 0. Clean files emit a small ack
+ * unless quiet mode is enabled.
+ *
+ * Most logic lives in `hook-lib.mjs` so it is unit-testable without a
+ * subprocess. This file is the thin stdin/stdout adapter.
+ */
+
+import { runHook, 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');
+}
+
+async function main() {
+ // Snapshot the inherited env FIRST so the re-entrancy guard checks the
+ // parent's value, not the value we are about to export for any child
+ // processes the hook might ever spawn.
+ const inheritedEnv = { ...process.env };
+ process.env.IMPECCABLE_HOOK_DEPTH = process.env.IMPECCABLE_HOOK_DEPTH || '1';
+
+ let stdinJson = '';
+ try { stdinJson = await readStdin(); } catch { /* fall through */ }
+
+ const result = await runHook({
+ stdinJson,
+ env: inheritedEnv,
+ cwd: process.cwd(),
+ });
+
+ writeAuditLog(process.env, result.audit);
+
+ if (result.stdout) process.stdout.write(result.stdout);
+ process.exit(result.exitCode || 0);
+}
+
+main().catch((err) => {
+ // Last-ditch: never break the agent's turn even if something we did not
+ // anticipate goes wrong. Audit-log the failure if logging is enabled.
+ try {
+ writeAuditLog(process.env, {
+ ts: new Date().toISOString(),
+ event: 'PostToolUse',
+ error: String(err && err.message ? err.message : err),
+ });
+ } catch { /* swallow */ }
+ if (process.env.IMPECCABLE_HOOK_DEBUG) {
+ process.stderr.write(`[impeccable-hook] ${err}\n`);
+ }
+ process.exit(0);
+});
diff --git a/.cursor/skills/impeccable/scripts/live-inject.mjs b/.cursor/skills/impeccable/scripts/live-inject.mjs
index 4e5c5dc0a..69ce530c1 100644
--- a/.cursor/skills/impeccable/scripts/live-inject.mjs
+++ b/.cursor/skills/impeccable/scripts/live-inject.mjs
@@ -32,6 +32,8 @@ const IGNORE_MARKER_CLOSE = '# impeccable-live-ignore-end';
export const LIVE_IGNORE_PATTERNS = Object.freeze([
'.impeccable/hook.cache.json',
+ '.impeccable/hook.pending.json',
+ '.impeccable/hook.local.json',
'.impeccable/live/server.json',
'.impeccable/live/sessions/',
'.impeccable/live/previews/',
diff --git a/.gemini/skills/impeccable/SKILL.md b/.gemini/skills/impeccable/SKILL.md
index 4c555696e..50d3db7b2 100644
--- a/.gemini/skills/impeccable/SKILL.md
+++ b/.gemini/skills/impeccable/SKILL.md
@@ -123,7 +123,7 @@ If someone could look at this interface and say "AI made that" without doubt, it
| `optimize [target]` | Fix | Diagnose and fix UI performance | [reference/optimize.md](reference/optimize.md) |
| `live` | Iterate | Visual variant mode: pick elements in the browser, generate alternatives | [reference/live.md](reference/live.md) |
-Plus two management commands: `pin <command>` and `unpin <command>`, detailed below.
+Plus three management commands: `pin <command>`, `unpin <command>`, and `hooks <on|off|status|...>`, detailed below.
### Routing rules
@@ -140,7 +140,7 @@ Plus two management commands: `pin <command>` and `unpin <command>`, detailed be
**If `scan.targets` is non-empty, run `node .gemini/skills/impeccable/scripts/detect.mjs --json <scan.targets joined by spaces>` once** (the bundled detector over local files: no network, no npx). `scan.via` tells you what they are: `git-changes` (the markup/style files in your dirty tree, the most relevant set), `source-dir` (e.g. `src`, `app`), `html`, or `root`. Fold the hits into your picks: many quality / contrast hits → `audit` or `polish`; a specific slop family → the matching command (gradient text or eyebrows → `quieter` / `typeset`, flat or gray palette → `colorize`, and so on). It's a real, current signal that beats guessing. If detect errors or the tree is large and slow, skip it and recommend the user run `audit` themselves; never block the suggestion on it.
Keep it to 2-3 pointed picks with the exact command to type. The menu stays the fallback; the recommendation is the lede.
-2. **First word matches a command**: load its reference file and follow its instructions. Everything after the command name is the target.
+2. **First word matches a command** (table above OR `pin` / `unpin` / `hooks`): load its reference file and follow its instructions. Everything after the command name is the target.
3. **First word doesn't match, but the intent clearly maps to one command** (e.g. "fix the spacing" → `layout`, "rewrite this error message" → `clarify`, "the colors feel flat" → `colorize`): load that command's reference and proceed as if invoked. If two commands could fit, ask once which.
4. **No clear command match**: general design invocation. Apply the setup steps, the General rules, and the loaded register reference, using the full argument as context.
@@ -158,4 +158,8 @@ If the first word is `craft`, setup still runs first, but [reference/craft.md](r
node .gemini/skills/impeccable/scripts/pin.mjs <pin|unpin> <command>
```
-Valid `<command>` is any command from the table above. Report the script's result concisely. Confirm the new shortcut on success, relay stderr verbatim on error.
\ No newline at end of file
+Valid `<command>` is any command from the table above. Report the script's result concisely. Confirm the new shortcut on success, relay stderr verbatim on error.
+
+## Hooks
+
+`/impeccable hooks <on|off|status|ignore-rule|ignore-file|ignore-value|reset>` manages the design detector hook for this project. The hook auto-runs the detector after direct UI file edits and surfaces findings as system reminders. Full flow is in [reference/hooks.md](reference/hooks.md); load it when the user invokes `/impeccable hooks` with any argument.
\ No newline at end of file
diff --git a/.gemini/skills/impeccable/reference/hooks.md b/.gemini/skills/impeccable/reference/hooks.md
new file mode 100644
index 000000000..189c35b29
--- /dev/null
+++ b/.gemini/skills/impeccable/reference/hooks.md
@@ -0,0 +1,82 @@
+# /impeccable hooks
+
+Manage the **design detector hook** for the current project.
+
+The hook runs the impeccable design detector on direct file edits to design-relevant files (`.tsx`, `.jsx`, `.html`, `.vue`, `.svelte`, `.astro`, `.css`, `.scss`, `.sass`, `.less`, `.ts`, `.js`). Claude Code and Codex use `PostToolUse` and push a short system reminder into the agent's context after the edit; findings get a correction prompt, pending issues get a re-nudge, and clean UI-ish files get a short ack unless `IMPECCABLE_HOOK_QUIET=1` is set. Plain `.ts` and `.js` files are still scanned, but stay quiet unless the detector finds something. Cursor uses `preToolUse` to block bad proposed writes before they land and stays silent when it allows a clean write.
+
+This command toggles the hook **per project** by editing `.impeccable/hook.json`. Local-only ignore policy lives in `.impeccable/hook.local.json`, which is gitignored. To disable globally, set `IMPECCABLE_HOOK_DISABLED=1` in your shell environment.
+
+Supported harnesses: Claude Code (`.claude/settings.json` in the project), Codex (`.codex/hooks.json` in the project), and Cursor (`.cursor/hooks.json` in the project).
+
+On **Cursor**, `preToolUse` checks proposed Write/Edit/Shell write content and denies only when the real detector finds an issue. The denial message is visible to the agent as the tool error, so the agent can reconsider before the bad write lands.
+
+## Routing
+
+The first argument is the action. Defaults to `status`.
+
+| Action | What it does |
+|---|---|
+| `status` | Print current state, shared/local config paths, ignored rules / files / values, env override. |
+| `on` | Set `enabled: true` in `.impeccable/hook.json`. |
+| `off` | Set `enabled: false` in `.impeccable/hook.json`. |
+| `ignore-rule <id>` | Append `<id>` to `ignoreRules`; for `overused-font`, requires `--all-values`. |
+| `ignore-file <glob>` | Append `<glob>` to `ignoreFiles`. |
+| `ignore-value <id> <value> [--shared] [--reason "..."]` | Append a rule/value suppression to shared `.impeccable/hook.json`. |
+| `ignore-value <id> <value> --local [--reason "..."]` | Append a private rule/value suppression to `.impeccable/hook.local.json`. |
+| `reset` | Delete the project config, dedup cache, and Cursor pending queue. |
+
+## Flow
+
+1. Resolve the action from the user's argument. If no action was given, default to `status`.
+2. Invoke the admin script and pass the user's output through verbatim:
+
+ ```bash
+ node .gemini/skills/impeccable/scripts/hook-admin.mjs <action> [args...]
+ ```
+
+3. If `<action>` is `off`, follow up with a one-line note: "Done. New edits will not trigger the design hook in this project until you run `/impeccable hooks on`."
+4. If `<action>` is `on`, follow up with: "Done. The design hook will fire after the next Edit/Write/MultiEdit on a UI file."
+5. If `<action>` is `ignore-value`, `ignore-file`, or `ignore-rule`, just print the script output. The default scope is shared `.impeccable/hook.json`; add `--local` only when the user explicitly asks for a private exception.
+6. If `<action>` is `status`, just print the script output. Do not add commentary unless the user asked a follow-up question.
+
+## Intentional findings
+
+The hook itself never writes ignore config. Persist an exception only after the user explicitly confirms the flagged issue is intentional, and always go through `hook-admin.mjs`.
+
+Prefer the narrowest exception:
+
+- If the finding line shows an exact `ignore-value` command, run that command. This writes shared `.impeccable/hook.json` by default.
+- For `overused-font`, use `ignore-value` when the user confirms a specific font. Do not use `ignore-rule overused-font` for a specific font.
+- If the finding has no value-specific command, such as `side-tab`, prefer `ignore-file <path>` for the current file.
+- Use `ignore-rule <id>` only when the user asks to suppress that whole rule across the project. For broad overused-font suppression, use `ignore-rule overused-font --all-values` only when the user asks to ignore overused fonts generally.
+- Do not add source comments such as `impeccable: ignore`; inline comments pollute code and are not a supported suppression mechanism.
+
+Example value-specific exception:
+
+```bash
+node .gemini/skills/impeccable/scripts/hook-admin.mjs ignore-value overused-font Inter --shared --reason "User confirmed Inter is intentional"
+```
+
+Example whole-rule font exception:
+
+```bash
+node .gemini/skills/impeccable/scripts/hook-admin.mjs ignore-rule overused-font --all-values --reason "User asked to ignore overused fonts generally"
+```
+
+Example file-scoped exception:
+
+```bash
+node .gemini/skills/impeccable/scripts/hook-admin.mjs ignore-file "src/legacy/Card.tsx"
+```
+
+## Constraints
+
+- Never modify `.impeccable/hook.json` or `.impeccable/hook.local.json` by hand from this command. Always go through `hook-admin.mjs` so writes stay validated and the file shape stays consistent.
+- Do not edit the hook scripts themselves (`hook.mjs`, `hook-lib.mjs`, `hook-before-edit.mjs`) from this flow. Those are skill plumbing.
+- Cursor can block a proposed write when the detector finds a real issue. Claude Code and Codex do not block the edit; they emit a post-edit reminder instead. Disabling stops both blocking and reminders.
+- The hook is bundled with the Impeccable skill and installed through project-local manifests: `.claude/settings.json`, `.codex/hooks.json`, and `.cursor/hooks.json`. On Codex, the user must approve the hook via `/hooks` the first time. On Cursor, confirm hooks are enabled under Settings -> Hooks.
+
+## Failure modes
+
+- If `.impeccable/hook.json` or `.impeccable/hook.local.json` is unreadable or malformed, the hook ignores that file and uses the remaining valid config/defaults. `hook-admin.mjs status` will show malformed files as ignored.
+- If the user asks to "disable the hook" globally, suggest both options: `IMPECCABLE_HOOK_DISABLED=1` env var (one-shot, follows the shell), and `/impeccable hooks off` (persistent for this project, committable).
diff --git a/.gemini/skills/impeccable/scripts/detector/engines/regex/detect-text.mjs b/.gemini/skills/impeccable/scripts/detector/engines/regex/detect-text.mjs
index fd0d9c73f..4c0777c93 100644
--- a/.gemini/skills/impeccable/scripts/detector/engines/regex/detect-text.mjs
+++ b/.gemini/skills/impeccable/scripts/detector/engines/regex/detect-text.mjs
@@ -446,7 +446,7 @@ function detectText(content, filePath, options = {}) {
// Run regex matchers on the full file content (catches Tailwind classes, inline styles)
// Enable block context for CSS files where related properties span multiple lines
- const cssLike = new Set(['.css', '.scss', '.less']);
+ const cssLike = new Set(['.css', '.scss', '.sass', '.less']);
findings.push(...runRegexMatchers(lines, filePath, 0, cssLike.has(ext) || null, {
profile,
phase: 'source',
diff --git a/.gemini/skills/impeccable/scripts/detector/node/file-system.mjs b/.gemini/skills/impeccable/scripts/detector/node/file-system.mjs
index a80250a0e..aaa8c6df7 100644
--- a/.gemini/skills/impeccable/scripts/detector/node/file-system.mjs
+++ b/.gemini/skills/impeccable/scripts/detector/node/file-system.mjs
@@ -11,7 +11,7 @@ const SKIP_DIRS = new Set([
]);
const SCANNABLE_EXTENSIONS = new Set([
- '.html', '.htm', '.css', '.scss', '.less',
+ '.html', '.htm', '.css', '.scss', '.sass', '.less',
'.jsx', '.tsx', '.js', '.ts',
'.vue', '.svelte', '.astro',
]);
diff --git a/.gemini/skills/impeccable/scripts/hook-admin.mjs b/.gemini/skills/impeccable/scripts/hook-admin.mjs
new file mode 100644
index 000000000..86fcfa909
--- /dev/null
+++ b/.gemini/skills/impeccable/scripts/hook-admin.mjs
@@ -0,0 +1,300 @@
+#!/usr/bin/env node
+/**
+ * `/impeccable hooks <on|off|status|reset>` — manage the design hook
+ * via .impeccable/hook.json and .impeccable/hook.local.json in the current
+ * project.
+ *
+ * Usage:
+ * node hook-admin.mjs status # print current state
+ * node hook-admin.mjs on # set enabled: true
+ * node hook-admin.mjs off # set enabled: false
+ * node hook-admin.mjs ignore-rule <rule-id> # append to ignoreRules
+ * node hook-admin.mjs ignore-rule overused-font --all-values
+ * node hook-admin.mjs ignore-file <glob> # append to ignoreFiles
+ * node hook-admin.mjs ignore-value <rule> <value> # append to shared ignoreValues
+ * node hook-admin.mjs ignore-value <rule> <value> --local
+ * node hook-admin.mjs reset # remove all config + cache
+ *
+ * Designed to be invoked by the LLM from the reference/hooks.md flow.
+ * Output is human-readable; the harness will pass it back to the user.
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+
+import {
+ getConfigPath,
+ getLocalConfigPath,
+ getCachePath,
+ getPendingPath,
+ readConfig,
+ DEFAULT_CONFIG,
+ ensureHookGitExcludes,
+ normalizeIgnoreValue,
+ normalizeIgnoreValueEntries,
+} from './hook-lib.mjs';
+
+const ACTIONS = new Set(['status', 'on', 'off', 'ignore-rule', 'ignore-file', 'ignore-value', 'reset']);
+
+function readRawConfigFile(filePath) {
+ if (!fs.existsSync(filePath)) return { exists: false, malformed: false, raw: null };
+ try {
+ return { exists: true, malformed: false, raw: JSON.parse(fs.readFileSync(filePath, 'utf-8')) };
+ } catch {
+ return { exists: true, malformed: true, raw: null };
+ }
+}
+
+function readRawConfig(cwd, opts = {}) {
+ const filePath = opts.local ? getLocalConfigPath(cwd) : getConfigPath(cwd);
+ return readRawConfigFile(filePath).raw;
+}
+
+function writeConfig(cwd, config, opts = {}) {
+ const filePath = opts.local ? getLocalConfigPath(cwd) : getConfigPath(cwd);
+ if (opts.local) ensureHookGitExcludes(cwd);
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
+ fs.writeFileSync(filePath, JSON.stringify(config, null, 2) + '\n');
+ return filePath;
+}
+
+function mergeConfig(existing) {
+ // Persist the full shape so /impeccable hooks edits leave a complete file
+ // for the user to see, not an unhelpful `{"enabled":false}`.
+ const base = existing && typeof existing === 'object' ? existing : {};
+ return {
+ enabled: base.enabled === false ? false : true,
+ ignoreRules: Array.isArray(base.ignoreRules) ? Array.from(new Set(base.ignoreRules.map(String))) : [],
+ ignoreFiles: Array.isArray(base.ignoreFiles) ? Array.from(new Set(base.ignoreFiles.map(String))) : [],
+ ignoreValues: normalizeIgnoreValueEntries(base.ignoreValues || []),
+ limits: {
+ maxFindings: Number.isFinite(base?.limits?.maxFindings) ? base.limits.maxFindings : DEFAULT_CONFIG.limits.maxFindings,
+ maxChars: Number.isFinite(base?.limits?.maxChars) ? base.limits.maxChars : DEFAULT_CONFIG.limits.maxChars,
+ },
+ };
+}
+
+function mergeLocalConfig(existing) {
+ const base = existing && typeof existing === 'object' ? existing : {};
+ const out = {};
+ if (Object.prototype.hasOwnProperty.call(base, 'enabled')) {
+ out.enabled = base.enabled === false ? false : true;
+ }
+ if (Array.isArray(base.ignoreRules)) {
+ out.ignoreRules = Array.from(new Set(base.ignoreRules.map(String)));
+ }
+ if (Array.isArray(base.ignoreFiles)) {
+ out.ignoreFiles = Array.from(new Set(base.ignoreFiles.map(String)));
+ }
+ out.ignoreValues = normalizeIgnoreValueEntries(base.ignoreValues || []);
+ if (base.limits && typeof base.limits === 'object') {
+ const limits = {};
+ if (Number.isFinite(base.limits.maxFindings)) limits.maxFindings = base.limits.maxFindings;
+ if (Number.isFinite(base.limits.maxChars)) limits.maxChars = base.limits.maxChars;
+ if (Object.keys(limits).length) out.limits = limits;
+ }
+ return out;
+}
+
+function statusReport(cwd) {
+ const shared = readRawConfigFile(getConfigPath(cwd));
+ const local = readRawConfigFile(getLocalConfigPath(cwd));
+ const cfg = readConfig(cwd);
+ const envKill = process.env.IMPECCABLE_HOOK_DISABLED;
+ const envState = envKill ? `IMPECCABLE_HOOK_DISABLED=${envKill}` : 'unset';
+ const cfgPath = path.relative(cwd, getConfigPath(cwd)) || '.impeccable/hook.json';
+ const localPath = path.relative(cwd, getLocalConfigPath(cwd)) || '.impeccable/hook.local.json';
+ const cachePath = path.relative(cwd, getCachePath(cwd)) || '.impeccable/hook.cache.json';
+ const fileState = (info, relPath, absent) => {
+ if (info.malformed) return `${relPath} (malformed; ignored)`;
+ if (info.exists) return relPath;
+ return `${relPath} (${absent})`;
+ };
+ const ignoreValues = cfg.ignoreValues.map((entry) => `${entry.rule}=${entry.value}`);
+
+ const lines = [
+ `Impeccable design hook`,
+ ` state: ${cfg.enabled ? 'enabled' : 'disabled'}`,
+ ` shared file: ${fileState(shared, cfgPath, 'using defaults; file not present')}`,
+ ` local file: ${fileState(local, localPath, 'not present')}`,
+ ` ignoreRules: ${cfg.ignoreRules.length ? cfg.ignoreRules.join(', ') : '(none)'}`,
+ ` ignoreFiles: ${cfg.ignoreFiles.length ? cfg.ignoreFiles.join(', ') : '(none)'}`,
+ ` ignoreValues: ${ignoreValues.length ? ignoreValues.join(', ') : '(none)'}`,
+ ` maxFindings: ${cfg.limits.maxFindings}`,
+ ` maxChars: ${cfg.limits.maxChars}`,
+ ` env override: ${envState}`,
+ ` cache file: ${fs.existsSync(getCachePath(cwd)) ? cachePath : `${cachePath} (not present)`}`,
+ ];
+ return lines.join('\n');
+}
+
+function setEnabled(cwd, value) {
+ const config = mergeConfig(readRawConfig(cwd));
+ config.enabled = value;
+ const target = writeConfig(cwd, config);
+ return `Design hook ${value ? 'enabled' : 'disabled'} for this project (wrote ${path.relative(cwd, target) || target}).`;
+}
+
+function normalizeRuleId(rule) {
+ return String(rule || '').trim().toLowerCase();
+}
+
+function parseIgnoreRuleArgs(args) {
+ const positionals = [];
+ let allValues = false;
+
+ for (let i = 0; i < args.length; i++) {
+ const arg = String(args[i] || '');
+ if (arg === '--all-values') {
+ allValues = true;
+ } else if (arg === '--reason') {
+ while (i + 1 < args.length && !String(args[i + 1]).startsWith('--')) i++;
+ } else if (arg.startsWith('--reason=')) {
+ // Accepted for command symmetry; ignoreRules stores rule ids only.
+ } else if (arg.startsWith('--')) {
+ throw new Error(`Unknown ignore-rule flag: ${arg}`);
+ } else {
+ positionals.push(arg);
+ }
+ }
+
+ return {
+ rule: normalizeRuleId(positionals[0]),
+ allValues,
+ };
+}
+
+function addIgnoreRule(cwd, args) {
+ const parsed = parseIgnoreRuleArgs(args);
+ const rule = parsed.rule;
+ if (!rule) throw new Error('Pass a rule id, e.g. /impeccable hooks ignore-rule side-tab');
+ if (rule === 'overused-font' && !parsed.allValues) {
+ throw new Error('overused-font is value-specific by default. Use /impeccable hooks ignore-value overused-font <font> for a confirmed font, or /impeccable hooks ignore-rule overused-font --all-values only when the user asked to ignore overused fonts generally.');
+ }
+ const config = mergeConfig(readRawConfig(cwd));
+ if (!config.ignoreRules.includes(rule)) config.ignoreRules.push(rule);
+ writeConfig(cwd, config);
+ return `Added "${rule}" to ignoreRules. Current: ${config.ignoreRules.join(', ')}`;
+}
+
+function addIgnoreFile(cwd, glob) {
+ if (!glob) throw new Error('Pass a glob, e.g. /impeccable hooks ignore-file "src/legacy/**"');
+ const config = mergeConfig(readRawConfig(cwd));
+ if (!config.ignoreFiles.includes(glob)) config.ignoreFiles.push(glob);
+ writeConfig(cwd, config);
+ return `Added "${glob}" to ignoreFiles. Current: ${config.ignoreFiles.join(', ')}`;
+}
+
+function parseIgnoreValueArgs(args) {
+ const positionals = [];
+ let shared = false;
+ let local = false;
+ let reason = '';
+
+ for (let i = 0; i < args.length; i++) {
+ const arg = args[i];
+ if (arg === '--shared') {
+ shared = true;
+ } else if (arg === '--local') {
+ local = true;
+ } else if (arg === '--reason') {
+ const chunks = [];
+ while (i + 1 < args.length && !String(args[i + 1]).startsWith('--')) {
+ chunks.push(args[++i]);
+ }
+ reason = chunks.join(' ').trim();
+ } else if (String(arg).startsWith('--reason=')) {
+ reason = String(arg).slice('--reason='.length).trim();
+ } else {
+ positionals.push(arg);
+ }
+ }
+
+ const [rule, ...valueParts] = positionals;
+ return {
+ rule: String(rule || '').trim().toLowerCase(),
+ value: normalizeIgnoreValue(valueParts.join(' ')),
+ shared,
+ local,
+ reason,
+ };
+}
+
+function addIgnoreValue(cwd, args) {
+ const parsed = parseIgnoreValueArgs(args);
+ if (!parsed.rule || !parsed.value) {
+ throw new Error('Pass a rule id and value, e.g. /impeccable hooks ignore-value overused-font Inter');
+ }
+
+ if (parsed.shared && parsed.local) {
+ throw new Error('Pass only one scope flag: --shared or --local');
+ }
+
+ const local = parsed.local;
+ const config = local
+ ? mergeLocalConfig(readRawConfig(cwd, { local: true }))
+ : mergeConfig(readRawConfig(cwd, { local: false }));
+ const key = `${parsed.rule}\0${parsed.value}`;
+ const existing = config.ignoreValues.find((entry) => `${entry.rule}\0${entry.value}` === key);
+
+ if (existing) {
+ if (parsed.reason) existing.reason = parsed.reason;
+ } else {
+ const entry = {
+ rule: parsed.rule,
+ value: parsed.value,
+ createdAt: new Date().toISOString(),
+ };
+ if (parsed.reason) entry.reason = parsed.reason;
+ config.ignoreValues.push(entry);
+ }
+
+ const target = writeConfig(cwd, config, { local });
+ const scope = local ? 'local ignoreValues' : 'shared ignoreValues';
+ return `Added ${parsed.rule}=${parsed.value} to ${scope} (${path.relative(cwd, target) || target}).`;
+}
+
+function reset(cwd) {
+ const removed = [];
+ for (const filePath of [getConfigPath(cwd), getLocalConfigPath(cwd), getCachePath(cwd), getPendingPath(cwd)]) {
+ try {
+ if (fs.existsSync(filePath)) {
+ fs.unlinkSync(filePath);
+ removed.push(path.relative(cwd, filePath) || filePath);
+ }
+ } catch { /* ignore */ }
+ }
+ return removed.length
+ ? `Reset design hook config and cache (removed: ${removed.join(', ')}).`
+ : 'No hook config or cache to remove. Already at defaults.';
+}
+
+function main() {
+ const [, , actionArg, ...rest] = process.argv;
+ const action = (actionArg || 'status').toLowerCase();
+ const cwd = process.cwd();
+
+ if (!ACTIONS.has(action)) {
+ process.stderr.write(`Unknown action: ${action}\nValid: ${Array.from(ACTIONS).join(', ')}\n`);
+ process.exit(1);
+ }
+
+ try {
+ let out = '';
+ switch (action) {
+ case 'status': out = statusReport(cwd); break;
+ case 'on': out = setEnabled(cwd, true); break;
+ case 'off': out = setEnabled(cwd, false); break;
+ case 'ignore-rule': out = addIgnoreRule(cwd, rest); break;
+ case 'ignore-file': out = addIgnoreFile(cwd, rest[0]); break;
+ case 'ignore-value': out = addIgnoreValue(cwd, rest); break;
+ case 'reset': out = reset(cwd); break;
+ }
+ process.stdout.write(out + '\n');
+ } catch (err) {
+ process.stderr.write(`Error: ${err.message || err}\n`);
+ process.exit(1);
+ }
+}
+
+main();
diff --git a/.gemini/skills/impeccable/scripts/hook-before-edit.mjs b/.gemini/skills/impeccable/scripts/hook-before-edit.mjs
new file mode 100644
index 000000000..54b2709d2
--- /dev/null
+++ b/.gemini/skills/impeccable/scripts/hook-before-edit.mjs
@@ -0,0 +1,408 @@
+#!/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 shellContent = shellHereDocContent(shellCommand(input));
+ if (shellContent) return shellContent;
+ const copiedContent = shellCopiedFileContent(shellCommand(input), 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 || '';
+}
+
+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 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' });
+});
diff --git a/.gemini/skills/impeccable/scripts/hook-lib.mjs b/.gemini/skills/impeccable/scripts/hook-lib.mjs
new file mode 100644
index 000000000..02199f530
--- /dev/null
+++ b/.gemini/skills/impeccable/scripts/hook-lib.mjs
@@ -0,0 +1,1232 @@
+/**
+ * Shared library for the Impeccable design hook.
+ *
+ * Pure-ish helpers split out from `hook.mjs` so unit tests can exercise
+ * config parsing, finding filtering, dedup, render, and cache logic without
+ * spawning a subprocess. `hook.mjs` itself is the thin stdin/stdout shim.
+ *
+ * Public surface (everything exported is part of the contract):
+ * ENVELOPE_PREFIX, ALLOWED_EXTS, ACK_EXTS, SENSITIVE_PATH, GENERATED_PATH, TRUTHY
+ * truthy(value)
+ * readConfig(cwd) / DEFAULT_CONFIG / getConfigPath(cwd) / getLocalConfigPath(cwd)
+ * normalizeIgnoreValue(value)
+ * readCache(cwd) / persistCache(cwd, cache)
+ * bumpEditCount(cache, sessionId, filePath) -> number
+ * suppressionNotice(filePath)
+ * filterFindings(findings, content, ext, config)
+ * dedupeAgainstCache(findings, cache, sessionId, filePath)
+ * renderTemplate(findings, filePath, config, opts)
+ * renderCleanAck(filePath, opts) / renderPendingAck(filePath, known, opts)
+ * shouldEmitAckForFile(filePath)
+ * writeAuditLog(env, entry)
+ * loadDetector() -> Promise<{ detectText, detectHtml }>
+ * matchesAnyGlob(filePath, globs)
+ * normalizeScanTargets(primaryTargets, projectCwd)
+ * runHook(deps) -> { exitCode, stdout, audit, reason? }
+ *
+ * Design notes:
+ * - All errors are swallowed at the runHook seam. The detector throwing must
+ * never break a turn. See PRD §5 "Failure modes".
+ * - Cache shape is JSON-friendly; we gc the oldest sessions when there are
+ * more than 8 to keep file size predictable across long-lived projects.
+ * - The detector loader looks for `detector/detect-antipatterns.mjs` next to
+ * this file first (built skill layout) and falls back to the repo root's
+ * `cli/engine/detect-antipatterns.mjs` (running from source).
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+import { pathToFileURL, fileURLToPath } from 'node:url';
+
+const __filename = fileURLToPath(import.meta.url);
+const __dirname = path.dirname(__filename);
+
+export const ENVELOPE_PREFIX = '[impeccable@1]';
+
+export const ALLOWED_EXTS = new Set([
+ '.tsx', '.jsx', '.html', '.htm', '.vue', '.svelte', '.astro',
+ '.css', '.scss', '.sass', '.less', '.ts', '.js',
+]);
+
+export const ACK_EXTS = new Set([
+ '.tsx', '.jsx', '.html', '.htm', '.vue', '.svelte', '.astro',
+ '.css', '.scss', '.sass', '.less',
+]);
+
+// Hard-skip regex for sensitive files. Cannot be turned off via config.
+// Match tokenized secret/credential filenames, not UI names such as
+// CredentialForm.tsx, SecretPage.jsx, or secretary-dashboard.vue.
+export const SENSITIVE_PATH = new RegExp([
+ String.raw`(?:^|[/\\])\.env(?:\.|$)`,
+ String.raw`(?:^|[/\\])\.git(?:[/\\]|$)`,
+ String.raw`(?:^|[/\\])id_rsa(?:$|[._-])[^/\\]*$`,
+ String.raw`(?:^|[/\\])[^/\\]*\.pem$`,
+ String.raw`(?:^|[/\\])(?:[^/\\]*[._-])?(?:secret|secrets|credential|credentials)(?=[._-])[^/\\]*\.(?:json|ya?ml|toml|ini|conf|config|env|txt|key|cert|crt|pem|js|ts)$`,
+].join('|'), 'i');
+
+// Hard-skip regex for generated, lock, minified, and build-output paths.
+export const GENERATED_PATH = /(?:\.generated\.[a-z]+$|\.d\.ts$|\.min\.[a-z]+$|[/\\]node_modules[/\\]|[/\\](?:dist|build|out|\.next|\.cache|coverage)[/\\]|[/\\]?[^/\\]+\.lock(?:\.json)?$)/i;
+
+export const TRUTHY = /^(1|true|yes|on)$/i;
+
+export const DEFAULT_CONFIG = Object.freeze({
+ enabled: true,
+ ignoreRules: [],
+ ignoreFiles: [],
+ ignoreValues: [],
+ limits: { maxFindings: 5, maxChars: 8000 },
+});
+
+export const HOOK_LOCAL_IGNORE_PATTERNS = Object.freeze([
+ '.impeccable/hook.cache.json',
+ '.impeccable/hook.pending.json',
+ '.impeccable/hook.local.json',
+]);
+
+const HOOK_IGNORE_MARKER_OPEN = '# impeccable-hook-ignore-start';
+const HOOK_IGNORE_MARKER_CLOSE = '# impeccable-hook-ignore-end';
+const CACHE_MAX_SESSIONS = 8;
+export const EDIT_COUNT_THRESHOLD = 6;
+
+export function truthy(value) {
+ return typeof value === 'string' && TRUTHY.test(value);
+}
+
+function depthIsSet(value) {
+ if (value === undefined || value === null) return false;
+ const text = String(value).trim();
+ if (!text) return false;
+ if (TRUTHY.test(text)) return true;
+ return /^\d+$/.test(text) && Number(text) > 0;
+}
+
+function safeReadJson(filePath) {
+ try {
+ return JSON.parse(fs.readFileSync(filePath, 'utf-8'));
+ } catch {
+ return null;
+ }
+}
+
+export function getConfigPath(cwd) {
+ return path.join(cwd, '.impeccable', 'hook.json');
+}
+
+export function getLocalConfigPath(cwd) {
+ return path.join(cwd, '.impeccable', 'hook.local.json');
+}
+
+export function getCachePath(cwd) {
+ return path.join(cwd, '.impeccable', 'hook.cache.json');
+}
+
+export function getPendingPath(cwd) {
+ return path.join(cwd, '.impeccable', 'hook.pending.json');
+}
+
+export function resolveProjectCwd(event, fallback = process.cwd()) {
+ return event?.cwd
+ || (Array.isArray(event?.workspace_roots) && event.workspace_roots[0])
+ || envProjectDir(fallback)
+ || fallback;
+}
+
+export function readConfig(cwd) {
+ const config = cloneDefaultConfig();
+ applyConfigSource(config, safeReadJson(getConfigPath(cwd)));
+ applyConfigSource(config, safeReadJson(getLocalConfigPath(cwd)));
+ return config;
+}
+
+function numberOr(value, fallback) {
+ return Number.isFinite(value) && value > 0 ? value : fallback;
+}
+
+function cloneDefaultConfig() {
+ return {
+ ...DEFAULT_CONFIG,
+ ignoreRules: [],
+ ignoreFiles: [],
+ ignoreValues: [],
+ limits: { ...DEFAULT_CONFIG.limits },
+ };
+}
+
+function applyConfigSource(config, raw) {
+ if (!raw || typeof raw !== 'object') return config;
+ if (Object.prototype.hasOwnProperty.call(raw, 'enabled')) {
+ config.enabled = raw.enabled === false ? false : true;
+ }
+ if (Array.isArray(raw.ignoreRules)) {
+ config.ignoreRules = uniqueStrings([...config.ignoreRules, ...raw.ignoreRules]);
+ }
+ if (Array.isArray(raw.ignoreFiles)) {
+ config.ignoreFiles = uniqueStrings([...config.ignoreFiles, ...raw.ignoreFiles]);
+ }
+ if (Array.isArray(raw.ignoreValues)) {
+ config.ignoreValues = mergeIgnoreValues(config.ignoreValues, raw.ignoreValues);
+ }
+ if (raw.limits && typeof raw.limits === 'object') {
+ config.limits = {
+ maxFindings: numberOr(raw.limits.maxFindings, config.limits.maxFindings),
+ maxChars: numberOr(raw.limits.maxChars, config.limits.maxChars),
+ };
+ }
+ return config;
+}
+
+function uniqueStrings(values) {
+ return Array.from(new Set(values.map(String)));
+}
+
+export function normalizeIgnoreValue(value) {
+ return String(value || '')
+ .trim()
+ .replace(/^["']|["']$/g, '')
+ .replace(/\+/g, ' ')
+ .replace(/\s+/g, ' ')
+ .toLowerCase();
+}
+
+function normalizeIgnoreRule(rule) {
+ return String(rule || '').trim().toLowerCase();
+}
+
+export function normalizeIgnoreValueEntries(entries) {
+ if (!Array.isArray(entries)) return [];
+ const out = [];
+ for (const entry of entries) {
+ if (!entry || typeof entry !== 'object') continue;
+ const rule = normalizeIgnoreRule(entry.rule);
+ const value = normalizeIgnoreValue(entry.value);
+ if (!rule || !value) continue;
+ const normalized = { rule, value };
+ if (typeof entry.reason === 'string' && entry.reason.trim()) {
+ normalized.reason = entry.reason.trim();
+ }
+ if (typeof entry.createdAt === 'string' && entry.createdAt.trim()) {
+ normalized.createdAt = entry.createdAt.trim();
+ }
+ out.push(normalized);
+ }
+ return out;
+}
+
+function mergeIgnoreValues(existing, incoming) {
+ const map = new Map();
+ for (const entry of normalizeIgnoreValueEntries(existing)) {
+ map.set(`${entry.rule}\0${entry.value}`, entry);
+ }
+ for (const entry of normalizeIgnoreValueEntries(incoming)) {
+ map.set(`${entry.rule}\0${entry.value}`, entry);
+ }
+ return Array.from(map.values());
+}
+
+export function readCache(cwd) {
+ const raw = safeReadJson(getCachePath(cwd));
+ if (!raw || typeof raw !== 'object' || raw.version !== 1) {
+ return { version: 1, sessions: {} };
+ }
+ return {
+ version: 1,
+ sessions: raw.sessions && typeof raw.sessions === 'object' ? raw.sessions : {},
+ };
+}
+
+export function persistCache(cwd, cache) {
+ const sessions = cache.sessions || {};
+ const ids = Object.keys(sessions);
+ if (ids.length > CACHE_MAX_SESSIONS) {
+ // Garbage-collect oldest sessions by updatedAt.
+ const ordered = ids
+ .map((id) => [id, sessions[id]?.updatedAt || 0])
+ .sort((a, b) => b[1] - a[1])
+ .slice(0, CACHE_MAX_SESSIONS);
+ const next = {};
+ for (const [id] of ordered) next[id] = sessions[id];
+ cache = { ...cache, sessions: next };
+ }
+ const target = getCachePath(cwd);
+ try {
+ ensureHookGitExcludes(cwd);
+ fs.mkdirSync(path.dirname(target), { recursive: true });
+ fs.writeFileSync(target, JSON.stringify(cache));
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+export function ensureHookGitExcludes(cwd = process.cwd()) {
+ try {
+ const target = resolveHookGitExcludeTarget(cwd);
+ if (!target) {
+ return { mode: 'none', changed: false, patterns: [...HOOK_LOCAL_IGNORE_PATTERNS] };
+ }
+
+ const patterns = target.patternPrefix
+ ? HOOK_LOCAL_IGNORE_PATTERNS.map((pattern) => `${target.patternPrefix}/${pattern}`)
+ : [...HOOK_LOCAL_IGNORE_PATTERNS];
+ const markerSuffix = target.patternPrefix || '.';
+ const markerOpen = `${HOOK_IGNORE_MARKER_OPEN} ${markerSuffix}`;
+ const markerClose = `${HOOK_IGNORE_MARKER_CLOSE} ${markerSuffix}`;
+ const existing = fs.existsSync(target.path) ? fs.readFileSync(target.path, 'utf-8') : '';
+ const block = [markerOpen, ...patterns, markerClose].join('\n');
+ const markerRe = new RegExp(`${escapeRegExp(markerOpen)}[\\s\\S]*?${escapeRegExp(markerClose)}`);
+
+ let updated;
+ if (markerRe.test(existing)) {
+ updated = existing.replace(markerRe, block);
+ } else {
+ const prefix = existing.length === 0 ? '' : existing.endsWith('\n') ? existing : `${existing}\n`;
+ updated = `${prefix}${prefix.endsWith('\n\n') || prefix === '' ? '' : '\n'}${block}\n`;
+ }
+
+ if (updated !== existing) {
+ fs.mkdirSync(path.dirname(target.path), { recursive: true });
+ fs.writeFileSync(target.path, updated, 'utf-8');
+ }
+
+ return {
+ mode: 'git-info-exclude',
+ file: path.relative(path.resolve(cwd), target.path).split(path.sep).join('/'),
+ changed: updated !== existing,
+ patterns,
+ };
+ } catch {
+ return { mode: 'error', changed: false, patterns: [...HOOK_LOCAL_IGNORE_PATTERNS] };
+ }
+}
+
+function resolveHookGitExcludeTarget(cwd) {
+ const start = path.resolve(cwd);
+ let dir = start;
+ while (true) {
+ const dotGit = path.join(dir, '.git');
+ if (fs.existsSync(dotGit)) {
+ const gitDir = resolveGitDir(dotGit, dir);
+ if (!gitDir) return null;
+ const relPrefix = path.relative(dir, start).split(path.sep).join('/');
+ return {
+ path: path.join(gitDir, 'info', 'exclude'),
+ patternPrefix: relPrefix && relPrefix !== '.' ? relPrefix : '',
+ };
+ }
+ const parent = path.dirname(dir);
+ if (parent === dir) return null;
+ dir = parent;
+ }
+}
+
+function resolveGitDir(dotGit, worktreeDir) {
+ const stat = fs.statSync(dotGit);
+ if (stat.isDirectory()) return dotGit;
+ if (!stat.isFile()) return null;
+
+ const body = fs.readFileSync(dotGit, 'utf-8').trim();
+ const match = body.match(/^gitdir:\s*(.+)$/i);
+ if (!match) return null;
+ return path.isAbsolute(match[1]) ? match[1] : path.resolve(worktreeDir, match[1]);
+}
+
+function escapeRegExp(value) {
+ return String(value).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+}
+
+function ensureSession(cache, sessionId) {
+ if (!cache.sessions[sessionId]) {
+ cache.sessions[sessionId] = { updatedAt: Date.now(), files: {} };
+ }
+ return cache.sessions[sessionId];
+}
+
+function ensureFile(cache, sessionId, filePath) {
+ const session = ensureSession(cache, sessionId);
+ if (!session.files[filePath]) {
+ session.files[filePath] = { editCount: 0, findings: [] };
+ }
+ return session.files[filePath];
+}
+
+export function bumpEditCount(cache, sessionId, filePath) {
+ const fileEntry = ensureFile(cache, sessionId, filePath);
+ fileEntry.editCount = (fileEntry.editCount || 0) + 1;
+ ensureSession(cache, sessionId).updatedAt = Date.now();
+ return fileEntry.editCount;
+}
+
+export function suppressionNotice(filePath) {
+ return `${ENVELOPE_PREFIX} Suppressing further design hints on ${filePath}. More than ${EDIT_COUNT_THRESHOLD} edits in this session reached. Run /impeccable audit to revisit.`;
+}
+
+// Glob → RegExp. Supports `**`, `*`, `?`, and `{a,b}` alternation.
+function globToRegex(glob) {
+ let re = '^';
+ let i = 0;
+ while (i < glob.length) {
+ const c = glob[i];
+ if (c === '*') {
+ if (glob[i + 1] === '*') {
+ re += '.*';
+ i += 2;
+ if (glob[i] === '/') i += 1;
+ } else {
+ re += '[^/]*';
+ i += 1;
+ }
+ } else if (c === '?') {
+ re += '[^/]';
+ i += 1;
+ } else if (c === '{') {
+ const end = glob.indexOf('}', i);
+ if (end === -1) { re += '\\{'; i += 1; continue; }
+ const parts = glob.slice(i + 1, end).split(',').map((p) => p.replace(/[.+^$()|[\]\\]/g, '\\$&'));
+ re += `(?:${parts.join('|')})`;
+ i = end + 1;
+ } else if (/[.+^$()|[\]\\]/.test(c)) {
+ re += `\\${c}`;
+ i += 1;
+ } else {
+ re += c;
+ i += 1;
+ }
+ }
+ re += '$';
+ return new RegExp(re);
+}
+
+export function matchesAnyGlob(filePath, globs) {
+ if (!Array.isArray(globs) || globs.length === 0) return false;
+ const normalized = filePath.split(path.sep).join('/');
+ for (const glob of globs) {
+ try {
+ const re = globToRegex(String(glob));
+ if (re.test(normalized)) return true;
+ // Match against basename too for convenience: `*.generated.tsx` should
+ // catch `src/foo.generated.tsx` without requiring `**/`.
+ const base = normalized.split('/').pop();
+ if (re.test(base)) return true;
+ } catch {
+ /* malformed glob, skip */
+ }
+ }
+ return false;
+}
+
+export function filterFindings(findings, _content, _ext, config) {
+ if (!Array.isArray(findings) || findings.length === 0) return [];
+ const ignoreRules = new Set((config.ignoreRules || []).map((rule) => normalizeIgnoreRule(rule)));
+ const ignoreValues = normalizeIgnoreValueEntries(config.ignoreValues || []);
+ return findings.filter((f) => {
+ if (!f || typeof f !== 'object') return false;
+ if (ignoreRules.has(normalizeIgnoreRule(f.antipattern))) return false;
+ if (isIgnoredFindingValue(f, ignoreValues)) return false;
+ return true;
+ });
+}
+
+function isIgnoredFindingValue(finding, ignoreValues) {
+ if (!Array.isArray(ignoreValues) || ignoreValues.length === 0) return false;
+ const rule = normalizeIgnoreRule(finding.antipattern);
+ const value = extractFindingIgnoreValue(finding);
+ if (!rule || !value) return false;
+ return ignoreValues.some((entry) => entry.rule === rule && entry.value === value);
+}
+
+export function extractFindingIgnoreValue(finding) {
+ if (!finding || typeof finding !== 'object') return '';
+ const rule = normalizeIgnoreRule(finding.antipattern);
+ if (rule !== 'overused-font') return '';
+ return normalizeIgnoreValue(extractFindingIgnoreValueRaw(finding));
+}
+
+function extractFindingIgnoreValueRaw(finding) {
+ const direct = cleanIgnoreValueDisplay(finding.ignoreValue || finding.value || '');
+ if (direct) return direct;
+
+ const candidates = [finding.detail, finding.snippet].filter((v) => typeof v === 'string' && v);
+ for (const text of candidates) {
+ const primary = text.match(/Primary font:\s*([^()\n;]+)/i);
+ if (primary) return cleanIgnoreValueDisplay(primary[1]);
+
+ const family = text.match(/font-family\s*:\s*["']?([^'",;\n]+)/i);
+ if (family) return cleanIgnoreValueDisplay(family[1]);
+
+ const google = text.match(/[?&]family=([^&:;\n]+)/i);
+ if (google) {
+ try {
+ return cleanIgnoreValueDisplay(decodeURIComponent(google[1]));
+ } catch {
+ return cleanIgnoreValueDisplay(google[1]);
+ }
+ }
+ }
+
+ return '';
+}
+
+function cleanIgnoreValueDisplay(value) {
+ return String(value || '')
+ .trim()
+ .replace(/^["']|["']$/g, '')
+ .replace(/\+/g, ' ')
+ .replace(/\s+/g, ' ');
+}
+
+export function dedupeAgainstCache(findings, cache, sessionId, filePath) {
+ if (!Array.isArray(findings) || findings.length === 0) return [];
+ const fileEntry = ensureFile(cache, sessionId, filePath);
+ const known = new Set(fileEntry.findings || []);
+ const fresh = [];
+ for (const f of findings) {
+ const key = `${f.antipattern}:${f.line || 0}`;
+ if (known.has(key)) continue;
+ known.add(key);
+ fresh.push(f);
+ }
+ return fresh;
+}
+
+export function rememberFindings(cache, sessionId, filePath, findings) {
+ const fileEntry = ensureFile(cache, sessionId, filePath);
+ const known = new Set(fileEntry.findings || []);
+ for (const f of findings) known.add(`${f.antipattern}:${f.line || 0}`);
+ fileEntry.findings = Array.from(known);
+ ensureSession(cache, sessionId).updatedAt = Date.now();
+}
+
+export function renderTemplate(findings, filePath, config, opts = {}) {
+ if (!Array.isArray(findings) || findings.length === 0) return '';
+ const limits = config?.limits || DEFAULT_CONFIG.limits;
+ const cap = Math.max(1, limits.maxFindings || DEFAULT_CONFIG.limits.maxFindings);
+ const maxChars = Math.max(500, limits.maxChars || DEFAULT_CONFIG.limits.maxChars);
+
+ const cwd = opts.cwd || process.cwd();
+ const display = relativize(filePath, cwd);
+ const total = findings.length;
+ const shown = findings.slice(0, cap);
+ const remaining = total - shown.length;
+
+ const header = `${ENVELOPE_PREFIX} Required design corrections in ${display} (${total} issue(s)):`;
+ const lines = shown.map((f) => formatFindingLine(f));
+ const more = remaining > 0
+ ? `... and ${remaining} more (see /impeccable audit).`
+ : null;
+ const footer = directiveFooter(display);
+
+ const blocks = [header, ...lines];
+ if (more) blocks.push(more);
+ blocks.push('');
+ blocks.push(footer);
+ let text = blocks.join('\n');
+
+ if (text.length > maxChars) {
+ text = clampToBudget(header, lines, more, footer, maxChars);
+ }
+ return text;
+}
+
+function renderGroupedTemplate(groups, config, opts = {}) {
+ const realGroups = groups.filter((group) => Array.isArray(group.findings) && group.findings.length > 0);
+ if (realGroups.length === 0) return '';
+ if (realGroups.length === 1) {
+ const [group] = realGroups;
+ return renderTemplate(group.findings, group.filePath, config, opts);
+ }
+
+ const limits = config?.limits || DEFAULT_CONFIG.limits;
+ const cap = Math.max(1, limits.maxFindings || DEFAULT_CONFIG.limits.maxFindings);
+ const maxChars = Math.max(500, limits.maxChars || DEFAULT_CONFIG.limits.maxChars);
+ const cwd = opts.cwd || process.cwd();
+ const total = realGroups.reduce((sum, group) => sum + group.findings.length, 0);
+ const header = `${ENVELOPE_PREFIX} Required design corrections across ${realGroups.length} files (${total} issue(s)):`;
+ const lines = [];
+ let shownCount = 0;
+
+ for (const group of realGroups) {
+ const display = relativize(group.filePath, cwd);
+ lines.push(`${display} (${group.findings.length} issue(s)):`);
+ const remainingCap = Math.max(0, cap - shownCount);
+ const shown = group.findings.slice(0, remainingCap);
+ for (const finding of shown) {
+ lines.push(formatFindingLine(finding));
+ }
+ shownCount += shown.length;
+ const hidden = group.findings.length - shown.length;
+ if (hidden > 0) {
+ lines.push(`- ... ${hidden} more in ${display} (see /impeccable audit).`);
+ }
+ }
+
+ const footer = directiveFooter('the affected files', { grouped: true });
+ let text = [header, ...lines, '', footer].join('\n');
+ if (text.length > maxChars) {
+ text = clampGroupedToBudget(header, lines, footer, maxChars);
+ }
+ return text;
+}
+
+function clampGroupedToBudget(header, lines, footer, maxChars) {
+ const assemble = (linesArr, omitted) => [
+ header,
+ ...linesArr,
+ ...(omitted ? ['... and more (see /impeccable audit).'] : []),
+ '',
+ footer,
+ ].join('\n');
+
+ let working = lines.slice();
+ let omitted = false;
+ let assembled = assemble(working, omitted);
+ while (assembled.length > maxChars && working.length > 1) {
+ working.pop();
+ omitted = true;
+ assembled = assemble(working, omitted);
+ }
+ if (assembled.length > maxChars) {
+ assembled = `${assembled.slice(0, maxChars - 1)}…`;
+ }
+ return assembled;
+}
+
+function clampToBudget(header, lines, more, footer, maxChars) {
+ const assemble = (linesArr, moreText) => {
+ const blocks = [header, ...linesArr];
+ if (moreText) blocks.push(moreText);
+ blocks.push('');
+ blocks.push(footer);
+ return blocks.join('\n');
+ };
+
+ let working = lines.slice();
+ let moreText = more;
+ let assembled = assemble(working, moreText);
+ while (assembled.length > maxChars && working.length > 1) {
+ working.pop();
+ moreText = '... and more (see /impeccable audit).';
+ assembled = assemble(working, moreText);
+ }
+ if (assembled.length > maxChars) {
+ assembled = `${assembled.slice(0, maxChars - 1)}…`;
+ }
+ return assembled;
+}
+
+function formatFindingLine(f) {
+ const prefix = f.line && f.line > 0 ? `- L${f.line}` : '-';
+ const desc = (f.description || '').trim();
+ const name = (f.name || '').trim();
+ // Description from the registry already ends in punctuation; join with a
+ // single space. `name` may have a trailing period already, keep it clean.
+ const nameSegment = name ? `${name.replace(/\.+\s*$/, '')}.` : '';
+ const ignoreCommand = formatFindingIgnoreCommand(f);
+ const ignoreSegment = ignoreCommand
+ ? ` If the user explicitly confirms this value is intentional: \`${ignoreCommand}\`.`
+ : '';
+ return `${prefix} [${f.antipattern}] ${nameSegment} ${desc}${ignoreSegment}`.replace(/\s+/g, ' ').trim();
+}
+
+function formatFindingIgnoreCommand(finding) {
+ if (!finding || typeof finding !== 'object') return '';
+ const rule = normalizeIgnoreRule(finding.antipattern);
+ if (!rule) return '';
+ const normalizedValue = extractFindingIgnoreValue(finding);
+ if (!normalizedValue) return '';
+ const value = extractFindingIgnoreValueRaw(finding);
+ const valueArg = quoteCommandArg(value);
+ const reason = quoteCommandArg(`User confirmed ${value} is intentional`);
+ return `/impeccable hooks ignore-value ${rule} ${valueArg} --shared --reason ${reason}`;
+}
+
+function quoteCommandArg(value) {
+ const text = String(value || '').trim();
+ if (/^[A-Za-z0-9._:-]+$/.test(text)) return text;
+ return `"${text.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
+}
+
+function relativize(filePath, cwd) {
+ try {
+ const rel = path.relative(cwd, filePath);
+ if (!rel || rel.startsWith('..')) return filePath;
+ return rel.split(path.sep).join('/');
+ } catch {
+ return filePath;
+ }
+}
+
+// Codex `apply_patch` exposes the raw patch in `tool_input.command`, not
+// `tool_input.file_path`. Claude Code may send both; parse the patch body
+// so we can scan the file(s) the tool actually touched.
+// https://developers.openai.com/codex/hooks#posttooluse
+const APPLY_PATCH_FILE_RE = /^\*\*\* (?:Update|Add) File: (.+)$/gm;
+
+export function parseApplyPatchPaths(command, projectCwd) {
+ if (!command || typeof command !== 'string') return [];
+ const out = [];
+ for (const m of command.matchAll(APPLY_PATCH_FILE_RE)) {
+ let p = (m[1] || '').trim();
+ if (!p) continue;
+ if (!path.isAbsolute(p)) p = path.resolve(projectCwd, p);
+ out.push(p);
+ }
+ return out;
+}
+
+export function resolveTargetFiles(event, projectCwd) {
+ const ti = event?.tool_input;
+ const out = [];
+ const add = (filePath) => {
+ if (typeof filePath !== 'string' || !filePath) return;
+ if (!out.includes(filePath)) out.push(filePath);
+ };
+
+ if (event?.tool_name === 'apply_patch' && ti && typeof ti.command === 'string') {
+ for (const filePath of parseApplyPatchPaths(ti.command, projectCwd)) add(filePath);
+ }
+ if (ti && typeof ti.file_path === 'string' && ti.file_path) {
+ add(ti.file_path);
+ }
+ // Cursor Write / StrReplace use `path`, not `file_path`.
+ if (ti && typeof ti.path === 'string' && ti.path) {
+ add(ti.path);
+ }
+ if (typeof event?.file_path === 'string' && event.file_path) {
+ add(event.file_path);
+ }
+ return out;
+}
+
+export function resolveHarness(env = {}, event = null) {
+ const explicit = env?.IMPECCABLE_HOOK_HARNESS;
+ if (explicit === 'cursor') return 'cursor';
+ if (explicit === 'claude' || explicit === 'codex') return 'claude';
+ if (typeof event?.conversation_id === 'string' && event.conversation_id) return 'cursor';
+ return 'claude';
+}
+
+export function normalizeHookEvent(event, projectCwd, harness = 'claude') {
+ if (!event || typeof event !== 'object' || harness !== 'cursor') return event;
+
+ const cwd = event.cwd
+ || (Array.isArray(event.workspace_roots) && event.workspace_roots[0])
+ || envProjectDir(projectCwd)
+ || projectCwd;
+ const sessionId = event.session_id || event.conversation_id || 'unknown';
+
+ const ti = event.tool_input && typeof event.tool_input === 'object' ? event.tool_input : {};
+ const filePath = ti.file_path || ti.path || event.file_path;
+ if (filePath) {
+ return {
+ ...event,
+ cwd,
+ session_id: sessionId,
+ tool_input: { ...ti, file_path: filePath },
+ };
+ }
+
+ return { ...event, cwd, session_id: sessionId };
+}
+
+function envProjectDir(fallback) {
+ if (typeof process.env.CURSOR_PROJECT_DIR === 'string' && process.env.CURSOR_PROJECT_DIR) {
+ return process.env.CURSOR_PROJECT_DIR;
+ }
+ return fallback;
+}
+
+// UI components often keep slop in a sibling/co-located stylesheet while the
+// JSX edit is what triggered PostToolUse. Scan those styles too so an App.jsx
+// patch doesn't report "clean" while styles.css still has Inter/bounce/etc.
+const UI_CODE_EXTS = new Set(['.jsx', '.tsx', '.vue', '.svelte', '.astro']);
+const STYLE_EXTS = new Set(['.css', '.scss', '.sass', '.less']);
+const CO_SCAN_STYLE_NAMES = [
+ 'styles.css', 'styles.scss', 'styles.sass', 'styles.less',
+ 'index.css', 'index.scss', 'index.sass', 'index.less',
+ 'global.css', 'global.scss', 'global.sass', 'global.less',
+ 'globals.css', 'globals.scss', 'globals.sass', 'globals.less',
+];
+const MAX_SCAN_TARGETS = 6;
+
+const STATIC_STYLE_IMPORT_RE = /import\s+(?:[\w*{}\s,$]+\s+from\s+)?['"]([^'"]+\.(?:css|scss|sass|less))['"]/gi;
+
+function hasPathTraversal(filePath) {
+ return typeof filePath === 'string' && filePath.includes('..');
+}
+
+function isInsideProject(filePath, projectCwd) {
+ if (!filePath || !projectCwd || hasPathTraversal(filePath)) return false;
+ try {
+ const rel = path.relative(projectCwd, filePath);
+ return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));
+ } catch {
+ return false;
+ }
+}
+
+export function parseStaticStyleImports(content, fromFile, projectCwd) {
+ if (!content || typeof content !== 'string') return [];
+ const dir = path.dirname(fromFile);
+ const out = [];
+ for (const m of content.matchAll(STATIC_STYLE_IMPORT_RE)) {
+ let p = (m[1] || '').trim();
+ if (!p) continue;
+ if (p.startsWith('.')) p = path.resolve(dir, p);
+ else if (!path.isAbsolute(p)) p = path.resolve(projectCwd, p);
+ if (!isInsideProject(p, projectCwd)) continue;
+ out.push(p);
+ }
+ return out;
+}
+
+export function coLocatedStylesheets(filePath) {
+ const dir = path.dirname(filePath);
+ const base = path.basename(filePath, path.extname(filePath));
+ const candidates = new Set([
+ path.join(dir, `${base}.css`),
+ path.join(dir, `${base}.module.css`),
+ path.join(dir, `${base}.scss`),
+ path.join(dir, `${base}.module.scss`),
+ path.join(dir, `${base}.sass`),
+ path.join(dir, `${base}.module.sass`),
+ path.join(dir, `${base}.less`),
+ path.join(dir, `${base}.module.less`),
+ ]);
+ for (const name of CO_SCAN_STYLE_NAMES) {
+ candidates.add(path.join(dir, name));
+ }
+ return [...candidates].filter((p) => fs.existsSync(p));
+}
+
+export function normalizeScanTargets(primaryTargets, projectCwd) {
+ if (!Array.isArray(primaryTargets) || primaryTargets.length === 0) return [];
+ const ordered = [];
+ const seen = new Set();
+ const baseCwd = projectCwd || process.cwd();
+ const normalizeTarget = (p) => {
+ // Preserve literal `..` segments so downstream sensitive-path checks
+ // still fire. path.resolve would collapse `/foo/../etc/passwd`.
+ if (hasPathTraversal(p)) return p;
+ return path.isAbsolute(p) ? p : path.resolve(baseCwd, p);
+ };
+ const add = (p) => {
+ if (ordered.length >= MAX_SCAN_TARGETS) return;
+ const abs = normalizeTarget(p);
+ if (seen.has(abs)) return;
+ seen.add(abs);
+ ordered.push(abs);
+ return abs;
+ };
+
+ for (const p of primaryTargets) add(p);
+ return ordered;
+}
+
+export function expandScanTargets(primaryTargets, projectCwd) {
+ const ordered = normalizeScanTargets(primaryTargets, projectCwd);
+ if (ordered.length === 0) return [];
+ const seen = new Set(ordered);
+ const baseCwd = projectCwd || process.cwd();
+ const add = (p) => {
+ if (ordered.length >= MAX_SCAN_TARGETS) return;
+ const abs = hasPathTraversal(p) ? p : (path.isAbsolute(p) ? p : path.resolve(baseCwd, p));
+ if (seen.has(abs)) return;
+ seen.add(abs);
+ ordered.push(abs);
+ return abs;
+ };
+
+ const normalizedPrimaries = [];
+ for (const p of ordered) normalizedPrimaries.push(p);
+
+ for (const p of normalizedPrimaries) {
+ if (ordered.length >= MAX_SCAN_TARGETS) break;
+ if (!isInsideProject(p, baseCwd)) continue;
+ const ext = path.extname(p).toLowerCase();
+ if (STYLE_EXTS.has(ext) || !UI_CODE_EXTS.has(ext)) continue;
+
+ let content = '';
+ try { content = fs.readFileSync(p, 'utf-8'); } catch { /* unreadable primary */ }
+
+ for (const imp of parseStaticStyleImports(content, p, projectCwd)) {
+ add(imp);
+ if (ordered.length >= MAX_SCAN_TARGETS) break;
+ }
+ for (const col of coLocatedStylesheets(p)) {
+ add(col);
+ if (ordered.length >= MAX_SCAN_TARGETS) break;
+ }
+ }
+
+ return ordered;
+}
+
+export function writeAuditLog(env, entry) {
+ const target = env?.IMPECCABLE_HOOK_LOG;
+ if (!target || typeof target !== 'string') return false;
+ try {
+ const expanded = target.startsWith('~/')
+ ? path.join(process.env.HOME || process.env.USERPROFILE || '.', target.slice(2))
+ : target;
+ fs.mkdirSync(path.dirname(expanded), { recursive: true });
+ const line = JSON.stringify({ ts: new Date().toISOString(), ...entry }) + '\n';
+ fs.appendFileSync(expanded, line);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+const DETECTOR_CANDIDATES = [
+ path.join(__dirname, 'detector', 'detect-antipatterns.mjs'),
+ path.join(__dirname, '..', '..', 'cli', 'engine', 'detect-antipatterns.mjs'),
+ path.join(__dirname, '..', '..', '..', 'cli', 'engine', 'detect-antipatterns.mjs'),
+];
+
+let detectorCache = null;
+export async function loadDetector(candidates = DETECTOR_CANDIDATES) {
+ if (detectorCache) return detectorCache;
+ const found = candidates.find((c) => fs.existsSync(c));
+ if (!found) return null;
+ const mod = await import(pathToFileURL(found));
+ detectorCache = { detectText: mod.detectText, detectHtml: mod.detectHtml };
+ return detectorCache;
+}
+
+// For tests: allow injecting a detector implementation.
+export function setDetectorForTesting(impl) {
+ detectorCache = impl;
+}
+
+// ────────────────────────────────────────────────────────────────────────
+// Nudge/steer messages for the no-silent-fires policy.
+//
+// The hook is designed to be a conversational presence: every fire that
+// actually scans a file emits a developer-role message into the model's
+// next turn. Three states map to three templates:
+//
+// 1. **Fresh findings** → `renderTemplate` (existing, imperative).
+// 2. **Pending findings** → `renderPendingAck` (re-nudge for issues the
+// model was already told about in this
+// session but hasn't fixed yet).
+// 3. **Truly clean** → `renderCleanAck` (short positive nudge that
+// keeps the design discipline in context).
+//
+// All three are short (≤ ~40 tokens each) so the cumulative cost stays
+// bounded across a long active editing session. Users who explicitly want
+// silence-on-clean can set `IMPECCABLE_HOOK_QUIET=1` — runHook checks that
+// env before emitting #2 or #3.
+//
+// Why not stay silent on dedup-clean? Earlier versions did. The model
+// quickly forgets the prior reminder once tool output scrolls past it, so
+// re-nudging on the same file with a short "still pending" line keeps the
+// pressure on. The wording deliberately points back to "earlier this
+// session" so the model knows it's a re-mind, not a new finding.
+// ────────────────────────────────────────────────────────────────────────
+
+const STEER_LINE = 'Keep typography hierarchy, spacing rhythm, and color contrast intentional on the next change.';
+
+export function renderCleanAck(filePath, opts = {}) {
+ const cwd = opts.cwd || process.cwd();
+ const display = relativize(filePath, cwd);
+ return `${ENVELOPE_PREFIX} Design hook scanned ${display}. No anti-patterns. ${STEER_LINE}`;
+}
+
+export function renderPendingAck(filePath, knownFindings, opts = {}) {
+ const cwd = opts.cwd || process.cwd();
+ const display = relativize(filePath, cwd);
+ const count = knownFindings.length;
+ // `knownFindings` here are the cache strings like "side-tab:3".
+ const sample = knownFindings.slice(0, 3).join(', ');
+ const more = count > 3 ? `, +${count - 3} more` : '';
+ return `${ENVELOPE_PREFIX} Design hook scanned ${display}. Still has ${count} issue(s) flagged earlier this session (${sample}${more}). Address them before finalizing — the previous reminder still applies.`;
+}
+
+export function shouldEmitAckForFile(filePath) {
+ return ACK_EXTS.has(path.extname(String(filePath || '')).toLowerCase());
+}
+
+// The directive footer is the part of the hook output that steers model
+// behavior. Three intentional moves:
+// 1. **Imperative, not advisory.** "Fix these..." beats "Consider
+// revising..." which the model treats as a soft suggestion it can
+// override when the user asked for any kind of throwaway / demo UI.
+// 2. **Explicit exception clause.** Without it, the model will try to
+// "fix" intentional bad fixtures, anti-pattern examples in docs, or
+// test cases. Naming the exception inline beats hoping the model
+// infers it from context.
+// 3. **Acknowledgement instruction.** Hook output is injected as
+// developer-role context, not a chat turn, so the user never sees the
+// raw envelope. Asking the model to surface the fix in its reply is
+// the cheapest way to make the feedback loop visible to the user.
+function directiveFooter(display, opts = {}) {
+ const ignoreFileCommand = `/impeccable hooks ignore-file ${quoteCommandArg(display)}`;
+ const fileIgnoreGuidance = opts.grouped
+ ? 'run `/impeccable hooks ignore-file <path>` for the specific file'
+ : `run \`${ignoreFileCommand}\``;
+ return [
+ 'Fix these in your next reply before finalizing. Acknowledge what you changed so the user sees the correction.',
+ '',
+ 'Skip the fix only if the user explicitly asked for an intentionally bad UI, an anti-pattern example, a test fixture, or documentation of bad design. In that case, say so and continue.',
+ '',
+ `Do not add source comments such as \`impeccable: ignore\`; those pollute the code and do not suppress hook findings. Do not add hook ignores unless the user explicitly confirms the finding is intentional. Prefer the narrowest persisted exception: run the exact \`/impeccable hooks ignore-value ... --shared\` command shown next to a value-specific finding. For \`overused-font\`, use \`ignore-value\` for a specific font and use \`/impeccable hooks ignore-rule overused-font --all-values\` only when the user asks to ignore overused fonts generally. For file-specific findings without an ignore-value command, ${fileIgnoreGuidance}; use \`/impeccable hooks ignore-rule <id>\` only when the user asks to suppress the whole non-value-specific rule. Run /impeccable audit for the full pass.`,
+ ].join('\n');
+}
+
+/**
+ * Run the hook with explicit dependencies. Returns a result object:
+ * { exitCode, stdout, audit, reason? }
+ *
+ * Never throws. All errors are converted to `exitCode: 0` + audit entry.
+ */
+export async function runHook({ stdinJson, env = {}, cwd = process.cwd(), now = Date.now, detector } = {}) {
+ const audit = { ts: new Date(now()).toISOString(), event: 'PostToolUse' };
+ const result = (extra) => ({ exitCode: 0, stdout: '', audit: { ...audit, ...extra } });
+
+ try {
+ // Re-entrancy guard.
+ if (depthIsSet(env.IMPECCABLE_HOOK_DEPTH) || depthIsSet(env.CLAUDE_HOOK_DEPTH)) {
+ return result({ reentrant: true, durationMs: 0 });
+ }
+
+ if (truthy(env.IMPECCABLE_HOOK_DISABLED)) {
+ return result({ skipped: 'env-disabled', durationMs: 0 });
+ }
+
+ const started = Date.now();
+
+ let event;
+ try {
+ event = typeof stdinJson === 'string' ? JSON.parse(stdinJson) : stdinJson;
+ } catch {
+ return result({ skipped: 'stdin-malformed', durationMs: Date.now() - started });
+ }
+ if (!event || typeof event !== 'object') {
+ return result({ skipped: 'stdin-empty', durationMs: Date.now() - started });
+ }
+
+ const harness = resolveHarness(env, event);
+ event = normalizeHookEvent(event, cwd, harness);
+ audit.harness = harness;
+
+ const projectCwd = event.cwd || cwd;
+ const primaryFiles = normalizeScanTargets(resolveTargetFiles(event, projectCwd), projectCwd);
+ const primaryFileSet = new Set(primaryFiles);
+ const targetFiles = expandScanTargets(primaryFiles, projectCwd);
+ audit.session = event.session_id || null;
+ if (event.tool_name) audit.tool = event.tool_name;
+
+ if (targetFiles.length === 0) {
+ return result({ skipped: 'no-file-path', durationMs: Date.now() - started });
+ }
+
+ const config = readConfig(projectCwd);
+ if (config.enabled === false) {
+ return result({ skipped: 'config-disabled', durationMs: Date.now() - started });
+ }
+
+ const cache = readCache(projectCwd);
+ const sessionId = event.session_id || 'unknown';
+ const det = detector || await loadDetector();
+ if (!det || typeof det.detectText !== 'function') {
+ persistCache(projectCwd, cache);
+ return result({ skipped: 'detector-missing', durationMs: Date.now() - started });
+ }
+
+ let pendingWinner = null;
+ let cleanWinner = null;
+ const freshGroups = [];
+ let suppressionWinner = null;
+ let detectorThrewAny = false;
+ let lastSkip = 'no-scannable-file';
+ let suppressedHit = false;
+
+ for (const filePath of targetFiles) {
+ audit.file = filePath;
+
+ if (hasPathTraversal(filePath) || SENSITIVE_PATH.test(filePath)) {
+ lastSkip = 'sensitive';
+ continue;
+ }
+ if (GENERATED_PATH.test(filePath)) {
+ lastSkip = 'generated';
+ continue;
+ }
+
+ const ext = path.extname(filePath).toLowerCase();
+ audit.ext = ext;
+ if (!ALLOWED_EXTS.has(ext)) {
+ lastSkip = 'extension';
+ continue;
+ }
+
+ const relForMatch = relativize(filePath, projectCwd);
+ if (matchesAnyGlob(relForMatch, config.ignoreFiles) || matchesAnyGlob(filePath, config.ignoreFiles)) {
+ lastSkip = 'config-ignore-file';
+ continue;
+ }
+ if (!fs.existsSync(filePath)) {
+ lastSkip = 'file-missing';
+ continue;
+ }
+
+ if (primaryFileSet.has(filePath)) {
+ const editCount = bumpEditCount(cache, sessionId, filePath);
+ audit.editCount = editCount;
+
+ if (editCount > EDIT_COUNT_THRESHOLD) {
+ const wasJustCrossed = editCount === EDIT_COUNT_THRESHOLD + 1;
+ if (wasJustCrossed && !suppressionWinner) {
+ suppressionWinner = { filePath };
+ }
+ lastSkip = 'suppressed';
+ suppressedHit = true;
+ continue;
+ }
+ }
+
+ const content = fs.readFileSync(filePath, 'utf-8');
+ let findings;
+ let detectorThrew = false;
+ if ((ext === '.html' || ext === '.htm') && typeof det.detectHtml === 'function') {
+ try { findings = await det.detectHtml(filePath); } catch { findings = []; detectorThrew = true; }
+ } else {
+ try { findings = await det.detectText(content, filePath); } catch { findings = []; detectorThrew = true; }
+ }
+
+ const filtered = filterFindings(findings || [], content, ext, config);
+ const fresh = dedupeAgainstCache(filtered, cache, sessionId, filePath);
+ audit.findings = (findings || []).length;
+ audit.freshFindings = fresh.length;
+
+ if (fresh.length > 0) {
+ rememberFindings(cache, sessionId, filePath, fresh);
+ freshGroups.push({ filePath, findings: fresh });
+ continue;
+ }
+
+ if (detectorThrew) {
+ detectorThrewAny = true;
+ continue;
+ }
+
+ if (filtered.length > 0 && !pendingWinner) {
+ const known = (ensureFile(cache, sessionId, filePath).findings || []).slice();
+ pendingWinner = { filePath, known };
+ } else if (filtered.length === 0 && !cleanWinner) {
+ cleanWinner = { filePath };
+ }
+ }
+
+ persistCache(projectCwd, cache);
+
+ if (freshGroups.length > 0) {
+ const firstGroup = freshGroups[0];
+ const text = renderGroupedTemplate(freshGroups, config, { cwd: projectCwd });
+ const allFindings = freshGroups.flatMap((group) => group.findings);
+ return {
+ exitCode: 0,
+ stdout: payload(text, 'PostToolUse', harness),
+ emission: {
+ kind: 'fresh',
+ file: firstGroup.filePath,
+ findings: firstGroup.findings,
+ groups: freshGroups,
+ },
+ audit: {
+ ...audit,
+ file: firstGroup.filePath,
+ emitted: true,
+ freshFiles: freshGroups.length,
+ freshFindings: allFindings.length,
+ chars: text.length,
+ durationMs: Date.now() - started,
+ },
+ };
+ }
+
+ if (detectorThrewAny && !pendingWinner && !cleanWinner) {
+ return result({ emitted: false, error: 'detector-threw', durationMs: Date.now() - started });
+ }
+
+ if (truthy(env.IMPECCABLE_HOOK_QUIET)) {
+ return result({ emitted: false, quiet: true, durationMs: Date.now() - started });
+ }
+
+ if (pendingWinner && shouldEmitAckForFile(pendingWinner.filePath)) {
+ const text = renderPendingAck(pendingWinner.filePath, pendingWinner.known, { cwd: projectCwd });
+ return {
+ exitCode: 0,
+ stdout: payload(text, 'PostToolUse', harness),
+ emission: { kind: 'pending', file: pendingWinner.filePath, known: pendingWinner.known },
+ audit: {
+ ...audit,
+ file: pendingWinner.filePath,
+ emitted: true,
+ kind: 'pending',
+ pending: pendingWinner.known.length,
+ chars: text.length,
+ durationMs: Date.now() - started,
+ },
+ };
+ }
+
+ if (suppressionWinner) {
+ const text = suppressionNotice(relativize(suppressionWinner.filePath, projectCwd));
+ return {
+ exitCode: 0,
+ stdout: payload(text, 'PostToolUse', harness),
+ emission: { kind: 'suppression', file: suppressionWinner.filePath },
+ audit: {
+ ...audit,
+ file: suppressionWinner.filePath,
+ suppressed: true,
+ emitted: true,
+ durationMs: Date.now() - started,
+ },
+ };
+ }
+
+ if (cleanWinner && shouldEmitAckForFile(cleanWinner.filePath)) {
+ const text = renderCleanAck(cleanWinner.filePath, { cwd: projectCwd });
+ return {
+ exitCode: 0,
+ stdout: payload(text, 'PostToolUse', harness),
+ emission: { kind: 'clean', file: cleanWinner.filePath },
+ audit: {
+ ...audit,
+ file: cleanWinner.filePath,
+ emitted: true,
+ kind: 'clean',
+ chars: text.length,
+ durationMs: Date.now() - started,
+ },
+ };
+ }
+
+ if (pendingWinner || cleanWinner) {
+ return result({ emitted: false, skipped: 'non-ui-ack', durationMs: Date.now() - started });
+ }
+
+ if (suppressedHit) {
+ return result({ suppressed: true, emitted: false, durationMs: Date.now() - started });
+ }
+
+ return result({ skipped: lastSkip, durationMs: Date.now() - started });
+ } catch (err) {
+ return {
+ exitCode: 0,
+ stdout: '',
+ audit: { ...audit, error: String(err && err.message ? err.message : err) },
+ };
+ }
+}
+
+export function payload(text, eventName = 'PostToolUse', harness = 'claude') {
+ if (harness === 'cursor') {
+ return JSON.stringify({ additional_context: text });
+ }
+ return JSON.stringify({
+ hookSpecificOutput: { hookEventName: eventName, additionalContext: text },
+ });
+}
diff --git a/.gemini/skills/impeccable/scripts/hook.mjs b/.gemini/skills/impeccable/scripts/hook.mjs
new file mode 100644
index 000000000..b862f8033
--- /dev/null
+++ b/.gemini/skills/impeccable/scripts/hook.mjs
@@ -0,0 +1,61 @@
+#!/usr/bin/env node
+/**
+ * Impeccable design hook — PostToolUse entry point.
+ *
+ * Reads the Claude Code / Codex / Cursor hook event from stdin, runs the design
+ * detector against the touched file, and emits a system reminder via
+ * `hookSpecificOutput.additionalContext` when findings exist.
+ *
+ * Contract: never break a turn. Always exit 0. Clean files emit a small ack
+ * unless quiet mode is enabled.
+ *
+ * Most logic lives in `hook-lib.mjs` so it is unit-testable without a
+ * subprocess. This file is the thin stdin/stdout adapter.
+ */
+
+import { runHook, 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');
+}
+
+async function main() {
+ // Snapshot the inherited env FIRST so the re-entrancy guard checks the
+ // parent's value, not the value we are about to export for any child
+ // processes the hook might ever spawn.
+ const inheritedEnv = { ...process.env };
+ process.env.IMPECCABLE_HOOK_DEPTH = process.env.IMPECCABLE_HOOK_DEPTH || '1';
+
+ let stdinJson = '';
+ try { stdinJson = await readStdin(); } catch { /* fall through */ }
+
+ const result = await runHook({
+ stdinJson,
+ env: inheritedEnv,
+ cwd: process.cwd(),
+ });
+
+ writeAuditLog(process.env, result.audit);
+
+ if (result.stdout) process.stdout.write(result.stdout);
+ process.exit(result.exitCode || 0);
+}
+
+main().catch((err) => {
+ // Last-ditch: never break the agent's turn even if something we did not
+ // anticipate goes wrong. Audit-log the failure if logging is enabled.
+ try {
+ writeAuditLog(process.env, {
+ ts: new Date().toISOString(),
+ event: 'PostToolUse',
+ error: String(err && err.message ? err.message : err),
+ });
+ } catch { /* swallow */ }
+ if (process.env.IMPECCABLE_HOOK_DEBUG) {
+ process.stderr.write(`[impeccable-hook] ${err}\n`);
+ }
+ process.exit(0);
+});
diff --git a/.gemini/skills/impeccable/scripts/live-inject.mjs b/.gemini/skills/impeccable/scripts/live-inject.mjs
index 4e5c5dc0a..69ce530c1 100644
--- a/.gemini/skills/impeccable/scripts/live-inject.mjs
+++ b/.gemini/skills/impeccable/scripts/live-inject.mjs
@@ -32,6 +32,8 @@ const IGNORE_MARKER_CLOSE = '# impeccable-live-ignore-end';
export const LIVE_IGNORE_PATTERNS = Object.freeze([
'.impeccable/hook.cache.json',
+ '.impeccable/hook.pending.json',
+ '.impeccable/hook.local.json',
'.impeccable/live/server.json',
'.impeccable/live/sessions/',
'.impeccable/live/previews/',
diff --git a/.github/skills/impeccable/SKILL.md b/.github/skills/impeccable/SKILL.md
index f3a23c231..25fc8b4de 100644
--- a/.github/skills/impeccable/SKILL.md
+++ b/.github/skills/impeccable/SKILL.md
@@ -124,7 +124,7 @@ If someone could look at this interface and say "AI made that" without doubt, it
| `optimize [target]` | Fix | Diagnose and fix UI performance | [reference/optimize.md](reference/optimize.md) |
| `live` | Iterate | Visual variant mode: pick elements in the browser, generate alternatives | [reference/live.md](reference/live.md) |
-Plus two management commands: `pin <command>` and `unpin <command>`, detailed below.
+Plus three management commands: `pin <command>`, `unpin <command>`, and `hooks <on|off|status|...>`, detailed below.
### Routing rules
@@ -141,7 +141,7 @@ Plus two management commands: `pin <command>` and `unpin <command>`, detailed be
**If `scan.targets` is non-empty, run `node .github/skills/impeccable/scripts/detect.mjs --json <scan.targets joined by spaces>` once** (the bundled detector over local files: no network, no npx). `scan.via` tells you what they are: `git-changes` (the markup/style files in your dirty tree, the most relevant set), `source-dir` (e.g. `src`, `app`), `html`, or `root`. Fold the hits into your picks: many quality / contrast hits → `audit` or `polish`; a specific slop family → the matching command (gradient text or eyebrows → `quieter` / `typeset`, flat or gray palette → `colorize`, and so on). It's a real, current signal that beats guessing. If detect errors or the tree is large and slow, skip it and recommend the user run `audit` themselves; never block the suggestion on it.
Keep it to 2-3 pointed picks with the exact command to type. The menu stays the fallback; the recommendation is the lede.
-2. **First word matches a command**: load its reference file and follow its instructions. Everything after the command name is the target.
+2. **First word matches a command** (table above OR `pin` / `unpin` / `hooks`): load its reference file and follow its instructions. Everything after the command name is the target.
3. **First word doesn't match, but the intent clearly maps to one command** (e.g. "fix the spacing" → `layout`, "rewrite this error message" → `clarify`, "the colors feel flat" → `colorize`): load that command's reference and proceed as if invoked. If two commands could fit, ask once which.
4. **No clear command match**: general design invocation. Apply the setup steps, the General rules, and the loaded register reference, using the full argument as context.
@@ -159,4 +159,8 @@ If the first word is `craft`, setup still runs first, but [reference/craft.md](r
node .github/skills/impeccable/scripts/pin.mjs <pin|unpin> <command>
```
-Valid `<command>` is any command from the table above. Report the script's result concisely. Confirm the new shortcut on success, relay stderr verbatim on error.
\ No newline at end of file
+Valid `<command>` is any command from the table above. Report the script's result concisely. Confirm the new shortcut on success, relay stderr verbatim on error.
+
+## Hooks
+
+`/impeccable hooks <on|off|status|ignore-rule|ignore-file|ignore-value|reset>` manages the design detector hook for this project. The hook auto-runs the detector after direct UI file edits and surfaces findings as system reminders. Full flow is in [reference/hooks.md](reference/hooks.md); load it when the user invokes `/impeccable hooks` with any argument.
\ No newline at end of file
diff --git a/.github/skills/impeccable/reference/hooks.md b/.github/skills/impeccable/reference/hooks.md
new file mode 100644
index 000000000..19ba4b289
--- /dev/null
+++ b/.github/skills/impeccable/reference/hooks.md
@@ -0,0 +1,82 @@
+# /impeccable hooks
+
+Manage the **design detector hook** for the current project.
+
+The hook runs the impeccable design detector on direct file edits to design-relevant files (`.tsx`, `.jsx`, `.html`, `.vue`, `.svelte`, `.astro`, `.css`, `.scss`, `.sass`, `.less`, `.ts`, `.js`). Claude Code and Codex use `PostToolUse` and push a short system reminder into the agent's context after the edit; findings get a correction prompt, pending issues get a re-nudge, and clean UI-ish files get a short ack unless `IMPECCABLE_HOOK_QUIET=1` is set. Plain `.ts` and `.js` files are still scanned, but stay quiet unless the detector finds something. Cursor uses `preToolUse` to block bad proposed writes before they land and stays silent when it allows a clean write.
+
+This command toggles the hook **per project** by editing `.impeccable/hook.json`. Local-only ignore policy lives in `.impeccable/hook.local.json`, which is gitignored. To disable globally, set `IMPECCABLE_HOOK_DISABLED=1` in your shell environment.
+
+Supported harnesses: Claude Code (`.claude/settings.json` in the project), Codex (`.codex/hooks.json` in the project), and Cursor (`.cursor/hooks.json` in the project).
+
+On **Cursor**, `preToolUse` checks proposed Write/Edit/Shell write content and denies only when the real detector finds an issue. The denial message is visible to the agent as the tool error, so the agent can reconsider before the bad write lands.
+
+## Routing
+
+The first argument is the action. Defaults to `status`.
+
+| Action | What it does |
+|---|---|
+| `status` | Print current state, shared/local config paths, ignored rules / files / values, env override. |
+| `on` | Set `enabled: true` in `.impeccable/hook.json`. |
+| `off` | Set `enabled: false` in `.impeccable/hook.json`. |
+| `ignore-rule <id>` | Append `<id>` to `ignoreRules`; for `overused-font`, requires `--all-values`. |
+| `ignore-file <glob>` | Append `<glob>` to `ignoreFiles`. |
+| `ignore-value <id> <value> [--shared] [--reason "..."]` | Append a rule/value suppression to shared `.impeccable/hook.json`. |
+| `ignore-value <id> <value> --local [--reason "..."]` | Append a private rule/value suppression to `.impeccable/hook.local.json`. |
+| `reset` | Delete the project config, dedup cache, and Cursor pending queue. |
+
+## Flow
+
+1. Resolve the action from the user's argument. If no action was given, default to `status`.
+2. Invoke the admin script and pass the user's output through verbatim:
+
+ ```bash
+ node .github/skills/impeccable/scripts/hook-admin.mjs <action> [args...]
+ ```
+
+3. If `<action>` is `off`, follow up with a one-line note: "Done. New edits will not trigger the design hook in this project until you run `/impeccable hooks on`."
+4. If `<action>` is `on`, follow up with: "Done. The design hook will fire after the next Edit/Write/MultiEdit on a UI file."
+5. If `<action>` is `ignore-value`, `ignore-file`, or `ignore-rule`, just print the script output. The default scope is shared `.impeccable/hook.json`; add `--local` only when the user explicitly asks for a private exception.
+6. If `<action>` is `status`, just print the script output. Do not add commentary unless the user asked a follow-up question.
+
+## Intentional findings
+
+The hook itself never writes ignore config. Persist an exception only after the user explicitly confirms the flagged issue is intentional, and always go through `hook-admin.mjs`.
+
+Prefer the narrowest exception:
+
+- If the finding line shows an exact `ignore-value` command, run that command. This writes shared `.impeccable/hook.json` by default.
+- For `overused-font`, use `ignore-value` when the user confirms a specific font. Do not use `ignore-rule overused-font` for a specific font.
+- If the finding has no value-specific command, such as `side-tab`, prefer `ignore-file <path>` for the current file.
+- Use `ignore-rule <id>` only when the user asks to suppress that whole rule across the project. For broad overused-font suppression, use `ignore-rule overused-font --all-values` only when the user asks to ignore overused fonts generally.
+- Do not add source comments such as `impeccable: ignore`; inline comments pollute code and are not a supported suppression mechanism.
+
+Example value-specific exception:
+
+```bash
+node .github/skills/impeccable/scripts/hook-admin.mjs ignore-value overused-font Inter --shared --reason "User confirmed Inter is intentional"
+```
+
+Example whole-rule font exception:
+
+```bash
+node .github/skills/impeccable/scripts/hook-admin.mjs ignore-rule overused-font --all-values --reason "User asked to ignore overused fonts generally"
+```
+
+Example file-scoped exception:
+
+```bash
+node .github/skills/impeccable/scripts/hook-admin.mjs ignore-file "src/legacy/Card.tsx"
+```
+
+## Constraints
+
+- Never modify `.impeccable/hook.json` or `.impeccable/hook.local.json` by hand from this command. Always go through `hook-admin.mjs` so writes stay validated and the file shape stays consistent.
+- Do not edit the hook scripts themselves (`hook.mjs`, `hook-lib.mjs`, `hook-before-edit.mjs`) from this flow. Those are skill plumbing.
+- Cursor can block a proposed write when the detector finds a real issue. Claude Code and Codex do not block the edit; they emit a post-edit reminder instead. Disabling stops both blocking and reminders.
+- The hook is bundled with the Impeccable skill and installed through project-local manifests: `.claude/settings.json`, `.codex/hooks.json`, and `.cursor/hooks.json`. On Codex, the user must approve the hook via `/hooks` the first time. On Cursor, confirm hooks are enabled under Settings -> Hooks.
+
+## Failure modes
+
+- If `.impeccable/hook.json` or `.impeccable/hook.local.json` is unreadable or malformed, the hook ignores that file and uses the remaining valid config/defaults. `hook-admin.mjs status` will show malformed files as ignored.
+- If the user asks to "disable the hook" globally, suggest both options: `IMPECCABLE_HOOK_DISABLED=1` env var (one-shot, follows the shell), and `/impeccable hooks off` (persistent for this project, committable).
diff --git a/.github/skills/impeccable/scripts/detector/engines/regex/detect-text.mjs b/.github/skills/impeccable/scripts/detector/engines/regex/detect-text.mjs
index fd0d9c73f..4c0777c93 100644
--- a/.github/skills/impeccable/scripts/detector/engines/regex/detect-text.mjs
+++ b/.github/skills/impeccable/scripts/detector/engines/regex/detect-text.mjs
@@ -446,7 +446,7 @@ function detectText(content, filePath, options = {}) {
// Run regex matchers on the full file content (catches Tailwind classes, inline styles)
// Enable block context for CSS files where related properties span multiple lines
- const cssLike = new Set(['.css', '.scss', '.less']);
+ const cssLike = new Set(['.css', '.scss', '.sass', '.less']);
findings.push(...runRegexMatchers(lines, filePath, 0, cssLike.has(ext) || null, {
profile,
phase: 'source',
diff --git a/.github/skills/impeccable/scripts/detector/node/file-system.mjs b/.github/skills/impeccable/scripts/detector/node/file-system.mjs
index a80250a0e..aaa8c6df7 100644
--- a/.github/skills/impeccable/scripts/detector/node/file-system.mjs
+++ b/.github/skills/impeccable/scripts/detector/node/file-system.mjs
@@ -11,7 +11,7 @@ const SKIP_DIRS = new Set([
]);
const SCANNABLE_EXTENSIONS = new Set([
- '.html', '.htm', '.css', '.scss', '.less',
+ '.html', '.htm', '.css', '.scss', '.sass', '.less',
'.jsx', '.tsx', '.js', '.ts',
'.vue', '.svelte', '.astro',
]);
diff --git a/.github/skills/impeccable/scripts/hook-admin.mjs b/.github/skills/impeccable/scripts/hook-admin.mjs
new file mode 100644
index 000000000..86fcfa909
--- /dev/null
+++ b/.github/skills/impeccable/scripts/hook-admin.mjs
@@ -0,0 +1,300 @@
+#!/usr/bin/env node
+/**
+ * `/impeccable hooks <on|off|status|reset>` — manage the design hook
+ * via .impeccable/hook.json and .impeccable/hook.local.json in the current
+ * project.
+ *
+ * Usage:
+ * node hook-admin.mjs status # print current state
+ * node hook-admin.mjs on # set enabled: true
+ * node hook-admin.mjs off # set enabled: false
+ * node hook-admin.mjs ignore-rule <rule-id> # append to ignoreRules
+ * node hook-admin.mjs ignore-rule overused-font --all-values
+ * node hook-admin.mjs ignore-file <glob> # append to ignoreFiles
+ * node hook-admin.mjs ignore-value <rule> <value> # append to shared ignoreValues
+ * node hook-admin.mjs ignore-value <rule> <value> --local
+ * node hook-admin.mjs reset # remove all config + cache
+ *
+ * Designed to be invoked by the LLM from the reference/hooks.md flow.
+ * Output is human-readable; the harness will pass it back to the user.
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+
+import {
+ getConfigPath,
+ getLocalConfigPath,
+ getCachePath,
+ getPendingPath,
+ readConfig,
+ DEFAULT_CONFIG,
+ ensureHookGitExcludes,
+ normalizeIgnoreValue,
+ normalizeIgnoreValueEntries,
+} from './hook-lib.mjs';
+
+const ACTIONS = new Set(['status', 'on', 'off', 'ignore-rule', 'ignore-file', 'ignore-value', 'reset']);
+
+function readRawConfigFile(filePath) {
+ if (!fs.existsSync(filePath)) return { exists: false, malformed: false, raw: null };
+ try {
+ return { exists: true, malformed: false, raw: JSON.parse(fs.readFileSync(filePath, 'utf-8')) };
+ } catch {
+ return { exists: true, malformed: true, raw: null };
+ }
+}
+
+function readRawConfig(cwd, opts = {}) {
+ const filePath = opts.local ? getLocalConfigPath(cwd) : getConfigPath(cwd);
+ return readRawConfigFile(filePath).raw;
+}
+
+function writeConfig(cwd, config, opts = {}) {
+ const filePath = opts.local ? getLocalConfigPath(cwd) : getConfigPath(cwd);
+ if (opts.local) ensureHookGitExcludes(cwd);
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
+ fs.writeFileSync(filePath, JSON.stringify(config, null, 2) + '\n');
+ return filePath;
+}
+
+function mergeConfig(existing) {
+ // Persist the full shape so /impeccable hooks edits leave a complete file
+ // for the user to see, not an unhelpful `{"enabled":false}`.
+ const base = existing && typeof existing === 'object' ? existing : {};
+ return {
+ enabled: base.enabled === false ? false : true,
+ ignoreRules: Array.isArray(base.ignoreRules) ? Array.from(new Set(base.ignoreRules.map(String))) : [],
+ ignoreFiles: Array.isArray(base.ignoreFiles) ? Array.from(new Set(base.ignoreFiles.map(String))) : [],
+ ignoreValues: normalizeIgnoreValueEntries(base.ignoreValues || []),
+ limits: {
+ maxFindings: Number.isFinite(base?.limits?.maxFindings) ? base.limits.maxFindings : DEFAULT_CONFIG.limits.maxFindings,
+ maxChars: Number.isFinite(base?.limits?.maxChars) ? base.limits.maxChars : DEFAULT_CONFIG.limits.maxChars,
+ },
+ };
+}
+
+function mergeLocalConfig(existing) {
+ const base = existing && typeof existing === 'object' ? existing : {};
+ const out = {};
+ if (Object.prototype.hasOwnProperty.call(base, 'enabled')) {
+ out.enabled = base.enabled === false ? false : true;
+ }
+ if (Array.isArray(base.ignoreRules)) {
+ out.ignoreRules = Array.from(new Set(base.ignoreRules.map(String)));
+ }
+ if (Array.isArray(base.ignoreFiles)) {
+ out.ignoreFiles = Array.from(new Set(base.ignoreFiles.map(String)));
+ }
+ out.ignoreValues = normalizeIgnoreValueEntries(base.ignoreValues || []);
+ if (base.limits && typeof base.limits === 'object') {
+ const limits = {};
+ if (Number.isFinite(base.limits.maxFindings)) limits.maxFindings = base.limits.maxFindings;
+ if (Number.isFinite(base.limits.maxChars)) limits.maxChars = base.limits.maxChars;
+ if (Object.keys(limits).length) out.limits = limits;
+ }
+ return out;
+}
+
+function statusReport(cwd) {
+ const shared = readRawConfigFile(getConfigPath(cwd));
+ const local = readRawConfigFile(getLocalConfigPath(cwd));
+ const cfg = readConfig(cwd);
+ const envKill = process.env.IMPECCABLE_HOOK_DISABLED;
+ const envState = envKill ? `IMPECCABLE_HOOK_DISABLED=${envKill}` : 'unset';
+ const cfgPath = path.relative(cwd, getConfigPath(cwd)) || '.impeccable/hook.json';
+ const localPath = path.relative(cwd, getLocalConfigPath(cwd)) || '.impeccable/hook.local.json';
+ const cachePath = path.relative(cwd, getCachePath(cwd)) || '.impeccable/hook.cache.json';
+ const fileState = (info, relPath, absent) => {
+ if (info.malformed) return `${relPath} (malformed; ignored)`;
+ if (info.exists) return relPath;
+ return `${relPath} (${absent})`;
+ };
+ const ignoreValues = cfg.ignoreValues.map((entry) => `${entry.rule}=${entry.value}`);
+
+ const lines = [
+ `Impeccable design hook`,
+ ` state: ${cfg.enabled ? 'enabled' : 'disabled'}`,
+ ` shared file: ${fileState(shared, cfgPath, 'using defaults; file not present')}`,
+ ` local file: ${fileState(local, localPath, 'not present')}`,
+ ` ignoreRules: ${cfg.ignoreRules.length ? cfg.ignoreRules.join(', ') : '(none)'}`,
+ ` ignoreFiles: ${cfg.ignoreFiles.length ? cfg.ignoreFiles.join(', ') : '(none)'}`,
+ ` ignoreValues: ${ignoreValues.length ? ignoreValues.join(', ') : '(none)'}`,
+ ` maxFindings: ${cfg.limits.maxFindings}`,
+ ` maxChars: ${cfg.limits.maxChars}`,
+ ` env override: ${envState}`,
+ ` cache file: ${fs.existsSync(getCachePath(cwd)) ? cachePath : `${cachePath} (not present)`}`,
+ ];
+ return lines.join('\n');
+}
+
+function setEnabled(cwd, value) {
+ const config = mergeConfig(readRawConfig(cwd));
+ config.enabled = value;
+ const target = writeConfig(cwd, config);
+ return `Design hook ${value ? 'enabled' : 'disabled'} for this project (wrote ${path.relative(cwd, target) || target}).`;
+}
+
+function normalizeRuleId(rule) {
+ return String(rule || '').trim().toLowerCase();
+}
+
+function parseIgnoreRuleArgs(args) {
+ const positionals = [];
+ let allValues = false;
+
+ for (let i = 0; i < args.length; i++) {
+ const arg = String(args[i] || '');
+ if (arg === '--all-values') {
+ allValues = true;
+ } else if (arg === '--reason') {
+ while (i + 1 < args.length && !String(args[i + 1]).startsWith('--')) i++;
+ } else if (arg.startsWith('--reason=')) {
+ // Accepted for command symmetry; ignoreRules stores rule ids only.
+ } else if (arg.startsWith('--')) {
+ throw new Error(`Unknown ignore-rule flag: ${arg}`);
+ } else {
+ positionals.push(arg);
+ }
+ }
+
+ return {
+ rule: normalizeRuleId(positionals[0]),
+ allValues,
+ };
+}
+
+function addIgnoreRule(cwd, args) {
+ const parsed = parseIgnoreRuleArgs(args);
+ const rule = parsed.rule;
+ if (!rule) throw new Error('Pass a rule id, e.g. /impeccable hooks ignore-rule side-tab');
+ if (rule === 'overused-font' && !parsed.allValues) {
+ throw new Error('overused-font is value-specific by default. Use /impeccable hooks ignore-value overused-font <font> for a confirmed font, or /impeccable hooks ignore-rule overused-font --all-values only when the user asked to ignore overused fonts generally.');
+ }
+ const config = mergeConfig(readRawConfig(cwd));
+ if (!config.ignoreRules.includes(rule)) config.ignoreRules.push(rule);
+ writeConfig(cwd, config);
+ return `Added "${rule}" to ignoreRules. Current: ${config.ignoreRules.join(', ')}`;
+}
+
+function addIgnoreFile(cwd, glob) {
+ if (!glob) throw new Error('Pass a glob, e.g. /impeccable hooks ignore-file "src/legacy/**"');
+ const config = mergeConfig(readRawConfig(cwd));
+ if (!config.ignoreFiles.includes(glob)) config.ignoreFiles.push(glob);
+ writeConfig(cwd, config);
+ return `Added "${glob}" to ignoreFiles. Current: ${config.ignoreFiles.join(', ')}`;
+}
+
+function parseIgnoreValueArgs(args) {
+ const positionals = [];
+ let shared = false;
+ let local = false;
+ let reason = '';
+
+ for (let i = 0; i < args.length; i++) {
+ const arg = args[i];
+ if (arg === '--shared') {
+ shared = true;
+ } else if (arg === '--local') {
+ local = true;
+ } else if (arg === '--reason') {
+ const chunks = [];
+ while (i + 1 < args.length && !String(args[i + 1]).startsWith('--')) {
+ chunks.push(args[++i]);
+ }
+ reason = chunks.join(' ').trim();
+ } else if (String(arg).startsWith('--reason=')) {
+ reason = String(arg).slice('--reason='.length).trim();
+ } else {
+ positionals.push(arg);
+ }
+ }
+
+ const [rule, ...valueParts] = positionals;
+ return {
+ rule: String(rule || '').trim().toLowerCase(),
+ value: normalizeIgnoreValue(valueParts.join(' ')),
+ shared,
+ local,
+ reason,
+ };
+}
+
+function addIgnoreValue(cwd, args) {
+ const parsed = parseIgnoreValueArgs(args);
+ if (!parsed.rule || !parsed.value) {
+ throw new Error('Pass a rule id and value, e.g. /impeccable hooks ignore-value overused-font Inter');
+ }
+
+ if (parsed.shared && parsed.local) {
+ throw new Error('Pass only one scope flag: --shared or --local');
+ }
+
+ const local = parsed.local;
+ const config = local
+ ? mergeLocalConfig(readRawConfig(cwd, { local: true }))
+ : mergeConfig(readRawConfig(cwd, { local: false }));
+ const key = `${parsed.rule}\0${parsed.value}`;
+ const existing = config.ignoreValues.find((entry) => `${entry.rule}\0${entry.value}` === key);
+
+ if (existing) {
+ if (parsed.reason) existing.reason = parsed.reason;
+ } else {
+ const entry = {
+ rule: parsed.rule,
+ value: parsed.value,
+ createdAt: new Date().toISOString(),
+ };
+ if (parsed.reason) entry.reason = parsed.reason;
+ config.ignoreValues.push(entry);
+ }
+
+ const target = writeConfig(cwd, config, { local });
+ const scope = local ? 'local ignoreValues' : 'shared ignoreValues';
+ return `Added ${parsed.rule}=${parsed.value} to ${scope} (${path.relative(cwd, target) || target}).`;
+}
+
+function reset(cwd) {
+ const removed = [];
+ for (const filePath of [getConfigPath(cwd), getLocalConfigPath(cwd), getCachePath(cwd), getPendingPath(cwd)]) {
+ try {
+ if (fs.existsSync(filePath)) {
+ fs.unlinkSync(filePath);
+ removed.push(path.relative(cwd, filePath) || filePath);
+ }
+ } catch { /* ignore */ }
+ }
+ return removed.length
+ ? `Reset design hook config and cache (removed: ${removed.join(', ')}).`
+ : 'No hook config or cache to remove. Already at defaults.';
+}
+
+function main() {
+ const [, , actionArg, ...rest] = process.argv;
+ const action = (actionArg || 'status').toLowerCase();
+ const cwd = process.cwd();
+
+ if (!ACTIONS.has(action)) {
+ process.stderr.write(`Unknown action: ${action}\nValid: ${Array.from(ACTIONS).join(', ')}\n`);
+ process.exit(1);
+ }
+
+ try {
+ let out = '';
+ switch (action) {
+ case 'status': out = statusReport(cwd); break;
+ case 'on': out = setEnabled(cwd, true); break;
+ case 'off': out = setEnabled(cwd, false); break;
+ case 'ignore-rule': out = addIgnoreRule(cwd, rest); break;
+ case 'ignore-file': out = addIgnoreFile(cwd, rest[0]); break;
+ case 'ignore-value': out = addIgnoreValue(cwd, rest); break;
+ case 'reset': out = reset(cwd); break;
+ }
+ process.stdout.write(out + '\n');
+ } catch (err) {
+ process.stderr.write(`Error: ${err.message || err}\n`);
+ process.exit(1);
+ }
+}
+
+main();
diff --git a/.github/skills/impeccable/scripts/hook-before-edit.mjs b/.github/skills/impeccable/scripts/hook-before-edit.mjs
new file mode 100644
index 000000000..54b2709d2
--- /dev/null
+++ b/.github/skills/impeccable/scripts/hook-before-edit.mjs
@@ -0,0 +1,408 @@
+#!/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 shellContent = shellHereDocContent(shellCommand(input));
+ if (shellContent) return shellContent;
+ const copiedContent = shellCopiedFileContent(shellCommand(input), 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 || '';
+}
+
+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 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' });
+});
diff --git a/.github/skills/impeccable/scripts/hook-lib.mjs b/.github/skills/impeccable/scripts/hook-lib.mjs
new file mode 100644
index 000000000..02199f530
--- /dev/null
+++ b/.github/skills/impeccable/scripts/hook-lib.mjs
@@ -0,0 +1,1232 @@
+/**
+ * Shared library for the Impeccable design hook.
+ *
+ * Pure-ish helpers split out from `hook.mjs` so unit tests can exercise
+ * config parsing, finding filtering, dedup, render, and cache logic without
+ * spawning a subprocess. `hook.mjs` itself is the thin stdin/stdout shim.
+ *
+ * Public surface (everything exported is part of the contract):
+ * ENVELOPE_PREFIX, ALLOWED_EXTS, ACK_EXTS, SENSITIVE_PATH, GENERATED_PATH, TRUTHY
+ * truthy(value)
+ * readConfig(cwd) / DEFAULT_CONFIG / getConfigPath(cwd) / getLocalConfigPath(cwd)
+ * normalizeIgnoreValue(value)
+ * readCache(cwd) / persistCache(cwd, cache)
+ * bumpEditCount(cache, sessionId, filePath) -> number
+ * suppressionNotice(filePath)
+ * filterFindings(findings, content, ext, config)
+ * dedupeAgainstCache(findings, cache, sessionId, filePath)
+ * renderTemplate(findings, filePath, config, opts)
+ * renderCleanAck(filePath, opts) / renderPendingAck(filePath, known, opts)
+ * shouldEmitAckForFile(filePath)
+ * writeAuditLog(env, entry)
+ * loadDetector() -> Promise<{ detectText, detectHtml }>
+ * matchesAnyGlob(filePath, globs)
+ * normalizeScanTargets(primaryTargets, projectCwd)
+ * runHook(deps) -> { exitCode, stdout, audit, reason? }
+ *
+ * Design notes:
+ * - All errors are swallowed at the runHook seam. The detector throwing must
+ * never break a turn. See PRD §5 "Failure modes".
+ * - Cache shape is JSON-friendly; we gc the oldest sessions when there are
+ * more than 8 to keep file size predictable across long-lived projects.
+ * - The detector loader looks for `detector/detect-antipatterns.mjs` next to
+ * this file first (built skill layout) and falls back to the repo root's
+ * `cli/engine/detect-antipatterns.mjs` (running from source).
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+import { pathToFileURL, fileURLToPath } from 'node:url';
+
+const __filename = fileURLToPath(import.meta.url);
+const __dirname = path.dirname(__filename);
+
+export const ENVELOPE_PREFIX = '[impeccable@1]';
+
+export const ALLOWED_EXTS = new Set([
+ '.tsx', '.jsx', '.html', '.htm', '.vue', '.svelte', '.astro',
+ '.css', '.scss', '.sass', '.less', '.ts', '.js',
+]);
+
+export const ACK_EXTS = new Set([
+ '.tsx', '.jsx', '.html', '.htm', '.vue', '.svelte', '.astro',
+ '.css', '.scss', '.sass', '.less',
+]);
+
+// Hard-skip regex for sensitive files. Cannot be turned off via config.
+// Match tokenized secret/credential filenames, not UI names such as
+// CredentialForm.tsx, SecretPage.jsx, or secretary-dashboard.vue.
+export const SENSITIVE_PATH = new RegExp([
+ String.raw`(?:^|[/\\])\.env(?:\.|$)`,
+ String.raw`(?:^|[/\\])\.git(?:[/\\]|$)`,
+ String.raw`(?:^|[/\\])id_rsa(?:$|[._-])[^/\\]*$`,
+ String.raw`(?:^|[/\\])[^/\\]*\.pem$`,
+ String.raw`(?:^|[/\\])(?:[^/\\]*[._-])?(?:secret|secrets|credential|credentials)(?=[._-])[^/\\]*\.(?:json|ya?ml|toml|ini|conf|config|env|txt|key|cert|crt|pem|js|ts)$`,
+].join('|'), 'i');
+
+// Hard-skip regex for generated, lock, minified, and build-output paths.
+export const GENERATED_PATH = /(?:\.generated\.[a-z]+$|\.d\.ts$|\.min\.[a-z]+$|[/\\]node_modules[/\\]|[/\\](?:dist|build|out|\.next|\.cache|coverage)[/\\]|[/\\]?[^/\\]+\.lock(?:\.json)?$)/i;
+
+export const TRUTHY = /^(1|true|yes|on)$/i;
+
+export const DEFAULT_CONFIG = Object.freeze({
+ enabled: true,
+ ignoreRules: [],
+ ignoreFiles: [],
+ ignoreValues: [],
+ limits: { maxFindings: 5, maxChars: 8000 },
+});
+
+export const HOOK_LOCAL_IGNORE_PATTERNS = Object.freeze([
+ '.impeccable/hook.cache.json',
+ '.impeccable/hook.pending.json',
+ '.impeccable/hook.local.json',
+]);
+
+const HOOK_IGNORE_MARKER_OPEN = '# impeccable-hook-ignore-start';
+const HOOK_IGNORE_MARKER_CLOSE = '# impeccable-hook-ignore-end';
+const CACHE_MAX_SESSIONS = 8;
+export const EDIT_COUNT_THRESHOLD = 6;
+
+export function truthy(value) {
+ return typeof value === 'string' && TRUTHY.test(value);
+}
+
+function depthIsSet(value) {
+ if (value === undefined || value === null) return false;
+ const text = String(value).trim();
+ if (!text) return false;
+ if (TRUTHY.test(text)) return true;
+ return /^\d+$/.test(text) && Number(text) > 0;
+}
+
+function safeReadJson(filePath) {
+ try {
+ return JSON.parse(fs.readFileSync(filePath, 'utf-8'));
+ } catch {
+ return null;
+ }
+}
+
+export function getConfigPath(cwd) {
+ return path.join(cwd, '.impeccable', 'hook.json');
+}
+
+export function getLocalConfigPath(cwd) {
+ return path.join(cwd, '.impeccable', 'hook.local.json');
+}
+
+export function getCachePath(cwd) {
+ return path.join(cwd, '.impeccable', 'hook.cache.json');
+}
+
+export function getPendingPath(cwd) {
+ return path.join(cwd, '.impeccable', 'hook.pending.json');
+}
+
+export function resolveProjectCwd(event, fallback = process.cwd()) {
+ return event?.cwd
+ || (Array.isArray(event?.workspace_roots) && event.workspace_roots[0])
+ || envProjectDir(fallback)
+ || fallback;
+}
+
+export function readConfig(cwd) {
+ const config = cloneDefaultConfig();
+ applyConfigSource(config, safeReadJson(getConfigPath(cwd)));
+ applyConfigSource(config, safeReadJson(getLocalConfigPath(cwd)));
+ return config;
+}
+
+function numberOr(value, fallback) {
+ return Number.isFinite(value) && value > 0 ? value : fallback;
+}
+
+function cloneDefaultConfig() {
+ return {
+ ...DEFAULT_CONFIG,
+ ignoreRules: [],
+ ignoreFiles: [],
+ ignoreValues: [],
+ limits: { ...DEFAULT_CONFIG.limits },
+ };
+}
+
+function applyConfigSource(config, raw) {
+ if (!raw || typeof raw !== 'object') return config;
+ if (Object.prototype.hasOwnProperty.call(raw, 'enabled')) {
+ config.enabled = raw.enabled === false ? false : true;
+ }
+ if (Array.isArray(raw.ignoreRules)) {
+ config.ignoreRules = uniqueStrings([...config.ignoreRules, ...raw.ignoreRules]);
+ }
+ if (Array.isArray(raw.ignoreFiles)) {
+ config.ignoreFiles = uniqueStrings([...config.ignoreFiles, ...raw.ignoreFiles]);
+ }
+ if (Array.isArray(raw.ignoreValues)) {
+ config.ignoreValues = mergeIgnoreValues(config.ignoreValues, raw.ignoreValues);
+ }
+ if (raw.limits && typeof raw.limits === 'object') {
+ config.limits = {
+ maxFindings: numberOr(raw.limits.maxFindings, config.limits.maxFindings),
+ maxChars: numberOr(raw.limits.maxChars, config.limits.maxChars),
+ };
+ }
+ return config;
+}
+
+function uniqueStrings(values) {
+ return Array.from(new Set(values.map(String)));
+}
+
+export function normalizeIgnoreValue(value) {
+ return String(value || '')
+ .trim()
+ .replace(/^["']|["']$/g, '')
+ .replace(/\+/g, ' ')
+ .replace(/\s+/g, ' ')
+ .toLowerCase();
+}
+
+function normalizeIgnoreRule(rule) {
+ return String(rule || '').trim().toLowerCase();
+}
+
+export function normalizeIgnoreValueEntries(entries) {
+ if (!Array.isArray(entries)) return [];
+ const out = [];
+ for (const entry of entries) {
+ if (!entry || typeof entry !== 'object') continue;
+ const rule = normalizeIgnoreRule(entry.rule);
+ const value = normalizeIgnoreValue(entry.value);
+ if (!rule || !value) continue;
+ const normalized = { rule, value };
+ if (typeof entry.reason === 'string' && entry.reason.trim()) {
+ normalized.reason = entry.reason.trim();
+ }
+ if (typeof entry.createdAt === 'string' && entry.createdAt.trim()) {
+ normalized.createdAt = entry.createdAt.trim();
+ }
+ out.push(normalized);
+ }
+ return out;
+}
+
+function mergeIgnoreValues(existing, incoming) {
+ const map = new Map();
+ for (const entry of normalizeIgnoreValueEntries(existing)) {
+ map.set(`${entry.rule}\0${entry.value}`, entry);
+ }
+ for (const entry of normalizeIgnoreValueEntries(incoming)) {
+ map.set(`${entry.rule}\0${entry.value}`, entry);
+ }
+ return Array.from(map.values());
+}
+
+export function readCache(cwd) {
+ const raw = safeReadJson(getCachePath(cwd));
+ if (!raw || typeof raw !== 'object' || raw.version !== 1) {
+ return { version: 1, sessions: {} };
+ }
+ return {
+ version: 1,
+ sessions: raw.sessions && typeof raw.sessions === 'object' ? raw.sessions : {},
+ };
+}
+
+export function persistCache(cwd, cache) {
+ const sessions = cache.sessions || {};
+ const ids = Object.keys(sessions);
+ if (ids.length > CACHE_MAX_SESSIONS) {
+ // Garbage-collect oldest sessions by updatedAt.
+ const ordered = ids
+ .map((id) => [id, sessions[id]?.updatedAt || 0])
+ .sort((a, b) => b[1] - a[1])
+ .slice(0, CACHE_MAX_SESSIONS);
+ const next = {};
+ for (const [id] of ordered) next[id] = sessions[id];
+ cache = { ...cache, sessions: next };
+ }
+ const target = getCachePath(cwd);
+ try {
+ ensureHookGitExcludes(cwd);
+ fs.mkdirSync(path.dirname(target), { recursive: true });
+ fs.writeFileSync(target, JSON.stringify(cache));
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+export function ensureHookGitExcludes(cwd = process.cwd()) {
+ try {
+ const target = resolveHookGitExcludeTarget(cwd);
+ if (!target) {
+ return { mode: 'none', changed: false, patterns: [...HOOK_LOCAL_IGNORE_PATTERNS] };
+ }
+
+ const patterns = target.patternPrefix
+ ? HOOK_LOCAL_IGNORE_PATTERNS.map((pattern) => `${target.patternPrefix}/${pattern}`)
+ : [...HOOK_LOCAL_IGNORE_PATTERNS];
+ const markerSuffix = target.patternPrefix || '.';
+ const markerOpen = `${HOOK_IGNORE_MARKER_OPEN} ${markerSuffix}`;
+ const markerClose = `${HOOK_IGNORE_MARKER_CLOSE} ${markerSuffix}`;
+ const existing = fs.existsSync(target.path) ? fs.readFileSync(target.path, 'utf-8') : '';
+ const block = [markerOpen, ...patterns, markerClose].join('\n');
+ const markerRe = new RegExp(`${escapeRegExp(markerOpen)}[\\s\\S]*?${escapeRegExp(markerClose)}`);
+
+ let updated;
+ if (markerRe.test(existing)) {
+ updated = existing.replace(markerRe, block);
+ } else {
+ const prefix = existing.length === 0 ? '' : existing.endsWith('\n') ? existing : `${existing}\n`;
+ updated = `${prefix}${prefix.endsWith('\n\n') || prefix === '' ? '' : '\n'}${block}\n`;
+ }
+
+ if (updated !== existing) {
+ fs.mkdirSync(path.dirname(target.path), { recursive: true });
+ fs.writeFileSync(target.path, updated, 'utf-8');
+ }
+
+ return {
+ mode: 'git-info-exclude',
+ file: path.relative(path.resolve(cwd), target.path).split(path.sep).join('/'),
+ changed: updated !== existing,
+ patterns,
+ };
+ } catch {
+ return { mode: 'error', changed: false, patterns: [...HOOK_LOCAL_IGNORE_PATTERNS] };
+ }
+}
+
+function resolveHookGitExcludeTarget(cwd) {
+ const start = path.resolve(cwd);
+ let dir = start;
+ while (true) {
+ const dotGit = path.join(dir, '.git');
+ if (fs.existsSync(dotGit)) {
+ const gitDir = resolveGitDir(dotGit, dir);
+ if (!gitDir) return null;
+ const relPrefix = path.relative(dir, start).split(path.sep).join('/');
+ return {
+ path: path.join(gitDir, 'info', 'exclude'),
+ patternPrefix: relPrefix && relPrefix !== '.' ? relPrefix : '',
+ };
+ }
+ const parent = path.dirname(dir);
+ if (parent === dir) return null;
+ dir = parent;
+ }
+}
+
+function resolveGitDir(dotGit, worktreeDir) {
+ const stat = fs.statSync(dotGit);
+ if (stat.isDirectory()) return dotGit;
+ if (!stat.isFile()) return null;
+
+ const body = fs.readFileSync(dotGit, 'utf-8').trim();
+ const match = body.match(/^gitdir:\s*(.+)$/i);
+ if (!match) return null;
+ return path.isAbsolute(match[1]) ? match[1] : path.resolve(worktreeDir, match[1]);
+}
+
+function escapeRegExp(value) {
+ return String(value).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+}
+
+function ensureSession(cache, sessionId) {
+ if (!cache.sessions[sessionId]) {
+ cache.sessions[sessionId] = { updatedAt: Date.now(), files: {} };
+ }
+ return cache.sessions[sessionId];
+}
+
+function ensureFile(cache, sessionId, filePath) {
+ const session = ensureSession(cache, sessionId);
+ if (!session.files[filePath]) {
+ session.files[filePath] = { editCount: 0, findings: [] };
+ }
+ return session.files[filePath];
+}
+
+export function bumpEditCount(cache, sessionId, filePath) {
+ const fileEntry = ensureFile(cache, sessionId, filePath);
+ fileEntry.editCount = (fileEntry.editCount || 0) + 1;
+ ensureSession(cache, sessionId).updatedAt = Date.now();
+ return fileEntry.editCount;
+}
+
+export function suppressionNotice(filePath) {
+ return `${ENVELOPE_PREFIX} Suppressing further design hints on ${filePath}. More than ${EDIT_COUNT_THRESHOLD} edits in this session reached. Run /impeccable audit to revisit.`;
+}
+
+// Glob → RegExp. Supports `**`, `*`, `?`, and `{a,b}` alternation.
+function globToRegex(glob) {
+ let re = '^';
+ let i = 0;
+ while (i < glob.length) {
+ const c = glob[i];
+ if (c === '*') {
+ if (glob[i + 1] === '*') {
+ re += '.*';
+ i += 2;
+ if (glob[i] === '/') i += 1;
+ } else {
+ re += '[^/]*';
+ i += 1;
+ }
+ } else if (c === '?') {
+ re += '[^/]';
+ i += 1;
+ } else if (c === '{') {
+ const end = glob.indexOf('}', i);
+ if (end === -1) { re += '\\{'; i += 1; continue; }
+ const parts = glob.slice(i + 1, end).split(',').map((p) => p.replace(/[.+^$()|[\]\\]/g, '\\$&'));
+ re += `(?:${parts.join('|')})`;
+ i = end + 1;
+ } else if (/[.+^$()|[\]\\]/.test(c)) {
+ re += `\\${c}`;
+ i += 1;
+ } else {
+ re += c;
+ i += 1;
+ }
+ }
+ re += '$';
+ return new RegExp(re);
+}
+
+export function matchesAnyGlob(filePath, globs) {
+ if (!Array.isArray(globs) || globs.length === 0) return false;
+ const normalized = filePath.split(path.sep).join('/');
+ for (const glob of globs) {
+ try {
+ const re = globToRegex(String(glob));
+ if (re.test(normalized)) return true;
+ // Match against basename too for convenience: `*.generated.tsx` should
+ // catch `src/foo.generated.tsx` without requiring `**/`.
+ const base = normalized.split('/').pop();
+ if (re.test(base)) return true;
+ } catch {
+ /* malformed glob, skip */
+ }
+ }
+ return false;
+}
+
+export function filterFindings(findings, _content, _ext, config) {
+ if (!Array.isArray(findings) || findings.length === 0) return [];
+ const ignoreRules = new Set((config.ignoreRules || []).map((rule) => normalizeIgnoreRule(rule)));
+ const ignoreValues = normalizeIgnoreValueEntries(config.ignoreValues || []);
+ return findings.filter((f) => {
+ if (!f || typeof f !== 'object') return false;
+ if (ignoreRules.has(normalizeIgnoreRule(f.antipattern))) return false;
+ if (isIgnoredFindingValue(f, ignoreValues)) return false;
+ return true;
+ });
+}
+
+function isIgnoredFindingValue(finding, ignoreValues) {
+ if (!Array.isArray(ignoreValues) || ignoreValues.length === 0) return false;
+ const rule = normalizeIgnoreRule(finding.antipattern);
+ const value = extractFindingIgnoreValue(finding);
+ if (!rule || !value) return false;
+ return ignoreValues.some((entry) => entry.rule === rule && entry.value === value);
+}
+
+export function extractFindingIgnoreValue(finding) {
+ if (!finding || typeof finding !== 'object') return '';
+ const rule = normalizeIgnoreRule(finding.antipattern);
+ if (rule !== 'overused-font') return '';
+ return normalizeIgnoreValue(extractFindingIgnoreValueRaw(finding));
+}
+
+function extractFindingIgnoreValueRaw(finding) {
+ const direct = cleanIgnoreValueDisplay(finding.ignoreValue || finding.value || '');
+ if (direct) return direct;
+
+ const candidates = [finding.detail, finding.snippet].filter((v) => typeof v === 'string' && v);
+ for (const text of candidates) {
+ const primary = text.match(/Primary font:\s*([^()\n;]+)/i);
+ if (primary) return cleanIgnoreValueDisplay(primary[1]);
+
+ const family = text.match(/font-family\s*:\s*["']?([^'",;\n]+)/i);
+ if (family) return cleanIgnoreValueDisplay(family[1]);
+
+ const google = text.match(/[?&]family=([^&:;\n]+)/i);
+ if (google) {
+ try {
+ return cleanIgnoreValueDisplay(decodeURIComponent(google[1]));
+ } catch {
+ return cleanIgnoreValueDisplay(google[1]);
+ }
+ }
+ }
+
+ return '';
+}
+
+function cleanIgnoreValueDisplay(value) {
+ return String(value || '')
+ .trim()
+ .replace(/^["']|["']$/g, '')
+ .replace(/\+/g, ' ')
+ .replace(/\s+/g, ' ');
+}
+
+export function dedupeAgainstCache(findings, cache, sessionId, filePath) {
+ if (!Array.isArray(findings) || findings.length === 0) return [];
+ const fileEntry = ensureFile(cache, sessionId, filePath);
+ const known = new Set(fileEntry.findings || []);
+ const fresh = [];
+ for (const f of findings) {
+ const key = `${f.antipattern}:${f.line || 0}`;
+ if (known.has(key)) continue;
+ known.add(key);
+ fresh.push(f);
+ }
+ return fresh;
+}
+
+export function rememberFindings(cache, sessionId, filePath, findings) {
+ const fileEntry = ensureFile(cache, sessionId, filePath);
+ const known = new Set(fileEntry.findings || []);
+ for (const f of findings) known.add(`${f.antipattern}:${f.line || 0}`);
+ fileEntry.findings = Array.from(known);
+ ensureSession(cache, sessionId).updatedAt = Date.now();
+}
+
+export function renderTemplate(findings, filePath, config, opts = {}) {
+ if (!Array.isArray(findings) || findings.length === 0) return '';
+ const limits = config?.limits || DEFAULT_CONFIG.limits;
+ const cap = Math.max(1, limits.maxFindings || DEFAULT_CONFIG.limits.maxFindings);
+ const maxChars = Math.max(500, limits.maxChars || DEFAULT_CONFIG.limits.maxChars);
+
+ const cwd = opts.cwd || process.cwd();
+ const display = relativize(filePath, cwd);
+ const total = findings.length;
+ const shown = findings.slice(0, cap);
+ const remaining = total - shown.length;
+
+ const header = `${ENVELOPE_PREFIX} Required design corrections in ${display} (${total} issue(s)):`;
+ const lines = shown.map((f) => formatFindingLine(f));
+ const more = remaining > 0
+ ? `... and ${remaining} more (see /impeccable audit).`
+ : null;
+ const footer = directiveFooter(display);
+
+ const blocks = [header, ...lines];
+ if (more) blocks.push(more);
+ blocks.push('');
+ blocks.push(footer);
+ let text = blocks.join('\n');
+
+ if (text.length > maxChars) {
+ text = clampToBudget(header, lines, more, footer, maxChars);
+ }
+ return text;
+}
+
+function renderGroupedTemplate(groups, config, opts = {}) {
+ const realGroups = groups.filter((group) => Array.isArray(group.findings) && group.findings.length > 0);
+ if (realGroups.length === 0) return '';
+ if (realGroups.length === 1) {
+ const [group] = realGroups;
+ return renderTemplate(group.findings, group.filePath, config, opts);
+ }
+
+ const limits = config?.limits || DEFAULT_CONFIG.limits;
+ const cap = Math.max(1, limits.maxFindings || DEFAULT_CONFIG.limits.maxFindings);
+ const maxChars = Math.max(500, limits.maxChars || DEFAULT_CONFIG.limits.maxChars);
+ const cwd = opts.cwd || process.cwd();
+ const total = realGroups.reduce((sum, group) => sum + group.findings.length, 0);
+ const header = `${ENVELOPE_PREFIX} Required design corrections across ${realGroups.length} files (${total} issue(s)):`;
+ const lines = [];
+ let shownCount = 0;
+
+ for (const group of realGroups) {
+ const display = relativize(group.filePath, cwd);
+ lines.push(`${display} (${group.findings.length} issue(s)):`);
+ const remainingCap = Math.max(0, cap - shownCount);
+ const shown = group.findings.slice(0, remainingCap);
+ for (const finding of shown) {
+ lines.push(formatFindingLine(finding));
+ }
+ shownCount += shown.length;
+ const hidden = group.findings.length - shown.length;
+ if (hidden > 0) {
+ lines.push(`- ... ${hidden} more in ${display} (see /impeccable audit).`);
+ }
+ }
+
+ const footer = directiveFooter('the affected files', { grouped: true });
+ let text = [header, ...lines, '', footer].join('\n');
+ if (text.length > maxChars) {
+ text = clampGroupedToBudget(header, lines, footer, maxChars);
+ }
+ return text;
+}
+
+function clampGroupedToBudget(header, lines, footer, maxChars) {
+ const assemble = (linesArr, omitted) => [
+ header,
+ ...linesArr,
+ ...(omitted ? ['... and more (see /impeccable audit).'] : []),
+ '',
+ footer,
+ ].join('\n');
+
+ let working = lines.slice();
+ let omitted = false;
+ let assembled = assemble(working, omitted);
+ while (assembled.length > maxChars && working.length > 1) {
+ working.pop();
+ omitted = true;
+ assembled = assemble(working, omitted);
+ }
+ if (assembled.length > maxChars) {
+ assembled = `${assembled.slice(0, maxChars - 1)}…`;
+ }
+ return assembled;
+}
+
+function clampToBudget(header, lines, more, footer, maxChars) {
+ const assemble = (linesArr, moreText) => {
+ const blocks = [header, ...linesArr];
+ if (moreText) blocks.push(moreText);
+ blocks.push('');
+ blocks.push(footer);
+ return blocks.join('\n');
+ };
+
+ let working = lines.slice();
+ let moreText = more;
+ let assembled = assemble(working, moreText);
+ while (assembled.length > maxChars && working.length > 1) {
+ working.pop();
+ moreText = '... and more (see /impeccable audit).';
+ assembled = assemble(working, moreText);
+ }
+ if (assembled.length > maxChars) {
+ assembled = `${assembled.slice(0, maxChars - 1)}…`;
+ }
+ return assembled;
+}
+
+function formatFindingLine(f) {
+ const prefix = f.line && f.line > 0 ? `- L${f.line}` : '-';
+ const desc = (f.description || '').trim();
+ const name = (f.name || '').trim();
+ // Description from the registry already ends in punctuation; join with a
+ // single space. `name` may have a trailing period already, keep it clean.
+ const nameSegment = name ? `${name.replace(/\.+\s*$/, '')}.` : '';
+ const ignoreCommand = formatFindingIgnoreCommand(f);
+ const ignoreSegment = ignoreCommand
+ ? ` If the user explicitly confirms this value is intentional: \`${ignoreCommand}\`.`
+ : '';
+ return `${prefix} [${f.antipattern}] ${nameSegment} ${desc}${ignoreSegment}`.replace(/\s+/g, ' ').trim();
+}
+
+function formatFindingIgnoreCommand(finding) {
+ if (!finding || typeof finding !== 'object') return '';
+ const rule = normalizeIgnoreRule(finding.antipattern);
+ if (!rule) return '';
+ const normalizedValue = extractFindingIgnoreValue(finding);
+ if (!normalizedValue) return '';
+ const value = extractFindingIgnoreValueRaw(finding);
+ const valueArg = quoteCommandArg(value);
+ const reason = quoteCommandArg(`User confirmed ${value} is intentional`);
+ return `/impeccable hooks ignore-value ${rule} ${valueArg} --shared --reason ${reason}`;
+}
+
+function quoteCommandArg(value) {
+ const text = String(value || '').trim();
+ if (/^[A-Za-z0-9._:-]+$/.test(text)) return text;
+ return `"${text.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
+}
+
+function relativize(filePath, cwd) {
+ try {
+ const rel = path.relative(cwd, filePath);
+ if (!rel || rel.startsWith('..')) return filePath;
+ return rel.split(path.sep).join('/');
+ } catch {
+ return filePath;
+ }
+}
+
+// Codex `apply_patch` exposes the raw patch in `tool_input.command`, not
+// `tool_input.file_path`. Claude Code may send both; parse the patch body
+// so we can scan the file(s) the tool actually touched.
+// https://developers.openai.com/codex/hooks#posttooluse
+const APPLY_PATCH_FILE_RE = /^\*\*\* (?:Update|Add) File: (.+)$/gm;
+
+export function parseApplyPatchPaths(command, projectCwd) {
+ if (!command || typeof command !== 'string') return [];
+ const out = [];
+ for (const m of command.matchAll(APPLY_PATCH_FILE_RE)) {
+ let p = (m[1] || '').trim();
+ if (!p) continue;
+ if (!path.isAbsolute(p)) p = path.resolve(projectCwd, p);
+ out.push(p);
+ }
+ return out;
+}
+
+export function resolveTargetFiles(event, projectCwd) {
+ const ti = event?.tool_input;
+ const out = [];
+ const add = (filePath) => {
+ if (typeof filePath !== 'string' || !filePath) return;
+ if (!out.includes(filePath)) out.push(filePath);
+ };
+
+ if (event?.tool_name === 'apply_patch' && ti && typeof ti.command === 'string') {
+ for (const filePath of parseApplyPatchPaths(ti.command, projectCwd)) add(filePath);
+ }
+ if (ti && typeof ti.file_path === 'string' && ti.file_path) {
+ add(ti.file_path);
+ }
+ // Cursor Write / StrReplace use `path`, not `file_path`.
+ if (ti && typeof ti.path === 'string' && ti.path) {
+ add(ti.path);
+ }
+ if (typeof event?.file_path === 'string' && event.file_path) {
+ add(event.file_path);
+ }
+ return out;
+}
+
+export function resolveHarness(env = {}, event = null) {
+ const explicit = env?.IMPECCABLE_HOOK_HARNESS;
+ if (explicit === 'cursor') return 'cursor';
+ if (explicit === 'claude' || explicit === 'codex') return 'claude';
+ if (typeof event?.conversation_id === 'string' && event.conversation_id) return 'cursor';
+ return 'claude';
+}
+
+export function normalizeHookEvent(event, projectCwd, harness = 'claude') {
+ if (!event || typeof event !== 'object' || harness !== 'cursor') return event;
+
+ const cwd = event.cwd
+ || (Array.isArray(event.workspace_roots) && event.workspace_roots[0])
+ || envProjectDir(projectCwd)
+ || projectCwd;
+ const sessionId = event.session_id || event.conversation_id || 'unknown';
+
+ const ti = event.tool_input && typeof event.tool_input === 'object' ? event.tool_input : {};
+ const filePath = ti.file_path || ti.path || event.file_path;
+ if (filePath) {
+ return {
+ ...event,
+ cwd,
+ session_id: sessionId,
+ tool_input: { ...ti, file_path: filePath },
+ };
+ }
+
+ return { ...event, cwd, session_id: sessionId };
+}
+
+function envProjectDir(fallback) {
+ if (typeof process.env.CURSOR_PROJECT_DIR === 'string' && process.env.CURSOR_PROJECT_DIR) {
+ return process.env.CURSOR_PROJECT_DIR;
+ }
+ return fallback;
+}
+
+// UI components often keep slop in a sibling/co-located stylesheet while the
+// JSX edit is what triggered PostToolUse. Scan those styles too so an App.jsx
+// patch doesn't report "clean" while styles.css still has Inter/bounce/etc.
+const UI_CODE_EXTS = new Set(['.jsx', '.tsx', '.vue', '.svelte', '.astro']);
+const STYLE_EXTS = new Set(['.css', '.scss', '.sass', '.less']);
+const CO_SCAN_STYLE_NAMES = [
+ 'styles.css', 'styles.scss', 'styles.sass', 'styles.less',
+ 'index.css', 'index.scss', 'index.sass', 'index.less',
+ 'global.css', 'global.scss', 'global.sass', 'global.less',
+ 'globals.css', 'globals.scss', 'globals.sass', 'globals.less',
+];
+const MAX_SCAN_TARGETS = 6;
+
+const STATIC_STYLE_IMPORT_RE = /import\s+(?:[\w*{}\s,$]+\s+from\s+)?['"]([^'"]+\.(?:css|scss|sass|less))['"]/gi;
+
+function hasPathTraversal(filePath) {
+ return typeof filePath === 'string' && filePath.includes('..');
+}
+
+function isInsideProject(filePath, projectCwd) {
+ if (!filePath || !projectCwd || hasPathTraversal(filePath)) return false;
+ try {
+ const rel = path.relative(projectCwd, filePath);
+ return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));
+ } catch {
+ return false;
+ }
+}
+
+export function parseStaticStyleImports(content, fromFile, projectCwd) {
+ if (!content || typeof content !== 'string') return [];
+ const dir = path.dirname(fromFile);
+ const out = [];
+ for (const m of content.matchAll(STATIC_STYLE_IMPORT_RE)) {
+ let p = (m[1] || '').trim();
+ if (!p) continue;
+ if (p.startsWith('.')) p = path.resolve(dir, p);
+ else if (!path.isAbsolute(p)) p = path.resolve(projectCwd, p);
+ if (!isInsideProject(p, projectCwd)) continue;
+ out.push(p);
+ }
+ return out;
+}
+
+export function coLocatedStylesheets(filePath) {
+ const dir = path.dirname(filePath);
+ const base = path.basename(filePath, path.extname(filePath));
+ const candidates = new Set([
+ path.join(dir, `${base}.css`),
+ path.join(dir, `${base}.module.css`),
+ path.join(dir, `${base}.scss`),
+ path.join(dir, `${base}.module.scss`),
+ path.join(dir, `${base}.sass`),
+ path.join(dir, `${base}.module.sass`),
+ path.join(dir, `${base}.less`),
+ path.join(dir, `${base}.module.less`),
+ ]);
+ for (const name of CO_SCAN_STYLE_NAMES) {
+ candidates.add(path.join(dir, name));
+ }
+ return [...candidates].filter((p) => fs.existsSync(p));
+}
+
+export function normalizeScanTargets(primaryTargets, projectCwd) {
+ if (!Array.isArray(primaryTargets) || primaryTargets.length === 0) return [];
+ const ordered = [];
+ const seen = new Set();
+ const baseCwd = projectCwd || process.cwd();
+ const normalizeTarget = (p) => {
+ // Preserve literal `..` segments so downstream sensitive-path checks
+ // still fire. path.resolve would collapse `/foo/../etc/passwd`.
+ if (hasPathTraversal(p)) return p;
+ return path.isAbsolute(p) ? p : path.resolve(baseCwd, p);
+ };
+ const add = (p) => {
+ if (ordered.length >= MAX_SCAN_TARGETS) return;
+ const abs = normalizeTarget(p);
+ if (seen.has(abs)) return;
+ seen.add(abs);
+ ordered.push(abs);
+ return abs;
+ };
+
+ for (const p of primaryTargets) add(p);
+ return ordered;
+}
+
+export function expandScanTargets(primaryTargets, projectCwd) {
+ const ordered = normalizeScanTargets(primaryTargets, projectCwd);
+ if (ordered.length === 0) return [];
+ const seen = new Set(ordered);
+ const baseCwd = projectCwd || process.cwd();
+ const add = (p) => {
+ if (ordered.length >= MAX_SCAN_TARGETS) return;
+ const abs = hasPathTraversal(p) ? p : (path.isAbsolute(p) ? p : path.resolve(baseCwd, p));
+ if (seen.has(abs)) return;
+ seen.add(abs);
+ ordered.push(abs);
+ return abs;
+ };
+
+ const normalizedPrimaries = [];
+ for (const p of ordered) normalizedPrimaries.push(p);
+
+ for (const p of normalizedPrimaries) {
+ if (ordered.length >= MAX_SCAN_TARGETS) break;
+ if (!isInsideProject(p, baseCwd)) continue;
+ const ext = path.extname(p).toLowerCase();
+ if (STYLE_EXTS.has(ext) || !UI_CODE_EXTS.has(ext)) continue;
+
+ let content = '';
+ try { content = fs.readFileSync(p, 'utf-8'); } catch { /* unreadable primary */ }
+
+ for (const imp of parseStaticStyleImports(content, p, projectCwd)) {
+ add(imp);
+ if (ordered.length >= MAX_SCAN_TARGETS) break;
+ }
+ for (const col of coLocatedStylesheets(p)) {
+ add(col);
+ if (ordered.length >= MAX_SCAN_TARGETS) break;
+ }
+ }
+
+ return ordered;
+}
+
+export function writeAuditLog(env, entry) {
+ const target = env?.IMPECCABLE_HOOK_LOG;
+ if (!target || typeof target !== 'string') return false;
+ try {
+ const expanded = target.startsWith('~/')
+ ? path.join(process.env.HOME || process.env.USERPROFILE || '.', target.slice(2))
+ : target;
+ fs.mkdirSync(path.dirname(expanded), { recursive: true });
+ const line = JSON.stringify({ ts: new Date().toISOString(), ...entry }) + '\n';
+ fs.appendFileSync(expanded, line);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+const DETECTOR_CANDIDATES = [
+ path.join(__dirname, 'detector', 'detect-antipatterns.mjs'),
+ path.join(__dirname, '..', '..', 'cli', 'engine', 'detect-antipatterns.mjs'),
+ path.join(__dirname, '..', '..', '..', 'cli', 'engine', 'detect-antipatterns.mjs'),
+];
+
+let detectorCache = null;
+export async function loadDetector(candidates = DETECTOR_CANDIDATES) {
+ if (detectorCache) return detectorCache;
+ const found = candidates.find((c) => fs.existsSync(c));
+ if (!found) return null;
+ const mod = await import(pathToFileURL(found));
+ detectorCache = { detectText: mod.detectText, detectHtml: mod.detectHtml };
+ return detectorCache;
+}
+
+// For tests: allow injecting a detector implementation.
+export function setDetectorForTesting(impl) {
+ detectorCache = impl;
+}
+
+// ────────────────────────────────────────────────────────────────────────
+// Nudge/steer messages for the no-silent-fires policy.
+//
+// The hook is designed to be a conversational presence: every fire that
+// actually scans a file emits a developer-role message into the model's
+// next turn. Three states map to three templates:
+//
+// 1. **Fresh findings** → `renderTemplate` (existing, imperative).
+// 2. **Pending findings** → `renderPendingAck` (re-nudge for issues the
+// model was already told about in this
+// session but hasn't fixed yet).
+// 3. **Truly clean** → `renderCleanAck` (short positive nudge that
+// keeps the design discipline in context).
+//
+// All three are short (≤ ~40 tokens each) so the cumulative cost stays
+// bounded across a long active editing session. Users who explicitly want
+// silence-on-clean can set `IMPECCABLE_HOOK_QUIET=1` — runHook checks that
+// env before emitting #2 or #3.
+//
+// Why not stay silent on dedup-clean? Earlier versions did. The model
+// quickly forgets the prior reminder once tool output scrolls past it, so
+// re-nudging on the same file with a short "still pending" line keeps the
+// pressure on. The wording deliberately points back to "earlier this
+// session" so the model knows it's a re-mind, not a new finding.
+// ────────────────────────────────────────────────────────────────────────
+
+const STEER_LINE = 'Keep typography hierarchy, spacing rhythm, and color contrast intentional on the next change.';
+
+export function renderCleanAck(filePath, opts = {}) {
+ const cwd = opts.cwd || process.cwd();
+ const display = relativize(filePath, cwd);
+ return `${ENVELOPE_PREFIX} Design hook scanned ${display}. No anti-patterns. ${STEER_LINE}`;
+}
+
+export function renderPendingAck(filePath, knownFindings, opts = {}) {
+ const cwd = opts.cwd || process.cwd();
+ const display = relativize(filePath, cwd);
+ const count = knownFindings.length;
+ // `knownFindings` here are the cache strings like "side-tab:3".
+ const sample = knownFindings.slice(0, 3).join(', ');
+ const more = count > 3 ? `, +${count - 3} more` : '';
+ return `${ENVELOPE_PREFIX} Design hook scanned ${display}. Still has ${count} issue(s) flagged earlier this session (${sample}${more}). Address them before finalizing — the previous reminder still applies.`;
+}
+
+export function shouldEmitAckForFile(filePath) {
+ return ACK_EXTS.has(path.extname(String(filePath || '')).toLowerCase());
+}
+
+// The directive footer is the part of the hook output that steers model
+// behavior. Three intentional moves:
+// 1. **Imperative, not advisory.** "Fix these..." beats "Consider
+// revising..." which the model treats as a soft suggestion it can
+// override when the user asked for any kind of throwaway / demo UI.
+// 2. **Explicit exception clause.** Without it, the model will try to
+// "fix" intentional bad fixtures, anti-pattern examples in docs, or
+// test cases. Naming the exception inline beats hoping the model
+// infers it from context.
+// 3. **Acknowledgement instruction.** Hook output is injected as
+// developer-role context, not a chat turn, so the user never sees the
+// raw envelope. Asking the model to surface the fix in its reply is
+// the cheapest way to make the feedback loop visible to the user.
+function directiveFooter(display, opts = {}) {
+ const ignoreFileCommand = `/impeccable hooks ignore-file ${quoteCommandArg(display)}`;
+ const fileIgnoreGuidance = opts.grouped
+ ? 'run `/impeccable hooks ignore-file <path>` for the specific file'
+ : `run \`${ignoreFileCommand}\``;
+ return [
+ 'Fix these in your next reply before finalizing. Acknowledge what you changed so the user sees the correction.',
+ '',
+ 'Skip the fix only if the user explicitly asked for an intentionally bad UI, an anti-pattern example, a test fixture, or documentation of bad design. In that case, say so and continue.',
+ '',
+ `Do not add source comments such as \`impeccable: ignore\`; those pollute the code and do not suppress hook findings. Do not add hook ignores unless the user explicitly confirms the finding is intentional. Prefer the narrowest persisted exception: run the exact \`/impeccable hooks ignore-value ... --shared\` command shown next to a value-specific finding. For \`overused-font\`, use \`ignore-value\` for a specific font and use \`/impeccable hooks ignore-rule overused-font --all-values\` only when the user asks to ignore overused fonts generally. For file-specific findings without an ignore-value command, ${fileIgnoreGuidance}; use \`/impeccable hooks ignore-rule <id>\` only when the user asks to suppress the whole non-value-specific rule. Run /impeccable audit for the full pass.`,
+ ].join('\n');
+}
+
+/**
+ * Run the hook with explicit dependencies. Returns a result object:
+ * { exitCode, stdout, audit, reason? }
+ *
+ * Never throws. All errors are converted to `exitCode: 0` + audit entry.
+ */
+export async function runHook({ stdinJson, env = {}, cwd = process.cwd(), now = Date.now, detector } = {}) {
+ const audit = { ts: new Date(now()).toISOString(), event: 'PostToolUse' };
+ const result = (extra) => ({ exitCode: 0, stdout: '', audit: { ...audit, ...extra } });
+
+ try {
+ // Re-entrancy guard.
+ if (depthIsSet(env.IMPECCABLE_HOOK_DEPTH) || depthIsSet(env.CLAUDE_HOOK_DEPTH)) {
+ return result({ reentrant: true, durationMs: 0 });
+ }
+
+ if (truthy(env.IMPECCABLE_HOOK_DISABLED)) {
+ return result({ skipped: 'env-disabled', durationMs: 0 });
+ }
+
+ const started = Date.now();
+
+ let event;
+ try {
+ event = typeof stdinJson === 'string' ? JSON.parse(stdinJson) : stdinJson;
+ } catch {
+ return result({ skipped: 'stdin-malformed', durationMs: Date.now() - started });
+ }
+ if (!event || typeof event !== 'object') {
+ return result({ skipped: 'stdin-empty', durationMs: Date.now() - started });
+ }
+
+ const harness = resolveHarness(env, event);
+ event = normalizeHookEvent(event, cwd, harness);
+ audit.harness = harness;
+
+ const projectCwd = event.cwd || cwd;
+ const primaryFiles = normalizeScanTargets(resolveTargetFiles(event, projectCwd), projectCwd);
+ const primaryFileSet = new Set(primaryFiles);
+ const targetFiles = expandScanTargets(primaryFiles, projectCwd);
+ audit.session = event.session_id || null;
+ if (event.tool_name) audit.tool = event.tool_name;
+
+ if (targetFiles.length === 0) {
+ return result({ skipped: 'no-file-path', durationMs: Date.now() - started });
+ }
+
+ const config = readConfig(projectCwd);
+ if (config.enabled === false) {
+ return result({ skipped: 'config-disabled', durationMs: Date.now() - started });
+ }
+
+ const cache = readCache(projectCwd);
+ const sessionId = event.session_id || 'unknown';
+ const det = detector || await loadDetector();
+ if (!det || typeof det.detectText !== 'function') {
+ persistCache(projectCwd, cache);
+ return result({ skipped: 'detector-missing', durationMs: Date.now() - started });
+ }
+
+ let pendingWinner = null;
+ let cleanWinner = null;
+ const freshGroups = [];
+ let suppressionWinner = null;
+ let detectorThrewAny = false;
+ let lastSkip = 'no-scannable-file';
+ let suppressedHit = false;
+
+ for (const filePath of targetFiles) {
+ audit.file = filePath;
+
+ if (hasPathTraversal(filePath) || SENSITIVE_PATH.test(filePath)) {
+ lastSkip = 'sensitive';
+ continue;
+ }
+ if (GENERATED_PATH.test(filePath)) {
+ lastSkip = 'generated';
+ continue;
+ }
+
+ const ext = path.extname(filePath).toLowerCase();
+ audit.ext = ext;
+ if (!ALLOWED_EXTS.has(ext)) {
+ lastSkip = 'extension';
+ continue;
+ }
+
+ const relForMatch = relativize(filePath, projectCwd);
+ if (matchesAnyGlob(relForMatch, config.ignoreFiles) || matchesAnyGlob(filePath, config.ignoreFiles)) {
+ lastSkip = 'config-ignore-file';
+ continue;
+ }
+ if (!fs.existsSync(filePath)) {
+ lastSkip = 'file-missing';
+ continue;
+ }
+
+ if (primaryFileSet.has(filePath)) {
+ const editCount = bumpEditCount(cache, sessionId, filePath);
+ audit.editCount = editCount;
+
+ if (editCount > EDIT_COUNT_THRESHOLD) {
+ const wasJustCrossed = editCount === EDIT_COUNT_THRESHOLD + 1;
+ if (wasJustCrossed && !suppressionWinner) {
+ suppressionWinner = { filePath };
+ }
+ lastSkip = 'suppressed';
+ suppressedHit = true;
+ continue;
+ }
+ }
+
+ const content = fs.readFileSync(filePath, 'utf-8');
+ let findings;
+ let detectorThrew = false;
+ if ((ext === '.html' || ext === '.htm') && typeof det.detectHtml === 'function') {
+ try { findings = await det.detectHtml(filePath); } catch { findings = []; detectorThrew = true; }
+ } else {
+ try { findings = await det.detectText(content, filePath); } catch { findings = []; detectorThrew = true; }
+ }
+
+ const filtered = filterFindings(findings || [], content, ext, config);
+ const fresh = dedupeAgainstCache(filtered, cache, sessionId, filePath);
+ audit.findings = (findings || []).length;
+ audit.freshFindings = fresh.length;
+
+ if (fresh.length > 0) {
+ rememberFindings(cache, sessionId, filePath, fresh);
+ freshGroups.push({ filePath, findings: fresh });
+ continue;
+ }
+
+ if (detectorThrew) {
+ detectorThrewAny = true;
+ continue;
+ }
+
+ if (filtered.length > 0 && !pendingWinner) {
+ const known = (ensureFile(cache, sessionId, filePath).findings || []).slice();
+ pendingWinner = { filePath, known };
+ } else if (filtered.length === 0 && !cleanWinner) {
+ cleanWinner = { filePath };
+ }
+ }
+
+ persistCache(projectCwd, cache);
+
+ if (freshGroups.length > 0) {
+ const firstGroup = freshGroups[0];
+ const text = renderGroupedTemplate(freshGroups, config, { cwd: projectCwd });
+ const allFindings = freshGroups.flatMap((group) => group.findings);
+ return {
+ exitCode: 0,
+ stdout: payload(text, 'PostToolUse', harness),
+ emission: {
+ kind: 'fresh',
+ file: firstGroup.filePath,
+ findings: firstGroup.findings,
+ groups: freshGroups,
+ },
+ audit: {
+ ...audit,
+ file: firstGroup.filePath,
+ emitted: true,
+ freshFiles: freshGroups.length,
+ freshFindings: allFindings.length,
+ chars: text.length,
+ durationMs: Date.now() - started,
+ },
+ };
+ }
+
+ if (detectorThrewAny && !pendingWinner && !cleanWinner) {
+ return result({ emitted: false, error: 'detector-threw', durationMs: Date.now() - started });
+ }
+
+ if (truthy(env.IMPECCABLE_HOOK_QUIET)) {
+ return result({ emitted: false, quiet: true, durationMs: Date.now() - started });
+ }
+
+ if (pendingWinner && shouldEmitAckForFile(pendingWinner.filePath)) {
+ const text = renderPendingAck(pendingWinner.filePath, pendingWinner.known, { cwd: projectCwd });
+ return {
+ exitCode: 0,
+ stdout: payload(text, 'PostToolUse', harness),
+ emission: { kind: 'pending', file: pendingWinner.filePath, known: pendingWinner.known },
+ audit: {
+ ...audit,
+ file: pendingWinner.filePath,
+ emitted: true,
+ kind: 'pending',
+ pending: pendingWinner.known.length,
+ chars: text.length,
+ durationMs: Date.now() - started,
+ },
+ };
+ }
+
+ if (suppressionWinner) {
+ const text = suppressionNotice(relativize(suppressionWinner.filePath, projectCwd));
+ return {
+ exitCode: 0,
+ stdout: payload(text, 'PostToolUse', harness),
+ emission: { kind: 'suppression', file: suppressionWinner.filePath },
+ audit: {
+ ...audit,
+ file: suppressionWinner.filePath,
+ suppressed: true,
+ emitted: true,
+ durationMs: Date.now() - started,
+ },
+ };
+ }
+
+ if (cleanWinner && shouldEmitAckForFile(cleanWinner.filePath)) {
+ const text = renderCleanAck(cleanWinner.filePath, { cwd: projectCwd });
+ return {
+ exitCode: 0,
+ stdout: payload(text, 'PostToolUse', harness),
+ emission: { kind: 'clean', file: cleanWinner.filePath },
+ audit: {
+ ...audit,
+ file: cleanWinner.filePath,
+ emitted: true,
+ kind: 'clean',
+ chars: text.length,
+ durationMs: Date.now() - started,
+ },
+ };
+ }
+
+ if (pendingWinner || cleanWinner) {
+ return result({ emitted: false, skipped: 'non-ui-ack', durationMs: Date.now() - started });
+ }
+
+ if (suppressedHit) {
+ return result({ suppressed: true, emitted: false, durationMs: Date.now() - started });
+ }
+
+ return result({ skipped: lastSkip, durationMs: Date.now() - started });
+ } catch (err) {
+ return {
+ exitCode: 0,
+ stdout: '',
+ audit: { ...audit, error: String(err && err.message ? err.message : err) },
+ };
+ }
+}
+
+export function payload(text, eventName = 'PostToolUse', harness = 'claude') {
+ if (harness === 'cursor') {
+ return JSON.stringify({ additional_context: text });
+ }
+ return JSON.stringify({
+ hookSpecificOutput: { hookEventName: eventName, additionalContext: text },
+ });
+}
diff --git a/.github/skills/impeccable/scripts/hook.mjs b/.github/skills/impeccable/scripts/hook.mjs
new file mode 100644
index 000000000..b862f8033
--- /dev/null
+++ b/.github/skills/impeccable/scripts/hook.mjs
@@ -0,0 +1,61 @@
+#!/usr/bin/env node
+/**
+ * Impeccable design hook — PostToolUse entry point.
+ *
+ * Reads the Claude Code / Codex / Cursor hook event from stdin, runs the design
+ * detector against the touched file, and emits a system reminder via
+ * `hookSpecificOutput.additionalContext` when findings exist.
+ *
+ * Contract: never break a turn. Always exit 0. Clean files emit a small ack
+ * unless quiet mode is enabled.
+ *
+ * Most logic lives in `hook-lib.mjs` so it is unit-testable without a
+ * subprocess. This file is the thin stdin/stdout adapter.
+ */
+
+import { runHook, 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');
+}
+
+async function main() {
+ // Snapshot the inherited env FIRST so the re-entrancy guard checks the
+ // parent's value, not the value we are about to export for any child
+ // processes the hook might ever spawn.
+ const inheritedEnv = { ...process.env };
+ process.env.IMPECCABLE_HOOK_DEPTH = process.env.IMPECCABLE_HOOK_DEPTH || '1';
+
+ let stdinJson = '';
+ try { stdinJson = await readStdin(); } catch { /* fall through */ }
+
+ const result = await runHook({
+ stdinJson,
+ env: inheritedEnv,
+ cwd: process.cwd(),
+ });
+
+ writeAuditLog(process.env, result.audit);
+
+ if (result.stdout) process.stdout.write(result.stdout);
+ process.exit(result.exitCode || 0);
+}
+
+main().catch((err) => {
+ // Last-ditch: never break the agent's turn even if something we did not
+ // anticipate goes wrong. Audit-log the failure if logging is enabled.
+ try {
+ writeAuditLog(process.env, {
+ ts: new Date().toISOString(),
+ event: 'PostToolUse',
+ error: String(err && err.message ? err.message : err),
+ });
+ } catch { /* swallow */ }
+ if (process.env.IMPECCABLE_HOOK_DEBUG) {
+ process.stderr.write(`[impeccable-hook] ${err}\n`);
+ }
+ process.exit(0);
+});
diff --git a/.github/skills/impeccable/scripts/live-inject.mjs b/.github/skills/impeccable/scripts/live-inject.mjs
index 4e5c5dc0a..69ce530c1 100644
--- a/.github/skills/impeccable/scripts/live-inject.mjs
+++ b/.github/skills/impeccable/scripts/live-inject.mjs
@@ -32,6 +32,8 @@ const IGNORE_MARKER_CLOSE = '# impeccable-live-ignore-end';
export const LIVE_IGNORE_PATTERNS = Object.freeze([
'.impeccable/hook.cache.json',
+ '.impeccable/hook.pending.json',
+ '.impeccable/hook.local.json',
'.impeccable/live/server.json',
'.impeccable/live/sessions/',
'.impeccable/live/previews/',
diff --git a/.gitignore b/.gitignore
index cc621260e..7806ac4b9 100644
--- a/.gitignore
+++ b/.gitignore
@@ -51,6 +51,10 @@ Thumbs.db
.impeccable/live/pending-manual-edits.json
.impeccable/live/deferred-svelte-component-accepts.json
.impeccable/history/
+.impeccable/hook.local.json
+.impeccable/hook.pending.json
+.impeccable/provider-smoke/
+src/__impeccable_provider_smoke_*.html
# Per-run critique snapshots are local artifacts. ignore.md (also under
# this dir) carries deferrals the user may want to share, so it's
# explicitly re-included below.
@@ -106,10 +110,11 @@ site/public/js/generated/
# time, and they enable clean submodule use. Run `bun run build` to refresh
# them after editing skill/.
#
-# Codex CLI consumes `.agents/skills/`; the asset-producer subagent now ships
-# nested inside that skill (agents/*.toml), auto-discovered on install, so
-# nothing under `.codex/` is tracked.
+# Codex CLI consumes `.agents/skills/`; the asset-producer subagent ships
+# nested inside that skill (agents/*.toml), auto-discovered on install.
+# The project-local hook manifest is the one tracked `.codex/` artifact.
.codex/*
+!.codex/hooks.json
.astro/
# Local-only scratch for exploratory scripts, parked pages, and unused asset candidates.
diff --git a/.impeccable/hook.json b/.impeccable/hook.json
new file mode 100644
index 000000000..b6d320ce8
--- /dev/null
+++ b/.impeccable/hook.json
@@ -0,0 +1,13 @@
+{
+ "enabled": true,
+ "ignoreRules": [],
+ "ignoreFiles": [
+ "tests/fixtures/**",
+ "site/pages/slop/**"
+ ],
+ "ignoreValues": [],
+ "limits": {
+ "maxFindings": 5,
+ "maxChars": 8000
+ }
+}
diff --git a/.kiro/skills/impeccable/SKILL.md b/.kiro/skills/impeccable/SKILL.md
index bf2276000..23fcd684a 100644
--- a/.kiro/skills/impeccable/SKILL.md
+++ b/.kiro/skills/impeccable/SKILL.md
@@ -122,7 +122,7 @@ If someone could look at this interface and say "AI made that" without doubt, it
| `optimize [target]` | Fix | Diagnose and fix UI performance | [reference/optimize.md](reference/optimize.md) |
| `live` | Iterate | Visual variant mode: pick elements in the browser, generate alternatives | [reference/live.md](reference/live.md) |
-Plus two management commands: `pin <command>` and `unpin <command>`, detailed below.
+Plus three management commands: `pin <command>`, `unpin <command>`, and `hooks <on|off|status|...>`, detailed below.
### Routing rules
@@ -139,7 +139,7 @@ Plus two management commands: `pin <command>` and `unpin <command>`, detailed be
**If `scan.targets` is non-empty, run `node .kiro/skills/impeccable/scripts/detect.mjs --json <scan.targets joined by spaces>` once** (the bundled detector over local files: no network, no npx). `scan.via` tells you what they are: `git-changes` (the markup/style files in your dirty tree, the most relevant set), `source-dir` (e.g. `src`, `app`), `html`, or `root`. Fold the hits into your picks: many quality / contrast hits → `audit` or `polish`; a specific slop family → the matching command (gradient text or eyebrows → `quieter` / `typeset`, flat or gray palette → `colorize`, and so on). It's a real, current signal that beats guessing. If detect errors or the tree is large and slow, skip it and recommend the user run `audit` themselves; never block the suggestion on it.
Keep it to 2-3 pointed picks with the exact command to type. The menu stays the fallback; the recommendation is the lede.
-2. **First word matches a command**: load its reference file and follow its instructions. Everything after the command name is the target.
+2. **First word matches a command** (table above OR `pin` / `unpin` / `hooks`): load its reference file and follow its instructions. Everything after the command name is the target.
3. **First word doesn't match, but the intent clearly maps to one command** (e.g. "fix the spacing" → `layout`, "rewrite this error message" → `clarify`, "the colors feel flat" → `colorize`): load that command's reference and proceed as if invoked. If two commands could fit, ask once which.
4. **No clear command match**: general design invocation. Apply the setup steps, the General rules, and the loaded register reference, using the full argument as context.
@@ -157,4 +157,8 @@ If the first word is `craft`, setup still runs first, but [reference/craft.md](r
node .kiro/skills/impeccable/scripts/pin.mjs <pin|unpin> <command>
```
-Valid `<command>` is any command from the table above. Report the script's result concisely. Confirm the new shortcut on success, relay stderr verbatim on error.
\ No newline at end of file
+Valid `<command>` is any command from the table above. Report the script's result concisely. Confirm the new shortcut on success, relay stderr verbatim on error.
+
+## Hooks
+
+`/impeccable hooks <on|off|status|ignore-rule|ignore-file|ignore-value|reset>` manages the design detector hook for this project. The hook auto-runs the detector after direct UI file edits and surfaces findings as system reminders. Full flow is in [reference/hooks.md](reference/hooks.md); load it when the user invokes `/impeccable hooks` with any argument.
\ No newline at end of file
diff --git a/.kiro/skills/impeccable/reference/hooks.md b/.kiro/skills/impeccable/reference/hooks.md
new file mode 100644
index 000000000..88a4063ef
--- /dev/null
+++ b/.kiro/skills/impeccable/reference/hooks.md
@@ -0,0 +1,82 @@
+# /impeccable hooks
+
+Manage the **design detector hook** for the current project.
+
+The hook runs the impeccable design detector on direct file edits to design-relevant files (`.tsx`, `.jsx`, `.html`, `.vue`, `.svelte`, `.astro`, `.css`, `.scss`, `.sass`, `.less`, `.ts`, `.js`). Claude Code and Codex use `PostToolUse` and push a short system reminder into the agent's context after the edit; findings get a correction prompt, pending issues get a re-nudge, and clean UI-ish files get a short ack unless `IMPECCABLE_HOOK_QUIET=1` is set. Plain `.ts` and `.js` files are still scanned, but stay quiet unless the detector finds something. Cursor uses `preToolUse` to block bad proposed writes before they land and stays silent when it allows a clean write.
+
+This command toggles the hook **per project** by editing `.impeccable/hook.json`. Local-only ignore policy lives in `.impeccable/hook.local.json`, which is gitignored. To disable globally, set `IMPECCABLE_HOOK_DISABLED=1` in your shell environment.
+
+Supported harnesses: Claude Code (`.claude/settings.json` in the project), Codex (`.codex/hooks.json` in the project), and Cursor (`.cursor/hooks.json` in the project).
+
+On **Cursor**, `preToolUse` checks proposed Write/Edit/Shell write content and denies only when the real detector finds an issue. The denial message is visible to the agent as the tool error, so the agent can reconsider before the bad write lands.
+
+## Routing
+
+The first argument is the action. Defaults to `status`.
+
+| Action | What it does |
+|---|---|
+| `status` | Print current state, shared/local config paths, ignored rules / files / values, env override. |
+| `on` | Set `enabled: true` in `.impeccable/hook.json`. |
+| `off` | Set `enabled: false` in `.impeccable/hook.json`. |
+| `ignore-rule <id>` | Append `<id>` to `ignoreRules`; for `overused-font`, requires `--all-values`. |
+| `ignore-file <glob>` | Append `<glob>` to `ignoreFiles`. |
+| `ignore-value <id> <value> [--shared] [--reason "..."]` | Append a rule/value suppression to shared `.impeccable/hook.json`. |
+| `ignore-value <id> <value> --local [--reason "..."]` | Append a private rule/value suppression to `.impeccable/hook.local.json`. |
+| `reset` | Delete the project config, dedup cache, and Cursor pending queue. |
+
+## Flow
+
+1. Resolve the action from the user's argument. If no action was given, default to `status`.
+2. Invoke the admin script and pass the user's output through verbatim:
+
+ ```bash
+ node .kiro/skills/impeccable/scripts/hook-admin.mjs <action> [args...]
+ ```
+
+3. If `<action>` is `off`, follow up with a one-line note: "Done. New edits will not trigger the design hook in this project until you run `/impeccable hooks on`."
+4. If `<action>` is `on`, follow up with: "Done. The design hook will fire after the next Edit/Write/MultiEdit on a UI file."
+5. If `<action>` is `ignore-value`, `ignore-file`, or `ignore-rule`, just print the script output. The default scope is shared `.impeccable/hook.json`; add `--local` only when the user explicitly asks for a private exception.
+6. If `<action>` is `status`, just print the script output. Do not add commentary unless the user asked a follow-up question.
+
+## Intentional findings
+
+The hook itself never writes ignore config. Persist an exception only after the user explicitly confirms the flagged issue is intentional, and always go through `hook-admin.mjs`.
+
+Prefer the narrowest exception:
+
+- If the finding line shows an exact `ignore-value` command, run that command. This writes shared `.impeccable/hook.json` by default.
+- For `overused-font`, use `ignore-value` when the user confirms a specific font. Do not use `ignore-rule overused-font` for a specific font.
+- If the finding has no value-specific command, such as `side-tab`, prefer `ignore-file <path>` for the current file.
+- Use `ignore-rule <id>` only when the user asks to suppress that whole rule across the project. For broad overused-font suppression, use `ignore-rule overused-font --all-values` only when the user asks to ignore overused fonts generally.
+- Do not add source comments such as `impeccable: ignore`; inline comments pollute code and are not a supported suppression mechanism.
+
+Example value-specific exception:
+
+```bash
+node .kiro/skills/impeccable/scripts/hook-admin.mjs ignore-value overused-font Inter --shared --reason "User confirmed Inter is intentional"
+```
+
+Example whole-rule font exception:
+
+```bash
+node .kiro/skills/impeccable/scripts/hook-admin.mjs ignore-rule overused-font --all-values --reason "User asked to ignore overused fonts generally"
+```
+
+Example file-scoped exception:
+
+```bash
+node .kiro/skills/impeccable/scripts/hook-admin.mjs ignore-file "src/legacy/Card.tsx"
+```
+
+## Constraints
+
+- Never modify `.impeccable/hook.json` or `.impeccable/hook.local.json` by hand from this command. Always go through `hook-admin.mjs` so writes stay validated and the file shape stays consistent.
+- Do not edit the hook scripts themselves (`hook.mjs`, `hook-lib.mjs`, `hook-before-edit.mjs`) from this flow. Those are skill plumbing.
+- Cursor can block a proposed write when the detector finds a real issue. Claude Code and Codex do not block the edit; they emit a post-edit reminder instead. Disabling stops both blocking and reminders.
+- The hook is bundled with the Impeccable skill and installed through project-local manifests: `.claude/settings.json`, `.codex/hooks.json`, and `.cursor/hooks.json`. On Codex, the user must approve the hook via `/hooks` the first time. On Cursor, confirm hooks are enabled under Settings -> Hooks.
+
+## Failure modes
+
+- If `.impeccable/hook.json` or `.impeccable/hook.local.json` is unreadable or malformed, the hook ignores that file and uses the remaining valid config/defaults. `hook-admin.mjs status` will show malformed files as ignored.
+- If the user asks to "disable the hook" globally, suggest both options: `IMPECCABLE_HOOK_DISABLED=1` env var (one-shot, follows the shell), and `/impeccable hooks off` (persistent for this project, committable).
diff --git a/.kiro/skills/impeccable/scripts/detector/engines/regex/detect-text.mjs b/.kiro/skills/impeccable/scripts/detector/engines/regex/detect-text.mjs
index fd0d9c73f..4c0777c93 100644
--- a/.kiro/skills/impeccable/scripts/detector/engines/regex/detect-text.mjs
+++ b/.kiro/skills/impeccable/scripts/detector/engines/regex/detect-text.mjs
@@ -446,7 +446,7 @@ function detectText(content, filePath, options = {}) {
// Run regex matchers on the full file content (catches Tailwind classes, inline styles)
// Enable block context for CSS files where related properties span multiple lines
- const cssLike = new Set(['.css', '.scss', '.less']);
+ const cssLike = new Set(['.css', '.scss', '.sass', '.less']);
findings.push(...runRegexMatchers(lines, filePath, 0, cssLike.has(ext) || null, {
profile,
phase: 'source',
diff --git a/.kiro/skills/impeccable/scripts/detector/node/file-system.mjs b/.kiro/skills/impeccable/scripts/detector/node/file-system.mjs
index a80250a0e..aaa8c6df7 100644
--- a/.kiro/skills/impeccable/scripts/detector/node/file-system.mjs
+++ b/.kiro/skills/impeccable/scripts/detector/node/file-system.mjs
@@ -11,7 +11,7 @@ const SKIP_DIRS = new Set([
]);
const SCANNABLE_EXTENSIONS = new Set([
- '.html', '.htm', '.css', '.scss', '.less',
+ '.html', '.htm', '.css', '.scss', '.sass', '.less',
'.jsx', '.tsx', '.js', '.ts',
'.vue', '.svelte', '.astro',
]);
diff --git a/.kiro/skills/impeccable/scripts/hook-admin.mjs b/.kiro/skills/impeccable/scripts/hook-admin.mjs
new file mode 100644
index 000000000..86fcfa909
--- /dev/null
+++ b/.kiro/skills/impeccable/scripts/hook-admin.mjs
@@ -0,0 +1,300 @@
+#!/usr/bin/env node
+/**
+ * `/impeccable hooks <on|off|status|reset>` — manage the design hook
+ * via .impeccable/hook.json and .impeccable/hook.local.json in the current
+ * project.
+ *
+ * Usage:
+ * node hook-admin.mjs status # print current state
+ * node hook-admin.mjs on # set enabled: true
+ * node hook-admin.mjs off # set enabled: false
+ * node hook-admin.mjs ignore-rule <rule-id> # append to ignoreRules
+ * node hook-admin.mjs ignore-rule overused-font --all-values
+ * node hook-admin.mjs ignore-file <glob> # append to ignoreFiles
+ * node hook-admin.mjs ignore-value <rule> <value> # append to shared ignoreValues
+ * node hook-admin.mjs ignore-value <rule> <value> --local
+ * node hook-admin.mjs reset # remove all config + cache
+ *
+ * Designed to be invoked by the LLM from the reference/hooks.md flow.
+ * Output is human-readable; the harness will pass it back to the user.
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+
+import {
+ getConfigPath,
+ getLocalConfigPath,
+ getCachePath,
+ getPendingPath,
+ readConfig,
+ DEFAULT_CONFIG,
+ ensureHookGitExcludes,
+ normalizeIgnoreValue,
+ normalizeIgnoreValueEntries,
+} from './hook-lib.mjs';
+
+const ACTIONS = new Set(['status', 'on', 'off', 'ignore-rule', 'ignore-file', 'ignore-value', 'reset']);
+
+function readRawConfigFile(filePath) {
+ if (!fs.existsSync(filePath)) return { exists: false, malformed: false, raw: null };
+ try {
+ return { exists: true, malformed: false, raw: JSON.parse(fs.readFileSync(filePath, 'utf-8')) };
+ } catch {
+ return { exists: true, malformed: true, raw: null };
+ }
+}
+
+function readRawConfig(cwd, opts = {}) {
+ const filePath = opts.local ? getLocalConfigPath(cwd) : getConfigPath(cwd);
+ return readRawConfigFile(filePath).raw;
+}
+
+function writeConfig(cwd, config, opts = {}) {
+ const filePath = opts.local ? getLocalConfigPath(cwd) : getConfigPath(cwd);
+ if (opts.local) ensureHookGitExcludes(cwd);
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
+ fs.writeFileSync(filePath, JSON.stringify(config, null, 2) + '\n');
+ return filePath;
+}
+
+function mergeConfig(existing) {
+ // Persist the full shape so /impeccable hooks edits leave a complete file
+ // for the user to see, not an unhelpful `{"enabled":false}`.
+ const base = existing && typeof existing === 'object' ? existing : {};
+ return {
+ enabled: base.enabled === false ? false : true,
+ ignoreRules: Array.isArray(base.ignoreRules) ? Array.from(new Set(base.ignoreRules.map(String))) : [],
+ ignoreFiles: Array.isArray(base.ignoreFiles) ? Array.from(new Set(base.ignoreFiles.map(String))) : [],
+ ignoreValues: normalizeIgnoreValueEntries(base.ignoreValues || []),
+ limits: {
+ maxFindings: Number.isFinite(base?.limits?.maxFindings) ? base.limits.maxFindings : DEFAULT_CONFIG.limits.maxFindings,
+ maxChars: Number.isFinite(base?.limits?.maxChars) ? base.limits.maxChars : DEFAULT_CONFIG.limits.maxChars,
+ },
+ };
+}
+
+function mergeLocalConfig(existing) {
+ const base = existing && typeof existing === 'object' ? existing : {};
+ const out = {};
+ if (Object.prototype.hasOwnProperty.call(base, 'enabled')) {
+ out.enabled = base.enabled === false ? false : true;
+ }
+ if (Array.isArray(base.ignoreRules)) {
+ out.ignoreRules = Array.from(new Set(base.ignoreRules.map(String)));
+ }
+ if (Array.isArray(base.ignoreFiles)) {
+ out.ignoreFiles = Array.from(new Set(base.ignoreFiles.map(String)));
+ }
+ out.ignoreValues = normalizeIgnoreValueEntries(base.ignoreValues || []);
+ if (base.limits && typeof base.limits === 'object') {
+ const limits = {};
+ if (Number.isFinite(base.limits.maxFindings)) limits.maxFindings = base.limits.maxFindings;
+ if (Number.isFinite(base.limits.maxChars)) limits.maxChars = base.limits.maxChars;
+ if (Object.keys(limits).length) out.limits = limits;
+ }
+ return out;
+}
+
+function statusReport(cwd) {
+ const shared = readRawConfigFile(getConfigPath(cwd));
+ const local = readRawConfigFile(getLocalConfigPath(cwd));
+ const cfg = readConfig(cwd);
+ const envKill = process.env.IMPECCABLE_HOOK_DISABLED;
+ const envState = envKill ? `IMPECCABLE_HOOK_DISABLED=${envKill}` : 'unset';
+ const cfgPath = path.relative(cwd, getConfigPath(cwd)) || '.impeccable/hook.json';
+ const localPath = path.relative(cwd, getLocalConfigPath(cwd)) || '.impeccable/hook.local.json';
+ const cachePath = path.relative(cwd, getCachePath(cwd)) || '.impeccable/hook.cache.json';
+ const fileState = (info, relPath, absent) => {
+ if (info.malformed) return `${relPath} (malformed; ignored)`;
+ if (info.exists) return relPath;
+ return `${relPath} (${absent})`;
+ };
+ const ignoreValues = cfg.ignoreValues.map((entry) => `${entry.rule}=${entry.value}`);
+
+ const lines = [
+ `Impeccable design hook`,
+ ` state: ${cfg.enabled ? 'enabled' : 'disabled'}`,
+ ` shared file: ${fileState(shared, cfgPath, 'using defaults; file not present')}`,
+ ` local file: ${fileState(local, localPath, 'not present')}`,
+ ` ignoreRules: ${cfg.ignoreRules.length ? cfg.ignoreRules.join(', ') : '(none)'}`,
+ ` ignoreFiles: ${cfg.ignoreFiles.length ? cfg.ignoreFiles.join(', ') : '(none)'}`,
+ ` ignoreValues: ${ignoreValues.length ? ignoreValues.join(', ') : '(none)'}`,
+ ` maxFindings: ${cfg.limits.maxFindings}`,
+ ` maxChars: ${cfg.limits.maxChars}`,
+ ` env override: ${envState}`,
+ ` cache file: ${fs.existsSync(getCachePath(cwd)) ? cachePath : `${cachePath} (not present)`}`,
+ ];
+ return lines.join('\n');
+}
+
+function setEnabled(cwd, value) {
+ const config = mergeConfig(readRawConfig(cwd));
+ config.enabled = value;
+ const target = writeConfig(cwd, config);
+ return `Design hook ${value ? 'enabled' : 'disabled'} for this project (wrote ${path.relative(cwd, target) || target}).`;
+}
+
+function normalizeRuleId(rule) {
+ return String(rule || '').trim().toLowerCase();
+}
+
+function parseIgnoreRuleArgs(args) {
+ const positionals = [];
+ let allValues = false;
+
+ for (let i = 0; i < args.length; i++) {
+ const arg = String(args[i] || '');
+ if (arg === '--all-values') {
+ allValues = true;
+ } else if (arg === '--reason') {
+ while (i + 1 < args.length && !String(args[i + 1]).startsWith('--')) i++;
+ } else if (arg.startsWith('--reason=')) {
+ // Accepted for command symmetry; ignoreRules stores rule ids only.
+ } else if (arg.startsWith('--')) {
+ throw new Error(`Unknown ignore-rule flag: ${arg}`);
+ } else {
+ positionals.push(arg);
+ }
+ }
+
+ return {
+ rule: normalizeRuleId(positionals[0]),
+ allValues,
+ };
+}
+
+function addIgnoreRule(cwd, args) {
+ const parsed = parseIgnoreRuleArgs(args);
+ const rule = parsed.rule;
+ if (!rule) throw new Error('Pass a rule id, e.g. /impeccable hooks ignore-rule side-tab');
+ if (rule === 'overused-font' && !parsed.allValues) {
+ throw new Error('overused-font is value-specific by default. Use /impeccable hooks ignore-value overused-font <font> for a confirmed font, or /impeccable hooks ignore-rule overused-font --all-values only when the user asked to ignore overused fonts generally.');
+ }
+ const config = mergeConfig(readRawConfig(cwd));
+ if (!config.ignoreRules.includes(rule)) config.ignoreRules.push(rule);
+ writeConfig(cwd, config);
+ return `Added "${rule}" to ignoreRules. Current: ${config.ignoreRules.join(', ')}`;
+}
+
+function addIgnoreFile(cwd, glob) {
+ if (!glob) throw new Error('Pass a glob, e.g. /impeccable hooks ignore-file "src/legacy/**"');
+ const config = mergeConfig(readRawConfig(cwd));
+ if (!config.ignoreFiles.includes(glob)) config.ignoreFiles.push(glob);
+ writeConfig(cwd, config);
+ return `Added "${glob}" to ignoreFiles. Current: ${config.ignoreFiles.join(', ')}`;
+}
+
+function parseIgnoreValueArgs(args) {
+ const positionals = [];
+ let shared = false;
+ let local = false;
+ let reason = '';
+
+ for (let i = 0; i < args.length; i++) {
+ const arg = args[i];
+ if (arg === '--shared') {
+ shared = true;
+ } else if (arg === '--local') {
+ local = true;
+ } else if (arg === '--reason') {
+ const chunks = [];
+ while (i + 1 < args.length && !String(args[i + 1]).startsWith('--')) {
+ chunks.push(args[++i]);
+ }
+ reason = chunks.join(' ').trim();
+ } else if (String(arg).startsWith('--reason=')) {
+ reason = String(arg).slice('--reason='.length).trim();
+ } else {
+ positionals.push(arg);
+ }
+ }
+
+ const [rule, ...valueParts] = positionals;
+ return {
+ rule: String(rule || '').trim().toLowerCase(),
+ value: normalizeIgnoreValue(valueParts.join(' ')),
+ shared,
+ local,
+ reason,
+ };
+}
+
+function addIgnoreValue(cwd, args) {
+ const parsed = parseIgnoreValueArgs(args);
+ if (!parsed.rule || !parsed.value) {
+ throw new Error('Pass a rule id and value, e.g. /impeccable hooks ignore-value overused-font Inter');
+ }
+
+ if (parsed.shared && parsed.local) {
+ throw new Error('Pass only one scope flag: --shared or --local');
+ }
+
+ const local = parsed.local;
+ const config = local
+ ? mergeLocalConfig(readRawConfig(cwd, { local: true }))
+ : mergeConfig(readRawConfig(cwd, { local: false }));
+ const key = `${parsed.rule}\0${parsed.value}`;
+ const existing = config.ignoreValues.find((entry) => `${entry.rule}\0${entry.value}` === key);
+
+ if (existing) {
+ if (parsed.reason) existing.reason = parsed.reason;
+ } else {
+ const entry = {
+ rule: parsed.rule,
+ value: parsed.value,
+ createdAt: new Date().toISOString(),
+ };
+ if (parsed.reason) entry.reason = parsed.reason;
+ config.ignoreValues.push(entry);
+ }
+
+ const target = writeConfig(cwd, config, { local });
+ const scope = local ? 'local ignoreValues' : 'shared ignoreValues';
+ return `Added ${parsed.rule}=${parsed.value} to ${scope} (${path.relative(cwd, target) || target}).`;
+}
+
+function reset(cwd) {
+ const removed = [];
+ for (const filePath of [getConfigPath(cwd), getLocalConfigPath(cwd), getCachePath(cwd), getPendingPath(cwd)]) {
+ try {
+ if (fs.existsSync(filePath)) {
+ fs.unlinkSync(filePath);
+ removed.push(path.relative(cwd, filePath) || filePath);
+ }
+ } catch { /* ignore */ }
+ }
+ return removed.length
+ ? `Reset design hook config and cache (removed: ${removed.join(', ')}).`
+ : 'No hook config or cache to remove. Already at defaults.';
+}
+
+function main() {
+ const [, , actionArg, ...rest] = process.argv;
+ const action = (actionArg || 'status').toLowerCase();
+ const cwd = process.cwd();
+
+ if (!ACTIONS.has(action)) {
+ process.stderr.write(`Unknown action: ${action}\nValid: ${Array.from(ACTIONS).join(', ')}\n`);
+ process.exit(1);
+ }
+
+ try {
+ let out = '';
+ switch (action) {
+ case 'status': out = statusReport(cwd); break;
+ case 'on': out = setEnabled(cwd, true); break;
+ case 'off': out = setEnabled(cwd, false); break;
+ case 'ignore-rule': out = addIgnoreRule(cwd, rest); break;
+ case 'ignore-file': out = addIgnoreFile(cwd, rest[0]); break;
+ case 'ignore-value': out = addIgnoreValue(cwd, rest); break;
+ case 'reset': out = reset(cwd); break;
+ }
+ process.stdout.write(out + '\n');
+ } catch (err) {
+ process.stderr.write(`Error: ${err.message || err}\n`);
+ process.exit(1);
+ }
+}
+
+main();
diff --git a/.kiro/skills/impeccable/scripts/hook-before-edit.mjs b/.kiro/skills/impeccable/scripts/hook-before-edit.mjs
new file mode 100644
index 000000000..54b2709d2
--- /dev/null
+++ b/.kiro/skills/impeccable/scripts/hook-before-edit.mjs
@@ -0,0 +1,408 @@
+#!/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 shellContent = shellHereDocContent(shellCommand(input));
+ if (shellContent) return shellContent;
+ const copiedContent = shellCopiedFileContent(shellCommand(input), 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 || '';
+}
+
+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 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' });
+});
diff --git a/.kiro/skills/impeccable/scripts/hook-lib.mjs b/.kiro/skills/impeccable/scripts/hook-lib.mjs
new file mode 100644
index 000000000..02199f530
--- /dev/null
+++ b/.kiro/skills/impeccable/scripts/hook-lib.mjs
@@ -0,0 +1,1232 @@
+/**
+ * Shared library for the Impeccable design hook.
+ *
+ * Pure-ish helpers split out from `hook.mjs` so unit tests can exercise
+ * config parsing, finding filtering, dedup, render, and cache logic without
+ * spawning a subprocess. `hook.mjs` itself is the thin stdin/stdout shim.
+ *
+ * Public surface (everything exported is part of the contract):
+ * ENVELOPE_PREFIX, ALLOWED_EXTS, ACK_EXTS, SENSITIVE_PATH, GENERATED_PATH, TRUTHY
+ * truthy(value)
+ * readConfig(cwd) / DEFAULT_CONFIG / getConfigPath(cwd) / getLocalConfigPath(cwd)
+ * normalizeIgnoreValue(value)
+ * readCache(cwd) / persistCache(cwd, cache)
+ * bumpEditCount(cache, sessionId, filePath) -> number
+ * suppressionNotice(filePath)
+ * filterFindings(findings, content, ext, config)
+ * dedupeAgainstCache(findings, cache, sessionId, filePath)
+ * renderTemplate(findings, filePath, config, opts)
+ * renderCleanAck(filePath, opts) / renderPendingAck(filePath, known, opts)
+ * shouldEmitAckForFile(filePath)
+ * writeAuditLog(env, entry)
+ * loadDetector() -> Promise<{ detectText, detectHtml }>
+ * matchesAnyGlob(filePath, globs)
+ * normalizeScanTargets(primaryTargets, projectCwd)
+ * runHook(deps) -> { exitCode, stdout, audit, reason? }
+ *
+ * Design notes:
+ * - All errors are swallowed at the runHook seam. The detector throwing must
+ * never break a turn. See PRD §5 "Failure modes".
+ * - Cache shape is JSON-friendly; we gc the oldest sessions when there are
+ * more than 8 to keep file size predictable across long-lived projects.
+ * - The detector loader looks for `detector/detect-antipatterns.mjs` next to
+ * this file first (built skill layout) and falls back to the repo root's
+ * `cli/engine/detect-antipatterns.mjs` (running from source).
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+import { pathToFileURL, fileURLToPath } from 'node:url';
+
+const __filename = fileURLToPath(import.meta.url);
+const __dirname = path.dirname(__filename);
+
+export const ENVELOPE_PREFIX = '[impeccable@1]';
+
+export const ALLOWED_EXTS = new Set([
+ '.tsx', '.jsx', '.html', '.htm', '.vue', '.svelte', '.astro',
+ '.css', '.scss', '.sass', '.less', '.ts', '.js',
+]);
+
+export const ACK_EXTS = new Set([
+ '.tsx', '.jsx', '.html', '.htm', '.vue', '.svelte', '.astro',
+ '.css', '.scss', '.sass', '.less',
+]);
+
+// Hard-skip regex for sensitive files. Cannot be turned off via config.
+// Match tokenized secret/credential filenames, not UI names such as
+// CredentialForm.tsx, SecretPage.jsx, or secretary-dashboard.vue.
+export const SENSITIVE_PATH = new RegExp([
+ String.raw`(?:^|[/\\])\.env(?:\.|$)`,
+ String.raw`(?:^|[/\\])\.git(?:[/\\]|$)`,
+ String.raw`(?:^|[/\\])id_rsa(?:$|[._-])[^/\\]*$`,
+ String.raw`(?:^|[/\\])[^/\\]*\.pem$`,
+ String.raw`(?:^|[/\\])(?:[^/\\]*[._-])?(?:secret|secrets|credential|credentials)(?=[._-])[^/\\]*\.(?:json|ya?ml|toml|ini|conf|config|env|txt|key|cert|crt|pem|js|ts)$`,
+].join('|'), 'i');
+
+// Hard-skip regex for generated, lock, minified, and build-output paths.
+export const GENERATED_PATH = /(?:\.generated\.[a-z]+$|\.d\.ts$|\.min\.[a-z]+$|[/\\]node_modules[/\\]|[/\\](?:dist|build|out|\.next|\.cache|coverage)[/\\]|[/\\]?[^/\\]+\.lock(?:\.json)?$)/i;
+
+export const TRUTHY = /^(1|true|yes|on)$/i;
+
+export const DEFAULT_CONFIG = Object.freeze({
+ enabled: true,
+ ignoreRules: [],
+ ignoreFiles: [],
+ ignoreValues: [],
+ limits: { maxFindings: 5, maxChars: 8000 },
+});
+
+export const HOOK_LOCAL_IGNORE_PATTERNS = Object.freeze([
+ '.impeccable/hook.cache.json',
+ '.impeccable/hook.pending.json',
+ '.impeccable/hook.local.json',
+]);
+
+const HOOK_IGNORE_MARKER_OPEN = '# impeccable-hook-ignore-start';
+const HOOK_IGNORE_MARKER_CLOSE = '# impeccable-hook-ignore-end';
+const CACHE_MAX_SESSIONS = 8;
+export const EDIT_COUNT_THRESHOLD = 6;
+
+export function truthy(value) {
+ return typeof value === 'string' && TRUTHY.test(value);
+}
+
+function depthIsSet(value) {
+ if (value === undefined || value === null) return false;
+ const text = String(value).trim();
+ if (!text) return false;
+ if (TRUTHY.test(text)) return true;
+ return /^\d+$/.test(text) && Number(text) > 0;
+}
+
+function safeReadJson(filePath) {
+ try {
+ return JSON.parse(fs.readFileSync(filePath, 'utf-8'));
+ } catch {
+ return null;
+ }
+}
+
+export function getConfigPath(cwd) {
+ return path.join(cwd, '.impeccable', 'hook.json');
+}
+
+export function getLocalConfigPath(cwd) {
+ return path.join(cwd, '.impeccable', 'hook.local.json');
+}
+
+export function getCachePath(cwd) {
+ return path.join(cwd, '.impeccable', 'hook.cache.json');
+}
+
+export function getPendingPath(cwd) {
+ return path.join(cwd, '.impeccable', 'hook.pending.json');
+}
+
+export function resolveProjectCwd(event, fallback = process.cwd()) {
+ return event?.cwd
+ || (Array.isArray(event?.workspace_roots) && event.workspace_roots[0])
+ || envProjectDir(fallback)
+ || fallback;
+}
+
+export function readConfig(cwd) {
+ const config = cloneDefaultConfig();
+ applyConfigSource(config, safeReadJson(getConfigPath(cwd)));
+ applyConfigSource(config, safeReadJson(getLocalConfigPath(cwd)));
+ return config;
+}
+
+function numberOr(value, fallback) {
+ return Number.isFinite(value) && value > 0 ? value : fallback;
+}
+
+function cloneDefaultConfig() {
+ return {
+ ...DEFAULT_CONFIG,
+ ignoreRules: [],
+ ignoreFiles: [],
+ ignoreValues: [],
+ limits: { ...DEFAULT_CONFIG.limits },
+ };
+}
+
+function applyConfigSource(config, raw) {
+ if (!raw || typeof raw !== 'object') return config;
+ if (Object.prototype.hasOwnProperty.call(raw, 'enabled')) {
+ config.enabled = raw.enabled === false ? false : true;
+ }
+ if (Array.isArray(raw.ignoreRules)) {
+ config.ignoreRules = uniqueStrings([...config.ignoreRules, ...raw.ignoreRules]);
+ }
+ if (Array.isArray(raw.ignoreFiles)) {
+ config.ignoreFiles = uniqueStrings([...config.ignoreFiles, ...raw.ignoreFiles]);
+ }
+ if (Array.isArray(raw.ignoreValues)) {
+ config.ignoreValues = mergeIgnoreValues(config.ignoreValues, raw.ignoreValues);
+ }
+ if (raw.limits && typeof raw.limits === 'object') {
+ config.limits = {
+ maxFindings: numberOr(raw.limits.maxFindings, config.limits.maxFindings),
+ maxChars: numberOr(raw.limits.maxChars, config.limits.maxChars),
+ };
+ }
+ return config;
+}
+
+function uniqueStrings(values) {
+ return Array.from(new Set(values.map(String)));
+}
+
+export function normalizeIgnoreValue(value) {
+ return String(value || '')
+ .trim()
+ .replace(/^["']|["']$/g, '')
+ .replace(/\+/g, ' ')
+ .replace(/\s+/g, ' ')
+ .toLowerCase();
+}
+
+function normalizeIgnoreRule(rule) {
+ return String(rule || '').trim().toLowerCase();
+}
+
+export function normalizeIgnoreValueEntries(entries) {
+ if (!Array.isArray(entries)) return [];
+ const out = [];
+ for (const entry of entries) {
+ if (!entry || typeof entry !== 'object') continue;
+ const rule = normalizeIgnoreRule(entry.rule);
+ const value = normalizeIgnoreValue(entry.value);
+ if (!rule || !value) continue;
+ const normalized = { rule, value };
+ if (typeof entry.reason === 'string' && entry.reason.trim()) {
+ normalized.reason = entry.reason.trim();
+ }
+ if (typeof entry.createdAt === 'string' && entry.createdAt.trim()) {
+ normalized.createdAt = entry.createdAt.trim();
+ }
+ out.push(normalized);
+ }
+ return out;
+}
+
+function mergeIgnoreValues(existing, incoming) {
+ const map = new Map();
+ for (const entry of normalizeIgnoreValueEntries(existing)) {
+ map.set(`${entry.rule}\0${entry.value}`, entry);
+ }
+ for (const entry of normalizeIgnoreValueEntries(incoming)) {
+ map.set(`${entry.rule}\0${entry.value}`, entry);
+ }
+ return Array.from(map.values());
+}
+
+export function readCache(cwd) {
+ const raw = safeReadJson(getCachePath(cwd));
+ if (!raw || typeof raw !== 'object' || raw.version !== 1) {
+ return { version: 1, sessions: {} };
+ }
+ return {
+ version: 1,
+ sessions: raw.sessions && typeof raw.sessions === 'object' ? raw.sessions : {},
+ };
+}
+
+export function persistCache(cwd, cache) {
+ const sessions = cache.sessions || {};
+ const ids = Object.keys(sessions);
+ if (ids.length > CACHE_MAX_SESSIONS) {
+ // Garbage-collect oldest sessions by updatedAt.
+ const ordered = ids
+ .map((id) => [id, sessions[id]?.updatedAt || 0])
+ .sort((a, b) => b[1] - a[1])
+ .slice(0, CACHE_MAX_SESSIONS);
+ const next = {};
+ for (const [id] of ordered) next[id] = sessions[id];
+ cache = { ...cache, sessions: next };
+ }
+ const target = getCachePath(cwd);
+ try {
+ ensureHookGitExcludes(cwd);
+ fs.mkdirSync(path.dirname(target), { recursive: true });
+ fs.writeFileSync(target, JSON.stringify(cache));
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+export function ensureHookGitExcludes(cwd = process.cwd()) {
+ try {
+ const target = resolveHookGitExcludeTarget(cwd);
+ if (!target) {
+ return { mode: 'none', changed: false, patterns: [...HOOK_LOCAL_IGNORE_PATTERNS] };
+ }
+
+ const patterns = target.patternPrefix
+ ? HOOK_LOCAL_IGNORE_PATTERNS.map((pattern) => `${target.patternPrefix}/${pattern}`)
+ : [...HOOK_LOCAL_IGNORE_PATTERNS];
+ const markerSuffix = target.patternPrefix || '.';
+ const markerOpen = `${HOOK_IGNORE_MARKER_OPEN} ${markerSuffix}`;
+ const markerClose = `${HOOK_IGNORE_MARKER_CLOSE} ${markerSuffix}`;
+ const existing = fs.existsSync(target.path) ? fs.readFileSync(target.path, 'utf-8') : '';
+ const block = [markerOpen, ...patterns, markerClose].join('\n');
+ const markerRe = new RegExp(`${escapeRegExp(markerOpen)}[\\s\\S]*?${escapeRegExp(markerClose)}`);
+
+ let updated;
+ if (markerRe.test(existing)) {
+ updated = existing.replace(markerRe, block);
+ } else {
+ const prefix = existing.length === 0 ? '' : existing.endsWith('\n') ? existing : `${existing}\n`;
+ updated = `${prefix}${prefix.endsWith('\n\n') || prefix === '' ? '' : '\n'}${block}\n`;
+ }
+
+ if (updated !== existing) {
+ fs.mkdirSync(path.dirname(target.path), { recursive: true });
+ fs.writeFileSync(target.path, updated, 'utf-8');
+ }
+
+ return {
+ mode: 'git-info-exclude',
+ file: path.relative(path.resolve(cwd), target.path).split(path.sep).join('/'),
+ changed: updated !== existing,
+ patterns,
+ };
+ } catch {
+ return { mode: 'error', changed: false, patterns: [...HOOK_LOCAL_IGNORE_PATTERNS] };
+ }
+}
+
+function resolveHookGitExcludeTarget(cwd) {
+ const start = path.resolve(cwd);
+ let dir = start;
+ while (true) {
+ const dotGit = path.join(dir, '.git');
+ if (fs.existsSync(dotGit)) {
+ const gitDir = resolveGitDir(dotGit, dir);
+ if (!gitDir) return null;
+ const relPrefix = path.relative(dir, start).split(path.sep).join('/');
+ return {
+ path: path.join(gitDir, 'info', 'exclude'),
+ patternPrefix: relPrefix && relPrefix !== '.' ? relPrefix : '',
+ };
+ }
+ const parent = path.dirname(dir);
+ if (parent === dir) return null;
+ dir = parent;
+ }
+}
+
+function resolveGitDir(dotGit, worktreeDir) {
+ const stat = fs.statSync(dotGit);
+ if (stat.isDirectory()) return dotGit;
+ if (!stat.isFile()) return null;
+
+ const body = fs.readFileSync(dotGit, 'utf-8').trim();
+ const match = body.match(/^gitdir:\s*(.+)$/i);
+ if (!match) return null;
+ return path.isAbsolute(match[1]) ? match[1] : path.resolve(worktreeDir, match[1]);
+}
+
+function escapeRegExp(value) {
+ return String(value).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+}
+
+function ensureSession(cache, sessionId) {
+ if (!cache.sessions[sessionId]) {
+ cache.sessions[sessionId] = { updatedAt: Date.now(), files: {} };
+ }
+ return cache.sessions[sessionId];
+}
+
+function ensureFile(cache, sessionId, filePath) {
+ const session = ensureSession(cache, sessionId);
+ if (!session.files[filePath]) {
+ session.files[filePath] = { editCount: 0, findings: [] };
+ }
+ return session.files[filePath];
+}
+
+export function bumpEditCount(cache, sessionId, filePath) {
+ const fileEntry = ensureFile(cache, sessionId, filePath);
+ fileEntry.editCount = (fileEntry.editCount || 0) + 1;
+ ensureSession(cache, sessionId).updatedAt = Date.now();
+ return fileEntry.editCount;
+}
+
+export function suppressionNotice(filePath) {
+ return `${ENVELOPE_PREFIX} Suppressing further design hints on ${filePath}. More than ${EDIT_COUNT_THRESHOLD} edits in this session reached. Run /impeccable audit to revisit.`;
+}
+
+// Glob → RegExp. Supports `**`, `*`, `?`, and `{a,b}` alternation.
+function globToRegex(glob) {
+ let re = '^';
+ let i = 0;
+ while (i < glob.length) {
+ const c = glob[i];
+ if (c === '*') {
+ if (glob[i + 1] === '*') {
+ re += '.*';
+ i += 2;
+ if (glob[i] === '/') i += 1;
+ } else {
+ re += '[^/]*';
+ i += 1;
+ }
+ } else if (c === '?') {
+ re += '[^/]';
+ i += 1;
+ } else if (c === '{') {
+ const end = glob.indexOf('}', i);
+ if (end === -1) { re += '\\{'; i += 1; continue; }
+ const parts = glob.slice(i + 1, end).split(',').map((p) => p.replace(/[.+^$()|[\]\\]/g, '\\$&'));
+ re += `(?:${parts.join('|')})`;
+ i = end + 1;
+ } else if (/[.+^$()|[\]\\]/.test(c)) {
+ re += `\\${c}`;
+ i += 1;
+ } else {
+ re += c;
+ i += 1;
+ }
+ }
+ re += '$';
+ return new RegExp(re);
+}
+
+export function matchesAnyGlob(filePath, globs) {
+ if (!Array.isArray(globs) || globs.length === 0) return false;
+ const normalized = filePath.split(path.sep).join('/');
+ for (const glob of globs) {
+ try {
+ const re = globToRegex(String(glob));
+ if (re.test(normalized)) return true;
+ // Match against basename too for convenience: `*.generated.tsx` should
+ // catch `src/foo.generated.tsx` without requiring `**/`.
+ const base = normalized.split('/').pop();
+ if (re.test(base)) return true;
+ } catch {
+ /* malformed glob, skip */
+ }
+ }
+ return false;
+}
+
+export function filterFindings(findings, _content, _ext, config) {
+ if (!Array.isArray(findings) || findings.length === 0) return [];
+ const ignoreRules = new Set((config.ignoreRules || []).map((rule) => normalizeIgnoreRule(rule)));
+ const ignoreValues = normalizeIgnoreValueEntries(config.ignoreValues || []);
+ return findings.filter((f) => {
+ if (!f || typeof f !== 'object') return false;
+ if (ignoreRules.has(normalizeIgnoreRule(f.antipattern))) return false;
+ if (isIgnoredFindingValue(f, ignoreValues)) return false;
+ return true;
+ });
+}
+
+function isIgnoredFindingValue(finding, ignoreValues) {
+ if (!Array.isArray(ignoreValues) || ignoreValues.length === 0) return false;
+ const rule = normalizeIgnoreRule(finding.antipattern);
+ const value = extractFindingIgnoreValue(finding);
+ if (!rule || !value) return false;
+ return ignoreValues.some((entry) => entry.rule === rule && entry.value === value);
+}
+
+export function extractFindingIgnoreValue(finding) {
+ if (!finding || typeof finding !== 'object') return '';
+ const rule = normalizeIgnoreRule(finding.antipattern);
+ if (rule !== 'overused-font') return '';
+ return normalizeIgnoreValue(extractFindingIgnoreValueRaw(finding));
+}
+
+function extractFindingIgnoreValueRaw(finding) {
+ const direct = cleanIgnoreValueDisplay(finding.ignoreValue || finding.value || '');
+ if (direct) return direct;
+
+ const candidates = [finding.detail, finding.snippet].filter((v) => typeof v === 'string' && v);
+ for (const text of candidates) {
+ const primary = text.match(/Primary font:\s*([^()\n;]+)/i);
+ if (primary) return cleanIgnoreValueDisplay(primary[1]);
+
+ const family = text.match(/font-family\s*:\s*["']?([^'",;\n]+)/i);
+ if (family) return cleanIgnoreValueDisplay(family[1]);
+
+ const google = text.match(/[?&]family=([^&:;\n]+)/i);
+ if (google) {
+ try {
+ return cleanIgnoreValueDisplay(decodeURIComponent(google[1]));
+ } catch {
+ return cleanIgnoreValueDisplay(google[1]);
+ }
+ }
+ }
+
+ return '';
+}
+
+function cleanIgnoreValueDisplay(value) {
+ return String(value || '')
+ .trim()
+ .replace(/^["']|["']$/g, '')
+ .replace(/\+/g, ' ')
+ .replace(/\s+/g, ' ');
+}
+
+export function dedupeAgainstCache(findings, cache, sessionId, filePath) {
+ if (!Array.isArray(findings) || findings.length === 0) return [];
+ const fileEntry = ensureFile(cache, sessionId, filePath);
+ const known = new Set(fileEntry.findings || []);
+ const fresh = [];
+ for (const f of findings) {
+ const key = `${f.antipattern}:${f.line || 0}`;
+ if (known.has(key)) continue;
+ known.add(key);
+ fresh.push(f);
+ }
+ return fresh;
+}
+
+export function rememberFindings(cache, sessionId, filePath, findings) {
+ const fileEntry = ensureFile(cache, sessionId, filePath);
+ const known = new Set(fileEntry.findings || []);
+ for (const f of findings) known.add(`${f.antipattern}:${f.line || 0}`);
+ fileEntry.findings = Array.from(known);
+ ensureSession(cache, sessionId).updatedAt = Date.now();
+}
+
+export function renderTemplate(findings, filePath, config, opts = {}) {
+ if (!Array.isArray(findings) || findings.length === 0) return '';
+ const limits = config?.limits || DEFAULT_CONFIG.limits;
+ const cap = Math.max(1, limits.maxFindings || DEFAULT_CONFIG.limits.maxFindings);
+ const maxChars = Math.max(500, limits.maxChars || DEFAULT_CONFIG.limits.maxChars);
+
+ const cwd = opts.cwd || process.cwd();
+ const display = relativize(filePath, cwd);
+ const total = findings.length;
+ const shown = findings.slice(0, cap);
+ const remaining = total - shown.length;
+
+ const header = `${ENVELOPE_PREFIX} Required design corrections in ${display} (${total} issue(s)):`;
+ const lines = shown.map((f) => formatFindingLine(f));
+ const more = remaining > 0
+ ? `... and ${remaining} more (see /impeccable audit).`
+ : null;
+ const footer = directiveFooter(display);
+
+ const blocks = [header, ...lines];
+ if (more) blocks.push(more);
+ blocks.push('');
+ blocks.push(footer);
+ let text = blocks.join('\n');
+
+ if (text.length > maxChars) {
+ text = clampToBudget(header, lines, more, footer, maxChars);
+ }
+ return text;
+}
+
+function renderGroupedTemplate(groups, config, opts = {}) {
+ const realGroups = groups.filter((group) => Array.isArray(group.findings) && group.findings.length > 0);
+ if (realGroups.length === 0) return '';
+ if (realGroups.length === 1) {
+ const [group] = realGroups;
+ return renderTemplate(group.findings, group.filePath, config, opts);
+ }
+
+ const limits = config?.limits || DEFAULT_CONFIG.limits;
+ const cap = Math.max(1, limits.maxFindings || DEFAULT_CONFIG.limits.maxFindings);
+ const maxChars = Math.max(500, limits.maxChars || DEFAULT_CONFIG.limits.maxChars);
+ const cwd = opts.cwd || process.cwd();
+ const total = realGroups.reduce((sum, group) => sum + group.findings.length, 0);
+ const header = `${ENVELOPE_PREFIX} Required design corrections across ${realGroups.length} files (${total} issue(s)):`;
+ const lines = [];
+ let shownCount = 0;
+
+ for (const group of realGroups) {
+ const display = relativize(group.filePath, cwd);
+ lines.push(`${display} (${group.findings.length} issue(s)):`);
+ const remainingCap = Math.max(0, cap - shownCount);
+ const shown = group.findings.slice(0, remainingCap);
+ for (const finding of shown) {
+ lines.push(formatFindingLine(finding));
+ }
+ shownCount += shown.length;
+ const hidden = group.findings.length - shown.length;
+ if (hidden > 0) {
+ lines.push(`- ... ${hidden} more in ${display} (see /impeccable audit).`);
+ }
+ }
+
+ const footer = directiveFooter('the affected files', { grouped: true });
+ let text = [header, ...lines, '', footer].join('\n');
+ if (text.length > maxChars) {
+ text = clampGroupedToBudget(header, lines, footer, maxChars);
+ }
+ return text;
+}
+
+function clampGroupedToBudget(header, lines, footer, maxChars) {
+ const assemble = (linesArr, omitted) => [
+ header,
+ ...linesArr,
+ ...(omitted ? ['... and more (see /impeccable audit).'] : []),
+ '',
+ footer,
+ ].join('\n');
+
+ let working = lines.slice();
+ let omitted = false;
+ let assembled = assemble(working, omitted);
+ while (assembled.length > maxChars && working.length > 1) {
+ working.pop();
+ omitted = true;
+ assembled = assemble(working, omitted);
+ }
+ if (assembled.length > maxChars) {
+ assembled = `${assembled.slice(0, maxChars - 1)}…`;
+ }
+ return assembled;
+}
+
+function clampToBudget(header, lines, more, footer, maxChars) {
+ const assemble = (linesArr, moreText) => {
+ const blocks = [header, ...linesArr];
+ if (moreText) blocks.push(moreText);
+ blocks.push('');
+ blocks.push(footer);
+ return blocks.join('\n');
+ };
+
+ let working = lines.slice();
+ let moreText = more;
+ let assembled = assemble(working, moreText);
+ while (assembled.length > maxChars && working.length > 1) {
+ working.pop();
+ moreText = '... and more (see /impeccable audit).';
+ assembled = assemble(working, moreText);
+ }
+ if (assembled.length > maxChars) {
+ assembled = `${assembled.slice(0, maxChars - 1)}…`;
+ }
+ return assembled;
+}
+
+function formatFindingLine(f) {
+ const prefix = f.line && f.line > 0 ? `- L${f.line}` : '-';
+ const desc = (f.description || '').trim();
+ const name = (f.name || '').trim();
+ // Description from the registry already ends in punctuation; join with a
+ // single space. `name` may have a trailing period already, keep it clean.
+ const nameSegment = name ? `${name.replace(/\.+\s*$/, '')}.` : '';
+ const ignoreCommand = formatFindingIgnoreCommand(f);
+ const ignoreSegment = ignoreCommand
+ ? ` If the user explicitly confirms this value is intentional: \`${ignoreCommand}\`.`
+ : '';
+ return `${prefix} [${f.antipattern}] ${nameSegment} ${desc}${ignoreSegment}`.replace(/\s+/g, ' ').trim();
+}
+
+function formatFindingIgnoreCommand(finding) {
+ if (!finding || typeof finding !== 'object') return '';
+ const rule = normalizeIgnoreRule(finding.antipattern);
+ if (!rule) return '';
+ const normalizedValue = extractFindingIgnoreValue(finding);
+ if (!normalizedValue) return '';
+ const value = extractFindingIgnoreValueRaw(finding);
+ const valueArg = quoteCommandArg(value);
+ const reason = quoteCommandArg(`User confirmed ${value} is intentional`);
+ return `/impeccable hooks ignore-value ${rule} ${valueArg} --shared --reason ${reason}`;
+}
+
+function quoteCommandArg(value) {
+ const text = String(value || '').trim();
+ if (/^[A-Za-z0-9._:-]+$/.test(text)) return text;
+ return `"${text.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
+}
+
+function relativize(filePath, cwd) {
+ try {
+ const rel = path.relative(cwd, filePath);
+ if (!rel || rel.startsWith('..')) return filePath;
+ return rel.split(path.sep).join('/');
+ } catch {
+ return filePath;
+ }
+}
+
+// Codex `apply_patch` exposes the raw patch in `tool_input.command`, not
+// `tool_input.file_path`. Claude Code may send both; parse the patch body
+// so we can scan the file(s) the tool actually touched.
+// https://developers.openai.com/codex/hooks#posttooluse
+const APPLY_PATCH_FILE_RE = /^\*\*\* (?:Update|Add) File: (.+)$/gm;
+
+export function parseApplyPatchPaths(command, projectCwd) {
+ if (!command || typeof command !== 'string') return [];
+ const out = [];
+ for (const m of command.matchAll(APPLY_PATCH_FILE_RE)) {
+ let p = (m[1] || '').trim();
+ if (!p) continue;
+ if (!path.isAbsolute(p)) p = path.resolve(projectCwd, p);
+ out.push(p);
+ }
+ return out;
+}
+
+export function resolveTargetFiles(event, projectCwd) {
+ const ti = event?.tool_input;
+ const out = [];
+ const add = (filePath) => {
+ if (typeof filePath !== 'string' || !filePath) return;
+ if (!out.includes(filePath)) out.push(filePath);
+ };
+
+ if (event?.tool_name === 'apply_patch' && ti && typeof ti.command === 'string') {
+ for (const filePath of parseApplyPatchPaths(ti.command, projectCwd)) add(filePath);
+ }
+ if (ti && typeof ti.file_path === 'string' && ti.file_path) {
+ add(ti.file_path);
+ }
+ // Cursor Write / StrReplace use `path`, not `file_path`.
+ if (ti && typeof ti.path === 'string' && ti.path) {
+ add(ti.path);
+ }
+ if (typeof event?.file_path === 'string' && event.file_path) {
+ add(event.file_path);
+ }
+ return out;
+}
+
+export function resolveHarness(env = {}, event = null) {
+ const explicit = env?.IMPECCABLE_HOOK_HARNESS;
+ if (explicit === 'cursor') return 'cursor';
+ if (explicit === 'claude' || explicit === 'codex') return 'claude';
+ if (typeof event?.conversation_id === 'string' && event.conversation_id) return 'cursor';
+ return 'claude';
+}
+
+export function normalizeHookEvent(event, projectCwd, harness = 'claude') {
+ if (!event || typeof event !== 'object' || harness !== 'cursor') return event;
+
+ const cwd = event.cwd
+ || (Array.isArray(event.workspace_roots) && event.workspace_roots[0])
+ || envProjectDir(projectCwd)
+ || projectCwd;
+ const sessionId = event.session_id || event.conversation_id || 'unknown';
+
+ const ti = event.tool_input && typeof event.tool_input === 'object' ? event.tool_input : {};
+ const filePath = ti.file_path || ti.path || event.file_path;
+ if (filePath) {
+ return {
+ ...event,
+ cwd,
+ session_id: sessionId,
+ tool_input: { ...ti, file_path: filePath },
+ };
+ }
+
+ return { ...event, cwd, session_id: sessionId };
+}
+
+function envProjectDir(fallback) {
+ if (typeof process.env.CURSOR_PROJECT_DIR === 'string' && process.env.CURSOR_PROJECT_DIR) {
+ return process.env.CURSOR_PROJECT_DIR;
+ }
+ return fallback;
+}
+
+// UI components often keep slop in a sibling/co-located stylesheet while the
+// JSX edit is what triggered PostToolUse. Scan those styles too so an App.jsx
+// patch doesn't report "clean" while styles.css still has Inter/bounce/etc.
+const UI_CODE_EXTS = new Set(['.jsx', '.tsx', '.vue', '.svelte', '.astro']);
+const STYLE_EXTS = new Set(['.css', '.scss', '.sass', '.less']);
+const CO_SCAN_STYLE_NAMES = [
+ 'styles.css', 'styles.scss', 'styles.sass', 'styles.less',
+ 'index.css', 'index.scss', 'index.sass', 'index.less',
+ 'global.css', 'global.scss', 'global.sass', 'global.less',
+ 'globals.css', 'globals.scss', 'globals.sass', 'globals.less',
+];
+const MAX_SCAN_TARGETS = 6;
+
+const STATIC_STYLE_IMPORT_RE = /import\s+(?:[\w*{}\s,$]+\s+from\s+)?['"]([^'"]+\.(?:css|scss|sass|less))['"]/gi;
+
+function hasPathTraversal(filePath) {
+ return typeof filePath === 'string' && filePath.includes('..');
+}
+
+function isInsideProject(filePath, projectCwd) {
+ if (!filePath || !projectCwd || hasPathTraversal(filePath)) return false;
+ try {
+ const rel = path.relative(projectCwd, filePath);
+ return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));
+ } catch {
+ return false;
+ }
+}
+
+export function parseStaticStyleImports(content, fromFile, projectCwd) {
+ if (!content || typeof content !== 'string') return [];
+ const dir = path.dirname(fromFile);
+ const out = [];
+ for (const m of content.matchAll(STATIC_STYLE_IMPORT_RE)) {
+ let p = (m[1] || '').trim();
+ if (!p) continue;
+ if (p.startsWith('.')) p = path.resolve(dir, p);
+ else if (!path.isAbsolute(p)) p = path.resolve(projectCwd, p);
+ if (!isInsideProject(p, projectCwd)) continue;
+ out.push(p);
+ }
+ return out;
+}
+
+export function coLocatedStylesheets(filePath) {
+ const dir = path.dirname(filePath);
+ const base = path.basename(filePath, path.extname(filePath));
+ const candidates = new Set([
+ path.join(dir, `${base}.css`),
+ path.join(dir, `${base}.module.css`),
+ path.join(dir, `${base}.scss`),
+ path.join(dir, `${base}.module.scss`),
+ path.join(dir, `${base}.sass`),
+ path.join(dir, `${base}.module.sass`),
+ path.join(dir, `${base}.less`),
+ path.join(dir, `${base}.module.less`),
+ ]);
+ for (const name of CO_SCAN_STYLE_NAMES) {
+ candidates.add(path.join(dir, name));
+ }
+ return [...candidates].filter((p) => fs.existsSync(p));
+}
+
+export function normalizeScanTargets(primaryTargets, projectCwd) {
+ if (!Array.isArray(primaryTargets) || primaryTargets.length === 0) return [];
+ const ordered = [];
+ const seen = new Set();
+ const baseCwd = projectCwd || process.cwd();
+ const normalizeTarget = (p) => {
+ // Preserve literal `..` segments so downstream sensitive-path checks
+ // still fire. path.resolve would collapse `/foo/../etc/passwd`.
+ if (hasPathTraversal(p)) return p;
+ return path.isAbsolute(p) ? p : path.resolve(baseCwd, p);
+ };
+ const add = (p) => {
+ if (ordered.length >= MAX_SCAN_TARGETS) return;
+ const abs = normalizeTarget(p);
+ if (seen.has(abs)) return;
+ seen.add(abs);
+ ordered.push(abs);
+ return abs;
+ };
+
+ for (const p of primaryTargets) add(p);
+ return ordered;
+}
+
+export function expandScanTargets(primaryTargets, projectCwd) {
+ const ordered = normalizeScanTargets(primaryTargets, projectCwd);
+ if (ordered.length === 0) return [];
+ const seen = new Set(ordered);
+ const baseCwd = projectCwd || process.cwd();
+ const add = (p) => {
+ if (ordered.length >= MAX_SCAN_TARGETS) return;
+ const abs = hasPathTraversal(p) ? p : (path.isAbsolute(p) ? p : path.resolve(baseCwd, p));
+ if (seen.has(abs)) return;
+ seen.add(abs);
+ ordered.push(abs);
+ return abs;
+ };
+
+ const normalizedPrimaries = [];
+ for (const p of ordered) normalizedPrimaries.push(p);
+
+ for (const p of normalizedPrimaries) {
+ if (ordered.length >= MAX_SCAN_TARGETS) break;
+ if (!isInsideProject(p, baseCwd)) continue;
+ const ext = path.extname(p).toLowerCase();
+ if (STYLE_EXTS.has(ext) || !UI_CODE_EXTS.has(ext)) continue;
+
+ let content = '';
+ try { content = fs.readFileSync(p, 'utf-8'); } catch { /* unreadable primary */ }
+
+ for (const imp of parseStaticStyleImports(content, p, projectCwd)) {
+ add(imp);
+ if (ordered.length >= MAX_SCAN_TARGETS) break;
+ }
+ for (const col of coLocatedStylesheets(p)) {
+ add(col);
+ if (ordered.length >= MAX_SCAN_TARGETS) break;
+ }
+ }
+
+ return ordered;
+}
+
+export function writeAuditLog(env, entry) {
+ const target = env?.IMPECCABLE_HOOK_LOG;
+ if (!target || typeof target !== 'string') return false;
+ try {
+ const expanded = target.startsWith('~/')
+ ? path.join(process.env.HOME || process.env.USERPROFILE || '.', target.slice(2))
+ : target;
+ fs.mkdirSync(path.dirname(expanded), { recursive: true });
+ const line = JSON.stringify({ ts: new Date().toISOString(), ...entry }) + '\n';
+ fs.appendFileSync(expanded, line);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+const DETECTOR_CANDIDATES = [
+ path.join(__dirname, 'detector', 'detect-antipatterns.mjs'),
+ path.join(__dirname, '..', '..', 'cli', 'engine', 'detect-antipatterns.mjs'),
+ path.join(__dirname, '..', '..', '..', 'cli', 'engine', 'detect-antipatterns.mjs'),
+];
+
+let detectorCache = null;
+export async function loadDetector(candidates = DETECTOR_CANDIDATES) {
+ if (detectorCache) return detectorCache;
+ const found = candidates.find((c) => fs.existsSync(c));
+ if (!found) return null;
+ const mod = await import(pathToFileURL(found));
+ detectorCache = { detectText: mod.detectText, detectHtml: mod.detectHtml };
+ return detectorCache;
+}
+
+// For tests: allow injecting a detector implementation.
+export function setDetectorForTesting(impl) {
+ detectorCache = impl;
+}
+
+// ────────────────────────────────────────────────────────────────────────
+// Nudge/steer messages for the no-silent-fires policy.
+//
+// The hook is designed to be a conversational presence: every fire that
+// actually scans a file emits a developer-role message into the model's
+// next turn. Three states map to three templates:
+//
+// 1. **Fresh findings** → `renderTemplate` (existing, imperative).
+// 2. **Pending findings** → `renderPendingAck` (re-nudge for issues the
+// model was already told about in this
+// session but hasn't fixed yet).
+// 3. **Truly clean** → `renderCleanAck` (short positive nudge that
+// keeps the design discipline in context).
+//
+// All three are short (≤ ~40 tokens each) so the cumulative cost stays
+// bounded across a long active editing session. Users who explicitly want
+// silence-on-clean can set `IMPECCABLE_HOOK_QUIET=1` — runHook checks that
+// env before emitting #2 or #3.
+//
+// Why not stay silent on dedup-clean? Earlier versions did. The model
+// quickly forgets the prior reminder once tool output scrolls past it, so
+// re-nudging on the same file with a short "still pending" line keeps the
+// pressure on. The wording deliberately points back to "earlier this
+// session" so the model knows it's a re-mind, not a new finding.
+// ────────────────────────────────────────────────────────────────────────
+
+const STEER_LINE = 'Keep typography hierarchy, spacing rhythm, and color contrast intentional on the next change.';
+
+export function renderCleanAck(filePath, opts = {}) {
+ const cwd = opts.cwd || process.cwd();
+ const display = relativize(filePath, cwd);
+ return `${ENVELOPE_PREFIX} Design hook scanned ${display}. No anti-patterns. ${STEER_LINE}`;
+}
+
+export function renderPendingAck(filePath, knownFindings, opts = {}) {
+ const cwd = opts.cwd || process.cwd();
+ const display = relativize(filePath, cwd);
+ const count = knownFindings.length;
+ // `knownFindings` here are the cache strings like "side-tab:3".
+ const sample = knownFindings.slice(0, 3).join(', ');
+ const more = count > 3 ? `, +${count - 3} more` : '';
+ return `${ENVELOPE_PREFIX} Design hook scanned ${display}. Still has ${count} issue(s) flagged earlier this session (${sample}${more}). Address them before finalizing — the previous reminder still applies.`;
+}
+
+export function shouldEmitAckForFile(filePath) {
+ return ACK_EXTS.has(path.extname(String(filePath || '')).toLowerCase());
+}
+
+// The directive footer is the part of the hook output that steers model
+// behavior. Three intentional moves:
+// 1. **Imperative, not advisory.** "Fix these..." beats "Consider
+// revising..." which the model treats as a soft suggestion it can
+// override when the user asked for any kind of throwaway / demo UI.
+// 2. **Explicit exception clause.** Without it, the model will try to
+// "fix" intentional bad fixtures, anti-pattern examples in docs, or
+// test cases. Naming the exception inline beats hoping the model
+// infers it from context.
+// 3. **Acknowledgement instruction.** Hook output is injected as
+// developer-role context, not a chat turn, so the user never sees the
+// raw envelope. Asking the model to surface the fix in its reply is
+// the cheapest way to make the feedback loop visible to the user.
+function directiveFooter(display, opts = {}) {
+ const ignoreFileCommand = `/impeccable hooks ignore-file ${quoteCommandArg(display)}`;
+ const fileIgnoreGuidance = opts.grouped
+ ? 'run `/impeccable hooks ignore-file <path>` for the specific file'
+ : `run \`${ignoreFileCommand}\``;
+ return [
+ 'Fix these in your next reply before finalizing. Acknowledge what you changed so the user sees the correction.',
+ '',
+ 'Skip the fix only if the user explicitly asked for an intentionally bad UI, an anti-pattern example, a test fixture, or documentation of bad design. In that case, say so and continue.',
+ '',
+ `Do not add source comments such as \`impeccable: ignore\`; those pollute the code and do not suppress hook findings. Do not add hook ignores unless the user explicitly confirms the finding is intentional. Prefer the narrowest persisted exception: run the exact \`/impeccable hooks ignore-value ... --shared\` command shown next to a value-specific finding. For \`overused-font\`, use \`ignore-value\` for a specific font and use \`/impeccable hooks ignore-rule overused-font --all-values\` only when the user asks to ignore overused fonts generally. For file-specific findings without an ignore-value command, ${fileIgnoreGuidance}; use \`/impeccable hooks ignore-rule <id>\` only when the user asks to suppress the whole non-value-specific rule. Run /impeccable audit for the full pass.`,
+ ].join('\n');
+}
+
+/**
+ * Run the hook with explicit dependencies. Returns a result object:
+ * { exitCode, stdout, audit, reason? }
+ *
+ * Never throws. All errors are converted to `exitCode: 0` + audit entry.
+ */
+export async function runHook({ stdinJson, env = {}, cwd = process.cwd(), now = Date.now, detector } = {}) {
+ const audit = { ts: new Date(now()).toISOString(), event: 'PostToolUse' };
+ const result = (extra) => ({ exitCode: 0, stdout: '', audit: { ...audit, ...extra } });
+
+ try {
+ // Re-entrancy guard.
+ if (depthIsSet(env.IMPECCABLE_HOOK_DEPTH) || depthIsSet(env.CLAUDE_HOOK_DEPTH)) {
+ return result({ reentrant: true, durationMs: 0 });
+ }
+
+ if (truthy(env.IMPECCABLE_HOOK_DISABLED)) {
+ return result({ skipped: 'env-disabled', durationMs: 0 });
+ }
+
+ const started = Date.now();
+
+ let event;
+ try {
+ event = typeof stdinJson === 'string' ? JSON.parse(stdinJson) : stdinJson;
+ } catch {
+ return result({ skipped: 'stdin-malformed', durationMs: Date.now() - started });
+ }
+ if (!event || typeof event !== 'object') {
+ return result({ skipped: 'stdin-empty', durationMs: Date.now() - started });
+ }
+
+ const harness = resolveHarness(env, event);
+ event = normalizeHookEvent(event, cwd, harness);
+ audit.harness = harness;
+
+ const projectCwd = event.cwd || cwd;
+ const primaryFiles = normalizeScanTargets(resolveTargetFiles(event, projectCwd), projectCwd);
+ const primaryFileSet = new Set(primaryFiles);
+ const targetFiles = expandScanTargets(primaryFiles, projectCwd);
+ audit.session = event.session_id || null;
+ if (event.tool_name) audit.tool = event.tool_name;
+
+ if (targetFiles.length === 0) {
+ return result({ skipped: 'no-file-path', durationMs: Date.now() - started });
+ }
+
+ const config = readConfig(projectCwd);
+ if (config.enabled === false) {
+ return result({ skipped: 'config-disabled', durationMs: Date.now() - started });
+ }
+
+ const cache = readCache(projectCwd);
+ const sessionId = event.session_id || 'unknown';
+ const det = detector || await loadDetector();
+ if (!det || typeof det.detectText !== 'function') {
+ persistCache(projectCwd, cache);
+ return result({ skipped: 'detector-missing', durationMs: Date.now() - started });
+ }
+
+ let pendingWinner = null;
+ let cleanWinner = null;
+ const freshGroups = [];
+ let suppressionWinner = null;
+ let detectorThrewAny = false;
+ let lastSkip = 'no-scannable-file';
+ let suppressedHit = false;
+
+ for (const filePath of targetFiles) {
+ audit.file = filePath;
+
+ if (hasPathTraversal(filePath) || SENSITIVE_PATH.test(filePath)) {
+ lastSkip = 'sensitive';
+ continue;
+ }
+ if (GENERATED_PATH.test(filePath)) {
+ lastSkip = 'generated';
+ continue;
+ }
+
+ const ext = path.extname(filePath).toLowerCase();
+ audit.ext = ext;
+ if (!ALLOWED_EXTS.has(ext)) {
+ lastSkip = 'extension';
+ continue;
+ }
+
+ const relForMatch = relativize(filePath, projectCwd);
+ if (matchesAnyGlob(relForMatch, config.ignoreFiles) || matchesAnyGlob(filePath, config.ignoreFiles)) {
+ lastSkip = 'config-ignore-file';
+ continue;
+ }
+ if (!fs.existsSync(filePath)) {
+ lastSkip = 'file-missing';
+ continue;
+ }
+
+ if (primaryFileSet.has(filePath)) {
+ const editCount = bumpEditCount(cache, sessionId, filePath);
+ audit.editCount = editCount;
+
+ if (editCount > EDIT_COUNT_THRESHOLD) {
+ const wasJustCrossed = editCount === EDIT_COUNT_THRESHOLD + 1;
+ if (wasJustCrossed && !suppressionWinner) {
+ suppressionWinner = { filePath };
+ }
+ lastSkip = 'suppressed';
+ suppressedHit = true;
+ continue;
+ }
+ }
+
+ const content = fs.readFileSync(filePath, 'utf-8');
+ let findings;
+ let detectorThrew = false;
+ if ((ext === '.html' || ext === '.htm') && typeof det.detectHtml === 'function') {
+ try { findings = await det.detectHtml(filePath); } catch { findings = []; detectorThrew = true; }
+ } else {
+ try { findings = await det.detectText(content, filePath); } catch { findings = []; detectorThrew = true; }
+ }
+
+ const filtered = filterFindings(findings || [], content, ext, config);
+ const fresh = dedupeAgainstCache(filtered, cache, sessionId, filePath);
+ audit.findings = (findings || []).length;
+ audit.freshFindings = fresh.length;
+
+ if (fresh.length > 0) {
+ rememberFindings(cache, sessionId, filePath, fresh);
+ freshGroups.push({ filePath, findings: fresh });
+ continue;
+ }
+
+ if (detectorThrew) {
+ detectorThrewAny = true;
+ continue;
+ }
+
+ if (filtered.length > 0 && !pendingWinner) {
+ const known = (ensureFile(cache, sessionId, filePath).findings || []).slice();
+ pendingWinner = { filePath, known };
+ } else if (filtered.length === 0 && !cleanWinner) {
+ cleanWinner = { filePath };
+ }
+ }
+
+ persistCache(projectCwd, cache);
+
+ if (freshGroups.length > 0) {
+ const firstGroup = freshGroups[0];
+ const text = renderGroupedTemplate(freshGroups, config, { cwd: projectCwd });
+ const allFindings = freshGroups.flatMap((group) => group.findings);
+ return {
+ exitCode: 0,
+ stdout: payload(text, 'PostToolUse', harness),
+ emission: {
+ kind: 'fresh',
+ file: firstGroup.filePath,
+ findings: firstGroup.findings,
+ groups: freshGroups,
+ },
+ audit: {
+ ...audit,
+ file: firstGroup.filePath,
+ emitted: true,
+ freshFiles: freshGroups.length,
+ freshFindings: allFindings.length,
+ chars: text.length,
+ durationMs: Date.now() - started,
+ },
+ };
+ }
+
+ if (detectorThrewAny && !pendingWinner && !cleanWinner) {
+ return result({ emitted: false, error: 'detector-threw', durationMs: Date.now() - started });
+ }
+
+ if (truthy(env.IMPECCABLE_HOOK_QUIET)) {
+ return result({ emitted: false, quiet: true, durationMs: Date.now() - started });
+ }
+
+ if (pendingWinner && shouldEmitAckForFile(pendingWinner.filePath)) {
+ const text = renderPendingAck(pendingWinner.filePath, pendingWinner.known, { cwd: projectCwd });
+ return {
+ exitCode: 0,
+ stdout: payload(text, 'PostToolUse', harness),
+ emission: { kind: 'pending', file: pendingWinner.filePath, known: pendingWinner.known },
+ audit: {
+ ...audit,
+ file: pendingWinner.filePath,
+ emitted: true,
+ kind: 'pending',
+ pending: pendingWinner.known.length,
+ chars: text.length,
+ durationMs: Date.now() - started,
+ },
+ };
+ }
+
+ if (suppressionWinner) {
+ const text = suppressionNotice(relativize(suppressionWinner.filePath, projectCwd));
+ return {
+ exitCode: 0,
+ stdout: payload(text, 'PostToolUse', harness),
+ emission: { kind: 'suppression', file: suppressionWinner.filePath },
+ audit: {
+ ...audit,
+ file: suppressionWinner.filePath,
+ suppressed: true,
+ emitted: true,
+ durationMs: Date.now() - started,
+ },
+ };
+ }
+
+ if (cleanWinner && shouldEmitAckForFile(cleanWinner.filePath)) {
+ const text = renderCleanAck(cleanWinner.filePath, { cwd: projectCwd });
+ return {
+ exitCode: 0,
+ stdout: payload(text, 'PostToolUse', harness),
+ emission: { kind: 'clean', file: cleanWinner.filePath },
+ audit: {
+ ...audit,
+ file: cleanWinner.filePath,
+ emitted: true,
+ kind: 'clean',
+ chars: text.length,
+ durationMs: Date.now() - started,
+ },
+ };
+ }
+
+ if (pendingWinner || cleanWinner) {
+ return result({ emitted: false, skipped: 'non-ui-ack', durationMs: Date.now() - started });
+ }
+
+ if (suppressedHit) {
+ return result({ suppressed: true, emitted: false, durationMs: Date.now() - started });
+ }
+
+ return result({ skipped: lastSkip, durationMs: Date.now() - started });
+ } catch (err) {
+ return {
+ exitCode: 0,
+ stdout: '',
+ audit: { ...audit, error: String(err && err.message ? err.message : err) },
+ };
+ }
+}
+
+export function payload(text, eventName = 'PostToolUse', harness = 'claude') {
+ if (harness === 'cursor') {
+ return JSON.stringify({ additional_context: text });
+ }
+ return JSON.stringify({
+ hookSpecificOutput: { hookEventName: eventName, additionalContext: text },
+ });
+}
diff --git a/.kiro/skills/impeccable/scripts/hook.mjs b/.kiro/skills/impeccable/scripts/hook.mjs
new file mode 100644
index 000000000..b862f8033
--- /dev/null
+++ b/.kiro/skills/impeccable/scripts/hook.mjs
@@ -0,0 +1,61 @@
+#!/usr/bin/env node
+/**
+ * Impeccable design hook — PostToolUse entry point.
+ *
+ * Reads the Claude Code / Codex / Cursor hook event from stdin, runs the design
+ * detector against the touched file, and emits a system reminder via
+ * `hookSpecificOutput.additionalContext` when findings exist.
+ *
+ * Contract: never break a turn. Always exit 0. Clean files emit a small ack
+ * unless quiet mode is enabled.
+ *
+ * Most logic lives in `hook-lib.mjs` so it is unit-testable without a
+ * subprocess. This file is the thin stdin/stdout adapter.
+ */
+
+import { runHook, 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');
+}
+
+async function main() {
+ // Snapshot the inherited env FIRST so the re-entrancy guard checks the
+ // parent's value, not the value we are about to export for any child
+ // processes the hook might ever spawn.
+ const inheritedEnv = { ...process.env };
+ process.env.IMPECCABLE_HOOK_DEPTH = process.env.IMPECCABLE_HOOK_DEPTH || '1';
+
+ let stdinJson = '';
+ try { stdinJson = await readStdin(); } catch { /* fall through */ }
+
+ const result = await runHook({
+ stdinJson,
+ env: inheritedEnv,
+ cwd: process.cwd(),
+ });
+
+ writeAuditLog(process.env, result.audit);
+
+ if (result.stdout) process.stdout.write(result.stdout);
+ process.exit(result.exitCode || 0);
+}
+
+main().catch((err) => {
+ // Last-ditch: never break the agent's turn even if something we did not
+ // anticipate goes wrong. Audit-log the failure if logging is enabled.
+ try {
+ writeAuditLog(process.env, {
+ ts: new Date().toISOString(),
+ event: 'PostToolUse',
+ error: String(err && err.message ? err.message : err),
+ });
+ } catch { /* swallow */ }
+ if (process.env.IMPECCABLE_HOOK_DEBUG) {
+ process.stderr.write(`[impeccable-hook] ${err}\n`);
+ }
+ process.exit(0);
+});
diff --git a/.kiro/skills/impeccable/scripts/live-inject.mjs b/.kiro/skills/impeccable/scripts/live-inject.mjs
index 4e5c5dc0a..69ce530c1 100644
--- a/.kiro/skills/impeccable/scripts/live-inject.mjs
+++ b/.kiro/skills/impeccable/scripts/live-inject.mjs
@@ -32,6 +32,8 @@ const IGNORE_MARKER_CLOSE = '# impeccable-live-ignore-end';
export const LIVE_IGNORE_PATTERNS = Object.freeze([
'.impeccable/hook.cache.json',
+ '.impeccable/hook.pending.json',
+ '.impeccable/hook.local.json',
'.impeccable/live/server.json',
'.impeccable/live/sessions/',
'.impeccable/live/previews/',
diff --git a/.opencode/skills/impeccable/SKILL.md b/.opencode/skills/impeccable/SKILL.md
index c4cae0ca1..7dfae0809 100644
--- a/.opencode/skills/impeccable/SKILL.md
+++ b/.opencode/skills/impeccable/SKILL.md
@@ -126,7 +126,7 @@ If someone could look at this interface and say "AI made that" without doubt, it
| `optimize [target]` | Fix | Diagnose and fix UI performance | [reference/optimize.md](reference/optimize.md) |
| `live` | Iterate | Visual variant mode: pick elements in the browser, generate alternatives | [reference/live.md](reference/live.md) |
-Plus two management commands: `pin <command>` and `unpin <command>`, detailed below.
+Plus three management commands: `pin <command>`, `unpin <command>`, and `hooks <on|off|status|...>`, detailed below.
### Routing rules
@@ -143,7 +143,7 @@ Plus two management commands: `pin <command>` and `unpin <command>`, detailed be
**If `scan.targets` is non-empty, run `node .opencode/skills/impeccable/scripts/detect.mjs --json <scan.targets joined by spaces>` once** (the bundled detector over local files: no network, no npx). `scan.via` tells you what they are: `git-changes` (the markup/style files in your dirty tree, the most relevant set), `source-dir` (e.g. `src`, `app`), `html`, or `root`. Fold the hits into your picks: many quality / contrast hits → `audit` or `polish`; a specific slop family → the matching command (gradient text or eyebrows → `quieter` / `typeset`, flat or gray palette → `colorize`, and so on). It's a real, current signal that beats guessing. If detect errors or the tree is large and slow, skip it and recommend the user run `audit` themselves; never block the suggestion on it.
Keep it to 2-3 pointed picks with the exact command to type. The menu stays the fallback; the recommendation is the lede.
-2. **First word matches a command**: load its reference file and follow its instructions. Everything after the command name is the target.
+2. **First word matches a command** (table above OR `pin` / `unpin` / `hooks`): load its reference file and follow its instructions. Everything after the command name is the target.
3. **First word doesn't match, but the intent clearly maps to one command** (e.g. "fix the spacing" → `layout`, "rewrite this error message" → `clarify`, "the colors feel flat" → `colorize`): load that command's reference and proceed as if invoked. If two commands could fit, ask once which.
4. **No clear command match**: general design invocation. Apply the setup steps, the General rules, and the loaded register reference, using the full argument as context.
@@ -161,4 +161,8 @@ If the first word is `craft`, setup still runs first, but [reference/craft.md](r
node .opencode/skills/impeccable/scripts/pin.mjs <pin|unpin> <command>
```
-Valid `<command>` is any command from the table above. Report the script's result concisely. Confirm the new shortcut on success, relay stderr verbatim on error.
\ No newline at end of file
+Valid `<command>` is any command from the table above. Report the script's result concisely. Confirm the new shortcut on success, relay stderr verbatim on error.
+
+## Hooks
+
+`/impeccable hooks <on|off|status|ignore-rule|ignore-file|ignore-value|reset>` manages the design detector hook for this project. The hook auto-runs the detector after direct UI file edits and surfaces findings as system reminders. Full flow is in [reference/hooks.md](reference/hooks.md); load it when the user invokes `/impeccable hooks` with any argument.
\ No newline at end of file
diff --git a/.opencode/skills/impeccable/reference/hooks.md b/.opencode/skills/impeccable/reference/hooks.md
new file mode 100644
index 000000000..5caecfc45
--- /dev/null
+++ b/.opencode/skills/impeccable/reference/hooks.md
@@ -0,0 +1,82 @@
+# /impeccable hooks
+
+Manage the **design detector hook** for the current project.
+
+The hook runs the impeccable design detector on direct file edits to design-relevant files (`.tsx`, `.jsx`, `.html`, `.vue`, `.svelte`, `.astro`, `.css`, `.scss`, `.sass`, `.less`, `.ts`, `.js`). Claude Code and Codex use `PostToolUse` and push a short system reminder into the agent's context after the edit; findings get a correction prompt, pending issues get a re-nudge, and clean UI-ish files get a short ack unless `IMPECCABLE_HOOK_QUIET=1` is set. Plain `.ts` and `.js` files are still scanned, but stay quiet unless the detector finds something. Cursor uses `preToolUse` to block bad proposed writes before they land and stays silent when it allows a clean write.
+
+This command toggles the hook **per project** by editing `.impeccable/hook.json`. Local-only ignore policy lives in `.impeccable/hook.local.json`, which is gitignored. To disable globally, set `IMPECCABLE_HOOK_DISABLED=1` in your shell environment.
+
+Supported harnesses: Claude Code (`.claude/settings.json` in the project), Codex (`.codex/hooks.json` in the project), and Cursor (`.cursor/hooks.json` in the project).
+
+On **Cursor**, `preToolUse` checks proposed Write/Edit/Shell write content and denies only when the real detector finds an issue. The denial message is visible to the agent as the tool error, so the agent can reconsider before the bad write lands.
+
+## Routing
+
+The first argument is the action. Defaults to `status`.
+
+| Action | What it does |
+|---|---|
+| `status` | Print current state, shared/local config paths, ignored rules / files / values, env override. |
+| `on` | Set `enabled: true` in `.impeccable/hook.json`. |
+| `off` | Set `enabled: false` in `.impeccable/hook.json`. |
+| `ignore-rule <id>` | Append `<id>` to `ignoreRules`; for `overused-font`, requires `--all-values`. |
+| `ignore-file <glob>` | Append `<glob>` to `ignoreFiles`. |
+| `ignore-value <id> <value> [--shared] [--reason "..."]` | Append a rule/value suppression to shared `.impeccable/hook.json`. |
+| `ignore-value <id> <value> --local [--reason "..."]` | Append a private rule/value suppression to `.impeccable/hook.local.json`. |
+| `reset` | Delete the project config, dedup cache, and Cursor pending queue. |
+
+## Flow
+
+1. Resolve the action from the user's argument. If no action was given, default to `status`.
+2. Invoke the admin script and pass the user's output through verbatim:
+
+ ```bash
+ node .opencode/skills/impeccable/scripts/hook-admin.mjs <action> [args...]
+ ```
+
+3. If `<action>` is `off`, follow up with a one-line note: "Done. New edits will not trigger the design hook in this project until you run `/impeccable hooks on`."
+4. If `<action>` is `on`, follow up with: "Done. The design hook will fire after the next Edit/Write/MultiEdit on a UI file."
+5. If `<action>` is `ignore-value`, `ignore-file`, or `ignore-rule`, just print the script output. The default scope is shared `.impeccable/hook.json`; add `--local` only when the user explicitly asks for a private exception.
+6. If `<action>` is `status`, just print the script output. Do not add commentary unless the user asked a follow-up question.
+
+## Intentional findings
+
+The hook itself never writes ignore config. Persist an exception only after the user explicitly confirms the flagged issue is intentional, and always go through `hook-admin.mjs`.
+
+Prefer the narrowest exception:
+
+- If the finding line shows an exact `ignore-value` command, run that command. This writes shared `.impeccable/hook.json` by default.
+- For `overused-font`, use `ignore-value` when the user confirms a specific font. Do not use `ignore-rule overused-font` for a specific font.
+- If the finding has no value-specific command, such as `side-tab`, prefer `ignore-file <path>` for the current file.
+- Use `ignore-rule <id>` only when the user asks to suppress that whole rule across the project. For broad overused-font suppression, use `ignore-rule overused-font --all-values` only when the user asks to ignore overused fonts generally.
+- Do not add source comments such as `impeccable: ignore`; inline comments pollute code and are not a supported suppression mechanism.
+
+Example value-specific exception:
+
+```bash
+node .opencode/skills/impeccable/scripts/hook-admin.mjs ignore-value overused-font Inter --shared --reason "User confirmed Inter is intentional"
+```
+
+Example whole-rule font exception:
+
+```bash
+node .opencode/skills/impeccable/scripts/hook-admin.mjs ignore-rule overused-font --all-values --reason "User asked to ignore overused fonts generally"
+```
+
+Example file-scoped exception:
+
+```bash
+node .opencode/skills/impeccable/scripts/hook-admin.mjs ignore-file "src/legacy/Card.tsx"
+```
+
+## Constraints
+
+- Never modify `.impeccable/hook.json` or `.impeccable/hook.local.json` by hand from this command. Always go through `hook-admin.mjs` so writes stay validated and the file shape stays consistent.
+- Do not edit the hook scripts themselves (`hook.mjs`, `hook-lib.mjs`, `hook-before-edit.mjs`) from this flow. Those are skill plumbing.
+- Cursor can block a proposed write when the detector finds a real issue. Claude Code and Codex do not block the edit; they emit a post-edit reminder instead. Disabling stops both blocking and reminders.
+- The hook is bundled with the Impeccable skill and installed through project-local manifests: `.claude/settings.json`, `.codex/hooks.json`, and `.cursor/hooks.json`. On Codex, the user must approve the hook via `/hooks` the first time. On Cursor, confirm hooks are enabled under Settings -> Hooks.
+
+## Failure modes
+
+- If `.impeccable/hook.json` or `.impeccable/hook.local.json` is unreadable or malformed, the hook ignores that file and uses the remaining valid config/defaults. `hook-admin.mjs status` will show malformed files as ignored.
+- If the user asks to "disable the hook" globally, suggest both options: `IMPECCABLE_HOOK_DISABLED=1` env var (one-shot, follows the shell), and `/impeccable hooks off` (persistent for this project, committable).
diff --git a/.opencode/skills/impeccable/scripts/detector/engines/regex/detect-text.mjs b/.opencode/skills/impeccable/scripts/detector/engines/regex/detect-text.mjs
index fd0d9c73f..4c0777c93 100644
--- a/.opencode/skills/impeccable/scripts/detector/engines/regex/detect-text.mjs
+++ b/.opencode/skills/impeccable/scripts/detector/engines/regex/detect-text.mjs
@@ -446,7 +446,7 @@ function detectText(content, filePath, options = {}) {
// Run regex matchers on the full file content (catches Tailwind classes, inline styles)
// Enable block context for CSS files where related properties span multiple lines
- const cssLike = new Set(['.css', '.scss', '.less']);
+ const cssLike = new Set(['.css', '.scss', '.sass', '.less']);
findings.push(...runRegexMatchers(lines, filePath, 0, cssLike.has(ext) || null, {
profile,
phase: 'source',
diff --git a/.opencode/skills/impeccable/scripts/detector/node/file-system.mjs b/.opencode/skills/impeccable/scripts/detector/node/file-system.mjs
index a80250a0e..aaa8c6df7 100644
--- a/.opencode/skills/impeccable/scripts/detector/node/file-system.mjs
+++ b/.opencode/skills/impeccable/scripts/detector/node/file-system.mjs
@@ -11,7 +11,7 @@ const SKIP_DIRS = new Set([
]);
const SCANNABLE_EXTENSIONS = new Set([
- '.html', '.htm', '.css', '.scss', '.less',
+ '.html', '.htm', '.css', '.scss', '.sass', '.less',
'.jsx', '.tsx', '.js', '.ts',
'.vue', '.svelte', '.astro',
]);
diff --git a/.opencode/skills/impeccable/scripts/hook-admin.mjs b/.opencode/skills/impeccable/scripts/hook-admin.mjs
new file mode 100644
index 000000000..86fcfa909
--- /dev/null
+++ b/.opencode/skills/impeccable/scripts/hook-admin.mjs
@@ -0,0 +1,300 @@
+#!/usr/bin/env node
+/**
+ * `/impeccable hooks <on|off|status|reset>` — manage the design hook
+ * via .impeccable/hook.json and .impeccable/hook.local.json in the current
+ * project.
+ *
+ * Usage:
+ * node hook-admin.mjs status # print current state
+ * node hook-admin.mjs on # set enabled: true
+ * node hook-admin.mjs off # set enabled: false
+ * node hook-admin.mjs ignore-rule <rule-id> # append to ignoreRules
+ * node hook-admin.mjs ignore-rule overused-font --all-values
+ * node hook-admin.mjs ignore-file <glob> # append to ignoreFiles
+ * node hook-admin.mjs ignore-value <rule> <value> # append to shared ignoreValues
+ * node hook-admin.mjs ignore-value <rule> <value> --local
+ * node hook-admin.mjs reset # remove all config + cache
+ *
+ * Designed to be invoked by the LLM from the reference/hooks.md flow.
+ * Output is human-readable; the harness will pass it back to the user.
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+
+import {
+ getConfigPath,
+ getLocalConfigPath,
+ getCachePath,
+ getPendingPath,
+ readConfig,
+ DEFAULT_CONFIG,
+ ensureHookGitExcludes,
+ normalizeIgnoreValue,
+ normalizeIgnoreValueEntries,
+} from './hook-lib.mjs';
+
+const ACTIONS = new Set(['status', 'on', 'off', 'ignore-rule', 'ignore-file', 'ignore-value', 'reset']);
+
+function readRawConfigFile(filePath) {
+ if (!fs.existsSync(filePath)) return { exists: false, malformed: false, raw: null };
+ try {
+ return { exists: true, malformed: false, raw: JSON.parse(fs.readFileSync(filePath, 'utf-8')) };
+ } catch {
+ return { exists: true, malformed: true, raw: null };
+ }
+}
+
+function readRawConfig(cwd, opts = {}) {
+ const filePath = opts.local ? getLocalConfigPath(cwd) : getConfigPath(cwd);
+ return readRawConfigFile(filePath).raw;
+}
+
+function writeConfig(cwd, config, opts = {}) {
+ const filePath = opts.local ? getLocalConfigPath(cwd) : getConfigPath(cwd);
+ if (opts.local) ensureHookGitExcludes(cwd);
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
+ fs.writeFileSync(filePath, JSON.stringify(config, null, 2) + '\n');
+ return filePath;
+}
+
+function mergeConfig(existing) {
+ // Persist the full shape so /impeccable hooks edits leave a complete file
+ // for the user to see, not an unhelpful `{"enabled":false}`.
+ const base = existing && typeof existing === 'object' ? existing : {};
+ return {
+ enabled: base.enabled === false ? false : true,
+ ignoreRules: Array.isArray(base.ignoreRules) ? Array.from(new Set(base.ignoreRules.map(String))) : [],
+ ignoreFiles: Array.isArray(base.ignoreFiles) ? Array.from(new Set(base.ignoreFiles.map(String))) : [],
+ ignoreValues: normalizeIgnoreValueEntries(base.ignoreValues || []),
+ limits: {
+ maxFindings: Number.isFinite(base?.limits?.maxFindings) ? base.limits.maxFindings : DEFAULT_CONFIG.limits.maxFindings,
+ maxChars: Number.isFinite(base?.limits?.maxChars) ? base.limits.maxChars : DEFAULT_CONFIG.limits.maxChars,
+ },
+ };
+}
+
+function mergeLocalConfig(existing) {
+ const base = existing && typeof existing === 'object' ? existing : {};
+ const out = {};
+ if (Object.prototype.hasOwnProperty.call(base, 'enabled')) {
+ out.enabled = base.enabled === false ? false : true;
+ }
+ if (Array.isArray(base.ignoreRules)) {
+ out.ignoreRules = Array.from(new Set(base.ignoreRules.map(String)));
+ }
+ if (Array.isArray(base.ignoreFiles)) {
+ out.ignoreFiles = Array.from(new Set(base.ignoreFiles.map(String)));
+ }
+ out.ignoreValues = normalizeIgnoreValueEntries(base.ignoreValues || []);
+ if (base.limits && typeof base.limits === 'object') {
+ const limits = {};
+ if (Number.isFinite(base.limits.maxFindings)) limits.maxFindings = base.limits.maxFindings;
+ if (Number.isFinite(base.limits.maxChars)) limits.maxChars = base.limits.maxChars;
+ if (Object.keys(limits).length) out.limits = limits;
+ }
+ return out;
+}
+
+function statusReport(cwd) {
+ const shared = readRawConfigFile(getConfigPath(cwd));
+ const local = readRawConfigFile(getLocalConfigPath(cwd));
+ const cfg = readConfig(cwd);
+ const envKill = process.env.IMPECCABLE_HOOK_DISABLED;
+ const envState = envKill ? `IMPECCABLE_HOOK_DISABLED=${envKill}` : 'unset';
+ const cfgPath = path.relative(cwd, getConfigPath(cwd)) || '.impeccable/hook.json';
+ const localPath = path.relative(cwd, getLocalConfigPath(cwd)) || '.impeccable/hook.local.json';
+ const cachePath = path.relative(cwd, getCachePath(cwd)) || '.impeccable/hook.cache.json';
+ const fileState = (info, relPath, absent) => {
+ if (info.malformed) return `${relPath} (malformed; ignored)`;
+ if (info.exists) return relPath;
+ return `${relPath} (${absent})`;
+ };
+ const ignoreValues = cfg.ignoreValues.map((entry) => `${entry.rule}=${entry.value}`);
+
+ const lines = [
+ `Impeccable design hook`,
+ ` state: ${cfg.enabled ? 'enabled' : 'disabled'}`,
+ ` shared file: ${fileState(shared, cfgPath, 'using defaults; file not present')}`,
+ ` local file: ${fileState(local, localPath, 'not present')}`,
+ ` ignoreRules: ${cfg.ignoreRules.length ? cfg.ignoreRules.join(', ') : '(none)'}`,
+ ` ignoreFiles: ${cfg.ignoreFiles.length ? cfg.ignoreFiles.join(', ') : '(none)'}`,
+ ` ignoreValues: ${ignoreValues.length ? ignoreValues.join(', ') : '(none)'}`,
+ ` maxFindings: ${cfg.limits.maxFindings}`,
+ ` maxChars: ${cfg.limits.maxChars}`,
+ ` env override: ${envState}`,
+ ` cache file: ${fs.existsSync(getCachePath(cwd)) ? cachePath : `${cachePath} (not present)`}`,
+ ];
+ return lines.join('\n');
+}
+
+function setEnabled(cwd, value) {
+ const config = mergeConfig(readRawConfig(cwd));
+ config.enabled = value;
+ const target = writeConfig(cwd, config);
+ return `Design hook ${value ? 'enabled' : 'disabled'} for this project (wrote ${path.relative(cwd, target) || target}).`;
+}
+
+function normalizeRuleId(rule) {
+ return String(rule || '').trim().toLowerCase();
+}
+
+function parseIgnoreRuleArgs(args) {
+ const positionals = [];
+ let allValues = false;
+
+ for (let i = 0; i < args.length; i++) {
+ const arg = String(args[i] || '');
+ if (arg === '--all-values') {
+ allValues = true;
+ } else if (arg === '--reason') {
+ while (i + 1 < args.length && !String(args[i + 1]).startsWith('--')) i++;
+ } else if (arg.startsWith('--reason=')) {
+ // Accepted for command symmetry; ignoreRules stores rule ids only.
+ } else if (arg.startsWith('--')) {
+ throw new Error(`Unknown ignore-rule flag: ${arg}`);
+ } else {
+ positionals.push(arg);
+ }
+ }
+
+ return {
+ rule: normalizeRuleId(positionals[0]),
+ allValues,
+ };
+}
+
+function addIgnoreRule(cwd, args) {
+ const parsed = parseIgnoreRuleArgs(args);
+ const rule = parsed.rule;
+ if (!rule) throw new Error('Pass a rule id, e.g. /impeccable hooks ignore-rule side-tab');
+ if (rule === 'overused-font' && !parsed.allValues) {
+ throw new Error('overused-font is value-specific by default. Use /impeccable hooks ignore-value overused-font <font> for a confirmed font, or /impeccable hooks ignore-rule overused-font --all-values only when the user asked to ignore overused fonts generally.');
+ }
+ const config = mergeConfig(readRawConfig(cwd));
+ if (!config.ignoreRules.includes(rule)) config.ignoreRules.push(rule);
+ writeConfig(cwd, config);
+ return `Added "${rule}" to ignoreRules. Current: ${config.ignoreRules.join(', ')}`;
+}
+
+function addIgnoreFile(cwd, glob) {
+ if (!glob) throw new Error('Pass a glob, e.g. /impeccable hooks ignore-file "src/legacy/**"');
+ const config = mergeConfig(readRawConfig(cwd));
+ if (!config.ignoreFiles.includes(glob)) config.ignoreFiles.push(glob);
+ writeConfig(cwd, config);
+ return `Added "${glob}" to ignoreFiles. Current: ${config.ignoreFiles.join(', ')}`;
+}
+
+function parseIgnoreValueArgs(args) {
+ const positionals = [];
+ let shared = false;
+ let local = false;
+ let reason = '';
+
+ for (let i = 0; i < args.length; i++) {
+ const arg = args[i];
+ if (arg === '--shared') {
+ shared = true;
+ } else if (arg === '--local') {
+ local = true;
+ } else if (arg === '--reason') {
+ const chunks = [];
+ while (i + 1 < args.length && !String(args[i + 1]).startsWith('--')) {
+ chunks.push(args[++i]);
+ }
+ reason = chunks.join(' ').trim();
+ } else if (String(arg).startsWith('--reason=')) {
+ reason = String(arg).slice('--reason='.length).trim();
+ } else {
+ positionals.push(arg);
+ }
+ }
+
+ const [rule, ...valueParts] = positionals;
+ return {
+ rule: String(rule || '').trim().toLowerCase(),
+ value: normalizeIgnoreValue(valueParts.join(' ')),
+ shared,
+ local,
+ reason,
+ };
+}
+
+function addIgnoreValue(cwd, args) {
+ const parsed = parseIgnoreValueArgs(args);
+ if (!parsed.rule || !parsed.value) {
+ throw new Error('Pass a rule id and value, e.g. /impeccable hooks ignore-value overused-font Inter');
+ }
+
+ if (parsed.shared && parsed.local) {
+ throw new Error('Pass only one scope flag: --shared or --local');
+ }
+
+ const local = parsed.local;
+ const config = local
+ ? mergeLocalConfig(readRawConfig(cwd, { local: true }))
+ : mergeConfig(readRawConfig(cwd, { local: false }));
+ const key = `${parsed.rule}\0${parsed.value}`;
+ const existing = config.ignoreValues.find((entry) => `${entry.rule}\0${entry.value}` === key);
+
+ if (existing) {
+ if (parsed.reason) existing.reason = parsed.reason;
+ } else {
+ const entry = {
+ rule: parsed.rule,
+ value: parsed.value,
+ createdAt: new Date().toISOString(),
+ };
+ if (parsed.reason) entry.reason = parsed.reason;
+ config.ignoreValues.push(entry);
+ }
+
+ const target = writeConfig(cwd, config, { local });
+ const scope = local ? 'local ignoreValues' : 'shared ignoreValues';
+ return `Added ${parsed.rule}=${parsed.value} to ${scope} (${path.relative(cwd, target) || target}).`;
+}
+
+function reset(cwd) {
+ const removed = [];
+ for (const filePath of [getConfigPath(cwd), getLocalConfigPath(cwd), getCachePath(cwd), getPendingPath(cwd)]) {
+ try {
+ if (fs.existsSync(filePath)) {
+ fs.unlinkSync(filePath);
+ removed.push(path.relative(cwd, filePath) || filePath);
+ }
+ } catch { /* ignore */ }
+ }
+ return removed.length
+ ? `Reset design hook config and cache (removed: ${removed.join(', ')}).`
+ : 'No hook config or cache to remove. Already at defaults.';
+}
+
+function main() {
+ const [, , actionArg, ...rest] = process.argv;
+ const action = (actionArg || 'status').toLowerCase();
+ const cwd = process.cwd();
+
+ if (!ACTIONS.has(action)) {
+ process.stderr.write(`Unknown action: ${action}\nValid: ${Array.from(ACTIONS).join(', ')}\n`);
+ process.exit(1);
+ }
+
+ try {
+ let out = '';
+ switch (action) {
+ case 'status': out = statusReport(cwd); break;
+ case 'on': out = setEnabled(cwd, true); break;
+ case 'off': out = setEnabled(cwd, false); break;
+ case 'ignore-rule': out = addIgnoreRule(cwd, rest); break;
+ case 'ignore-file': out = addIgnoreFile(cwd, rest[0]); break;
+ case 'ignore-value': out = addIgnoreValue(cwd, rest); break;
+ case 'reset': out = reset(cwd); break;
+ }
+ process.stdout.write(out + '\n');
+ } catch (err) {
+ process.stderr.write(`Error: ${err.message || err}\n`);
+ process.exit(1);
+ }
+}
+
+main();
diff --git a/.opencode/skills/impeccable/scripts/hook-before-edit.mjs b/.opencode/skills/impeccable/scripts/hook-before-edit.mjs
new file mode 100644
index 000000000..54b2709d2
--- /dev/null
+++ b/.opencode/skills/impeccable/scripts/hook-before-edit.mjs
@@ -0,0 +1,408 @@
+#!/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 shellContent = shellHereDocContent(shellCommand(input));
+ if (shellContent) return shellContent;
+ const copiedContent = shellCopiedFileContent(shellCommand(input), 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 || '';
+}
+
+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 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' });
+});
diff --git a/.opencode/skills/impeccable/scripts/hook-lib.mjs b/.opencode/skills/impeccable/scripts/hook-lib.mjs
new file mode 100644
index 000000000..02199f530
--- /dev/null
+++ b/.opencode/skills/impeccable/scripts/hook-lib.mjs
@@ -0,0 +1,1232 @@
+/**
+ * Shared library for the Impeccable design hook.
+ *
+ * Pure-ish helpers split out from `hook.mjs` so unit tests can exercise
+ * config parsing, finding filtering, dedup, render, and cache logic without
+ * spawning a subprocess. `hook.mjs` itself is the thin stdin/stdout shim.
+ *
+ * Public surface (everything exported is part of the contract):
+ * ENVELOPE_PREFIX, ALLOWED_EXTS, ACK_EXTS, SENSITIVE_PATH, GENERATED_PATH, TRUTHY
+ * truthy(value)
+ * readConfig(cwd) / DEFAULT_CONFIG / getConfigPath(cwd) / getLocalConfigPath(cwd)
+ * normalizeIgnoreValue(value)
+ * readCache(cwd) / persistCache(cwd, cache)
+ * bumpEditCount(cache, sessionId, filePath) -> number
+ * suppressionNotice(filePath)
+ * filterFindings(findings, content, ext, config)
+ * dedupeAgainstCache(findings, cache, sessionId, filePath)
+ * renderTemplate(findings, filePath, config, opts)
+ * renderCleanAck(filePath, opts) / renderPendingAck(filePath, known, opts)
+ * shouldEmitAckForFile(filePath)
+ * writeAuditLog(env, entry)
+ * loadDetector() -> Promise<{ detectText, detectHtml }>
+ * matchesAnyGlob(filePath, globs)
+ * normalizeScanTargets(primaryTargets, projectCwd)
+ * runHook(deps) -> { exitCode, stdout, audit, reason? }
+ *
+ * Design notes:
+ * - All errors are swallowed at the runHook seam. The detector throwing must
+ * never break a turn. See PRD §5 "Failure modes".
+ * - Cache shape is JSON-friendly; we gc the oldest sessions when there are
+ * more than 8 to keep file size predictable across long-lived projects.
+ * - The detector loader looks for `detector/detect-antipatterns.mjs` next to
+ * this file first (built skill layout) and falls back to the repo root's
+ * `cli/engine/detect-antipatterns.mjs` (running from source).
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+import { pathToFileURL, fileURLToPath } from 'node:url';
+
+const __filename = fileURLToPath(import.meta.url);
+const __dirname = path.dirname(__filename);
+
+export const ENVELOPE_PREFIX = '[impeccable@1]';
+
+export const ALLOWED_EXTS = new Set([
+ '.tsx', '.jsx', '.html', '.htm', '.vue', '.svelte', '.astro',
+ '.css', '.scss', '.sass', '.less', '.ts', '.js',
+]);
+
+export const ACK_EXTS = new Set([
+ '.tsx', '.jsx', '.html', '.htm', '.vue', '.svelte', '.astro',
+ '.css', '.scss', '.sass', '.less',
+]);
+
+// Hard-skip regex for sensitive files. Cannot be turned off via config.
+// Match tokenized secret/credential filenames, not UI names such as
+// CredentialForm.tsx, SecretPage.jsx, or secretary-dashboard.vue.
+export const SENSITIVE_PATH = new RegExp([
+ String.raw`(?:^|[/\\])\.env(?:\.|$)`,
+ String.raw`(?:^|[/\\])\.git(?:[/\\]|$)`,
+ String.raw`(?:^|[/\\])id_rsa(?:$|[._-])[^/\\]*$`,
+ String.raw`(?:^|[/\\])[^/\\]*\.pem$`,
+ String.raw`(?:^|[/\\])(?:[^/\\]*[._-])?(?:secret|secrets|credential|credentials)(?=[._-])[^/\\]*\.(?:json|ya?ml|toml|ini|conf|config|env|txt|key|cert|crt|pem|js|ts)$`,
+].join('|'), 'i');
+
+// Hard-skip regex for generated, lock, minified, and build-output paths.
+export const GENERATED_PATH = /(?:\.generated\.[a-z]+$|\.d\.ts$|\.min\.[a-z]+$|[/\\]node_modules[/\\]|[/\\](?:dist|build|out|\.next|\.cache|coverage)[/\\]|[/\\]?[^/\\]+\.lock(?:\.json)?$)/i;
+
+export const TRUTHY = /^(1|true|yes|on)$/i;
+
+export const DEFAULT_CONFIG = Object.freeze({
+ enabled: true,
+ ignoreRules: [],
+ ignoreFiles: [],
+ ignoreValues: [],
+ limits: { maxFindings: 5, maxChars: 8000 },
+});
+
+export const HOOK_LOCAL_IGNORE_PATTERNS = Object.freeze([
+ '.impeccable/hook.cache.json',
+ '.impeccable/hook.pending.json',
+ '.impeccable/hook.local.json',
+]);
+
+const HOOK_IGNORE_MARKER_OPEN = '# impeccable-hook-ignore-start';
+const HOOK_IGNORE_MARKER_CLOSE = '# impeccable-hook-ignore-end';
+const CACHE_MAX_SESSIONS = 8;
+export const EDIT_COUNT_THRESHOLD = 6;
+
+export function truthy(value) {
+ return typeof value === 'string' && TRUTHY.test(value);
+}
+
+function depthIsSet(value) {
+ if (value === undefined || value === null) return false;
+ const text = String(value).trim();
+ if (!text) return false;
+ if (TRUTHY.test(text)) return true;
+ return /^\d+$/.test(text) && Number(text) > 0;
+}
+
+function safeReadJson(filePath) {
+ try {
+ return JSON.parse(fs.readFileSync(filePath, 'utf-8'));
+ } catch {
+ return null;
+ }
+}
+
+export function getConfigPath(cwd) {
+ return path.join(cwd, '.impeccable', 'hook.json');
+}
+
+export function getLocalConfigPath(cwd) {
+ return path.join(cwd, '.impeccable', 'hook.local.json');
+}
+
+export function getCachePath(cwd) {
+ return path.join(cwd, '.impeccable', 'hook.cache.json');
+}
+
+export function getPendingPath(cwd) {
+ return path.join(cwd, '.impeccable', 'hook.pending.json');
+}
+
+export function resolveProjectCwd(event, fallback = process.cwd()) {
+ return event?.cwd
+ || (Array.isArray(event?.workspace_roots) && event.workspace_roots[0])
+ || envProjectDir(fallback)
+ || fallback;
+}
+
+export function readConfig(cwd) {
+ const config = cloneDefaultConfig();
+ applyConfigSource(config, safeReadJson(getConfigPath(cwd)));
+ applyConfigSource(config, safeReadJson(getLocalConfigPath(cwd)));
+ return config;
+}
+
+function numberOr(value, fallback) {
+ return Number.isFinite(value) && value > 0 ? value : fallback;
+}
+
+function cloneDefaultConfig() {
+ return {
+ ...DEFAULT_CONFIG,
+ ignoreRules: [],
+ ignoreFiles: [],
+ ignoreValues: [],
+ limits: { ...DEFAULT_CONFIG.limits },
+ };
+}
+
+function applyConfigSource(config, raw) {
+ if (!raw || typeof raw !== 'object') return config;
+ if (Object.prototype.hasOwnProperty.call(raw, 'enabled')) {
+ config.enabled = raw.enabled === false ? false : true;
+ }
+ if (Array.isArray(raw.ignoreRules)) {
+ config.ignoreRules = uniqueStrings([...config.ignoreRules, ...raw.ignoreRules]);
+ }
+ if (Array.isArray(raw.ignoreFiles)) {
+ config.ignoreFiles = uniqueStrings([...config.ignoreFiles, ...raw.ignoreFiles]);
+ }
+ if (Array.isArray(raw.ignoreValues)) {
+ config.ignoreValues = mergeIgnoreValues(config.ignoreValues, raw.ignoreValues);
+ }
+ if (raw.limits && typeof raw.limits === 'object') {
+ config.limits = {
+ maxFindings: numberOr(raw.limits.maxFindings, config.limits.maxFindings),
+ maxChars: numberOr(raw.limits.maxChars, config.limits.maxChars),
+ };
+ }
+ return config;
+}
+
+function uniqueStrings(values) {
+ return Array.from(new Set(values.map(String)));
+}
+
+export function normalizeIgnoreValue(value) {
+ return String(value || '')
+ .trim()
+ .replace(/^["']|["']$/g, '')
+ .replace(/\+/g, ' ')
+ .replace(/\s+/g, ' ')
+ .toLowerCase();
+}
+
+function normalizeIgnoreRule(rule) {
+ return String(rule || '').trim().toLowerCase();
+}
+
+export function normalizeIgnoreValueEntries(entries) {
+ if (!Array.isArray(entries)) return [];
+ const out = [];
+ for (const entry of entries) {
+ if (!entry || typeof entry !== 'object') continue;
+ const rule = normalizeIgnoreRule(entry.rule);
+ const value = normalizeIgnoreValue(entry.value);
+ if (!rule || !value) continue;
+ const normalized = { rule, value };
+ if (typeof entry.reason === 'string' && entry.reason.trim()) {
+ normalized.reason = entry.reason.trim();
+ }
+ if (typeof entry.createdAt === 'string' && entry.createdAt.trim()) {
+ normalized.createdAt = entry.createdAt.trim();
+ }
+ out.push(normalized);
+ }
+ return out;
+}
+
+function mergeIgnoreValues(existing, incoming) {
+ const map = new Map();
+ for (const entry of normalizeIgnoreValueEntries(existing)) {
+ map.set(`${entry.rule}\0${entry.value}`, entry);
+ }
+ for (const entry of normalizeIgnoreValueEntries(incoming)) {
+ map.set(`${entry.rule}\0${entry.value}`, entry);
+ }
+ return Array.from(map.values());
+}
+
+export function readCache(cwd) {
+ const raw = safeReadJson(getCachePath(cwd));
+ if (!raw || typeof raw !== 'object' || raw.version !== 1) {
+ return { version: 1, sessions: {} };
+ }
+ return {
+ version: 1,
+ sessions: raw.sessions && typeof raw.sessions === 'object' ? raw.sessions : {},
+ };
+}
+
+export function persistCache(cwd, cache) {
+ const sessions = cache.sessions || {};
+ const ids = Object.keys(sessions);
+ if (ids.length > CACHE_MAX_SESSIONS) {
+ // Garbage-collect oldest sessions by updatedAt.
+ const ordered = ids
+ .map((id) => [id, sessions[id]?.updatedAt || 0])
+ .sort((a, b) => b[1] - a[1])
+ .slice(0, CACHE_MAX_SESSIONS);
+ const next = {};
+ for (const [id] of ordered) next[id] = sessions[id];
+ cache = { ...cache, sessions: next };
+ }
+ const target = getCachePath(cwd);
+ try {
+ ensureHookGitExcludes(cwd);
+ fs.mkdirSync(path.dirname(target), { recursive: true });
+ fs.writeFileSync(target, JSON.stringify(cache));
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+export function ensureHookGitExcludes(cwd = process.cwd()) {
+ try {
+ const target = resolveHookGitExcludeTarget(cwd);
+ if (!target) {
+ return { mode: 'none', changed: false, patterns: [...HOOK_LOCAL_IGNORE_PATTERNS] };
+ }
+
+ const patterns = target.patternPrefix
+ ? HOOK_LOCAL_IGNORE_PATTERNS.map((pattern) => `${target.patternPrefix}/${pattern}`)
+ : [...HOOK_LOCAL_IGNORE_PATTERNS];
+ const markerSuffix = target.patternPrefix || '.';
+ const markerOpen = `${HOOK_IGNORE_MARKER_OPEN} ${markerSuffix}`;
+ const markerClose = `${HOOK_IGNORE_MARKER_CLOSE} ${markerSuffix}`;
+ const existing = fs.existsSync(target.path) ? fs.readFileSync(target.path, 'utf-8') : '';
+ const block = [markerOpen, ...patterns, markerClose].join('\n');
+ const markerRe = new RegExp(`${escapeRegExp(markerOpen)}[\\s\\S]*?${escapeRegExp(markerClose)}`);
+
+ let updated;
+ if (markerRe.test(existing)) {
+ updated = existing.replace(markerRe, block);
+ } else {
+ const prefix = existing.length === 0 ? '' : existing.endsWith('\n') ? existing : `${existing}\n`;
+ updated = `${prefix}${prefix.endsWith('\n\n') || prefix === '' ? '' : '\n'}${block}\n`;
+ }
+
+ if (updated !== existing) {
+ fs.mkdirSync(path.dirname(target.path), { recursive: true });
+ fs.writeFileSync(target.path, updated, 'utf-8');
+ }
+
+ return {
+ mode: 'git-info-exclude',
+ file: path.relative(path.resolve(cwd), target.path).split(path.sep).join('/'),
+ changed: updated !== existing,
+ patterns,
+ };
+ } catch {
+ return { mode: 'error', changed: false, patterns: [...HOOK_LOCAL_IGNORE_PATTERNS] };
+ }
+}
+
+function resolveHookGitExcludeTarget(cwd) {
+ const start = path.resolve(cwd);
+ let dir = start;
+ while (true) {
+ const dotGit = path.join(dir, '.git');
+ if (fs.existsSync(dotGit)) {
+ const gitDir = resolveGitDir(dotGit, dir);
+ if (!gitDir) return null;
+ const relPrefix = path.relative(dir, start).split(path.sep).join('/');
+ return {
+ path: path.join(gitDir, 'info', 'exclude'),
+ patternPrefix: relPrefix && relPrefix !== '.' ? relPrefix : '',
+ };
+ }
+ const parent = path.dirname(dir);
+ if (parent === dir) return null;
+ dir = parent;
+ }
+}
+
+function resolveGitDir(dotGit, worktreeDir) {
+ const stat = fs.statSync(dotGit);
+ if (stat.isDirectory()) return dotGit;
+ if (!stat.isFile()) return null;
+
+ const body = fs.readFileSync(dotGit, 'utf-8').trim();
+ const match = body.match(/^gitdir:\s*(.+)$/i);
+ if (!match) return null;
+ return path.isAbsolute(match[1]) ? match[1] : path.resolve(worktreeDir, match[1]);
+}
+
+function escapeRegExp(value) {
+ return String(value).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+}
+
+function ensureSession(cache, sessionId) {
+ if (!cache.sessions[sessionId]) {
+ cache.sessions[sessionId] = { updatedAt: Date.now(), files: {} };
+ }
+ return cache.sessions[sessionId];
+}
+
+function ensureFile(cache, sessionId, filePath) {
+ const session = ensureSession(cache, sessionId);
+ if (!session.files[filePath]) {
+ session.files[filePath] = { editCount: 0, findings: [] };
+ }
+ return session.files[filePath];
+}
+
+export function bumpEditCount(cache, sessionId, filePath) {
+ const fileEntry = ensureFile(cache, sessionId, filePath);
+ fileEntry.editCount = (fileEntry.editCount || 0) + 1;
+ ensureSession(cache, sessionId).updatedAt = Date.now();
+ return fileEntry.editCount;
+}
+
+export function suppressionNotice(filePath) {
+ return `${ENVELOPE_PREFIX} Suppressing further design hints on ${filePath}. More than ${EDIT_COUNT_THRESHOLD} edits in this session reached. Run /impeccable audit to revisit.`;
+}
+
+// Glob → RegExp. Supports `**`, `*`, `?`, and `{a,b}` alternation.
+function globToRegex(glob) {
+ let re = '^';
+ let i = 0;
+ while (i < glob.length) {
+ const c = glob[i];
+ if (c === '*') {
+ if (glob[i + 1] === '*') {
+ re += '.*';
+ i += 2;
+ if (glob[i] === '/') i += 1;
+ } else {
+ re += '[^/]*';
+ i += 1;
+ }
+ } else if (c === '?') {
+ re += '[^/]';
+ i += 1;
+ } else if (c === '{') {
+ const end = glob.indexOf('}', i);
+ if (end === -1) { re += '\\{'; i += 1; continue; }
+ const parts = glob.slice(i + 1, end).split(',').map((p) => p.replace(/[.+^$()|[\]\\]/g, '\\$&'));
+ re += `(?:${parts.join('|')})`;
+ i = end + 1;
+ } else if (/[.+^$()|[\]\\]/.test(c)) {
+ re += `\\${c}`;
+ i += 1;
+ } else {
+ re += c;
+ i += 1;
+ }
+ }
+ re += '$';
+ return new RegExp(re);
+}
+
+export function matchesAnyGlob(filePath, globs) {
+ if (!Array.isArray(globs) || globs.length === 0) return false;
+ const normalized = filePath.split(path.sep).join('/');
+ for (const glob of globs) {
+ try {
+ const re = globToRegex(String(glob));
+ if (re.test(normalized)) return true;
+ // Match against basename too for convenience: `*.generated.tsx` should
+ // catch `src/foo.generated.tsx` without requiring `**/`.
+ const base = normalized.split('/').pop();
+ if (re.test(base)) return true;
+ } catch {
+ /* malformed glob, skip */
+ }
+ }
+ return false;
+}
+
+export function filterFindings(findings, _content, _ext, config) {
+ if (!Array.isArray(findings) || findings.length === 0) return [];
+ const ignoreRules = new Set((config.ignoreRules || []).map((rule) => normalizeIgnoreRule(rule)));
+ const ignoreValues = normalizeIgnoreValueEntries(config.ignoreValues || []);
+ return findings.filter((f) => {
+ if (!f || typeof f !== 'object') return false;
+ if (ignoreRules.has(normalizeIgnoreRule(f.antipattern))) return false;
+ if (isIgnoredFindingValue(f, ignoreValues)) return false;
+ return true;
+ });
+}
+
+function isIgnoredFindingValue(finding, ignoreValues) {
+ if (!Array.isArray(ignoreValues) || ignoreValues.length === 0) return false;
+ const rule = normalizeIgnoreRule(finding.antipattern);
+ const value = extractFindingIgnoreValue(finding);
+ if (!rule || !value) return false;
+ return ignoreValues.some((entry) => entry.rule === rule && entry.value === value);
+}
+
+export function extractFindingIgnoreValue(finding) {
+ if (!finding || typeof finding !== 'object') return '';
+ const rule = normalizeIgnoreRule(finding.antipattern);
+ if (rule !== 'overused-font') return '';
+ return normalizeIgnoreValue(extractFindingIgnoreValueRaw(finding));
+}
+
+function extractFindingIgnoreValueRaw(finding) {
+ const direct = cleanIgnoreValueDisplay(finding.ignoreValue || finding.value || '');
+ if (direct) return direct;
+
+ const candidates = [finding.detail, finding.snippet].filter((v) => typeof v === 'string' && v);
+ for (const text of candidates) {
+ const primary = text.match(/Primary font:\s*([^()\n;]+)/i);
+ if (primary) return cleanIgnoreValueDisplay(primary[1]);
+
+ const family = text.match(/font-family\s*:\s*["']?([^'",;\n]+)/i);
+ if (family) return cleanIgnoreValueDisplay(family[1]);
+
+ const google = text.match(/[?&]family=([^&:;\n]+)/i);
+ if (google) {
+ try {
+ return cleanIgnoreValueDisplay(decodeURIComponent(google[1]));
+ } catch {
+ return cleanIgnoreValueDisplay(google[1]);
+ }
+ }
+ }
+
+ return '';
+}
+
+function cleanIgnoreValueDisplay(value) {
+ return String(value || '')
+ .trim()
+ .replace(/^["']|["']$/g, '')
+ .replace(/\+/g, ' ')
+ .replace(/\s+/g, ' ');
+}
+
+export function dedupeAgainstCache(findings, cache, sessionId, filePath) {
+ if (!Array.isArray(findings) || findings.length === 0) return [];
+ const fileEntry = ensureFile(cache, sessionId, filePath);
+ const known = new Set(fileEntry.findings || []);
+ const fresh = [];
+ for (const f of findings) {
+ const key = `${f.antipattern}:${f.line || 0}`;
+ if (known.has(key)) continue;
+ known.add(key);
+ fresh.push(f);
+ }
+ return fresh;
+}
+
+export function rememberFindings(cache, sessionId, filePath, findings) {
+ const fileEntry = ensureFile(cache, sessionId, filePath);
+ const known = new Set(fileEntry.findings || []);
+ for (const f of findings) known.add(`${f.antipattern}:${f.line || 0}`);
+ fileEntry.findings = Array.from(known);
+ ensureSession(cache, sessionId).updatedAt = Date.now();
+}
+
+export function renderTemplate(findings, filePath, config, opts = {}) {
+ if (!Array.isArray(findings) || findings.length === 0) return '';
+ const limits = config?.limits || DEFAULT_CONFIG.limits;
+ const cap = Math.max(1, limits.maxFindings || DEFAULT_CONFIG.limits.maxFindings);
+ const maxChars = Math.max(500, limits.maxChars || DEFAULT_CONFIG.limits.maxChars);
+
+ const cwd = opts.cwd || process.cwd();
+ const display = relativize(filePath, cwd);
+ const total = findings.length;
+ const shown = findings.slice(0, cap);
+ const remaining = total - shown.length;
+
+ const header = `${ENVELOPE_PREFIX} Required design corrections in ${display} (${total} issue(s)):`;
+ const lines = shown.map((f) => formatFindingLine(f));
+ const more = remaining > 0
+ ? `... and ${remaining} more (see /impeccable audit).`
+ : null;
+ const footer = directiveFooter(display);
+
+ const blocks = [header, ...lines];
+ if (more) blocks.push(more);
+ blocks.push('');
+ blocks.push(footer);
+ let text = blocks.join('\n');
+
+ if (text.length > maxChars) {
+ text = clampToBudget(header, lines, more, footer, maxChars);
+ }
+ return text;
+}
+
+function renderGroupedTemplate(groups, config, opts = {}) {
+ const realGroups = groups.filter((group) => Array.isArray(group.findings) && group.findings.length > 0);
+ if (realGroups.length === 0) return '';
+ if (realGroups.length === 1) {
+ const [group] = realGroups;
+ return renderTemplate(group.findings, group.filePath, config, opts);
+ }
+
+ const limits = config?.limits || DEFAULT_CONFIG.limits;
+ const cap = Math.max(1, limits.maxFindings || DEFAULT_CONFIG.limits.maxFindings);
+ const maxChars = Math.max(500, limits.maxChars || DEFAULT_CONFIG.limits.maxChars);
+ const cwd = opts.cwd || process.cwd();
+ const total = realGroups.reduce((sum, group) => sum + group.findings.length, 0);
+ const header = `${ENVELOPE_PREFIX} Required design corrections across ${realGroups.length} files (${total} issue(s)):`;
+ const lines = [];
+ let shownCount = 0;
+
+ for (const group of realGroups) {
+ const display = relativize(group.filePath, cwd);
+ lines.push(`${display} (${group.findings.length} issue(s)):`);
+ const remainingCap = Math.max(0, cap - shownCount);
+ const shown = group.findings.slice(0, remainingCap);
+ for (const finding of shown) {
+ lines.push(formatFindingLine(finding));
+ }
+ shownCount += shown.length;
+ const hidden = group.findings.length - shown.length;
+ if (hidden > 0) {
+ lines.push(`- ... ${hidden} more in ${display} (see /impeccable audit).`);
+ }
+ }
+
+ const footer = directiveFooter('the affected files', { grouped: true });
+ let text = [header, ...lines, '', footer].join('\n');
+ if (text.length > maxChars) {
+ text = clampGroupedToBudget(header, lines, footer, maxChars);
+ }
+ return text;
+}
+
+function clampGroupedToBudget(header, lines, footer, maxChars) {
+ const assemble = (linesArr, omitted) => [
+ header,
+ ...linesArr,
+ ...(omitted ? ['... and more (see /impeccable audit).'] : []),
+ '',
+ footer,
+ ].join('\n');
+
+ let working = lines.slice();
+ let omitted = false;
+ let assembled = assemble(working, omitted);
+ while (assembled.length > maxChars && working.length > 1) {
+ working.pop();
+ omitted = true;
+ assembled = assemble(working, omitted);
+ }
+ if (assembled.length > maxChars) {
+ assembled = `${assembled.slice(0, maxChars - 1)}…`;
+ }
+ return assembled;
+}
+
+function clampToBudget(header, lines, more, footer, maxChars) {
+ const assemble = (linesArr, moreText) => {
+ const blocks = [header, ...linesArr];
+ if (moreText) blocks.push(moreText);
+ blocks.push('');
+ blocks.push(footer);
+ return blocks.join('\n');
+ };
+
+ let working = lines.slice();
+ let moreText = more;
+ let assembled = assemble(working, moreText);
+ while (assembled.length > maxChars && working.length > 1) {
+ working.pop();
+ moreText = '... and more (see /impeccable audit).';
+ assembled = assemble(working, moreText);
+ }
+ if (assembled.length > maxChars) {
+ assembled = `${assembled.slice(0, maxChars - 1)}…`;
+ }
+ return assembled;
+}
+
+function formatFindingLine(f) {
+ const prefix = f.line && f.line > 0 ? `- L${f.line}` : '-';
+ const desc = (f.description || '').trim();
+ const name = (f.name || '').trim();
+ // Description from the registry already ends in punctuation; join with a
+ // single space. `name` may have a trailing period already, keep it clean.
+ const nameSegment = name ? `${name.replace(/\.+\s*$/, '')}.` : '';
+ const ignoreCommand = formatFindingIgnoreCommand(f);
+ const ignoreSegment = ignoreCommand
+ ? ` If the user explicitly confirms this value is intentional: \`${ignoreCommand}\`.`
+ : '';
+ return `${prefix} [${f.antipattern}] ${nameSegment} ${desc}${ignoreSegment}`.replace(/\s+/g, ' ').trim();
+}
+
+function formatFindingIgnoreCommand(finding) {
+ if (!finding || typeof finding !== 'object') return '';
+ const rule = normalizeIgnoreRule(finding.antipattern);
+ if (!rule) return '';
+ const normalizedValue = extractFindingIgnoreValue(finding);
+ if (!normalizedValue) return '';
+ const value = extractFindingIgnoreValueRaw(finding);
+ const valueArg = quoteCommandArg(value);
+ const reason = quoteCommandArg(`User confirmed ${value} is intentional`);
+ return `/impeccable hooks ignore-value ${rule} ${valueArg} --shared --reason ${reason}`;
+}
+
+function quoteCommandArg(value) {
+ const text = String(value || '').trim();
+ if (/^[A-Za-z0-9._:-]+$/.test(text)) return text;
+ return `"${text.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
+}
+
+function relativize(filePath, cwd) {
+ try {
+ const rel = path.relative(cwd, filePath);
+ if (!rel || rel.startsWith('..')) return filePath;
+ return rel.split(path.sep).join('/');
+ } catch {
+ return filePath;
+ }
+}
+
+// Codex `apply_patch` exposes the raw patch in `tool_input.command`, not
+// `tool_input.file_path`. Claude Code may send both; parse the patch body
+// so we can scan the file(s) the tool actually touched.
+// https://developers.openai.com/codex/hooks#posttooluse
+const APPLY_PATCH_FILE_RE = /^\*\*\* (?:Update|Add) File: (.+)$/gm;
+
+export function parseApplyPatchPaths(command, projectCwd) {
+ if (!command || typeof command !== 'string') return [];
+ const out = [];
+ for (const m of command.matchAll(APPLY_PATCH_FILE_RE)) {
+ let p = (m[1] || '').trim();
+ if (!p) continue;
+ if (!path.isAbsolute(p)) p = path.resolve(projectCwd, p);
+ out.push(p);
+ }
+ return out;
+}
+
+export function resolveTargetFiles(event, projectCwd) {
+ const ti = event?.tool_input;
+ const out = [];
+ const add = (filePath) => {
+ if (typeof filePath !== 'string' || !filePath) return;
+ if (!out.includes(filePath)) out.push(filePath);
+ };
+
+ if (event?.tool_name === 'apply_patch' && ti && typeof ti.command === 'string') {
+ for (const filePath of parseApplyPatchPaths(ti.command, projectCwd)) add(filePath);
+ }
+ if (ti && typeof ti.file_path === 'string' && ti.file_path) {
+ add(ti.file_path);
+ }
+ // Cursor Write / StrReplace use `path`, not `file_path`.
+ if (ti && typeof ti.path === 'string' && ti.path) {
+ add(ti.path);
+ }
+ if (typeof event?.file_path === 'string' && event.file_path) {
+ add(event.file_path);
+ }
+ return out;
+}
+
+export function resolveHarness(env = {}, event = null) {
+ const explicit = env?.IMPECCABLE_HOOK_HARNESS;
+ if (explicit === 'cursor') return 'cursor';
+ if (explicit === 'claude' || explicit === 'codex') return 'claude';
+ if (typeof event?.conversation_id === 'string' && event.conversation_id) return 'cursor';
+ return 'claude';
+}
+
+export function normalizeHookEvent(event, projectCwd, harness = 'claude') {
+ if (!event || typeof event !== 'object' || harness !== 'cursor') return event;
+
+ const cwd = event.cwd
+ || (Array.isArray(event.workspace_roots) && event.workspace_roots[0])
+ || envProjectDir(projectCwd)
+ || projectCwd;
+ const sessionId = event.session_id || event.conversation_id || 'unknown';
+
+ const ti = event.tool_input && typeof event.tool_input === 'object' ? event.tool_input : {};
+ const filePath = ti.file_path || ti.path || event.file_path;
+ if (filePath) {
+ return {
+ ...event,
+ cwd,
+ session_id: sessionId,
+ tool_input: { ...ti, file_path: filePath },
+ };
+ }
+
+ return { ...event, cwd, session_id: sessionId };
+}
+
+function envProjectDir(fallback) {
+ if (typeof process.env.CURSOR_PROJECT_DIR === 'string' && process.env.CURSOR_PROJECT_DIR) {
+ return process.env.CURSOR_PROJECT_DIR;
+ }
+ return fallback;
+}
+
+// UI components often keep slop in a sibling/co-located stylesheet while the
+// JSX edit is what triggered PostToolUse. Scan those styles too so an App.jsx
+// patch doesn't report "clean" while styles.css still has Inter/bounce/etc.
+const UI_CODE_EXTS = new Set(['.jsx', '.tsx', '.vue', '.svelte', '.astro']);
+const STYLE_EXTS = new Set(['.css', '.scss', '.sass', '.less']);
+const CO_SCAN_STYLE_NAMES = [
+ 'styles.css', 'styles.scss', 'styles.sass', 'styles.less',
+ 'index.css', 'index.scss', 'index.sass', 'index.less',
+ 'global.css', 'global.scss', 'global.sass', 'global.less',
+ 'globals.css', 'globals.scss', 'globals.sass', 'globals.less',
+];
+const MAX_SCAN_TARGETS = 6;
+
+const STATIC_STYLE_IMPORT_RE = /import\s+(?:[\w*{}\s,$]+\s+from\s+)?['"]([^'"]+\.(?:css|scss|sass|less))['"]/gi;
+
+function hasPathTraversal(filePath) {
+ return typeof filePath === 'string' && filePath.includes('..');
+}
+
+function isInsideProject(filePath, projectCwd) {
+ if (!filePath || !projectCwd || hasPathTraversal(filePath)) return false;
+ try {
+ const rel = path.relative(projectCwd, filePath);
+ return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));
+ } catch {
+ return false;
+ }
+}
+
+export function parseStaticStyleImports(content, fromFile, projectCwd) {
+ if (!content || typeof content !== 'string') return [];
+ const dir = path.dirname(fromFile);
+ const out = [];
+ for (const m of content.matchAll(STATIC_STYLE_IMPORT_RE)) {
+ let p = (m[1] || '').trim();
+ if (!p) continue;
+ if (p.startsWith('.')) p = path.resolve(dir, p);
+ else if (!path.isAbsolute(p)) p = path.resolve(projectCwd, p);
+ if (!isInsideProject(p, projectCwd)) continue;
+ out.push(p);
+ }
+ return out;
+}
+
+export function coLocatedStylesheets(filePath) {
+ const dir = path.dirname(filePath);
+ const base = path.basename(filePath, path.extname(filePath));
+ const candidates = new Set([
+ path.join(dir, `${base}.css`),
+ path.join(dir, `${base}.module.css`),
+ path.join(dir, `${base}.scss`),
+ path.join(dir, `${base}.module.scss`),
+ path.join(dir, `${base}.sass`),
+ path.join(dir, `${base}.module.sass`),
+ path.join(dir, `${base}.less`),
+ path.join(dir, `${base}.module.less`),
+ ]);
+ for (const name of CO_SCAN_STYLE_NAMES) {
+ candidates.add(path.join(dir, name));
+ }
+ return [...candidates].filter((p) => fs.existsSync(p));
+}
+
+export function normalizeScanTargets(primaryTargets, projectCwd) {
+ if (!Array.isArray(primaryTargets) || primaryTargets.length === 0) return [];
+ const ordered = [];
+ const seen = new Set();
+ const baseCwd = projectCwd || process.cwd();
+ const normalizeTarget = (p) => {
+ // Preserve literal `..` segments so downstream sensitive-path checks
+ // still fire. path.resolve would collapse `/foo/../etc/passwd`.
+ if (hasPathTraversal(p)) return p;
+ return path.isAbsolute(p) ? p : path.resolve(baseCwd, p);
+ };
+ const add = (p) => {
+ if (ordered.length >= MAX_SCAN_TARGETS) return;
+ const abs = normalizeTarget(p);
+ if (seen.has(abs)) return;
+ seen.add(abs);
+ ordered.push(abs);
+ return abs;
+ };
+
+ for (const p of primaryTargets) add(p);
+ return ordered;
+}
+
+export function expandScanTargets(primaryTargets, projectCwd) {
+ const ordered = normalizeScanTargets(primaryTargets, projectCwd);
+ if (ordered.length === 0) return [];
+ const seen = new Set(ordered);
+ const baseCwd = projectCwd || process.cwd();
+ const add = (p) => {
+ if (ordered.length >= MAX_SCAN_TARGETS) return;
+ const abs = hasPathTraversal(p) ? p : (path.isAbsolute(p) ? p : path.resolve(baseCwd, p));
+ if (seen.has(abs)) return;
+ seen.add(abs);
+ ordered.push(abs);
+ return abs;
+ };
+
+ const normalizedPrimaries = [];
+ for (const p of ordered) normalizedPrimaries.push(p);
+
+ for (const p of normalizedPrimaries) {
+ if (ordered.length >= MAX_SCAN_TARGETS) break;
+ if (!isInsideProject(p, baseCwd)) continue;
+ const ext = path.extname(p).toLowerCase();
+ if (STYLE_EXTS.has(ext) || !UI_CODE_EXTS.has(ext)) continue;
+
+ let content = '';
+ try { content = fs.readFileSync(p, 'utf-8'); } catch { /* unreadable primary */ }
+
+ for (const imp of parseStaticStyleImports(content, p, projectCwd)) {
+ add(imp);
+ if (ordered.length >= MAX_SCAN_TARGETS) break;
+ }
+ for (const col of coLocatedStylesheets(p)) {
+ add(col);
+ if (ordered.length >= MAX_SCAN_TARGETS) break;
+ }
+ }
+
+ return ordered;
+}
+
+export function writeAuditLog(env, entry) {
+ const target = env?.IMPECCABLE_HOOK_LOG;
+ if (!target || typeof target !== 'string') return false;
+ try {
+ const expanded = target.startsWith('~/')
+ ? path.join(process.env.HOME || process.env.USERPROFILE || '.', target.slice(2))
+ : target;
+ fs.mkdirSync(path.dirname(expanded), { recursive: true });
+ const line = JSON.stringify({ ts: new Date().toISOString(), ...entry }) + '\n';
+ fs.appendFileSync(expanded, line);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+const DETECTOR_CANDIDATES = [
+ path.join(__dirname, 'detector', 'detect-antipatterns.mjs'),
+ path.join(__dirname, '..', '..', 'cli', 'engine', 'detect-antipatterns.mjs'),
+ path.join(__dirname, '..', '..', '..', 'cli', 'engine', 'detect-antipatterns.mjs'),
+];
+
+let detectorCache = null;
+export async function loadDetector(candidates = DETECTOR_CANDIDATES) {
+ if (detectorCache) return detectorCache;
+ const found = candidates.find((c) => fs.existsSync(c));
+ if (!found) return null;
+ const mod = await import(pathToFileURL(found));
+ detectorCache = { detectText: mod.detectText, detectHtml: mod.detectHtml };
+ return detectorCache;
+}
+
+// For tests: allow injecting a detector implementation.
+export function setDetectorForTesting(impl) {
+ detectorCache = impl;
+}
+
+// ────────────────────────────────────────────────────────────────────────
+// Nudge/steer messages for the no-silent-fires policy.
+//
+// The hook is designed to be a conversational presence: every fire that
+// actually scans a file emits a developer-role message into the model's
+// next turn. Three states map to three templates:
+//
+// 1. **Fresh findings** → `renderTemplate` (existing, imperative).
+// 2. **Pending findings** → `renderPendingAck` (re-nudge for issues the
+// model was already told about in this
+// session but hasn't fixed yet).
+// 3. **Truly clean** → `renderCleanAck` (short positive nudge that
+// keeps the design discipline in context).
+//
+// All three are short (≤ ~40 tokens each) so the cumulative cost stays
+// bounded across a long active editing session. Users who explicitly want
+// silence-on-clean can set `IMPECCABLE_HOOK_QUIET=1` — runHook checks that
+// env before emitting #2 or #3.
+//
+// Why not stay silent on dedup-clean? Earlier versions did. The model
+// quickly forgets the prior reminder once tool output scrolls past it, so
+// re-nudging on the same file with a short "still pending" line keeps the
+// pressure on. The wording deliberately points back to "earlier this
+// session" so the model knows it's a re-mind, not a new finding.
+// ────────────────────────────────────────────────────────────────────────
+
+const STEER_LINE = 'Keep typography hierarchy, spacing rhythm, and color contrast intentional on the next change.';
+
+export function renderCleanAck(filePath, opts = {}) {
+ const cwd = opts.cwd || process.cwd();
+ const display = relativize(filePath, cwd);
+ return `${ENVELOPE_PREFIX} Design hook scanned ${display}. No anti-patterns. ${STEER_LINE}`;
+}
+
+export function renderPendingAck(filePath, knownFindings, opts = {}) {
+ const cwd = opts.cwd || process.cwd();
+ const display = relativize(filePath, cwd);
+ const count = knownFindings.length;
+ // `knownFindings` here are the cache strings like "side-tab:3".
+ const sample = knownFindings.slice(0, 3).join(', ');
+ const more = count > 3 ? `, +${count - 3} more` : '';
+ return `${ENVELOPE_PREFIX} Design hook scanned ${display}. Still has ${count} issue(s) flagged earlier this session (${sample}${more}). Address them before finalizing — the previous reminder still applies.`;
+}
+
+export function shouldEmitAckForFile(filePath) {
+ return ACK_EXTS.has(path.extname(String(filePath || '')).toLowerCase());
+}
+
+// The directive footer is the part of the hook output that steers model
+// behavior. Three intentional moves:
+// 1. **Imperative, not advisory.** "Fix these..." beats "Consider
+// revising..." which the model treats as a soft suggestion it can
+// override when the user asked for any kind of throwaway / demo UI.
+// 2. **Explicit exception clause.** Without it, the model will try to
+// "fix" intentional bad fixtures, anti-pattern examples in docs, or
+// test cases. Naming the exception inline beats hoping the model
+// infers it from context.
+// 3. **Acknowledgement instruction.** Hook output is injected as
+// developer-role context, not a chat turn, so the user never sees the
+// raw envelope. Asking the model to surface the fix in its reply is
+// the cheapest way to make the feedback loop visible to the user.
+function directiveFooter(display, opts = {}) {
+ const ignoreFileCommand = `/impeccable hooks ignore-file ${quoteCommandArg(display)}`;
+ const fileIgnoreGuidance = opts.grouped
+ ? 'run `/impeccable hooks ignore-file <path>` for the specific file'
+ : `run \`${ignoreFileCommand}\``;
+ return [
+ 'Fix these in your next reply before finalizing. Acknowledge what you changed so the user sees the correction.',
+ '',
+ 'Skip the fix only if the user explicitly asked for an intentionally bad UI, an anti-pattern example, a test fixture, or documentation of bad design. In that case, say so and continue.',
+ '',
+ `Do not add source comments such as \`impeccable: ignore\`; those pollute the code and do not suppress hook findings. Do not add hook ignores unless the user explicitly confirms the finding is intentional. Prefer the narrowest persisted exception: run the exact \`/impeccable hooks ignore-value ... --shared\` command shown next to a value-specific finding. For \`overused-font\`, use \`ignore-value\` for a specific font and use \`/impeccable hooks ignore-rule overused-font --all-values\` only when the user asks to ignore overused fonts generally. For file-specific findings without an ignore-value command, ${fileIgnoreGuidance}; use \`/impeccable hooks ignore-rule <id>\` only when the user asks to suppress the whole non-value-specific rule. Run /impeccable audit for the full pass.`,
+ ].join('\n');
+}
+
+/**
+ * Run the hook with explicit dependencies. Returns a result object:
+ * { exitCode, stdout, audit, reason? }
+ *
+ * Never throws. All errors are converted to `exitCode: 0` + audit entry.
+ */
+export async function runHook({ stdinJson, env = {}, cwd = process.cwd(), now = Date.now, detector } = {}) {
+ const audit = { ts: new Date(now()).toISOString(), event: 'PostToolUse' };
+ const result = (extra) => ({ exitCode: 0, stdout: '', audit: { ...audit, ...extra } });
+
+ try {
+ // Re-entrancy guard.
+ if (depthIsSet(env.IMPECCABLE_HOOK_DEPTH) || depthIsSet(env.CLAUDE_HOOK_DEPTH)) {
+ return result({ reentrant: true, durationMs: 0 });
+ }
+
+ if (truthy(env.IMPECCABLE_HOOK_DISABLED)) {
+ return result({ skipped: 'env-disabled', durationMs: 0 });
+ }
+
+ const started = Date.now();
+
+ let event;
+ try {
+ event = typeof stdinJson === 'string' ? JSON.parse(stdinJson) : stdinJson;
+ } catch {
+ return result({ skipped: 'stdin-malformed', durationMs: Date.now() - started });
+ }
+ if (!event || typeof event !== 'object') {
+ return result({ skipped: 'stdin-empty', durationMs: Date.now() - started });
+ }
+
+ const harness = resolveHarness(env, event);
+ event = normalizeHookEvent(event, cwd, harness);
+ audit.harness = harness;
+
+ const projectCwd = event.cwd || cwd;
+ const primaryFiles = normalizeScanTargets(resolveTargetFiles(event, projectCwd), projectCwd);
+ const primaryFileSet = new Set(primaryFiles);
+ const targetFiles = expandScanTargets(primaryFiles, projectCwd);
+ audit.session = event.session_id || null;
+ if (event.tool_name) audit.tool = event.tool_name;
+
+ if (targetFiles.length === 0) {
+ return result({ skipped: 'no-file-path', durationMs: Date.now() - started });
+ }
+
+ const config = readConfig(projectCwd);
+ if (config.enabled === false) {
+ return result({ skipped: 'config-disabled', durationMs: Date.now() - started });
+ }
+
+ const cache = readCache(projectCwd);
+ const sessionId = event.session_id || 'unknown';
+ const det = detector || await loadDetector();
+ if (!det || typeof det.detectText !== 'function') {
+ persistCache(projectCwd, cache);
+ return result({ skipped: 'detector-missing', durationMs: Date.now() - started });
+ }
+
+ let pendingWinner = null;
+ let cleanWinner = null;
+ const freshGroups = [];
+ let suppressionWinner = null;
+ let detectorThrewAny = false;
+ let lastSkip = 'no-scannable-file';
+ let suppressedHit = false;
+
+ for (const filePath of targetFiles) {
+ audit.file = filePath;
+
+ if (hasPathTraversal(filePath) || SENSITIVE_PATH.test(filePath)) {
+ lastSkip = 'sensitive';
+ continue;
+ }
+ if (GENERATED_PATH.test(filePath)) {
+ lastSkip = 'generated';
+ continue;
+ }
+
+ const ext = path.extname(filePath).toLowerCase();
+ audit.ext = ext;
+ if (!ALLOWED_EXTS.has(ext)) {
+ lastSkip = 'extension';
+ continue;
+ }
+
+ const relForMatch = relativize(filePath, projectCwd);
+ if (matchesAnyGlob(relForMatch, config.ignoreFiles) || matchesAnyGlob(filePath, config.ignoreFiles)) {
+ lastSkip = 'config-ignore-file';
+ continue;
+ }
+ if (!fs.existsSync(filePath)) {
+ lastSkip = 'file-missing';
+ continue;
+ }
+
+ if (primaryFileSet.has(filePath)) {
+ const editCount = bumpEditCount(cache, sessionId, filePath);
+ audit.editCount = editCount;
+
+ if (editCount > EDIT_COUNT_THRESHOLD) {
+ const wasJustCrossed = editCount === EDIT_COUNT_THRESHOLD + 1;
+ if (wasJustCrossed && !suppressionWinner) {
+ suppressionWinner = { filePath };
+ }
+ lastSkip = 'suppressed';
+ suppressedHit = true;
+ continue;
+ }
+ }
+
+ const content = fs.readFileSync(filePath, 'utf-8');
+ let findings;
+ let detectorThrew = false;
+ if ((ext === '.html' || ext === '.htm') && typeof det.detectHtml === 'function') {
+ try { findings = await det.detectHtml(filePath); } catch { findings = []; detectorThrew = true; }
+ } else {
+ try { findings = await det.detectText(content, filePath); } catch { findings = []; detectorThrew = true; }
+ }
+
+ const filtered = filterFindings(findings || [], content, ext, config);
+ const fresh = dedupeAgainstCache(filtered, cache, sessionId, filePath);
+ audit.findings = (findings || []).length;
+ audit.freshFindings = fresh.length;
+
+ if (fresh.length > 0) {
+ rememberFindings(cache, sessionId, filePath, fresh);
+ freshGroups.push({ filePath, findings: fresh });
+ continue;
+ }
+
+ if (detectorThrew) {
+ detectorThrewAny = true;
+ continue;
+ }
+
+ if (filtered.length > 0 && !pendingWinner) {
+ const known = (ensureFile(cache, sessionId, filePath).findings || []).slice();
+ pendingWinner = { filePath, known };
+ } else if (filtered.length === 0 && !cleanWinner) {
+ cleanWinner = { filePath };
+ }
+ }
+
+ persistCache(projectCwd, cache);
+
+ if (freshGroups.length > 0) {
+ const firstGroup = freshGroups[0];
+ const text = renderGroupedTemplate(freshGroups, config, { cwd: projectCwd });
+ const allFindings = freshGroups.flatMap((group) => group.findings);
+ return {
+ exitCode: 0,
+ stdout: payload(text, 'PostToolUse', harness),
+ emission: {
+ kind: 'fresh',
+ file: firstGroup.filePath,
+ findings: firstGroup.findings,
+ groups: freshGroups,
+ },
+ audit: {
+ ...audit,
+ file: firstGroup.filePath,
+ emitted: true,
+ freshFiles: freshGroups.length,
+ freshFindings: allFindings.length,
+ chars: text.length,
+ durationMs: Date.now() - started,
+ },
+ };
+ }
+
+ if (detectorThrewAny && !pendingWinner && !cleanWinner) {
+ return result({ emitted: false, error: 'detector-threw', durationMs: Date.now() - started });
+ }
+
+ if (truthy(env.IMPECCABLE_HOOK_QUIET)) {
+ return result({ emitted: false, quiet: true, durationMs: Date.now() - started });
+ }
+
+ if (pendingWinner && shouldEmitAckForFile(pendingWinner.filePath)) {
+ const text = renderPendingAck(pendingWinner.filePath, pendingWinner.known, { cwd: projectCwd });
+ return {
+ exitCode: 0,
+ stdout: payload(text, 'PostToolUse', harness),
+ emission: { kind: 'pending', file: pendingWinner.filePath, known: pendingWinner.known },
+ audit: {
+ ...audit,
+ file: pendingWinner.filePath,
+ emitted: true,
+ kind: 'pending',
+ pending: pendingWinner.known.length,
+ chars: text.length,
+ durationMs: Date.now() - started,
+ },
+ };
+ }
+
+ if (suppressionWinner) {
+ const text = suppressionNotice(relativize(suppressionWinner.filePath, projectCwd));
+ return {
+ exitCode: 0,
+ stdout: payload(text, 'PostToolUse', harness),
+ emission: { kind: 'suppression', file: suppressionWinner.filePath },
+ audit: {
+ ...audit,
+ file: suppressionWinner.filePath,
+ suppressed: true,
+ emitted: true,
+ durationMs: Date.now() - started,
+ },
+ };
+ }
+
+ if (cleanWinner && shouldEmitAckForFile(cleanWinner.filePath)) {
+ const text = renderCleanAck(cleanWinner.filePath, { cwd: projectCwd });
+ return {
+ exitCode: 0,
+ stdout: payload(text, 'PostToolUse', harness),
+ emission: { kind: 'clean', file: cleanWinner.filePath },
+ audit: {
+ ...audit,
+ file: cleanWinner.filePath,
+ emitted: true,
+ kind: 'clean',
+ chars: text.length,
+ durationMs: Date.now() - started,
+ },
+ };
+ }
+
+ if (pendingWinner || cleanWinner) {
+ return result({ emitted: false, skipped: 'non-ui-ack', durationMs: Date.now() - started });
+ }
+
+ if (suppressedHit) {
+ return result({ suppressed: true, emitted: false, durationMs: Date.now() - started });
+ }
+
+ return result({ skipped: lastSkip, durationMs: Date.now() - started });
+ } catch (err) {
+ return {
+ exitCode: 0,
+ stdout: '',
+ audit: { ...audit, error: String(err && err.message ? err.message : err) },
+ };
+ }
+}
+
+export function payload(text, eventName = 'PostToolUse', harness = 'claude') {
+ if (harness === 'cursor') {
+ return JSON.stringify({ additional_context: text });
+ }
+ return JSON.stringify({
+ hookSpecificOutput: { hookEventName: eventName, additionalContext: text },
+ });
+}
diff --git a/.opencode/skills/impeccable/scripts/hook.mjs b/.opencode/skills/impeccable/scripts/hook.mjs
new file mode 100644
index 000000000..b862f8033
--- /dev/null
+++ b/.opencode/skills/impeccable/scripts/hook.mjs
@@ -0,0 +1,61 @@
+#!/usr/bin/env node
+/**
+ * Impeccable design hook — PostToolUse entry point.
+ *
+ * Reads the Claude Code / Codex / Cursor hook event from stdin, runs the design
+ * detector against the touched file, and emits a system reminder via
+ * `hookSpecificOutput.additionalContext` when findings exist.
+ *
+ * Contract: never break a turn. Always exit 0. Clean files emit a small ack
+ * unless quiet mode is enabled.
+ *
+ * Most logic lives in `hook-lib.mjs` so it is unit-testable without a
+ * subprocess. This file is the thin stdin/stdout adapter.
+ */
+
+import { runHook, 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');
+}
+
+async function main() {
+ // Snapshot the inherited env FIRST so the re-entrancy guard checks the
+ // parent's value, not the value we are about to export for any child
+ // processes the hook might ever spawn.
+ const inheritedEnv = { ...process.env };
+ process.env.IMPECCABLE_HOOK_DEPTH = process.env.IMPECCABLE_HOOK_DEPTH || '1';
+
+ let stdinJson = '';
+ try { stdinJson = await readStdin(); } catch { /* fall through */ }
+
+ const result = await runHook({
+ stdinJson,
+ env: inheritedEnv,
+ cwd: process.cwd(),
+ });
+
+ writeAuditLog(process.env, result.audit);
+
+ if (result.stdout) process.stdout.write(result.stdout);
+ process.exit(result.exitCode || 0);
+}
+
+main().catch((err) => {
+ // Last-ditch: never break the agent's turn even if something we did not
+ // anticipate goes wrong. Audit-log the failure if logging is enabled.
+ try {
+ writeAuditLog(process.env, {
+ ts: new Date().toISOString(),
+ event: 'PostToolUse',
+ error: String(err && err.message ? err.message : err),
+ });
+ } catch { /* swallow */ }
+ if (process.env.IMPECCABLE_HOOK_DEBUG) {
+ process.stderr.write(`[impeccable-hook] ${err}\n`);
+ }
+ process.exit(0);
+});
diff --git a/.opencode/skills/impeccable/scripts/live-inject.mjs b/.opencode/skills/impeccable/scripts/live-inject.mjs
index 4e5c5dc0a..69ce530c1 100644
--- a/.opencode/skills/impeccable/scripts/live-inject.mjs
+++ b/.opencode/skills/impeccable/scripts/live-inject.mjs
@@ -32,6 +32,8 @@ const IGNORE_MARKER_CLOSE = '# impeccable-live-ignore-end';
export const LIVE_IGNORE_PATTERNS = Object.freeze([
'.impeccable/hook.cache.json',
+ '.impeccable/hook.pending.json',
+ '.impeccable/hook.local.json',
'.impeccable/live/server.json',
'.impeccable/live/sessions/',
'.impeccable/live/previews/',
diff --git a/.pi/skills/impeccable/SKILL.md b/.pi/skills/impeccable/SKILL.md
index 9c26d3b36..3dbec85cb 100644
--- a/.pi/skills/impeccable/SKILL.md
+++ b/.pi/skills/impeccable/SKILL.md
@@ -124,7 +124,7 @@ If someone could look at this interface and say "AI made that" without doubt, it
| `optimize [target]` | Fix | Diagnose and fix UI performance | [reference/optimize.md](reference/optimize.md) |
| `live` | Iterate | Visual variant mode: pick elements in the browser, generate alternatives | [reference/live.md](reference/live.md) |
-Plus two management commands: `pin <command>` and `unpin <command>`, detailed below.
+Plus three management commands: `pin <command>`, `unpin <command>`, and `hooks <on|off|status|...>`, detailed below.
### Routing rules
@@ -141,7 +141,7 @@ Plus two management commands: `pin <command>` and `unpin <command>`, detailed be
**If `scan.targets` is non-empty, run `node .pi/skills/impeccable/scripts/detect.mjs --json <scan.targets joined by spaces>` once** (the bundled detector over local files: no network, no npx). `scan.via` tells you what they are: `git-changes` (the markup/style files in your dirty tree, the most relevant set), `source-dir` (e.g. `src`, `app`), `html`, or `root`. Fold the hits into your picks: many quality / contrast hits → `audit` or `polish`; a specific slop family → the matching command (gradient text or eyebrows → `quieter` / `typeset`, flat or gray palette → `colorize`, and so on). It's a real, current signal that beats guessing. If detect errors or the tree is large and slow, skip it and recommend the user run `audit` themselves; never block the suggestion on it.
Keep it to 2-3 pointed picks with the exact command to type. The menu stays the fallback; the recommendation is the lede.
-2. **First word matches a command**: load its reference file and follow its instructions. Everything after the command name is the target.
+2. **First word matches a command** (table above OR `pin` / `unpin` / `hooks`): load its reference file and follow its instructions. Everything after the command name is the target.
3. **First word doesn't match, but the intent clearly maps to one command** (e.g. "fix the spacing" → `layout`, "rewrite this error message" → `clarify`, "the colors feel flat" → `colorize`): load that command's reference and proceed as if invoked. If two commands could fit, ask once which.
4. **No clear command match**: general design invocation. Apply the setup steps, the General rules, and the loaded register reference, using the full argument as context.
@@ -159,4 +159,8 @@ If the first word is `craft`, setup still runs first, but [reference/craft.md](r
node .pi/skills/impeccable/scripts/pin.mjs <pin|unpin> <command>
```
-Valid `<command>` is any command from the table above. Report the script's result concisely. Confirm the new shortcut on success, relay stderr verbatim on error.
\ No newline at end of file
+Valid `<command>` is any command from the table above. Report the script's result concisely. Confirm the new shortcut on success, relay stderr verbatim on error.
+
+## Hooks
+
+`/impeccable hooks <on|off|status|ignore-rule|ignore-file|ignore-value|reset>` manages the design detector hook for this project. The hook auto-runs the detector after direct UI file edits and surfaces findings as system reminders. Full flow is in [reference/hooks.md](reference/hooks.md); load it when the user invokes `/impeccable hooks` with any argument.
\ No newline at end of file
diff --git a/.pi/skills/impeccable/reference/hooks.md b/.pi/skills/impeccable/reference/hooks.md
new file mode 100644
index 000000000..c595d3db2
--- /dev/null
+++ b/.pi/skills/impeccable/reference/hooks.md
@@ -0,0 +1,82 @@
+# /impeccable hooks
+
+Manage the **design detector hook** for the current project.
+
+The hook runs the impeccable design detector on direct file edits to design-relevant files (`.tsx`, `.jsx`, `.html`, `.vue`, `.svelte`, `.astro`, `.css`, `.scss`, `.sass`, `.less`, `.ts`, `.js`). Claude Code and Codex use `PostToolUse` and push a short system reminder into the agent's context after the edit; findings get a correction prompt, pending issues get a re-nudge, and clean UI-ish files get a short ack unless `IMPECCABLE_HOOK_QUIET=1` is set. Plain `.ts` and `.js` files are still scanned, but stay quiet unless the detector finds something. Cursor uses `preToolUse` to block bad proposed writes before they land and stays silent when it allows a clean write.
+
+This command toggles the hook **per project** by editing `.impeccable/hook.json`. Local-only ignore policy lives in `.impeccable/hook.local.json`, which is gitignored. To disable globally, set `IMPECCABLE_HOOK_DISABLED=1` in your shell environment.
+
+Supported harnesses: Claude Code (`.claude/settings.json` in the project), Codex (`.codex/hooks.json` in the project), and Cursor (`.cursor/hooks.json` in the project).
+
+On **Cursor**, `preToolUse` checks proposed Write/Edit/Shell write content and denies only when the real detector finds an issue. The denial message is visible to the agent as the tool error, so the agent can reconsider before the bad write lands.
+
+## Routing
+
+The first argument is the action. Defaults to `status`.
+
+| Action | What it does |
+|---|---|
+| `status` | Print current state, shared/local config paths, ignored rules / files / values, env override. |
+| `on` | Set `enabled: true` in `.impeccable/hook.json`. |
+| `off` | Set `enabled: false` in `.impeccable/hook.json`. |
+| `ignore-rule <id>` | Append `<id>` to `ignoreRules`; for `overused-font`, requires `--all-values`. |
+| `ignore-file <glob>` | Append `<glob>` to `ignoreFiles`. |
+| `ignore-value <id> <value> [--shared] [--reason "..."]` | Append a rule/value suppression to shared `.impeccable/hook.json`. |
+| `ignore-value <id> <value> --local [--reason "..."]` | Append a private rule/value suppression to `.impeccable/hook.local.json`. |
+| `reset` | Delete the project config, dedup cache, and Cursor pending queue. |
+
+## Flow
+
+1. Resolve the action from the user's argument. If no action was given, default to `status`.
+2. Invoke the admin script and pass the user's output through verbatim:
+
+ ```bash
+ node .pi/skills/impeccable/scripts/hook-admin.mjs <action> [args...]
+ ```
+
+3. If `<action>` is `off`, follow up with a one-line note: "Done. New edits will not trigger the design hook in this project until you run `/impeccable hooks on`."
+4. If `<action>` is `on`, follow up with: "Done. The design hook will fire after the next Edit/Write/MultiEdit on a UI file."
+5. If `<action>` is `ignore-value`, `ignore-file`, or `ignore-rule`, just print the script output. The default scope is shared `.impeccable/hook.json`; add `--local` only when the user explicitly asks for a private exception.
+6. If `<action>` is `status`, just print the script output. Do not add commentary unless the user asked a follow-up question.
+
+## Intentional findings
+
+The hook itself never writes ignore config. Persist an exception only after the user explicitly confirms the flagged issue is intentional, and always go through `hook-admin.mjs`.
+
+Prefer the narrowest exception:
+
+- If the finding line shows an exact `ignore-value` command, run that command. This writes shared `.impeccable/hook.json` by default.
+- For `overused-font`, use `ignore-value` when the user confirms a specific font. Do not use `ignore-rule overused-font` for a specific font.
+- If the finding has no value-specific command, such as `side-tab`, prefer `ignore-file <path>` for the current file.
+- Use `ignore-rule <id>` only when the user asks to suppress that whole rule across the project. For broad overused-font suppression, use `ignore-rule overused-font --all-values` only when the user asks to ignore overused fonts generally.
+- Do not add source comments such as `impeccable: ignore`; inline comments pollute code and are not a supported suppression mechanism.
+
+Example value-specific exception:
+
+```bash
+node .pi/skills/impeccable/scripts/hook-admin.mjs ignore-value overused-font Inter --shared --reason "User confirmed Inter is intentional"
+```
+
+Example whole-rule font exception:
+
+```bash
+node .pi/skills/impeccable/scripts/hook-admin.mjs ignore-rule overused-font --all-values --reason "User asked to ignore overused fonts generally"
+```
+
+Example file-scoped exception:
+
+```bash
+node .pi/skills/impeccable/scripts/hook-admin.mjs ignore-file "src/legacy/Card.tsx"
+```
+
+## Constraints
+
+- Never modify `.impeccable/hook.json` or `.impeccable/hook.local.json` by hand from this command. Always go through `hook-admin.mjs` so writes stay validated and the file shape stays consistent.
+- Do not edit the hook scripts themselves (`hook.mjs`, `hook-lib.mjs`, `hook-before-edit.mjs`) from this flow. Those are skill plumbing.
+- Cursor can block a proposed write when the detector finds a real issue. Claude Code and Codex do not block the edit; they emit a post-edit reminder instead. Disabling stops both blocking and reminders.
+- The hook is bundled with the Impeccable skill and installed through project-local manifests: `.claude/settings.json`, `.codex/hooks.json`, and `.cursor/hooks.json`. On Codex, the user must approve the hook via `/hooks` the first time. On Cursor, confirm hooks are enabled under Settings -> Hooks.
+
+## Failure modes
+
+- If `.impeccable/hook.json` or `.impeccable/hook.local.json` is unreadable or malformed, the hook ignores that file and uses the remaining valid config/defaults. `hook-admin.mjs status` will show malformed files as ignored.
+- If the user asks to "disable the hook" globally, suggest both options: `IMPECCABLE_HOOK_DISABLED=1` env var (one-shot, follows the shell), and `/impeccable hooks off` (persistent for this project, committable).
diff --git a/.pi/skills/impeccable/scripts/detector/engines/regex/detect-text.mjs b/.pi/skills/impeccable/scripts/detector/engines/regex/detect-text.mjs
index fd0d9c73f..4c0777c93 100644
--- a/.pi/skills/impeccable/scripts/detector/engines/regex/detect-text.mjs
+++ b/.pi/skills/impeccable/scripts/detector/engines/regex/detect-text.mjs
@@ -446,7 +446,7 @@ function detectText(content, filePath, options = {}) {
// Run regex matchers on the full file content (catches Tailwind classes, inline styles)
// Enable block context for CSS files where related properties span multiple lines
- const cssLike = new Set(['.css', '.scss', '.less']);
+ const cssLike = new Set(['.css', '.scss', '.sass', '.less']);
findings.push(...runRegexMatchers(lines, filePath, 0, cssLike.has(ext) || null, {
profile,
phase: 'source',
diff --git a/.pi/skills/impeccable/scripts/detector/node/file-system.mjs b/.pi/skills/impeccable/scripts/detector/node/file-system.mjs
index a80250a0e..aaa8c6df7 100644
--- a/.pi/skills/impeccable/scripts/detector/node/file-system.mjs
+++ b/.pi/skills/impeccable/scripts/detector/node/file-system.mjs
@@ -11,7 +11,7 @@ const SKIP_DIRS = new Set([
]);
const SCANNABLE_EXTENSIONS = new Set([
- '.html', '.htm', '.css', '.scss', '.less',
+ '.html', '.htm', '.css', '.scss', '.sass', '.less',
'.jsx', '.tsx', '.js', '.ts',
'.vue', '.svelte', '.astro',
]);
diff --git a/.pi/skills/impeccable/scripts/hook-admin.mjs b/.pi/skills/impeccable/scripts/hook-admin.mjs
new file mode 100644
index 000000000..86fcfa909
--- /dev/null
+++ b/.pi/skills/impeccable/scripts/hook-admin.mjs
@@ -0,0 +1,300 @@
+#!/usr/bin/env node
+/**
+ * `/impeccable hooks <on|off|status|reset>` — manage the design hook
+ * via .impeccable/hook.json and .impeccable/hook.local.json in the current
+ * project.
+ *
+ * Usage:
+ * node hook-admin.mjs status # print current state
+ * node hook-admin.mjs on # set enabled: true
+ * node hook-admin.mjs off # set enabled: false
+ * node hook-admin.mjs ignore-rule <rule-id> # append to ignoreRules
+ * node hook-admin.mjs ignore-rule overused-font --all-values
+ * node hook-admin.mjs ignore-file <glob> # append to ignoreFiles
+ * node hook-admin.mjs ignore-value <rule> <value> # append to shared ignoreValues
+ * node hook-admin.mjs ignore-value <rule> <value> --local
+ * node hook-admin.mjs reset # remove all config + cache
+ *
+ * Designed to be invoked by the LLM from the reference/hooks.md flow.
+ * Output is human-readable; the harness will pass it back to the user.
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+
+import {
+ getConfigPath,
+ getLocalConfigPath,
+ getCachePath,
+ getPendingPath,
+ readConfig,
+ DEFAULT_CONFIG,
+ ensureHookGitExcludes,
+ normalizeIgnoreValue,
+ normalizeIgnoreValueEntries,
+} from './hook-lib.mjs';
+
+const ACTIONS = new Set(['status', 'on', 'off', 'ignore-rule', 'ignore-file', 'ignore-value', 'reset']);
+
+function readRawConfigFile(filePath) {
+ if (!fs.existsSync(filePath)) return { exists: false, malformed: false, raw: null };
+ try {
+ return { exists: true, malformed: false, raw: JSON.parse(fs.readFileSync(filePath, 'utf-8')) };
+ } catch {
+ return { exists: true, malformed: true, raw: null };
+ }
+}
+
+function readRawConfig(cwd, opts = {}) {
+ const filePath = opts.local ? getLocalConfigPath(cwd) : getConfigPath(cwd);
+ return readRawConfigFile(filePath).raw;
+}
+
+function writeConfig(cwd, config, opts = {}) {
+ const filePath = opts.local ? getLocalConfigPath(cwd) : getConfigPath(cwd);
+ if (opts.local) ensureHookGitExcludes(cwd);
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
+ fs.writeFileSync(filePath, JSON.stringify(config, null, 2) + '\n');
+ return filePath;
+}
+
+function mergeConfig(existing) {
+ // Persist the full shape so /impeccable hooks edits leave a complete file
+ // for the user to see, not an unhelpful `{"enabled":false}`.
+ const base = existing && typeof existing === 'object' ? existing : {};
+ return {
+ enabled: base.enabled === false ? false : true,
+ ignoreRules: Array.isArray(base.ignoreRules) ? Array.from(new Set(base.ignoreRules.map(String))) : [],
+ ignoreFiles: Array.isArray(base.ignoreFiles) ? Array.from(new Set(base.ignoreFiles.map(String))) : [],
+ ignoreValues: normalizeIgnoreValueEntries(base.ignoreValues || []),
+ limits: {
+ maxFindings: Number.isFinite(base?.limits?.maxFindings) ? base.limits.maxFindings : DEFAULT_CONFIG.limits.maxFindings,
+ maxChars: Number.isFinite(base?.limits?.maxChars) ? base.limits.maxChars : DEFAULT_CONFIG.limits.maxChars,
+ },
+ };
+}
+
+function mergeLocalConfig(existing) {
+ const base = existing && typeof existing === 'object' ? existing : {};
+ const out = {};
+ if (Object.prototype.hasOwnProperty.call(base, 'enabled')) {
+ out.enabled = base.enabled === false ? false : true;
+ }
+ if (Array.isArray(base.ignoreRules)) {
+ out.ignoreRules = Array.from(new Set(base.ignoreRules.map(String)));
+ }
+ if (Array.isArray(base.ignoreFiles)) {
+ out.ignoreFiles = Array.from(new Set(base.ignoreFiles.map(String)));
+ }
+ out.ignoreValues = normalizeIgnoreValueEntries(base.ignoreValues || []);
+ if (base.limits && typeof base.limits === 'object') {
+ const limits = {};
+ if (Number.isFinite(base.limits.maxFindings)) limits.maxFindings = base.limits.maxFindings;
+ if (Number.isFinite(base.limits.maxChars)) limits.maxChars = base.limits.maxChars;
+ if (Object.keys(limits).length) out.limits = limits;
+ }
+ return out;
+}
+
+function statusReport(cwd) {
+ const shared = readRawConfigFile(getConfigPath(cwd));
+ const local = readRawConfigFile(getLocalConfigPath(cwd));
+ const cfg = readConfig(cwd);
+ const envKill = process.env.IMPECCABLE_HOOK_DISABLED;
+ const envState = envKill ? `IMPECCABLE_HOOK_DISABLED=${envKill}` : 'unset';
+ const cfgPath = path.relative(cwd, getConfigPath(cwd)) || '.impeccable/hook.json';
+ const localPath = path.relative(cwd, getLocalConfigPath(cwd)) || '.impeccable/hook.local.json';
+ const cachePath = path.relative(cwd, getCachePath(cwd)) || '.impeccable/hook.cache.json';
+ const fileState = (info, relPath, absent) => {
+ if (info.malformed) return `${relPath} (malformed; ignored)`;
+ if (info.exists) return relPath;
+ return `${relPath} (${absent})`;
+ };
+ const ignoreValues = cfg.ignoreValues.map((entry) => `${entry.rule}=${entry.value}`);
+
+ const lines = [
+ `Impeccable design hook`,
+ ` state: ${cfg.enabled ? 'enabled' : 'disabled'}`,
+ ` shared file: ${fileState(shared, cfgPath, 'using defaults; file not present')}`,
+ ` local file: ${fileState(local, localPath, 'not present')}`,
+ ` ignoreRules: ${cfg.ignoreRules.length ? cfg.ignoreRules.join(', ') : '(none)'}`,
+ ` ignoreFiles: ${cfg.ignoreFiles.length ? cfg.ignoreFiles.join(', ') : '(none)'}`,
+ ` ignoreValues: ${ignoreValues.length ? ignoreValues.join(', ') : '(none)'}`,
+ ` maxFindings: ${cfg.limits.maxFindings}`,
+ ` maxChars: ${cfg.limits.maxChars}`,
+ ` env override: ${envState}`,
+ ` cache file: ${fs.existsSync(getCachePath(cwd)) ? cachePath : `${cachePath} (not present)`}`,
+ ];
+ return lines.join('\n');
+}
+
+function setEnabled(cwd, value) {
+ const config = mergeConfig(readRawConfig(cwd));
+ config.enabled = value;
+ const target = writeConfig(cwd, config);
+ return `Design hook ${value ? 'enabled' : 'disabled'} for this project (wrote ${path.relative(cwd, target) || target}).`;
+}
+
+function normalizeRuleId(rule) {
+ return String(rule || '').trim().toLowerCase();
+}
+
+function parseIgnoreRuleArgs(args) {
+ const positionals = [];
+ let allValues = false;
+
+ for (let i = 0; i < args.length; i++) {
+ const arg = String(args[i] || '');
+ if (arg === '--all-values') {
+ allValues = true;
+ } else if (arg === '--reason') {
+ while (i + 1 < args.length && !String(args[i + 1]).startsWith('--')) i++;
+ } else if (arg.startsWith('--reason=')) {
+ // Accepted for command symmetry; ignoreRules stores rule ids only.
+ } else if (arg.startsWith('--')) {
+ throw new Error(`Unknown ignore-rule flag: ${arg}`);
+ } else {
+ positionals.push(arg);
+ }
+ }
+
+ return {
+ rule: normalizeRuleId(positionals[0]),
+ allValues,
+ };
+}
+
+function addIgnoreRule(cwd, args) {
+ const parsed = parseIgnoreRuleArgs(args);
+ const rule = parsed.rule;
+ if (!rule) throw new Error('Pass a rule id, e.g. /impeccable hooks ignore-rule side-tab');
+ if (rule === 'overused-font' && !parsed.allValues) {
+ throw new Error('overused-font is value-specific by default. Use /impeccable hooks ignore-value overused-font <font> for a confirmed font, or /impeccable hooks ignore-rule overused-font --all-values only when the user asked to ignore overused fonts generally.');
+ }
+ const config = mergeConfig(readRawConfig(cwd));
+ if (!config.ignoreRules.includes(rule)) config.ignoreRules.push(rule);
+ writeConfig(cwd, config);
+ return `Added "${rule}" to ignoreRules. Current: ${config.ignoreRules.join(', ')}`;
+}
+
+function addIgnoreFile(cwd, glob) {
+ if (!glob) throw new Error('Pass a glob, e.g. /impeccable hooks ignore-file "src/legacy/**"');
+ const config = mergeConfig(readRawConfig(cwd));
+ if (!config.ignoreFiles.includes(glob)) config.ignoreFiles.push(glob);
+ writeConfig(cwd, config);
+ return `Added "${glob}" to ignoreFiles. Current: ${config.ignoreFiles.join(', ')}`;
+}
+
+function parseIgnoreValueArgs(args) {
+ const positionals = [];
+ let shared = false;
+ let local = false;
+ let reason = '';
+
+ for (let i = 0; i < args.length; i++) {
+ const arg = args[i];
+ if (arg === '--shared') {
+ shared = true;
+ } else if (arg === '--local') {
+ local = true;
+ } else if (arg === '--reason') {
+ const chunks = [];
+ while (i + 1 < args.length && !String(args[i + 1]).startsWith('--')) {
+ chunks.push(args[++i]);
+ }
+ reason = chunks.join(' ').trim();
+ } else if (String(arg).startsWith('--reason=')) {
+ reason = String(arg).slice('--reason='.length).trim();
+ } else {
+ positionals.push(arg);
+ }
+ }
+
+ const [rule, ...valueParts] = positionals;
+ return {
+ rule: String(rule || '').trim().toLowerCase(),
+ value: normalizeIgnoreValue(valueParts.join(' ')),
+ shared,
+ local,
+ reason,
+ };
+}
+
+function addIgnoreValue(cwd, args) {
+ const parsed = parseIgnoreValueArgs(args);
+ if (!parsed.rule || !parsed.value) {
+ throw new Error('Pass a rule id and value, e.g. /impeccable hooks ignore-value overused-font Inter');
+ }
+
+ if (parsed.shared && parsed.local) {
+ throw new Error('Pass only one scope flag: --shared or --local');
+ }
+
+ const local = parsed.local;
+ const config = local
+ ? mergeLocalConfig(readRawConfig(cwd, { local: true }))
+ : mergeConfig(readRawConfig(cwd, { local: false }));
+ const key = `${parsed.rule}\0${parsed.value}`;
+ const existing = config.ignoreValues.find((entry) => `${entry.rule}\0${entry.value}` === key);
+
+ if (existing) {
+ if (parsed.reason) existing.reason = parsed.reason;
+ } else {
+ const entry = {
+ rule: parsed.rule,
+ value: parsed.value,
+ createdAt: new Date().toISOString(),
+ };
+ if (parsed.reason) entry.reason = parsed.reason;
+ config.ignoreValues.push(entry);
+ }
+
+ const target = writeConfig(cwd, config, { local });
+ const scope = local ? 'local ignoreValues' : 'shared ignoreValues';
+ return `Added ${parsed.rule}=${parsed.value} to ${scope} (${path.relative(cwd, target) || target}).`;
+}
+
+function reset(cwd) {
+ const removed = [];
+ for (const filePath of [getConfigPath(cwd), getLocalConfigPath(cwd), getCachePath(cwd), getPendingPath(cwd)]) {
+ try {
+ if (fs.existsSync(filePath)) {
+ fs.unlinkSync(filePath);
+ removed.push(path.relative(cwd, filePath) || filePath);
+ }
+ } catch { /* ignore */ }
+ }
+ return removed.length
+ ? `Reset design hook config and cache (removed: ${removed.join(', ')}).`
+ : 'No hook config or cache to remove. Already at defaults.';
+}
+
+function main() {
+ const [, , actionArg, ...rest] = process.argv;
+ const action = (actionArg || 'status').toLowerCase();
+ const cwd = process.cwd();
+
+ if (!ACTIONS.has(action)) {
+ process.stderr.write(`Unknown action: ${action}\nValid: ${Array.from(ACTIONS).join(', ')}\n`);
+ process.exit(1);
+ }
+
+ try {
+ let out = '';
+ switch (action) {
+ case 'status': out = statusReport(cwd); break;
+ case 'on': out = setEnabled(cwd, true); break;
+ case 'off': out = setEnabled(cwd, false); break;
+ case 'ignore-rule': out = addIgnoreRule(cwd, rest); break;
+ case 'ignore-file': out = addIgnoreFile(cwd, rest[0]); break;
+ case 'ignore-value': out = addIgnoreValue(cwd, rest); break;
+ case 'reset': out = reset(cwd); break;
+ }
+ process.stdout.write(out + '\n');
+ } catch (err) {
+ process.stderr.write(`Error: ${err.message || err}\n`);
+ process.exit(1);
+ }
+}
+
+main();
diff --git a/.pi/skills/impeccable/scripts/hook-before-edit.mjs b/.pi/skills/impeccable/scripts/hook-before-edit.mjs
new file mode 100644
index 000000000..54b2709d2
--- /dev/null
+++ b/.pi/skills/impeccable/scripts/hook-before-edit.mjs
@@ -0,0 +1,408 @@
+#!/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 shellContent = shellHereDocContent(shellCommand(input));
+ if (shellContent) return shellContent;
+ const copiedContent = shellCopiedFileContent(shellCommand(input), 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 || '';
+}
+
+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 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' });
+});
diff --git a/.pi/skills/impeccable/scripts/hook-lib.mjs b/.pi/skills/impeccable/scripts/hook-lib.mjs
new file mode 100644
index 000000000..02199f530
--- /dev/null
+++ b/.pi/skills/impeccable/scripts/hook-lib.mjs
@@ -0,0 +1,1232 @@
+/**
+ * Shared library for the Impeccable design hook.
+ *
+ * Pure-ish helpers split out from `hook.mjs` so unit tests can exercise
+ * config parsing, finding filtering, dedup, render, and cache logic without
+ * spawning a subprocess. `hook.mjs` itself is the thin stdin/stdout shim.
+ *
+ * Public surface (everything exported is part of the contract):
+ * ENVELOPE_PREFIX, ALLOWED_EXTS, ACK_EXTS, SENSITIVE_PATH, GENERATED_PATH, TRUTHY
+ * truthy(value)
+ * readConfig(cwd) / DEFAULT_CONFIG / getConfigPath(cwd) / getLocalConfigPath(cwd)
+ * normalizeIgnoreValue(value)
+ * readCache(cwd) / persistCache(cwd, cache)
+ * bumpEditCount(cache, sessionId, filePath) -> number
+ * suppressionNotice(filePath)
+ * filterFindings(findings, content, ext, config)
+ * dedupeAgainstCache(findings, cache, sessionId, filePath)
+ * renderTemplate(findings, filePath, config, opts)
+ * renderCleanAck(filePath, opts) / renderPendingAck(filePath, known, opts)
+ * shouldEmitAckForFile(filePath)
+ * writeAuditLog(env, entry)
+ * loadDetector() -> Promise<{ detectText, detectHtml }>
+ * matchesAnyGlob(filePath, globs)
+ * normalizeScanTargets(primaryTargets, projectCwd)
+ * runHook(deps) -> { exitCode, stdout, audit, reason? }
+ *
+ * Design notes:
+ * - All errors are swallowed at the runHook seam. The detector throwing must
+ * never break a turn. See PRD §5 "Failure modes".
+ * - Cache shape is JSON-friendly; we gc the oldest sessions when there are
+ * more than 8 to keep file size predictable across long-lived projects.
+ * - The detector loader looks for `detector/detect-antipatterns.mjs` next to
+ * this file first (built skill layout) and falls back to the repo root's
+ * `cli/engine/detect-antipatterns.mjs` (running from source).
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+import { pathToFileURL, fileURLToPath } from 'node:url';
+
+const __filename = fileURLToPath(import.meta.url);
+const __dirname = path.dirname(__filename);
+
+export const ENVELOPE_PREFIX = '[impeccable@1]';
+
+export const ALLOWED_EXTS = new Set([
+ '.tsx', '.jsx', '.html', '.htm', '.vue', '.svelte', '.astro',
+ '.css', '.scss', '.sass', '.less', '.ts', '.js',
+]);
+
+export const ACK_EXTS = new Set([
+ '.tsx', '.jsx', '.html', '.htm', '.vue', '.svelte', '.astro',
+ '.css', '.scss', '.sass', '.less',
+]);
+
+// Hard-skip regex for sensitive files. Cannot be turned off via config.
+// Match tokenized secret/credential filenames, not UI names such as
+// CredentialForm.tsx, SecretPage.jsx, or secretary-dashboard.vue.
+export const SENSITIVE_PATH = new RegExp([
+ String.raw`(?:^|[/\\])\.env(?:\.|$)`,
+ String.raw`(?:^|[/\\])\.git(?:[/\\]|$)`,
+ String.raw`(?:^|[/\\])id_rsa(?:$|[._-])[^/\\]*$`,
+ String.raw`(?:^|[/\\])[^/\\]*\.pem$`,
+ String.raw`(?:^|[/\\])(?:[^/\\]*[._-])?(?:secret|secrets|credential|credentials)(?=[._-])[^/\\]*\.(?:json|ya?ml|toml|ini|conf|config|env|txt|key|cert|crt|pem|js|ts)$`,
+].join('|'), 'i');
+
+// Hard-skip regex for generated, lock, minified, and build-output paths.
+export const GENERATED_PATH = /(?:\.generated\.[a-z]+$|\.d\.ts$|\.min\.[a-z]+$|[/\\]node_modules[/\\]|[/\\](?:dist|build|out|\.next|\.cache|coverage)[/\\]|[/\\]?[^/\\]+\.lock(?:\.json)?$)/i;
+
+export const TRUTHY = /^(1|true|yes|on)$/i;
+
+export const DEFAULT_CONFIG = Object.freeze({
+ enabled: true,
+ ignoreRules: [],
+ ignoreFiles: [],
+ ignoreValues: [],
+ limits: { maxFindings: 5, maxChars: 8000 },
+});
+
+export const HOOK_LOCAL_IGNORE_PATTERNS = Object.freeze([
+ '.impeccable/hook.cache.json',
+ '.impeccable/hook.pending.json',
+ '.impeccable/hook.local.json',
+]);
+
+const HOOK_IGNORE_MARKER_OPEN = '# impeccable-hook-ignore-start';
+const HOOK_IGNORE_MARKER_CLOSE = '# impeccable-hook-ignore-end';
+const CACHE_MAX_SESSIONS = 8;
+export const EDIT_COUNT_THRESHOLD = 6;
+
+export function truthy(value) {
+ return typeof value === 'string' && TRUTHY.test(value);
+}
+
+function depthIsSet(value) {
+ if (value === undefined || value === null) return false;
+ const text = String(value).trim();
+ if (!text) return false;
+ if (TRUTHY.test(text)) return true;
+ return /^\d+$/.test(text) && Number(text) > 0;
+}
+
+function safeReadJson(filePath) {
+ try {
+ return JSON.parse(fs.readFileSync(filePath, 'utf-8'));
+ } catch {
+ return null;
+ }
+}
+
+export function getConfigPath(cwd) {
+ return path.join(cwd, '.impeccable', 'hook.json');
+}
+
+export function getLocalConfigPath(cwd) {
+ return path.join(cwd, '.impeccable', 'hook.local.json');
+}
+
+export function getCachePath(cwd) {
+ return path.join(cwd, '.impeccable', 'hook.cache.json');
+}
+
+export function getPendingPath(cwd) {
+ return path.join(cwd, '.impeccable', 'hook.pending.json');
+}
+
+export function resolveProjectCwd(event, fallback = process.cwd()) {
+ return event?.cwd
+ || (Array.isArray(event?.workspace_roots) && event.workspace_roots[0])
+ || envProjectDir(fallback)
+ || fallback;
+}
+
+export function readConfig(cwd) {
+ const config = cloneDefaultConfig();
+ applyConfigSource(config, safeReadJson(getConfigPath(cwd)));
+ applyConfigSource(config, safeReadJson(getLocalConfigPath(cwd)));
+ return config;
+}
+
+function numberOr(value, fallback) {
+ return Number.isFinite(value) && value > 0 ? value : fallback;
+}
+
+function cloneDefaultConfig() {
+ return {
+ ...DEFAULT_CONFIG,
+ ignoreRules: [],
+ ignoreFiles: [],
+ ignoreValues: [],
+ limits: { ...DEFAULT_CONFIG.limits },
+ };
+}
+
+function applyConfigSource(config, raw) {
+ if (!raw || typeof raw !== 'object') return config;
+ if (Object.prototype.hasOwnProperty.call(raw, 'enabled')) {
+ config.enabled = raw.enabled === false ? false : true;
+ }
+ if (Array.isArray(raw.ignoreRules)) {
+ config.ignoreRules = uniqueStrings([...config.ignoreRules, ...raw.ignoreRules]);
+ }
+ if (Array.isArray(raw.ignoreFiles)) {
+ config.ignoreFiles = uniqueStrings([...config.ignoreFiles, ...raw.ignoreFiles]);
+ }
+ if (Array.isArray(raw.ignoreValues)) {
+ config.ignoreValues = mergeIgnoreValues(config.ignoreValues, raw.ignoreValues);
+ }
+ if (raw.limits && typeof raw.limits === 'object') {
+ config.limits = {
+ maxFindings: numberOr(raw.limits.maxFindings, config.limits.maxFindings),
+ maxChars: numberOr(raw.limits.maxChars, config.limits.maxChars),
+ };
+ }
+ return config;
+}
+
+function uniqueStrings(values) {
+ return Array.from(new Set(values.map(String)));
+}
+
+export function normalizeIgnoreValue(value) {
+ return String(value || '')
+ .trim()
+ .replace(/^["']|["']$/g, '')
+ .replace(/\+/g, ' ')
+ .replace(/\s+/g, ' ')
+ .toLowerCase();
+}
+
+function normalizeIgnoreRule(rule) {
+ return String(rule || '').trim().toLowerCase();
+}
+
+export function normalizeIgnoreValueEntries(entries) {
+ if (!Array.isArray(entries)) return [];
+ const out = [];
+ for (const entry of entries) {
+ if (!entry || typeof entry !== 'object') continue;
+ const rule = normalizeIgnoreRule(entry.rule);
+ const value = normalizeIgnoreValue(entry.value);
+ if (!rule || !value) continue;
+ const normalized = { rule, value };
+ if (typeof entry.reason === 'string' && entry.reason.trim()) {
+ normalized.reason = entry.reason.trim();
+ }
+ if (typeof entry.createdAt === 'string' && entry.createdAt.trim()) {
+ normalized.createdAt = entry.createdAt.trim();
+ }
+ out.push(normalized);
+ }
+ return out;
+}
+
+function mergeIgnoreValues(existing, incoming) {
+ const map = new Map();
+ for (const entry of normalizeIgnoreValueEntries(existing)) {
+ map.set(`${entry.rule}\0${entry.value}`, entry);
+ }
+ for (const entry of normalizeIgnoreValueEntries(incoming)) {
+ map.set(`${entry.rule}\0${entry.value}`, entry);
+ }
+ return Array.from(map.values());
+}
+
+export function readCache(cwd) {
+ const raw = safeReadJson(getCachePath(cwd));
+ if (!raw || typeof raw !== 'object' || raw.version !== 1) {
+ return { version: 1, sessions: {} };
+ }
+ return {
+ version: 1,
+ sessions: raw.sessions && typeof raw.sessions === 'object' ? raw.sessions : {},
+ };
+}
+
+export function persistCache(cwd, cache) {
+ const sessions = cache.sessions || {};
+ const ids = Object.keys(sessions);
+ if (ids.length > CACHE_MAX_SESSIONS) {
+ // Garbage-collect oldest sessions by updatedAt.
+ const ordered = ids
+ .map((id) => [id, sessions[id]?.updatedAt || 0])
+ .sort((a, b) => b[1] - a[1])
+ .slice(0, CACHE_MAX_SESSIONS);
+ const next = {};
+ for (const [id] of ordered) next[id] = sessions[id];
+ cache = { ...cache, sessions: next };
+ }
+ const target = getCachePath(cwd);
+ try {
+ ensureHookGitExcludes(cwd);
+ fs.mkdirSync(path.dirname(target), { recursive: true });
+ fs.writeFileSync(target, JSON.stringify(cache));
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+export function ensureHookGitExcludes(cwd = process.cwd()) {
+ try {
+ const target = resolveHookGitExcludeTarget(cwd);
+ if (!target) {
+ return { mode: 'none', changed: false, patterns: [...HOOK_LOCAL_IGNORE_PATTERNS] };
+ }
+
+ const patterns = target.patternPrefix
+ ? HOOK_LOCAL_IGNORE_PATTERNS.map((pattern) => `${target.patternPrefix}/${pattern}`)
+ : [...HOOK_LOCAL_IGNORE_PATTERNS];
+ const markerSuffix = target.patternPrefix || '.';
+ const markerOpen = `${HOOK_IGNORE_MARKER_OPEN} ${markerSuffix}`;
+ const markerClose = `${HOOK_IGNORE_MARKER_CLOSE} ${markerSuffix}`;
+ const existing = fs.existsSync(target.path) ? fs.readFileSync(target.path, 'utf-8') : '';
+ const block = [markerOpen, ...patterns, markerClose].join('\n');
+ const markerRe = new RegExp(`${escapeRegExp(markerOpen)}[\\s\\S]*?${escapeRegExp(markerClose)}`);
+
+ let updated;
+ if (markerRe.test(existing)) {
+ updated = existing.replace(markerRe, block);
+ } else {
+ const prefix = existing.length === 0 ? '' : existing.endsWith('\n') ? existing : `${existing}\n`;
+ updated = `${prefix}${prefix.endsWith('\n\n') || prefix === '' ? '' : '\n'}${block}\n`;
+ }
+
+ if (updated !== existing) {
+ fs.mkdirSync(path.dirname(target.path), { recursive: true });
+ fs.writeFileSync(target.path, updated, 'utf-8');
+ }
+
+ return {
+ mode: 'git-info-exclude',
+ file: path.relative(path.resolve(cwd), target.path).split(path.sep).join('/'),
+ changed: updated !== existing,
+ patterns,
+ };
+ } catch {
+ return { mode: 'error', changed: false, patterns: [...HOOK_LOCAL_IGNORE_PATTERNS] };
+ }
+}
+
+function resolveHookGitExcludeTarget(cwd) {
+ const start = path.resolve(cwd);
+ let dir = start;
+ while (true) {
+ const dotGit = path.join(dir, '.git');
+ if (fs.existsSync(dotGit)) {
+ const gitDir = resolveGitDir(dotGit, dir);
+ if (!gitDir) return null;
+ const relPrefix = path.relative(dir, start).split(path.sep).join('/');
+ return {
+ path: path.join(gitDir, 'info', 'exclude'),
+ patternPrefix: relPrefix && relPrefix !== '.' ? relPrefix : '',
+ };
+ }
+ const parent = path.dirname(dir);
+ if (parent === dir) return null;
+ dir = parent;
+ }
+}
+
+function resolveGitDir(dotGit, worktreeDir) {
+ const stat = fs.statSync(dotGit);
+ if (stat.isDirectory()) return dotGit;
+ if (!stat.isFile()) return null;
+
+ const body = fs.readFileSync(dotGit, 'utf-8').trim();
+ const match = body.match(/^gitdir:\s*(.+)$/i);
+ if (!match) return null;
+ return path.isAbsolute(match[1]) ? match[1] : path.resolve(worktreeDir, match[1]);
+}
+
+function escapeRegExp(value) {
+ return String(value).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+}
+
+function ensureSession(cache, sessionId) {
+ if (!cache.sessions[sessionId]) {
+ cache.sessions[sessionId] = { updatedAt: Date.now(), files: {} };
+ }
+ return cache.sessions[sessionId];
+}
+
+function ensureFile(cache, sessionId, filePath) {
+ const session = ensureSession(cache, sessionId);
+ if (!session.files[filePath]) {
+ session.files[filePath] = { editCount: 0, findings: [] };
+ }
+ return session.files[filePath];
+}
+
+export function bumpEditCount(cache, sessionId, filePath) {
+ const fileEntry = ensureFile(cache, sessionId, filePath);
+ fileEntry.editCount = (fileEntry.editCount || 0) + 1;
+ ensureSession(cache, sessionId).updatedAt = Date.now();
+ return fileEntry.editCount;
+}
+
+export function suppressionNotice(filePath) {
+ return `${ENVELOPE_PREFIX} Suppressing further design hints on ${filePath}. More than ${EDIT_COUNT_THRESHOLD} edits in this session reached. Run /impeccable audit to revisit.`;
+}
+
+// Glob → RegExp. Supports `**`, `*`, `?`, and `{a,b}` alternation.
+function globToRegex(glob) {
+ let re = '^';
+ let i = 0;
+ while (i < glob.length) {
+ const c = glob[i];
+ if (c === '*') {
+ if (glob[i + 1] === '*') {
+ re += '.*';
+ i += 2;
+ if (glob[i] === '/') i += 1;
+ } else {
+ re += '[^/]*';
+ i += 1;
+ }
+ } else if (c === '?') {
+ re += '[^/]';
+ i += 1;
+ } else if (c === '{') {
+ const end = glob.indexOf('}', i);
+ if (end === -1) { re += '\\{'; i += 1; continue; }
+ const parts = glob.slice(i + 1, end).split(',').map((p) => p.replace(/[.+^$()|[\]\\]/g, '\\$&'));
+ re += `(?:${parts.join('|')})`;
+ i = end + 1;
+ } else if (/[.+^$()|[\]\\]/.test(c)) {
+ re += `\\${c}`;
+ i += 1;
+ } else {
+ re += c;
+ i += 1;
+ }
+ }
+ re += '$';
+ return new RegExp(re);
+}
+
+export function matchesAnyGlob(filePath, globs) {
+ if (!Array.isArray(globs) || globs.length === 0) return false;
+ const normalized = filePath.split(path.sep).join('/');
+ for (const glob of globs) {
+ try {
+ const re = globToRegex(String(glob));
+ if (re.test(normalized)) return true;
+ // Match against basename too for convenience: `*.generated.tsx` should
+ // catch `src/foo.generated.tsx` without requiring `**/`.
+ const base = normalized.split('/').pop();
+ if (re.test(base)) return true;
+ } catch {
+ /* malformed glob, skip */
+ }
+ }
+ return false;
+}
+
+export function filterFindings(findings, _content, _ext, config) {
+ if (!Array.isArray(findings) || findings.length === 0) return [];
+ const ignoreRules = new Set((config.ignoreRules || []).map((rule) => normalizeIgnoreRule(rule)));
+ const ignoreValues = normalizeIgnoreValueEntries(config.ignoreValues || []);
+ return findings.filter((f) => {
+ if (!f || typeof f !== 'object') return false;
+ if (ignoreRules.has(normalizeIgnoreRule(f.antipattern))) return false;
+ if (isIgnoredFindingValue(f, ignoreValues)) return false;
+ return true;
+ });
+}
+
+function isIgnoredFindingValue(finding, ignoreValues) {
+ if (!Array.isArray(ignoreValues) || ignoreValues.length === 0) return false;
+ const rule = normalizeIgnoreRule(finding.antipattern);
+ const value = extractFindingIgnoreValue(finding);
+ if (!rule || !value) return false;
+ return ignoreValues.some((entry) => entry.rule === rule && entry.value === value);
+}
+
+export function extractFindingIgnoreValue(finding) {
+ if (!finding || typeof finding !== 'object') return '';
+ const rule = normalizeIgnoreRule(finding.antipattern);
+ if (rule !== 'overused-font') return '';
+ return normalizeIgnoreValue(extractFindingIgnoreValueRaw(finding));
+}
+
+function extractFindingIgnoreValueRaw(finding) {
+ const direct = cleanIgnoreValueDisplay(finding.ignoreValue || finding.value || '');
+ if (direct) return direct;
+
+ const candidates = [finding.detail, finding.snippet].filter((v) => typeof v === 'string' && v);
+ for (const text of candidates) {
+ const primary = text.match(/Primary font:\s*([^()\n;]+)/i);
+ if (primary) return cleanIgnoreValueDisplay(primary[1]);
+
+ const family = text.match(/font-family\s*:\s*["']?([^'",;\n]+)/i);
+ if (family) return cleanIgnoreValueDisplay(family[1]);
+
+ const google = text.match(/[?&]family=([^&:;\n]+)/i);
+ if (google) {
+ try {
+ return cleanIgnoreValueDisplay(decodeURIComponent(google[1]));
+ } catch {
+ return cleanIgnoreValueDisplay(google[1]);
+ }
+ }
+ }
+
+ return '';
+}
+
+function cleanIgnoreValueDisplay(value) {
+ return String(value || '')
+ .trim()
+ .replace(/^["']|["']$/g, '')
+ .replace(/\+/g, ' ')
+ .replace(/\s+/g, ' ');
+}
+
+export function dedupeAgainstCache(findings, cache, sessionId, filePath) {
+ if (!Array.isArray(findings) || findings.length === 0) return [];
+ const fileEntry = ensureFile(cache, sessionId, filePath);
+ const known = new Set(fileEntry.findings || []);
+ const fresh = [];
+ for (const f of findings) {
+ const key = `${f.antipattern}:${f.line || 0}`;
+ if (known.has(key)) continue;
+ known.add(key);
+ fresh.push(f);
+ }
+ return fresh;
+}
+
+export function rememberFindings(cache, sessionId, filePath, findings) {
+ const fileEntry = ensureFile(cache, sessionId, filePath);
+ const known = new Set(fileEntry.findings || []);
+ for (const f of findings) known.add(`${f.antipattern}:${f.line || 0}`);
+ fileEntry.findings = Array.from(known);
+ ensureSession(cache, sessionId).updatedAt = Date.now();
+}
+
+export function renderTemplate(findings, filePath, config, opts = {}) {
+ if (!Array.isArray(findings) || findings.length === 0) return '';
+ const limits = config?.limits || DEFAULT_CONFIG.limits;
+ const cap = Math.max(1, limits.maxFindings || DEFAULT_CONFIG.limits.maxFindings);
+ const maxChars = Math.max(500, limits.maxChars || DEFAULT_CONFIG.limits.maxChars);
+
+ const cwd = opts.cwd || process.cwd();
+ const display = relativize(filePath, cwd);
+ const total = findings.length;
+ const shown = findings.slice(0, cap);
+ const remaining = total - shown.length;
+
+ const header = `${ENVELOPE_PREFIX} Required design corrections in ${display} (${total} issue(s)):`;
+ const lines = shown.map((f) => formatFindingLine(f));
+ const more = remaining > 0
+ ? `... and ${remaining} more (see /impeccable audit).`
+ : null;
+ const footer = directiveFooter(display);
+
+ const blocks = [header, ...lines];
+ if (more) blocks.push(more);
+ blocks.push('');
+ blocks.push(footer);
+ let text = blocks.join('\n');
+
+ if (text.length > maxChars) {
+ text = clampToBudget(header, lines, more, footer, maxChars);
+ }
+ return text;
+}
+
+function renderGroupedTemplate(groups, config, opts = {}) {
+ const realGroups = groups.filter((group) => Array.isArray(group.findings) && group.findings.length > 0);
+ if (realGroups.length === 0) return '';
+ if (realGroups.length === 1) {
+ const [group] = realGroups;
+ return renderTemplate(group.findings, group.filePath, config, opts);
+ }
+
+ const limits = config?.limits || DEFAULT_CONFIG.limits;
+ const cap = Math.max(1, limits.maxFindings || DEFAULT_CONFIG.limits.maxFindings);
+ const maxChars = Math.max(500, limits.maxChars || DEFAULT_CONFIG.limits.maxChars);
+ const cwd = opts.cwd || process.cwd();
+ const total = realGroups.reduce((sum, group) => sum + group.findings.length, 0);
+ const header = `${ENVELOPE_PREFIX} Required design corrections across ${realGroups.length} files (${total} issue(s)):`;
+ const lines = [];
+ let shownCount = 0;
+
+ for (const group of realGroups) {
+ const display = relativize(group.filePath, cwd);
+ lines.push(`${display} (${group.findings.length} issue(s)):`);
+ const remainingCap = Math.max(0, cap - shownCount);
+ const shown = group.findings.slice(0, remainingCap);
+ for (const finding of shown) {
+ lines.push(formatFindingLine(finding));
+ }
+ shownCount += shown.length;
+ const hidden = group.findings.length - shown.length;
+ if (hidden > 0) {
+ lines.push(`- ... ${hidden} more in ${display} (see /impeccable audit).`);
+ }
+ }
+
+ const footer = directiveFooter('the affected files', { grouped: true });
+ let text = [header, ...lines, '', footer].join('\n');
+ if (text.length > maxChars) {
+ text = clampGroupedToBudget(header, lines, footer, maxChars);
+ }
+ return text;
+}
+
+function clampGroupedToBudget(header, lines, footer, maxChars) {
+ const assemble = (linesArr, omitted) => [
+ header,
+ ...linesArr,
+ ...(omitted ? ['... and more (see /impeccable audit).'] : []),
+ '',
+ footer,
+ ].join('\n');
+
+ let working = lines.slice();
+ let omitted = false;
+ let assembled = assemble(working, omitted);
+ while (assembled.length > maxChars && working.length > 1) {
+ working.pop();
+ omitted = true;
+ assembled = assemble(working, omitted);
+ }
+ if (assembled.length > maxChars) {
+ assembled = `${assembled.slice(0, maxChars - 1)}…`;
+ }
+ return assembled;
+}
+
+function clampToBudget(header, lines, more, footer, maxChars) {
+ const assemble = (linesArr, moreText) => {
+ const blocks = [header, ...linesArr];
+ if (moreText) blocks.push(moreText);
+ blocks.push('');
+ blocks.push(footer);
+ return blocks.join('\n');
+ };
+
+ let working = lines.slice();
+ let moreText = more;
+ let assembled = assemble(working, moreText);
+ while (assembled.length > maxChars && working.length > 1) {
+ working.pop();
+ moreText = '... and more (see /impeccable audit).';
+ assembled = assemble(working, moreText);
+ }
+ if (assembled.length > maxChars) {
+ assembled = `${assembled.slice(0, maxChars - 1)}…`;
+ }
+ return assembled;
+}
+
+function formatFindingLine(f) {
+ const prefix = f.line && f.line > 0 ? `- L${f.line}` : '-';
+ const desc = (f.description || '').trim();
+ const name = (f.name || '').trim();
+ // Description from the registry already ends in punctuation; join with a
+ // single space. `name` may have a trailing period already, keep it clean.
+ const nameSegment = name ? `${name.replace(/\.+\s*$/, '')}.` : '';
+ const ignoreCommand = formatFindingIgnoreCommand(f);
+ const ignoreSegment = ignoreCommand
+ ? ` If the user explicitly confirms this value is intentional: \`${ignoreCommand}\`.`
+ : '';
+ return `${prefix} [${f.antipattern}] ${nameSegment} ${desc}${ignoreSegment}`.replace(/\s+/g, ' ').trim();
+}
+
+function formatFindingIgnoreCommand(finding) {
+ if (!finding || typeof finding !== 'object') return '';
+ const rule = normalizeIgnoreRule(finding.antipattern);
+ if (!rule) return '';
+ const normalizedValue = extractFindingIgnoreValue(finding);
+ if (!normalizedValue) return '';
+ const value = extractFindingIgnoreValueRaw(finding);
+ const valueArg = quoteCommandArg(value);
+ const reason = quoteCommandArg(`User confirmed ${value} is intentional`);
+ return `/impeccable hooks ignore-value ${rule} ${valueArg} --shared --reason ${reason}`;
+}
+
+function quoteCommandArg(value) {
+ const text = String(value || '').trim();
+ if (/^[A-Za-z0-9._:-]+$/.test(text)) return text;
+ return `"${text.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
+}
+
+function relativize(filePath, cwd) {
+ try {
+ const rel = path.relative(cwd, filePath);
+ if (!rel || rel.startsWith('..')) return filePath;
+ return rel.split(path.sep).join('/');
+ } catch {
+ return filePath;
+ }
+}
+
+// Codex `apply_patch` exposes the raw patch in `tool_input.command`, not
+// `tool_input.file_path`. Claude Code may send both; parse the patch body
+// so we can scan the file(s) the tool actually touched.
+// https://developers.openai.com/codex/hooks#posttooluse
+const APPLY_PATCH_FILE_RE = /^\*\*\* (?:Update|Add) File: (.+)$/gm;
+
+export function parseApplyPatchPaths(command, projectCwd) {
+ if (!command || typeof command !== 'string') return [];
+ const out = [];
+ for (const m of command.matchAll(APPLY_PATCH_FILE_RE)) {
+ let p = (m[1] || '').trim();
+ if (!p) continue;
+ if (!path.isAbsolute(p)) p = path.resolve(projectCwd, p);
+ out.push(p);
+ }
+ return out;
+}
+
+export function resolveTargetFiles(event, projectCwd) {
+ const ti = event?.tool_input;
+ const out = [];
+ const add = (filePath) => {
+ if (typeof filePath !== 'string' || !filePath) return;
+ if (!out.includes(filePath)) out.push(filePath);
+ };
+
+ if (event?.tool_name === 'apply_patch' && ti && typeof ti.command === 'string') {
+ for (const filePath of parseApplyPatchPaths(ti.command, projectCwd)) add(filePath);
+ }
+ if (ti && typeof ti.file_path === 'string' && ti.file_path) {
+ add(ti.file_path);
+ }
+ // Cursor Write / StrReplace use `path`, not `file_path`.
+ if (ti && typeof ti.path === 'string' && ti.path) {
+ add(ti.path);
+ }
+ if (typeof event?.file_path === 'string' && event.file_path) {
+ add(event.file_path);
+ }
+ return out;
+}
+
+export function resolveHarness(env = {}, event = null) {
+ const explicit = env?.IMPECCABLE_HOOK_HARNESS;
+ if (explicit === 'cursor') return 'cursor';
+ if (explicit === 'claude' || explicit === 'codex') return 'claude';
+ if (typeof event?.conversation_id === 'string' && event.conversation_id) return 'cursor';
+ return 'claude';
+}
+
+export function normalizeHookEvent(event, projectCwd, harness = 'claude') {
+ if (!event || typeof event !== 'object' || harness !== 'cursor') return event;
+
+ const cwd = event.cwd
+ || (Array.isArray(event.workspace_roots) && event.workspace_roots[0])
+ || envProjectDir(projectCwd)
+ || projectCwd;
+ const sessionId = event.session_id || event.conversation_id || 'unknown';
+
+ const ti = event.tool_input && typeof event.tool_input === 'object' ? event.tool_input : {};
+ const filePath = ti.file_path || ti.path || event.file_path;
+ if (filePath) {
+ return {
+ ...event,
+ cwd,
+ session_id: sessionId,
+ tool_input: { ...ti, file_path: filePath },
+ };
+ }
+
+ return { ...event, cwd, session_id: sessionId };
+}
+
+function envProjectDir(fallback) {
+ if (typeof process.env.CURSOR_PROJECT_DIR === 'string' && process.env.CURSOR_PROJECT_DIR) {
+ return process.env.CURSOR_PROJECT_DIR;
+ }
+ return fallback;
+}
+
+// UI components often keep slop in a sibling/co-located stylesheet while the
+// JSX edit is what triggered PostToolUse. Scan those styles too so an App.jsx
+// patch doesn't report "clean" while styles.css still has Inter/bounce/etc.
+const UI_CODE_EXTS = new Set(['.jsx', '.tsx', '.vue', '.svelte', '.astro']);
+const STYLE_EXTS = new Set(['.css', '.scss', '.sass', '.less']);
+const CO_SCAN_STYLE_NAMES = [
+ 'styles.css', 'styles.scss', 'styles.sass', 'styles.less',
+ 'index.css', 'index.scss', 'index.sass', 'index.less',
+ 'global.css', 'global.scss', 'global.sass', 'global.less',
+ 'globals.css', 'globals.scss', 'globals.sass', 'globals.less',
+];
+const MAX_SCAN_TARGETS = 6;
+
+const STATIC_STYLE_IMPORT_RE = /import\s+(?:[\w*{}\s,$]+\s+from\s+)?['"]([^'"]+\.(?:css|scss|sass|less))['"]/gi;
+
+function hasPathTraversal(filePath) {
+ return typeof filePath === 'string' && filePath.includes('..');
+}
+
+function isInsideProject(filePath, projectCwd) {
+ if (!filePath || !projectCwd || hasPathTraversal(filePath)) return false;
+ try {
+ const rel = path.relative(projectCwd, filePath);
+ return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));
+ } catch {
+ return false;
+ }
+}
+
+export function parseStaticStyleImports(content, fromFile, projectCwd) {
+ if (!content || typeof content !== 'string') return [];
+ const dir = path.dirname(fromFile);
+ const out = [];
+ for (const m of content.matchAll(STATIC_STYLE_IMPORT_RE)) {
+ let p = (m[1] || '').trim();
+ if (!p) continue;
+ if (p.startsWith('.')) p = path.resolve(dir, p);
+ else if (!path.isAbsolute(p)) p = path.resolve(projectCwd, p);
+ if (!isInsideProject(p, projectCwd)) continue;
+ out.push(p);
+ }
+ return out;
+}
+
+export function coLocatedStylesheets(filePath) {
+ const dir = path.dirname(filePath);
+ const base = path.basename(filePath, path.extname(filePath));
+ const candidates = new Set([
+ path.join(dir, `${base}.css`),
+ path.join(dir, `${base}.module.css`),
+ path.join(dir, `${base}.scss`),
+ path.join(dir, `${base}.module.scss`),
+ path.join(dir, `${base}.sass`),
+ path.join(dir, `${base}.module.sass`),
+ path.join(dir, `${base}.less`),
+ path.join(dir, `${base}.module.less`),
+ ]);
+ for (const name of CO_SCAN_STYLE_NAMES) {
+ candidates.add(path.join(dir, name));
+ }
+ return [...candidates].filter((p) => fs.existsSync(p));
+}
+
+export function normalizeScanTargets(primaryTargets, projectCwd) {
+ if (!Array.isArray(primaryTargets) || primaryTargets.length === 0) return [];
+ const ordered = [];
+ const seen = new Set();
+ const baseCwd = projectCwd || process.cwd();
+ const normalizeTarget = (p) => {
+ // Preserve literal `..` segments so downstream sensitive-path checks
+ // still fire. path.resolve would collapse `/foo/../etc/passwd`.
+ if (hasPathTraversal(p)) return p;
+ return path.isAbsolute(p) ? p : path.resolve(baseCwd, p);
+ };
+ const add = (p) => {
+ if (ordered.length >= MAX_SCAN_TARGETS) return;
+ const abs = normalizeTarget(p);
+ if (seen.has(abs)) return;
+ seen.add(abs);
+ ordered.push(abs);
+ return abs;
+ };
+
+ for (const p of primaryTargets) add(p);
+ return ordered;
+}
+
+export function expandScanTargets(primaryTargets, projectCwd) {
+ const ordered = normalizeScanTargets(primaryTargets, projectCwd);
+ if (ordered.length === 0) return [];
+ const seen = new Set(ordered);
+ const baseCwd = projectCwd || process.cwd();
+ const add = (p) => {
+ if (ordered.length >= MAX_SCAN_TARGETS) return;
+ const abs = hasPathTraversal(p) ? p : (path.isAbsolute(p) ? p : path.resolve(baseCwd, p));
+ if (seen.has(abs)) return;
+ seen.add(abs);
+ ordered.push(abs);
+ return abs;
+ };
+
+ const normalizedPrimaries = [];
+ for (const p of ordered) normalizedPrimaries.push(p);
+
+ for (const p of normalizedPrimaries) {
+ if (ordered.length >= MAX_SCAN_TARGETS) break;
+ if (!isInsideProject(p, baseCwd)) continue;
+ const ext = path.extname(p).toLowerCase();
+ if (STYLE_EXTS.has(ext) || !UI_CODE_EXTS.has(ext)) continue;
+
+ let content = '';
+ try { content = fs.readFileSync(p, 'utf-8'); } catch { /* unreadable primary */ }
+
+ for (const imp of parseStaticStyleImports(content, p, projectCwd)) {
+ add(imp);
+ if (ordered.length >= MAX_SCAN_TARGETS) break;
+ }
+ for (const col of coLocatedStylesheets(p)) {
+ add(col);
+ if (ordered.length >= MAX_SCAN_TARGETS) break;
+ }
+ }
+
+ return ordered;
+}
+
+export function writeAuditLog(env, entry) {
+ const target = env?.IMPECCABLE_HOOK_LOG;
+ if (!target || typeof target !== 'string') return false;
+ try {
+ const expanded = target.startsWith('~/')
+ ? path.join(process.env.HOME || process.env.USERPROFILE || '.', target.slice(2))
+ : target;
+ fs.mkdirSync(path.dirname(expanded), { recursive: true });
+ const line = JSON.stringify({ ts: new Date().toISOString(), ...entry }) + '\n';
+ fs.appendFileSync(expanded, line);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+const DETECTOR_CANDIDATES = [
+ path.join(__dirname, 'detector', 'detect-antipatterns.mjs'),
+ path.join(__dirname, '..', '..', 'cli', 'engine', 'detect-antipatterns.mjs'),
+ path.join(__dirname, '..', '..', '..', 'cli', 'engine', 'detect-antipatterns.mjs'),
+];
+
+let detectorCache = null;
+export async function loadDetector(candidates = DETECTOR_CANDIDATES) {
+ if (detectorCache) return detectorCache;
+ const found = candidates.find((c) => fs.existsSync(c));
+ if (!found) return null;
+ const mod = await import(pathToFileURL(found));
+ detectorCache = { detectText: mod.detectText, detectHtml: mod.detectHtml };
+ return detectorCache;
+}
+
+// For tests: allow injecting a detector implementation.
+export function setDetectorForTesting(impl) {
+ detectorCache = impl;
+}
+
+// ────────────────────────────────────────────────────────────────────────
+// Nudge/steer messages for the no-silent-fires policy.
+//
+// The hook is designed to be a conversational presence: every fire that
+// actually scans a file emits a developer-role message into the model's
+// next turn. Three states map to three templates:
+//
+// 1. **Fresh findings** → `renderTemplate` (existing, imperative).
+// 2. **Pending findings** → `renderPendingAck` (re-nudge for issues the
+// model was already told about in this
+// session but hasn't fixed yet).
+// 3. **Truly clean** → `renderCleanAck` (short positive nudge that
+// keeps the design discipline in context).
+//
+// All three are short (≤ ~40 tokens each) so the cumulative cost stays
+// bounded across a long active editing session. Users who explicitly want
+// silence-on-clean can set `IMPECCABLE_HOOK_QUIET=1` — runHook checks that
+// env before emitting #2 or #3.
+//
+// Why not stay silent on dedup-clean? Earlier versions did. The model
+// quickly forgets the prior reminder once tool output scrolls past it, so
+// re-nudging on the same file with a short "still pending" line keeps the
+// pressure on. The wording deliberately points back to "earlier this
+// session" so the model knows it's a re-mind, not a new finding.
+// ────────────────────────────────────────────────────────────────────────
+
+const STEER_LINE = 'Keep typography hierarchy, spacing rhythm, and color contrast intentional on the next change.';
+
+export function renderCleanAck(filePath, opts = {}) {
+ const cwd = opts.cwd || process.cwd();
+ const display = relativize(filePath, cwd);
+ return `${ENVELOPE_PREFIX} Design hook scanned ${display}. No anti-patterns. ${STEER_LINE}`;
+}
+
+export function renderPendingAck(filePath, knownFindings, opts = {}) {
+ const cwd = opts.cwd || process.cwd();
+ const display = relativize(filePath, cwd);
+ const count = knownFindings.length;
+ // `knownFindings` here are the cache strings like "side-tab:3".
+ const sample = knownFindings.slice(0, 3).join(', ');
+ const more = count > 3 ? `, +${count - 3} more` : '';
+ return `${ENVELOPE_PREFIX} Design hook scanned ${display}. Still has ${count} issue(s) flagged earlier this session (${sample}${more}). Address them before finalizing — the previous reminder still applies.`;
+}
+
+export function shouldEmitAckForFile(filePath) {
+ return ACK_EXTS.has(path.extname(String(filePath || '')).toLowerCase());
+}
+
+// The directive footer is the part of the hook output that steers model
+// behavior. Three intentional moves:
+// 1. **Imperative, not advisory.** "Fix these..." beats "Consider
+// revising..." which the model treats as a soft suggestion it can
+// override when the user asked for any kind of throwaway / demo UI.
+// 2. **Explicit exception clause.** Without it, the model will try to
+// "fix" intentional bad fixtures, anti-pattern examples in docs, or
+// test cases. Naming the exception inline beats hoping the model
+// infers it from context.
+// 3. **Acknowledgement instruction.** Hook output is injected as
+// developer-role context, not a chat turn, so the user never sees the
+// raw envelope. Asking the model to surface the fix in its reply is
+// the cheapest way to make the feedback loop visible to the user.
+function directiveFooter(display, opts = {}) {
+ const ignoreFileCommand = `/impeccable hooks ignore-file ${quoteCommandArg(display)}`;
+ const fileIgnoreGuidance = opts.grouped
+ ? 'run `/impeccable hooks ignore-file <path>` for the specific file'
+ : `run \`${ignoreFileCommand}\``;
+ return [
+ 'Fix these in your next reply before finalizing. Acknowledge what you changed so the user sees the correction.',
+ '',
+ 'Skip the fix only if the user explicitly asked for an intentionally bad UI, an anti-pattern example, a test fixture, or documentation of bad design. In that case, say so and continue.',
+ '',
+ `Do not add source comments such as \`impeccable: ignore\`; those pollute the code and do not suppress hook findings. Do not add hook ignores unless the user explicitly confirms the finding is intentional. Prefer the narrowest persisted exception: run the exact \`/impeccable hooks ignore-value ... --shared\` command shown next to a value-specific finding. For \`overused-font\`, use \`ignore-value\` for a specific font and use \`/impeccable hooks ignore-rule overused-font --all-values\` only when the user asks to ignore overused fonts generally. For file-specific findings without an ignore-value command, ${fileIgnoreGuidance}; use \`/impeccable hooks ignore-rule <id>\` only when the user asks to suppress the whole non-value-specific rule. Run /impeccable audit for the full pass.`,
+ ].join('\n');
+}
+
+/**
+ * Run the hook with explicit dependencies. Returns a result object:
+ * { exitCode, stdout, audit, reason? }
+ *
+ * Never throws. All errors are converted to `exitCode: 0` + audit entry.
+ */
+export async function runHook({ stdinJson, env = {}, cwd = process.cwd(), now = Date.now, detector } = {}) {
+ const audit = { ts: new Date(now()).toISOString(), event: 'PostToolUse' };
+ const result = (extra) => ({ exitCode: 0, stdout: '', audit: { ...audit, ...extra } });
+
+ try {
+ // Re-entrancy guard.
+ if (depthIsSet(env.IMPECCABLE_HOOK_DEPTH) || depthIsSet(env.CLAUDE_HOOK_DEPTH)) {
+ return result({ reentrant: true, durationMs: 0 });
+ }
+
+ if (truthy(env.IMPECCABLE_HOOK_DISABLED)) {
+ return result({ skipped: 'env-disabled', durationMs: 0 });
+ }
+
+ const started = Date.now();
+
+ let event;
+ try {
+ event = typeof stdinJson === 'string' ? JSON.parse(stdinJson) : stdinJson;
+ } catch {
+ return result({ skipped: 'stdin-malformed', durationMs: Date.now() - started });
+ }
+ if (!event || typeof event !== 'object') {
+ return result({ skipped: 'stdin-empty', durationMs: Date.now() - started });
+ }
+
+ const harness = resolveHarness(env, event);
+ event = normalizeHookEvent(event, cwd, harness);
+ audit.harness = harness;
+
+ const projectCwd = event.cwd || cwd;
+ const primaryFiles = normalizeScanTargets(resolveTargetFiles(event, projectCwd), projectCwd);
+ const primaryFileSet = new Set(primaryFiles);
+ const targetFiles = expandScanTargets(primaryFiles, projectCwd);
+ audit.session = event.session_id || null;
+ if (event.tool_name) audit.tool = event.tool_name;
+
+ if (targetFiles.length === 0) {
+ return result({ skipped: 'no-file-path', durationMs: Date.now() - started });
+ }
+
+ const config = readConfig(projectCwd);
+ if (config.enabled === false) {
+ return result({ skipped: 'config-disabled', durationMs: Date.now() - started });
+ }
+
+ const cache = readCache(projectCwd);
+ const sessionId = event.session_id || 'unknown';
+ const det = detector || await loadDetector();
+ if (!det || typeof det.detectText !== 'function') {
+ persistCache(projectCwd, cache);
+ return result({ skipped: 'detector-missing', durationMs: Date.now() - started });
+ }
+
+ let pendingWinner = null;
+ let cleanWinner = null;
+ const freshGroups = [];
+ let suppressionWinner = null;
+ let detectorThrewAny = false;
+ let lastSkip = 'no-scannable-file';
+ let suppressedHit = false;
+
+ for (const filePath of targetFiles) {
+ audit.file = filePath;
+
+ if (hasPathTraversal(filePath) || SENSITIVE_PATH.test(filePath)) {
+ lastSkip = 'sensitive';
+ continue;
+ }
+ if (GENERATED_PATH.test(filePath)) {
+ lastSkip = 'generated';
+ continue;
+ }
+
+ const ext = path.extname(filePath).toLowerCase();
+ audit.ext = ext;
+ if (!ALLOWED_EXTS.has(ext)) {
+ lastSkip = 'extension';
+ continue;
+ }
+
+ const relForMatch = relativize(filePath, projectCwd);
+ if (matchesAnyGlob(relForMatch, config.ignoreFiles) || matchesAnyGlob(filePath, config.ignoreFiles)) {
+ lastSkip = 'config-ignore-file';
+ continue;
+ }
+ if (!fs.existsSync(filePath)) {
+ lastSkip = 'file-missing';
+ continue;
+ }
+
+ if (primaryFileSet.has(filePath)) {
+ const editCount = bumpEditCount(cache, sessionId, filePath);
+ audit.editCount = editCount;
+
+ if (editCount > EDIT_COUNT_THRESHOLD) {
+ const wasJustCrossed = editCount === EDIT_COUNT_THRESHOLD + 1;
+ if (wasJustCrossed && !suppressionWinner) {
+ suppressionWinner = { filePath };
+ }
+ lastSkip = 'suppressed';
+ suppressedHit = true;
+ continue;
+ }
+ }
+
+ const content = fs.readFileSync(filePath, 'utf-8');
+ let findings;
+ let detectorThrew = false;
+ if ((ext === '.html' || ext === '.htm') && typeof det.detectHtml === 'function') {
+ try { findings = await det.detectHtml(filePath); } catch { findings = []; detectorThrew = true; }
+ } else {
+ try { findings = await det.detectText(content, filePath); } catch { findings = []; detectorThrew = true; }
+ }
+
+ const filtered = filterFindings(findings || [], content, ext, config);
+ const fresh = dedupeAgainstCache(filtered, cache, sessionId, filePath);
+ audit.findings = (findings || []).length;
+ audit.freshFindings = fresh.length;
+
+ if (fresh.length > 0) {
+ rememberFindings(cache, sessionId, filePath, fresh);
+ freshGroups.push({ filePath, findings: fresh });
+ continue;
+ }
+
+ if (detectorThrew) {
+ detectorThrewAny = true;
+ continue;
+ }
+
+ if (filtered.length > 0 && !pendingWinner) {
+ const known = (ensureFile(cache, sessionId, filePath).findings || []).slice();
+ pendingWinner = { filePath, known };
+ } else if (filtered.length === 0 && !cleanWinner) {
+ cleanWinner = { filePath };
+ }
+ }
+
+ persistCache(projectCwd, cache);
+
+ if (freshGroups.length > 0) {
+ const firstGroup = freshGroups[0];
+ const text = renderGroupedTemplate(freshGroups, config, { cwd: projectCwd });
+ const allFindings = freshGroups.flatMap((group) => group.findings);
+ return {
+ exitCode: 0,
+ stdout: payload(text, 'PostToolUse', harness),
+ emission: {
+ kind: 'fresh',
+ file: firstGroup.filePath,
+ findings: firstGroup.findings,
+ groups: freshGroups,
+ },
+ audit: {
+ ...audit,
+ file: firstGroup.filePath,
+ emitted: true,
+ freshFiles: freshGroups.length,
+ freshFindings: allFindings.length,
+ chars: text.length,
+ durationMs: Date.now() - started,
+ },
+ };
+ }
+
+ if (detectorThrewAny && !pendingWinner && !cleanWinner) {
+ return result({ emitted: false, error: 'detector-threw', durationMs: Date.now() - started });
+ }
+
+ if (truthy(env.IMPECCABLE_HOOK_QUIET)) {
+ return result({ emitted: false, quiet: true, durationMs: Date.now() - started });
+ }
+
+ if (pendingWinner && shouldEmitAckForFile(pendingWinner.filePath)) {
+ const text = renderPendingAck(pendingWinner.filePath, pendingWinner.known, { cwd: projectCwd });
+ return {
+ exitCode: 0,
+ stdout: payload(text, 'PostToolUse', harness),
+ emission: { kind: 'pending', file: pendingWinner.filePath, known: pendingWinner.known },
+ audit: {
+ ...audit,
+ file: pendingWinner.filePath,
+ emitted: true,
+ kind: 'pending',
+ pending: pendingWinner.known.length,
+ chars: text.length,
+ durationMs: Date.now() - started,
+ },
+ };
+ }
+
+ if (suppressionWinner) {
+ const text = suppressionNotice(relativize(suppressionWinner.filePath, projectCwd));
+ return {
+ exitCode: 0,
+ stdout: payload(text, 'PostToolUse', harness),
+ emission: { kind: 'suppression', file: suppressionWinner.filePath },
+ audit: {
+ ...audit,
+ file: suppressionWinner.filePath,
+ suppressed: true,
+ emitted: true,
+ durationMs: Date.now() - started,
+ },
+ };
+ }
+
+ if (cleanWinner && shouldEmitAckForFile(cleanWinner.filePath)) {
+ const text = renderCleanAck(cleanWinner.filePath, { cwd: projectCwd });
+ return {
+ exitCode: 0,
+ stdout: payload(text, 'PostToolUse', harness),
+ emission: { kind: 'clean', file: cleanWinner.filePath },
+ audit: {
+ ...audit,
+ file: cleanWinner.filePath,
+ emitted: true,
+ kind: 'clean',
+ chars: text.length,
+ durationMs: Date.now() - started,
+ },
+ };
+ }
+
+ if (pendingWinner || cleanWinner) {
+ return result({ emitted: false, skipped: 'non-ui-ack', durationMs: Date.now() - started });
+ }
+
+ if (suppressedHit) {
+ return result({ suppressed: true, emitted: false, durationMs: Date.now() - started });
+ }
+
+ return result({ skipped: lastSkip, durationMs: Date.now() - started });
+ } catch (err) {
+ return {
+ exitCode: 0,
+ stdout: '',
+ audit: { ...audit, error: String(err && err.message ? err.message : err) },
+ };
+ }
+}
+
+export function payload(text, eventName = 'PostToolUse', harness = 'claude') {
+ if (harness === 'cursor') {
+ return JSON.stringify({ additional_context: text });
+ }
+ return JSON.stringify({
+ hookSpecificOutput: { hookEventName: eventName, additionalContext: text },
+ });
+}
diff --git a/.pi/skills/impeccable/scripts/hook.mjs b/.pi/skills/impeccable/scripts/hook.mjs
new file mode 100644
index 000000000..b862f8033
--- /dev/null
+++ b/.pi/skills/impeccable/scripts/hook.mjs
@@ -0,0 +1,61 @@
+#!/usr/bin/env node
+/**
+ * Impeccable design hook — PostToolUse entry point.
+ *
+ * Reads the Claude Code / Codex / Cursor hook event from stdin, runs the design
+ * detector against the touched file, and emits a system reminder via
+ * `hookSpecificOutput.additionalContext` when findings exist.
+ *
+ * Contract: never break a turn. Always exit 0. Clean files emit a small ack
+ * unless quiet mode is enabled.
+ *
+ * Most logic lives in `hook-lib.mjs` so it is unit-testable without a
+ * subprocess. This file is the thin stdin/stdout adapter.
+ */
+
+import { runHook, 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');
+}
+
+async function main() {
+ // Snapshot the inherited env FIRST so the re-entrancy guard checks the
+ // parent's value, not the value we are about to export for any child
+ // processes the hook might ever spawn.
+ const inheritedEnv = { ...process.env };
+ process.env.IMPECCABLE_HOOK_DEPTH = process.env.IMPECCABLE_HOOK_DEPTH || '1';
+
+ let stdinJson = '';
+ try { stdinJson = await readStdin(); } catch { /* fall through */ }
+
+ const result = await runHook({
+ stdinJson,
+ env: inheritedEnv,
+ cwd: process.cwd(),
+ });
+
+ writeAuditLog(process.env, result.audit);
+
+ if (result.stdout) process.stdout.write(result.stdout);
+ process.exit(result.exitCode || 0);
+}
+
+main().catch((err) => {
+ // Last-ditch: never break the agent's turn even if something we did not
+ // anticipate goes wrong. Audit-log the failure if logging is enabled.
+ try {
+ writeAuditLog(process.env, {
+ ts: new Date().toISOString(),
+ event: 'PostToolUse',
+ error: String(err && err.message ? err.message : err),
+ });
+ } catch { /* swallow */ }
+ if (process.env.IMPECCABLE_HOOK_DEBUG) {
+ process.stderr.write(`[impeccable-hook] ${err}\n`);
+ }
+ process.exit(0);
+});
diff --git a/.pi/skills/impeccable/scripts/live-inject.mjs b/.pi/skills/impeccable/scripts/live-inject.mjs
index 4e5c5dc0a..69ce530c1 100644
--- a/.pi/skills/impeccable/scripts/live-inject.mjs
+++ b/.pi/skills/impeccable/scripts/live-inject.mjs
@@ -32,6 +32,8 @@ const IGNORE_MARKER_CLOSE = '# impeccable-live-ignore-end';
export const LIVE_IGNORE_PATTERNS = Object.freeze([
'.impeccable/hook.cache.json',
+ '.impeccable/hook.pending.json',
+ '.impeccable/hook.local.json',
'.impeccable/live/server.json',
'.impeccable/live/sessions/',
'.impeccable/live/previews/',
diff --git a/.qoder/skills/impeccable/SKILL.md b/.qoder/skills/impeccable/SKILL.md
index b79784a57..d8ccbe204 100644
--- a/.qoder/skills/impeccable/SKILL.md
+++ b/.qoder/skills/impeccable/SKILL.md
@@ -126,7 +126,7 @@ If someone could look at this interface and say "AI made that" without doubt, it
| `optimize [target]` | Fix | Diagnose and fix UI performance | [reference/optimize.md](reference/optimize.md) |
| `live` | Iterate | Visual variant mode: pick elements in the browser, generate alternatives | [reference/live.md](reference/live.md) |
-Plus two management commands: `pin <command>` and `unpin <command>`, detailed below.
+Plus three management commands: `pin <command>`, `unpin <command>`, and `hooks <on|off|status|...>`, detailed below.
### Routing rules
@@ -143,7 +143,7 @@ Plus two management commands: `pin <command>` and `unpin <command>`, detailed be
**If `scan.targets` is non-empty, run `node .qoder/skills/impeccable/scripts/detect.mjs --json <scan.targets joined by spaces>` once** (the bundled detector over local files: no network, no npx). `scan.via` tells you what they are: `git-changes` (the markup/style files in your dirty tree, the most relevant set), `source-dir` (e.g. `src`, `app`), `html`, or `root`. Fold the hits into your picks: many quality / contrast hits → `audit` or `polish`; a specific slop family → the matching command (gradient text or eyebrows → `quieter` / `typeset`, flat or gray palette → `colorize`, and so on). It's a real, current signal that beats guessing. If detect errors or the tree is large and slow, skip it and recommend the user run `audit` themselves; never block the suggestion on it.
Keep it to 2-3 pointed picks with the exact command to type. The menu stays the fallback; the recommendation is the lede.
-2. **First word matches a command**: load its reference file and follow its instructions. Everything after the command name is the target.
+2. **First word matches a command** (table above OR `pin` / `unpin` / `hooks`): load its reference file and follow its instructions. Everything after the command name is the target.
3. **First word doesn't match, but the intent clearly maps to one command** (e.g. "fix the spacing" → `layout`, "rewrite this error message" → `clarify`, "the colors feel flat" → `colorize`): load that command's reference and proceed as if invoked. If two commands could fit, ask once which.
4. **No clear command match**: general design invocation. Apply the setup steps, the General rules, and the loaded register reference, using the full argument as context.
@@ -161,4 +161,8 @@ If the first word is `craft`, setup still runs first, but [reference/craft.md](r
node .qoder/skills/impeccable/scripts/pin.mjs <pin|unpin> <command>
```
-Valid `<command>` is any command from the table above. Report the script's result concisely. Confirm the new shortcut on success, relay stderr verbatim on error.
\ No newline at end of file
+Valid `<command>` is any command from the table above. Report the script's result concisely. Confirm the new shortcut on success, relay stderr verbatim on error.
+
+## Hooks
+
+`/impeccable hooks <on|off|status|ignore-rule|ignore-file|ignore-value|reset>` manages the design detector hook for this project. The hook auto-runs the detector after direct UI file edits and surfaces findings as system reminders. Full flow is in [reference/hooks.md](reference/hooks.md); load it when the user invokes `/impeccable hooks` with any argument.
\ No newline at end of file
diff --git a/.qoder/skills/impeccable/reference/hooks.md b/.qoder/skills/impeccable/reference/hooks.md
new file mode 100644
index 000000000..a139f51ce
--- /dev/null
+++ b/.qoder/skills/impeccable/reference/hooks.md
@@ -0,0 +1,82 @@
+# /impeccable hooks
+
+Manage the **design detector hook** for the current project.
+
+The hook runs the impeccable design detector on direct file edits to design-relevant files (`.tsx`, `.jsx`, `.html`, `.vue`, `.svelte`, `.astro`, `.css`, `.scss`, `.sass`, `.less`, `.ts`, `.js`). Claude Code and Codex use `PostToolUse` and push a short system reminder into the agent's context after the edit; findings get a correction prompt, pending issues get a re-nudge, and clean UI-ish files get a short ack unless `IMPECCABLE_HOOK_QUIET=1` is set. Plain `.ts` and `.js` files are still scanned, but stay quiet unless the detector finds something. Cursor uses `preToolUse` to block bad proposed writes before they land and stays silent when it allows a clean write.
+
+This command toggles the hook **per project** by editing `.impeccable/hook.json`. Local-only ignore policy lives in `.impeccable/hook.local.json`, which is gitignored. To disable globally, set `IMPECCABLE_HOOK_DISABLED=1` in your shell environment.
+
+Supported harnesses: Claude Code (`.claude/settings.json` in the project), Codex (`.codex/hooks.json` in the project), and Cursor (`.cursor/hooks.json` in the project).
+
+On **Cursor**, `preToolUse` checks proposed Write/Edit/Shell write content and denies only when the real detector finds an issue. The denial message is visible to the agent as the tool error, so the agent can reconsider before the bad write lands.
+
+## Routing
+
+The first argument is the action. Defaults to `status`.
+
+| Action | What it does |
+|---|---|
+| `status` | Print current state, shared/local config paths, ignored rules / files / values, env override. |
+| `on` | Set `enabled: true` in `.impeccable/hook.json`. |
+| `off` | Set `enabled: false` in `.impeccable/hook.json`. |
+| `ignore-rule <id>` | Append `<id>` to `ignoreRules`; for `overused-font`, requires `--all-values`. |
+| `ignore-file <glob>` | Append `<glob>` to `ignoreFiles`. |
+| `ignore-value <id> <value> [--shared] [--reason "..."]` | Append a rule/value suppression to shared `.impeccable/hook.json`. |
+| `ignore-value <id> <value> --local [--reason "..."]` | Append a private rule/value suppression to `.impeccable/hook.local.json`. |
+| `reset` | Delete the project config, dedup cache, and Cursor pending queue. |
+
+## Flow
+
+1. Resolve the action from the user's argument. If no action was given, default to `status`.
+2. Invoke the admin script and pass the user's output through verbatim:
+
+ ```bash
+ node .qoder/skills/impeccable/scripts/hook-admin.mjs <action> [args...]
+ ```
+
+3. If `<action>` is `off`, follow up with a one-line note: "Done. New edits will not trigger the design hook in this project until you run `/impeccable hooks on`."
+4. If `<action>` is `on`, follow up with: "Done. The design hook will fire after the next Edit/Write/MultiEdit on a UI file."
+5. If `<action>` is `ignore-value`, `ignore-file`, or `ignore-rule`, just print the script output. The default scope is shared `.impeccable/hook.json`; add `--local` only when the user explicitly asks for a private exception.
+6. If `<action>` is `status`, just print the script output. Do not add commentary unless the user asked a follow-up question.
+
+## Intentional findings
+
+The hook itself never writes ignore config. Persist an exception only after the user explicitly confirms the flagged issue is intentional, and always go through `hook-admin.mjs`.
+
+Prefer the narrowest exception:
+
+- If the finding line shows an exact `ignore-value` command, run that command. This writes shared `.impeccable/hook.json` by default.
+- For `overused-font`, use `ignore-value` when the user confirms a specific font. Do not use `ignore-rule overused-font` for a specific font.
+- If the finding has no value-specific command, such as `side-tab`, prefer `ignore-file <path>` for the current file.
+- Use `ignore-rule <id>` only when the user asks to suppress that whole rule across the project. For broad overused-font suppression, use `ignore-rule overused-font --all-values` only when the user asks to ignore overused fonts generally.
+- Do not add source comments such as `impeccable: ignore`; inline comments pollute code and are not a supported suppression mechanism.
+
+Example value-specific exception:
+
+```bash
+node .qoder/skills/impeccable/scripts/hook-admin.mjs ignore-value overused-font Inter --shared --reason "User confirmed Inter is intentional"
+```
+
+Example whole-rule font exception:
+
+```bash
+node .qoder/skills/impeccable/scripts/hook-admin.mjs ignore-rule overused-font --all-values --reason "User asked to ignore overused fonts generally"
+```
+
+Example file-scoped exception:
+
+```bash
+node .qoder/skills/impeccable/scripts/hook-admin.mjs ignore-file "src/legacy/Card.tsx"
+```
+
+## Constraints
+
+- Never modify `.impeccable/hook.json` or `.impeccable/hook.local.json` by hand from this command. Always go through `hook-admin.mjs` so writes stay validated and the file shape stays consistent.
+- Do not edit the hook scripts themselves (`hook.mjs`, `hook-lib.mjs`, `hook-before-edit.mjs`) from this flow. Those are skill plumbing.
+- Cursor can block a proposed write when the detector finds a real issue. Claude Code and Codex do not block the edit; they emit a post-edit reminder instead. Disabling stops both blocking and reminders.
+- The hook is bundled with the Impeccable skill and installed through project-local manifests: `.claude/settings.json`, `.codex/hooks.json`, and `.cursor/hooks.json`. On Codex, the user must approve the hook via `/hooks` the first time. On Cursor, confirm hooks are enabled under Settings -> Hooks.
+
+## Failure modes
+
+- If `.impeccable/hook.json` or `.impeccable/hook.local.json` is unreadable or malformed, the hook ignores that file and uses the remaining valid config/defaults. `hook-admin.mjs status` will show malformed files as ignored.
+- If the user asks to "disable the hook" globally, suggest both options: `IMPECCABLE_HOOK_DISABLED=1` env var (one-shot, follows the shell), and `/impeccable hooks off` (persistent for this project, committable).
diff --git a/.qoder/skills/impeccable/scripts/detector/engines/regex/detect-text.mjs b/.qoder/skills/impeccable/scripts/detector/engines/regex/detect-text.mjs
index fd0d9c73f..4c0777c93 100644
--- a/.qoder/skills/impeccable/scripts/detector/engines/regex/detect-text.mjs
+++ b/.qoder/skills/impeccable/scripts/detector/engines/regex/detect-text.mjs
@@ -446,7 +446,7 @@ function detectText(content, filePath, options = {}) {
// Run regex matchers on the full file content (catches Tailwind classes, inline styles)
// Enable block context for CSS files where related properties span multiple lines
- const cssLike = new Set(['.css', '.scss', '.less']);
+ const cssLike = new Set(['.css', '.scss', '.sass', '.less']);
findings.push(...runRegexMatchers(lines, filePath, 0, cssLike.has(ext) || null, {
profile,
phase: 'source',
diff --git a/.qoder/skills/impeccable/scripts/detector/node/file-system.mjs b/.qoder/skills/impeccable/scripts/detector/node/file-system.mjs
index a80250a0e..aaa8c6df7 100644
--- a/.qoder/skills/impeccable/scripts/detector/node/file-system.mjs
+++ b/.qoder/skills/impeccable/scripts/detector/node/file-system.mjs
@@ -11,7 +11,7 @@ const SKIP_DIRS = new Set([
]);
const SCANNABLE_EXTENSIONS = new Set([
- '.html', '.htm', '.css', '.scss', '.less',
+ '.html', '.htm', '.css', '.scss', '.sass', '.less',
'.jsx', '.tsx', '.js', '.ts',
'.vue', '.svelte', '.astro',
]);
diff --git a/.qoder/skills/impeccable/scripts/hook-admin.mjs b/.qoder/skills/impeccable/scripts/hook-admin.mjs
new file mode 100644
index 000000000..86fcfa909
--- /dev/null
+++ b/.qoder/skills/impeccable/scripts/hook-admin.mjs
@@ -0,0 +1,300 @@
+#!/usr/bin/env node
+/**
+ * `/impeccable hooks <on|off|status|reset>` — manage the design hook
+ * via .impeccable/hook.json and .impeccable/hook.local.json in the current
+ * project.
+ *
+ * Usage:
+ * node hook-admin.mjs status # print current state
+ * node hook-admin.mjs on # set enabled: true
+ * node hook-admin.mjs off # set enabled: false
+ * node hook-admin.mjs ignore-rule <rule-id> # append to ignoreRules
+ * node hook-admin.mjs ignore-rule overused-font --all-values
+ * node hook-admin.mjs ignore-file <glob> # append to ignoreFiles
+ * node hook-admin.mjs ignore-value <rule> <value> # append to shared ignoreValues
+ * node hook-admin.mjs ignore-value <rule> <value> --local
+ * node hook-admin.mjs reset # remove all config + cache
+ *
+ * Designed to be invoked by the LLM from the reference/hooks.md flow.
+ * Output is human-readable; the harness will pass it back to the user.
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+
+import {
+ getConfigPath,
+ getLocalConfigPath,
+ getCachePath,
+ getPendingPath,
+ readConfig,
+ DEFAULT_CONFIG,
+ ensureHookGitExcludes,
+ normalizeIgnoreValue,
+ normalizeIgnoreValueEntries,
+} from './hook-lib.mjs';
+
+const ACTIONS = new Set(['status', 'on', 'off', 'ignore-rule', 'ignore-file', 'ignore-value', 'reset']);
+
+function readRawConfigFile(filePath) {
+ if (!fs.existsSync(filePath)) return { exists: false, malformed: false, raw: null };
+ try {
+ return { exists: true, malformed: false, raw: JSON.parse(fs.readFileSync(filePath, 'utf-8')) };
+ } catch {
+ return { exists: true, malformed: true, raw: null };
+ }
+}
+
+function readRawConfig(cwd, opts = {}) {
+ const filePath = opts.local ? getLocalConfigPath(cwd) : getConfigPath(cwd);
+ return readRawConfigFile(filePath).raw;
+}
+
+function writeConfig(cwd, config, opts = {}) {
+ const filePath = opts.local ? getLocalConfigPath(cwd) : getConfigPath(cwd);
+ if (opts.local) ensureHookGitExcludes(cwd);
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
+ fs.writeFileSync(filePath, JSON.stringify(config, null, 2) + '\n');
+ return filePath;
+}
+
+function mergeConfig(existing) {
+ // Persist the full shape so /impeccable hooks edits leave a complete file
+ // for the user to see, not an unhelpful `{"enabled":false}`.
+ const base = existing && typeof existing === 'object' ? existing : {};
+ return {
+ enabled: base.enabled === false ? false : true,
+ ignoreRules: Array.isArray(base.ignoreRules) ? Array.from(new Set(base.ignoreRules.map(String))) : [],
+ ignoreFiles: Array.isArray(base.ignoreFiles) ? Array.from(new Set(base.ignoreFiles.map(String))) : [],
+ ignoreValues: normalizeIgnoreValueEntries(base.ignoreValues || []),
+ limits: {
+ maxFindings: Number.isFinite(base?.limits?.maxFindings) ? base.limits.maxFindings : DEFAULT_CONFIG.limits.maxFindings,
+ maxChars: Number.isFinite(base?.limits?.maxChars) ? base.limits.maxChars : DEFAULT_CONFIG.limits.maxChars,
+ },
+ };
+}
+
+function mergeLocalConfig(existing) {
+ const base = existing && typeof existing === 'object' ? existing : {};
+ const out = {};
+ if (Object.prototype.hasOwnProperty.call(base, 'enabled')) {
+ out.enabled = base.enabled === false ? false : true;
+ }
+ if (Array.isArray(base.ignoreRules)) {
+ out.ignoreRules = Array.from(new Set(base.ignoreRules.map(String)));
+ }
+ if (Array.isArray(base.ignoreFiles)) {
+ out.ignoreFiles = Array.from(new Set(base.ignoreFiles.map(String)));
+ }
+ out.ignoreValues = normalizeIgnoreValueEntries(base.ignoreValues || []);
+ if (base.limits && typeof base.limits === 'object') {
+ const limits = {};
+ if (Number.isFinite(base.limits.maxFindings)) limits.maxFindings = base.limits.maxFindings;
+ if (Number.isFinite(base.limits.maxChars)) limits.maxChars = base.limits.maxChars;
+ if (Object.keys(limits).length) out.limits = limits;
+ }
+ return out;
+}
+
+function statusReport(cwd) {
+ const shared = readRawConfigFile(getConfigPath(cwd));
+ const local = readRawConfigFile(getLocalConfigPath(cwd));
+ const cfg = readConfig(cwd);
+ const envKill = process.env.IMPECCABLE_HOOK_DISABLED;
+ const envState = envKill ? `IMPECCABLE_HOOK_DISABLED=${envKill}` : 'unset';
+ const cfgPath = path.relative(cwd, getConfigPath(cwd)) || '.impeccable/hook.json';
+ const localPath = path.relative(cwd, getLocalConfigPath(cwd)) || '.impeccable/hook.local.json';
+ const cachePath = path.relative(cwd, getCachePath(cwd)) || '.impeccable/hook.cache.json';
+ const fileState = (info, relPath, absent) => {
+ if (info.malformed) return `${relPath} (malformed; ignored)`;
+ if (info.exists) return relPath;
+ return `${relPath} (${absent})`;
+ };
+ const ignoreValues = cfg.ignoreValues.map((entry) => `${entry.rule}=${entry.value}`);
+
+ const lines = [
+ `Impeccable design hook`,
+ ` state: ${cfg.enabled ? 'enabled' : 'disabled'}`,
+ ` shared file: ${fileState(shared, cfgPath, 'using defaults; file not present')}`,
+ ` local file: ${fileState(local, localPath, 'not present')}`,
+ ` ignoreRules: ${cfg.ignoreRules.length ? cfg.ignoreRules.join(', ') : '(none)'}`,
+ ` ignoreFiles: ${cfg.ignoreFiles.length ? cfg.ignoreFiles.join(', ') : '(none)'}`,
+ ` ignoreValues: ${ignoreValues.length ? ignoreValues.join(', ') : '(none)'}`,
+ ` maxFindings: ${cfg.limits.maxFindings}`,
+ ` maxChars: ${cfg.limits.maxChars}`,
+ ` env override: ${envState}`,
+ ` cache file: ${fs.existsSync(getCachePath(cwd)) ? cachePath : `${cachePath} (not present)`}`,
+ ];
+ return lines.join('\n');
+}
+
+function setEnabled(cwd, value) {
+ const config = mergeConfig(readRawConfig(cwd));
+ config.enabled = value;
+ const target = writeConfig(cwd, config);
+ return `Design hook ${value ? 'enabled' : 'disabled'} for this project (wrote ${path.relative(cwd, target) || target}).`;
+}
+
+function normalizeRuleId(rule) {
+ return String(rule || '').trim().toLowerCase();
+}
+
+function parseIgnoreRuleArgs(args) {
+ const positionals = [];
+ let allValues = false;
+
+ for (let i = 0; i < args.length; i++) {
+ const arg = String(args[i] || '');
+ if (arg === '--all-values') {
+ allValues = true;
+ } else if (arg === '--reason') {
+ while (i + 1 < args.length && !String(args[i + 1]).startsWith('--')) i++;
+ } else if (arg.startsWith('--reason=')) {
+ // Accepted for command symmetry; ignoreRules stores rule ids only.
+ } else if (arg.startsWith('--')) {
+ throw new Error(`Unknown ignore-rule flag: ${arg}`);
+ } else {
+ positionals.push(arg);
+ }
+ }
+
+ return {
+ rule: normalizeRuleId(positionals[0]),
+ allValues,
+ };
+}
+
+function addIgnoreRule(cwd, args) {
+ const parsed = parseIgnoreRuleArgs(args);
+ const rule = parsed.rule;
+ if (!rule) throw new Error('Pass a rule id, e.g. /impeccable hooks ignore-rule side-tab');
+ if (rule === 'overused-font' && !parsed.allValues) {
+ throw new Error('overused-font is value-specific by default. Use /impeccable hooks ignore-value overused-font <font> for a confirmed font, or /impeccable hooks ignore-rule overused-font --all-values only when the user asked to ignore overused fonts generally.');
+ }
+ const config = mergeConfig(readRawConfig(cwd));
+ if (!config.ignoreRules.includes(rule)) config.ignoreRules.push(rule);
+ writeConfig(cwd, config);
+ return `Added "${rule}" to ignoreRules. Current: ${config.ignoreRules.join(', ')}`;
+}
+
+function addIgnoreFile(cwd, glob) {
+ if (!glob) throw new Error('Pass a glob, e.g. /impeccable hooks ignore-file "src/legacy/**"');
+ const config = mergeConfig(readRawConfig(cwd));
+ if (!config.ignoreFiles.includes(glob)) config.ignoreFiles.push(glob);
+ writeConfig(cwd, config);
+ return `Added "${glob}" to ignoreFiles. Current: ${config.ignoreFiles.join(', ')}`;
+}
+
+function parseIgnoreValueArgs(args) {
+ const positionals = [];
+ let shared = false;
+ let local = false;
+ let reason = '';
+
+ for (let i = 0; i < args.length; i++) {
+ const arg = args[i];
+ if (arg === '--shared') {
+ shared = true;
+ } else if (arg === '--local') {
+ local = true;
+ } else if (arg === '--reason') {
+ const chunks = [];
+ while (i + 1 < args.length && !String(args[i + 1]).startsWith('--')) {
+ chunks.push(args[++i]);
+ }
+ reason = chunks.join(' ').trim();
+ } else if (String(arg).startsWith('--reason=')) {
+ reason = String(arg).slice('--reason='.length).trim();
+ } else {
+ positionals.push(arg);
+ }
+ }
+
+ const [rule, ...valueParts] = positionals;
+ return {
+ rule: String(rule || '').trim().toLowerCase(),
+ value: normalizeIgnoreValue(valueParts.join(' ')),
+ shared,
+ local,
+ reason,
+ };
+}
+
+function addIgnoreValue(cwd, args) {
+ const parsed = parseIgnoreValueArgs(args);
+ if (!parsed.rule || !parsed.value) {
+ throw new Error('Pass a rule id and value, e.g. /impeccable hooks ignore-value overused-font Inter');
+ }
+
+ if (parsed.shared && parsed.local) {
+ throw new Error('Pass only one scope flag: --shared or --local');
+ }
+
+ const local = parsed.local;
+ const config = local
+ ? mergeLocalConfig(readRawConfig(cwd, { local: true }))
+ : mergeConfig(readRawConfig(cwd, { local: false }));
+ const key = `${parsed.rule}\0${parsed.value}`;
+ const existing = config.ignoreValues.find((entry) => `${entry.rule}\0${entry.value}` === key);
+
+ if (existing) {
+ if (parsed.reason) existing.reason = parsed.reason;
+ } else {
+ const entry = {
+ rule: parsed.rule,
+ value: parsed.value,
+ createdAt: new Date().toISOString(),
+ };
+ if (parsed.reason) entry.reason = parsed.reason;
+ config.ignoreValues.push(entry);
+ }
+
+ const target = writeConfig(cwd, config, { local });
+ const scope = local ? 'local ignoreValues' : 'shared ignoreValues';
+ return `Added ${parsed.rule}=${parsed.value} to ${scope} (${path.relative(cwd, target) || target}).`;
+}
+
+function reset(cwd) {
+ const removed = [];
+ for (const filePath of [getConfigPath(cwd), getLocalConfigPath(cwd), getCachePath(cwd), getPendingPath(cwd)]) {
+ try {
+ if (fs.existsSync(filePath)) {
+ fs.unlinkSync(filePath);
+ removed.push(path.relative(cwd, filePath) || filePath);
+ }
+ } catch { /* ignore */ }
+ }
+ return removed.length
+ ? `Reset design hook config and cache (removed: ${removed.join(', ')}).`
+ : 'No hook config or cache to remove. Already at defaults.';
+}
+
+function main() {
+ const [, , actionArg, ...rest] = process.argv;
+ const action = (actionArg || 'status').toLowerCase();
+ const cwd = process.cwd();
+
+ if (!ACTIONS.has(action)) {
+ process.stderr.write(`Unknown action: ${action}\nValid: ${Array.from(ACTIONS).join(', ')}\n`);
+ process.exit(1);
+ }
+
+ try {
+ let out = '';
+ switch (action) {
+ case 'status': out = statusReport(cwd); break;
+ case 'on': out = setEnabled(cwd, true); break;
+ case 'off': out = setEnabled(cwd, false); break;
+ case 'ignore-rule': out = addIgnoreRule(cwd, rest); break;
+ case 'ignore-file': out = addIgnoreFile(cwd, rest[0]); break;
+ case 'ignore-value': out = addIgnoreValue(cwd, rest); break;
+ case 'reset': out = reset(cwd); break;
+ }
+ process.stdout.write(out + '\n');
+ } catch (err) {
+ process.stderr.write(`Error: ${err.message || err}\n`);
+ process.exit(1);
+ }
+}
+
+main();
diff --git a/.qoder/skills/impeccable/scripts/hook-before-edit.mjs b/.qoder/skills/impeccable/scripts/hook-before-edit.mjs
new file mode 100644
index 000000000..54b2709d2
--- /dev/null
+++ b/.qoder/skills/impeccable/scripts/hook-before-edit.mjs
@@ -0,0 +1,408 @@
+#!/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 shellContent = shellHereDocContent(shellCommand(input));
+ if (shellContent) return shellContent;
+ const copiedContent = shellCopiedFileContent(shellCommand(input), 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 || '';
+}
+
+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 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' });
+});
diff --git a/.qoder/skills/impeccable/scripts/hook-lib.mjs b/.qoder/skills/impeccable/scripts/hook-lib.mjs
new file mode 100644
index 000000000..02199f530
--- /dev/null
+++ b/.qoder/skills/impeccable/scripts/hook-lib.mjs
@@ -0,0 +1,1232 @@
+/**
+ * Shared library for the Impeccable design hook.
+ *
+ * Pure-ish helpers split out from `hook.mjs` so unit tests can exercise
+ * config parsing, finding filtering, dedup, render, and cache logic without
+ * spawning a subprocess. `hook.mjs` itself is the thin stdin/stdout shim.
+ *
+ * Public surface (everything exported is part of the contract):
+ * ENVELOPE_PREFIX, ALLOWED_EXTS, ACK_EXTS, SENSITIVE_PATH, GENERATED_PATH, TRUTHY
+ * truthy(value)
+ * readConfig(cwd) / DEFAULT_CONFIG / getConfigPath(cwd) / getLocalConfigPath(cwd)
+ * normalizeIgnoreValue(value)
+ * readCache(cwd) / persistCache(cwd, cache)
+ * bumpEditCount(cache, sessionId, filePath) -> number
+ * suppressionNotice(filePath)
+ * filterFindings(findings, content, ext, config)
+ * dedupeAgainstCache(findings, cache, sessionId, filePath)
+ * renderTemplate(findings, filePath, config, opts)
+ * renderCleanAck(filePath, opts) / renderPendingAck(filePath, known, opts)
+ * shouldEmitAckForFile(filePath)
+ * writeAuditLog(env, entry)
+ * loadDetector() -> Promise<{ detectText, detectHtml }>
+ * matchesAnyGlob(filePath, globs)
+ * normalizeScanTargets(primaryTargets, projectCwd)
+ * runHook(deps) -> { exitCode, stdout, audit, reason? }
+ *
+ * Design notes:
+ * - All errors are swallowed at the runHook seam. The detector throwing must
+ * never break a turn. See PRD §5 "Failure modes".
+ * - Cache shape is JSON-friendly; we gc the oldest sessions when there are
+ * more than 8 to keep file size predictable across long-lived projects.
+ * - The detector loader looks for `detector/detect-antipatterns.mjs` next to
+ * this file first (built skill layout) and falls back to the repo root's
+ * `cli/engine/detect-antipatterns.mjs` (running from source).
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+import { pathToFileURL, fileURLToPath } from 'node:url';
+
+const __filename = fileURLToPath(import.meta.url);
+const __dirname = path.dirname(__filename);
+
+export const ENVELOPE_PREFIX = '[impeccable@1]';
+
+export const ALLOWED_EXTS = new Set([
+ '.tsx', '.jsx', '.html', '.htm', '.vue', '.svelte', '.astro',
+ '.css', '.scss', '.sass', '.less', '.ts', '.js',
+]);
+
+export const ACK_EXTS = new Set([
+ '.tsx', '.jsx', '.html', '.htm', '.vue', '.svelte', '.astro',
+ '.css', '.scss', '.sass', '.less',
+]);
+
+// Hard-skip regex for sensitive files. Cannot be turned off via config.
+// Match tokenized secret/credential filenames, not UI names such as
+// CredentialForm.tsx, SecretPage.jsx, or secretary-dashboard.vue.
+export const SENSITIVE_PATH = new RegExp([
+ String.raw`(?:^|[/\\])\.env(?:\.|$)`,
+ String.raw`(?:^|[/\\])\.git(?:[/\\]|$)`,
+ String.raw`(?:^|[/\\])id_rsa(?:$|[._-])[^/\\]*$`,
+ String.raw`(?:^|[/\\])[^/\\]*\.pem$`,
+ String.raw`(?:^|[/\\])(?:[^/\\]*[._-])?(?:secret|secrets|credential|credentials)(?=[._-])[^/\\]*\.(?:json|ya?ml|toml|ini|conf|config|env|txt|key|cert|crt|pem|js|ts)$`,
+].join('|'), 'i');
+
+// Hard-skip regex for generated, lock, minified, and build-output paths.
+export const GENERATED_PATH = /(?:\.generated\.[a-z]+$|\.d\.ts$|\.min\.[a-z]+$|[/\\]node_modules[/\\]|[/\\](?:dist|build|out|\.next|\.cache|coverage)[/\\]|[/\\]?[^/\\]+\.lock(?:\.json)?$)/i;
+
+export const TRUTHY = /^(1|true|yes|on)$/i;
+
+export const DEFAULT_CONFIG = Object.freeze({
+ enabled: true,
+ ignoreRules: [],
+ ignoreFiles: [],
+ ignoreValues: [],
+ limits: { maxFindings: 5, maxChars: 8000 },
+});
+
+export const HOOK_LOCAL_IGNORE_PATTERNS = Object.freeze([
+ '.impeccable/hook.cache.json',
+ '.impeccable/hook.pending.json',
+ '.impeccable/hook.local.json',
+]);
+
+const HOOK_IGNORE_MARKER_OPEN = '# impeccable-hook-ignore-start';
+const HOOK_IGNORE_MARKER_CLOSE = '# impeccable-hook-ignore-end';
+const CACHE_MAX_SESSIONS = 8;
+export const EDIT_COUNT_THRESHOLD = 6;
+
+export function truthy(value) {
+ return typeof value === 'string' && TRUTHY.test(value);
+}
+
+function depthIsSet(value) {
+ if (value === undefined || value === null) return false;
+ const text = String(value).trim();
+ if (!text) return false;
+ if (TRUTHY.test(text)) return true;
+ return /^\d+$/.test(text) && Number(text) > 0;
+}
+
+function safeReadJson(filePath) {
+ try {
+ return JSON.parse(fs.readFileSync(filePath, 'utf-8'));
+ } catch {
+ return null;
+ }
+}
+
+export function getConfigPath(cwd) {
+ return path.join(cwd, '.impeccable', 'hook.json');
+}
+
+export function getLocalConfigPath(cwd) {
+ return path.join(cwd, '.impeccable', 'hook.local.json');
+}
+
+export function getCachePath(cwd) {
+ return path.join(cwd, '.impeccable', 'hook.cache.json');
+}
+
+export function getPendingPath(cwd) {
+ return path.join(cwd, '.impeccable', 'hook.pending.json');
+}
+
+export function resolveProjectCwd(event, fallback = process.cwd()) {
+ return event?.cwd
+ || (Array.isArray(event?.workspace_roots) && event.workspace_roots[0])
+ || envProjectDir(fallback)
+ || fallback;
+}
+
+export function readConfig(cwd) {
+ const config = cloneDefaultConfig();
+ applyConfigSource(config, safeReadJson(getConfigPath(cwd)));
+ applyConfigSource(config, safeReadJson(getLocalConfigPath(cwd)));
+ return config;
+}
+
+function numberOr(value, fallback) {
+ return Number.isFinite(value) && value > 0 ? value : fallback;
+}
+
+function cloneDefaultConfig() {
+ return {
+ ...DEFAULT_CONFIG,
+ ignoreRules: [],
+ ignoreFiles: [],
+ ignoreValues: [],
+ limits: { ...DEFAULT_CONFIG.limits },
+ };
+}
+
+function applyConfigSource(config, raw) {
+ if (!raw || typeof raw !== 'object') return config;
+ if (Object.prototype.hasOwnProperty.call(raw, 'enabled')) {
+ config.enabled = raw.enabled === false ? false : true;
+ }
+ if (Array.isArray(raw.ignoreRules)) {
+ config.ignoreRules = uniqueStrings([...config.ignoreRules, ...raw.ignoreRules]);
+ }
+ if (Array.isArray(raw.ignoreFiles)) {
+ config.ignoreFiles = uniqueStrings([...config.ignoreFiles, ...raw.ignoreFiles]);
+ }
+ if (Array.isArray(raw.ignoreValues)) {
+ config.ignoreValues = mergeIgnoreValues(config.ignoreValues, raw.ignoreValues);
+ }
+ if (raw.limits && typeof raw.limits === 'object') {
+ config.limits = {
+ maxFindings: numberOr(raw.limits.maxFindings, config.limits.maxFindings),
+ maxChars: numberOr(raw.limits.maxChars, config.limits.maxChars),
+ };
+ }
+ return config;
+}
+
+function uniqueStrings(values) {
+ return Array.from(new Set(values.map(String)));
+}
+
+export function normalizeIgnoreValue(value) {
+ return String(value || '')
+ .trim()
+ .replace(/^["']|["']$/g, '')
+ .replace(/\+/g, ' ')
+ .replace(/\s+/g, ' ')
+ .toLowerCase();
+}
+
+function normalizeIgnoreRule(rule) {
+ return String(rule || '').trim().toLowerCase();
+}
+
+export function normalizeIgnoreValueEntries(entries) {
+ if (!Array.isArray(entries)) return [];
+ const out = [];
+ for (const entry of entries) {
+ if (!entry || typeof entry !== 'object') continue;
+ const rule = normalizeIgnoreRule(entry.rule);
+ const value = normalizeIgnoreValue(entry.value);
+ if (!rule || !value) continue;
+ const normalized = { rule, value };
+ if (typeof entry.reason === 'string' && entry.reason.trim()) {
+ normalized.reason = entry.reason.trim();
+ }
+ if (typeof entry.createdAt === 'string' && entry.createdAt.trim()) {
+ normalized.createdAt = entry.createdAt.trim();
+ }
+ out.push(normalized);
+ }
+ return out;
+}
+
+function mergeIgnoreValues(existing, incoming) {
+ const map = new Map();
+ for (const entry of normalizeIgnoreValueEntries(existing)) {
+ map.set(`${entry.rule}\0${entry.value}`, entry);
+ }
+ for (const entry of normalizeIgnoreValueEntries(incoming)) {
+ map.set(`${entry.rule}\0${entry.value}`, entry);
+ }
+ return Array.from(map.values());
+}
+
+export function readCache(cwd) {
+ const raw = safeReadJson(getCachePath(cwd));
+ if (!raw || typeof raw !== 'object' || raw.version !== 1) {
+ return { version: 1, sessions: {} };
+ }
+ return {
+ version: 1,
+ sessions: raw.sessions && typeof raw.sessions === 'object' ? raw.sessions : {},
+ };
+}
+
+export function persistCache(cwd, cache) {
+ const sessions = cache.sessions || {};
+ const ids = Object.keys(sessions);
+ if (ids.length > CACHE_MAX_SESSIONS) {
+ // Garbage-collect oldest sessions by updatedAt.
+ const ordered = ids
+ .map((id) => [id, sessions[id]?.updatedAt || 0])
+ .sort((a, b) => b[1] - a[1])
+ .slice(0, CACHE_MAX_SESSIONS);
+ const next = {};
+ for (const [id] of ordered) next[id] = sessions[id];
+ cache = { ...cache, sessions: next };
+ }
+ const target = getCachePath(cwd);
+ try {
+ ensureHookGitExcludes(cwd);
+ fs.mkdirSync(path.dirname(target), { recursive: true });
+ fs.writeFileSync(target, JSON.stringify(cache));
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+export function ensureHookGitExcludes(cwd = process.cwd()) {
+ try {
+ const target = resolveHookGitExcludeTarget(cwd);
+ if (!target) {
+ return { mode: 'none', changed: false, patterns: [...HOOK_LOCAL_IGNORE_PATTERNS] };
+ }
+
+ const patterns = target.patternPrefix
+ ? HOOK_LOCAL_IGNORE_PATTERNS.map((pattern) => `${target.patternPrefix}/${pattern}`)
+ : [...HOOK_LOCAL_IGNORE_PATTERNS];
+ const markerSuffix = target.patternPrefix || '.';
+ const markerOpen = `${HOOK_IGNORE_MARKER_OPEN} ${markerSuffix}`;
+ const markerClose = `${HOOK_IGNORE_MARKER_CLOSE} ${markerSuffix}`;
+ const existing = fs.existsSync(target.path) ? fs.readFileSync(target.path, 'utf-8') : '';
+ const block = [markerOpen, ...patterns, markerClose].join('\n');
+ const markerRe = new RegExp(`${escapeRegExp(markerOpen)}[\\s\\S]*?${escapeRegExp(markerClose)}`);
+
+ let updated;
+ if (markerRe.test(existing)) {
+ updated = existing.replace(markerRe, block);
+ } else {
+ const prefix = existing.length === 0 ? '' : existing.endsWith('\n') ? existing : `${existing}\n`;
+ updated = `${prefix}${prefix.endsWith('\n\n') || prefix === '' ? '' : '\n'}${block}\n`;
+ }
+
+ if (updated !== existing) {
+ fs.mkdirSync(path.dirname(target.path), { recursive: true });
+ fs.writeFileSync(target.path, updated, 'utf-8');
+ }
+
+ return {
+ mode: 'git-info-exclude',
+ file: path.relative(path.resolve(cwd), target.path).split(path.sep).join('/'),
+ changed: updated !== existing,
+ patterns,
+ };
+ } catch {
+ return { mode: 'error', changed: false, patterns: [...HOOK_LOCAL_IGNORE_PATTERNS] };
+ }
+}
+
+function resolveHookGitExcludeTarget(cwd) {
+ const start = path.resolve(cwd);
+ let dir = start;
+ while (true) {
+ const dotGit = path.join(dir, '.git');
+ if (fs.existsSync(dotGit)) {
+ const gitDir = resolveGitDir(dotGit, dir);
+ if (!gitDir) return null;
+ const relPrefix = path.relative(dir, start).split(path.sep).join('/');
+ return {
+ path: path.join(gitDir, 'info', 'exclude'),
+ patternPrefix: relPrefix && relPrefix !== '.' ? relPrefix : '',
+ };
+ }
+ const parent = path.dirname(dir);
+ if (parent === dir) return null;
+ dir = parent;
+ }
+}
+
+function resolveGitDir(dotGit, worktreeDir) {
+ const stat = fs.statSync(dotGit);
+ if (stat.isDirectory()) return dotGit;
+ if (!stat.isFile()) return null;
+
+ const body = fs.readFileSync(dotGit, 'utf-8').trim();
+ const match = body.match(/^gitdir:\s*(.+)$/i);
+ if (!match) return null;
+ return path.isAbsolute(match[1]) ? match[1] : path.resolve(worktreeDir, match[1]);
+}
+
+function escapeRegExp(value) {
+ return String(value).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+}
+
+function ensureSession(cache, sessionId) {
+ if (!cache.sessions[sessionId]) {
+ cache.sessions[sessionId] = { updatedAt: Date.now(), files: {} };
+ }
+ return cache.sessions[sessionId];
+}
+
+function ensureFile(cache, sessionId, filePath) {
+ const session = ensureSession(cache, sessionId);
+ if (!session.files[filePath]) {
+ session.files[filePath] = { editCount: 0, findings: [] };
+ }
+ return session.files[filePath];
+}
+
+export function bumpEditCount(cache, sessionId, filePath) {
+ const fileEntry = ensureFile(cache, sessionId, filePath);
+ fileEntry.editCount = (fileEntry.editCount || 0) + 1;
+ ensureSession(cache, sessionId).updatedAt = Date.now();
+ return fileEntry.editCount;
+}
+
+export function suppressionNotice(filePath) {
+ return `${ENVELOPE_PREFIX} Suppressing further design hints on ${filePath}. More than ${EDIT_COUNT_THRESHOLD} edits in this session reached. Run /impeccable audit to revisit.`;
+}
+
+// Glob → RegExp. Supports `**`, `*`, `?`, and `{a,b}` alternation.
+function globToRegex(glob) {
+ let re = '^';
+ let i = 0;
+ while (i < glob.length) {
+ const c = glob[i];
+ if (c === '*') {
+ if (glob[i + 1] === '*') {
+ re += '.*';
+ i += 2;
+ if (glob[i] === '/') i += 1;
+ } else {
+ re += '[^/]*';
+ i += 1;
+ }
+ } else if (c === '?') {
+ re += '[^/]';
+ i += 1;
+ } else if (c === '{') {
+ const end = glob.indexOf('}', i);
+ if (end === -1) { re += '\\{'; i += 1; continue; }
+ const parts = glob.slice(i + 1, end).split(',').map((p) => p.replace(/[.+^$()|[\]\\]/g, '\\$&'));
+ re += `(?:${parts.join('|')})`;
+ i = end + 1;
+ } else if (/[.+^$()|[\]\\]/.test(c)) {
+ re += `\\${c}`;
+ i += 1;
+ } else {
+ re += c;
+ i += 1;
+ }
+ }
+ re += '$';
+ return new RegExp(re);
+}
+
+export function matchesAnyGlob(filePath, globs) {
+ if (!Array.isArray(globs) || globs.length === 0) return false;
+ const normalized = filePath.split(path.sep).join('/');
+ for (const glob of globs) {
+ try {
+ const re = globToRegex(String(glob));
+ if (re.test(normalized)) return true;
+ // Match against basename too for convenience: `*.generated.tsx` should
+ // catch `src/foo.generated.tsx` without requiring `**/`.
+ const base = normalized.split('/').pop();
+ if (re.test(base)) return true;
+ } catch {
+ /* malformed glob, skip */
+ }
+ }
+ return false;
+}
+
+export function filterFindings(findings, _content, _ext, config) {
+ if (!Array.isArray(findings) || findings.length === 0) return [];
+ const ignoreRules = new Set((config.ignoreRules || []).map((rule) => normalizeIgnoreRule(rule)));
+ const ignoreValues = normalizeIgnoreValueEntries(config.ignoreValues || []);
+ return findings.filter((f) => {
+ if (!f || typeof f !== 'object') return false;
+ if (ignoreRules.has(normalizeIgnoreRule(f.antipattern))) return false;
+ if (isIgnoredFindingValue(f, ignoreValues)) return false;
+ return true;
+ });
+}
+
+function isIgnoredFindingValue(finding, ignoreValues) {
+ if (!Array.isArray(ignoreValues) || ignoreValues.length === 0) return false;
+ const rule = normalizeIgnoreRule(finding.antipattern);
+ const value = extractFindingIgnoreValue(finding);
+ if (!rule || !value) return false;
+ return ignoreValues.some((entry) => entry.rule === rule && entry.value === value);
+}
+
+export function extractFindingIgnoreValue(finding) {
+ if (!finding || typeof finding !== 'object') return '';
+ const rule = normalizeIgnoreRule(finding.antipattern);
+ if (rule !== 'overused-font') return '';
+ return normalizeIgnoreValue(extractFindingIgnoreValueRaw(finding));
+}
+
+function extractFindingIgnoreValueRaw(finding) {
+ const direct = cleanIgnoreValueDisplay(finding.ignoreValue || finding.value || '');
+ if (direct) return direct;
+
+ const candidates = [finding.detail, finding.snippet].filter((v) => typeof v === 'string' && v);
+ for (const text of candidates) {
+ const primary = text.match(/Primary font:\s*([^()\n;]+)/i);
+ if (primary) return cleanIgnoreValueDisplay(primary[1]);
+
+ const family = text.match(/font-family\s*:\s*["']?([^'",;\n]+)/i);
+ if (family) return cleanIgnoreValueDisplay(family[1]);
+
+ const google = text.match(/[?&]family=([^&:;\n]+)/i);
+ if (google) {
+ try {
+ return cleanIgnoreValueDisplay(decodeURIComponent(google[1]));
+ } catch {
+ return cleanIgnoreValueDisplay(google[1]);
+ }
+ }
+ }
+
+ return '';
+}
+
+function cleanIgnoreValueDisplay(value) {
+ return String(value || '')
+ .trim()
+ .replace(/^["']|["']$/g, '')
+ .replace(/\+/g, ' ')
+ .replace(/\s+/g, ' ');
+}
+
+export function dedupeAgainstCache(findings, cache, sessionId, filePath) {
+ if (!Array.isArray(findings) || findings.length === 0) return [];
+ const fileEntry = ensureFile(cache, sessionId, filePath);
+ const known = new Set(fileEntry.findings || []);
+ const fresh = [];
+ for (const f of findings) {
+ const key = `${f.antipattern}:${f.line || 0}`;
+ if (known.has(key)) continue;
+ known.add(key);
+ fresh.push(f);
+ }
+ return fresh;
+}
+
+export function rememberFindings(cache, sessionId, filePath, findings) {
+ const fileEntry = ensureFile(cache, sessionId, filePath);
+ const known = new Set(fileEntry.findings || []);
+ for (const f of findings) known.add(`${f.antipattern}:${f.line || 0}`);
+ fileEntry.findings = Array.from(known);
+ ensureSession(cache, sessionId).updatedAt = Date.now();
+}
+
+export function renderTemplate(findings, filePath, config, opts = {}) {
+ if (!Array.isArray(findings) || findings.length === 0) return '';
+ const limits = config?.limits || DEFAULT_CONFIG.limits;
+ const cap = Math.max(1, limits.maxFindings || DEFAULT_CONFIG.limits.maxFindings);
+ const maxChars = Math.max(500, limits.maxChars || DEFAULT_CONFIG.limits.maxChars);
+
+ const cwd = opts.cwd || process.cwd();
+ const display = relativize(filePath, cwd);
+ const total = findings.length;
+ const shown = findings.slice(0, cap);
+ const remaining = total - shown.length;
+
+ const header = `${ENVELOPE_PREFIX} Required design corrections in ${display} (${total} issue(s)):`;
+ const lines = shown.map((f) => formatFindingLine(f));
+ const more = remaining > 0
+ ? `... and ${remaining} more (see /impeccable audit).`
+ : null;
+ const footer = directiveFooter(display);
+
+ const blocks = [header, ...lines];
+ if (more) blocks.push(more);
+ blocks.push('');
+ blocks.push(footer);
+ let text = blocks.join('\n');
+
+ if (text.length > maxChars) {
+ text = clampToBudget(header, lines, more, footer, maxChars);
+ }
+ return text;
+}
+
+function renderGroupedTemplate(groups, config, opts = {}) {
+ const realGroups = groups.filter((group) => Array.isArray(group.findings) && group.findings.length > 0);
+ if (realGroups.length === 0) return '';
+ if (realGroups.length === 1) {
+ const [group] = realGroups;
+ return renderTemplate(group.findings, group.filePath, config, opts);
+ }
+
+ const limits = config?.limits || DEFAULT_CONFIG.limits;
+ const cap = Math.max(1, limits.maxFindings || DEFAULT_CONFIG.limits.maxFindings);
+ const maxChars = Math.max(500, limits.maxChars || DEFAULT_CONFIG.limits.maxChars);
+ const cwd = opts.cwd || process.cwd();
+ const total = realGroups.reduce((sum, group) => sum + group.findings.length, 0);
+ const header = `${ENVELOPE_PREFIX} Required design corrections across ${realGroups.length} files (${total} issue(s)):`;
+ const lines = [];
+ let shownCount = 0;
+
+ for (const group of realGroups) {
+ const display = relativize(group.filePath, cwd);
+ lines.push(`${display} (${group.findings.length} issue(s)):`);
+ const remainingCap = Math.max(0, cap - shownCount);
+ const shown = group.findings.slice(0, remainingCap);
+ for (const finding of shown) {
+ lines.push(formatFindingLine(finding));
+ }
+ shownCount += shown.length;
+ const hidden = group.findings.length - shown.length;
+ if (hidden > 0) {
+ lines.push(`- ... ${hidden} more in ${display} (see /impeccable audit).`);
+ }
+ }
+
+ const footer = directiveFooter('the affected files', { grouped: true });
+ let text = [header, ...lines, '', footer].join('\n');
+ if (text.length > maxChars) {
+ text = clampGroupedToBudget(header, lines, footer, maxChars);
+ }
+ return text;
+}
+
+function clampGroupedToBudget(header, lines, footer, maxChars) {
+ const assemble = (linesArr, omitted) => [
+ header,
+ ...linesArr,
+ ...(omitted ? ['... and more (see /impeccable audit).'] : []),
+ '',
+ footer,
+ ].join('\n');
+
+ let working = lines.slice();
+ let omitted = false;
+ let assembled = assemble(working, omitted);
+ while (assembled.length > maxChars && working.length > 1) {
+ working.pop();
+ omitted = true;
+ assembled = assemble(working, omitted);
+ }
+ if (assembled.length > maxChars) {
+ assembled = `${assembled.slice(0, maxChars - 1)}…`;
+ }
+ return assembled;
+}
+
+function clampToBudget(header, lines, more, footer, maxChars) {
+ const assemble = (linesArr, moreText) => {
+ const blocks = [header, ...linesArr];
+ if (moreText) blocks.push(moreText);
+ blocks.push('');
+ blocks.push(footer);
+ return blocks.join('\n');
+ };
+
+ let working = lines.slice();
+ let moreText = more;
+ let assembled = assemble(working, moreText);
+ while (assembled.length > maxChars && working.length > 1) {
+ working.pop();
+ moreText = '... and more (see /impeccable audit).';
+ assembled = assemble(working, moreText);
+ }
+ if (assembled.length > maxChars) {
+ assembled = `${assembled.slice(0, maxChars - 1)}…`;
+ }
+ return assembled;
+}
+
+function formatFindingLine(f) {
+ const prefix = f.line && f.line > 0 ? `- L${f.line}` : '-';
+ const desc = (f.description || '').trim();
+ const name = (f.name || '').trim();
+ // Description from the registry already ends in punctuation; join with a
+ // single space. `name` may have a trailing period already, keep it clean.
+ const nameSegment = name ? `${name.replace(/\.+\s*$/, '')}.` : '';
+ const ignoreCommand = formatFindingIgnoreCommand(f);
+ const ignoreSegment = ignoreCommand
+ ? ` If the user explicitly confirms this value is intentional: \`${ignoreCommand}\`.`
+ : '';
+ return `${prefix} [${f.antipattern}] ${nameSegment} ${desc}${ignoreSegment}`.replace(/\s+/g, ' ').trim();
+}
+
+function formatFindingIgnoreCommand(finding) {
+ if (!finding || typeof finding !== 'object') return '';
+ const rule = normalizeIgnoreRule(finding.antipattern);
+ if (!rule) return '';
+ const normalizedValue = extractFindingIgnoreValue(finding);
+ if (!normalizedValue) return '';
+ const value = extractFindingIgnoreValueRaw(finding);
+ const valueArg = quoteCommandArg(value);
+ const reason = quoteCommandArg(`User confirmed ${value} is intentional`);
+ return `/impeccable hooks ignore-value ${rule} ${valueArg} --shared --reason ${reason}`;
+}
+
+function quoteCommandArg(value) {
+ const text = String(value || '').trim();
+ if (/^[A-Za-z0-9._:-]+$/.test(text)) return text;
+ return `"${text.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
+}
+
+function relativize(filePath, cwd) {
+ try {
+ const rel = path.relative(cwd, filePath);
+ if (!rel || rel.startsWith('..')) return filePath;
+ return rel.split(path.sep).join('/');
+ } catch {
+ return filePath;
+ }
+}
+
+// Codex `apply_patch` exposes the raw patch in `tool_input.command`, not
+// `tool_input.file_path`. Claude Code may send both; parse the patch body
+// so we can scan the file(s) the tool actually touched.
+// https://developers.openai.com/codex/hooks#posttooluse
+const APPLY_PATCH_FILE_RE = /^\*\*\* (?:Update|Add) File: (.+)$/gm;
+
+export function parseApplyPatchPaths(command, projectCwd) {
+ if (!command || typeof command !== 'string') return [];
+ const out = [];
+ for (const m of command.matchAll(APPLY_PATCH_FILE_RE)) {
+ let p = (m[1] || '').trim();
+ if (!p) continue;
+ if (!path.isAbsolute(p)) p = path.resolve(projectCwd, p);
+ out.push(p);
+ }
+ return out;
+}
+
+export function resolveTargetFiles(event, projectCwd) {
+ const ti = event?.tool_input;
+ const out = [];
+ const add = (filePath) => {
+ if (typeof filePath !== 'string' || !filePath) return;
+ if (!out.includes(filePath)) out.push(filePath);
+ };
+
+ if (event?.tool_name === 'apply_patch' && ti && typeof ti.command === 'string') {
+ for (const filePath of parseApplyPatchPaths(ti.command, projectCwd)) add(filePath);
+ }
+ if (ti && typeof ti.file_path === 'string' && ti.file_path) {
+ add(ti.file_path);
+ }
+ // Cursor Write / StrReplace use `path`, not `file_path`.
+ if (ti && typeof ti.path === 'string' && ti.path) {
+ add(ti.path);
+ }
+ if (typeof event?.file_path === 'string' && event.file_path) {
+ add(event.file_path);
+ }
+ return out;
+}
+
+export function resolveHarness(env = {}, event = null) {
+ const explicit = env?.IMPECCABLE_HOOK_HARNESS;
+ if (explicit === 'cursor') return 'cursor';
+ if (explicit === 'claude' || explicit === 'codex') return 'claude';
+ if (typeof event?.conversation_id === 'string' && event.conversation_id) return 'cursor';
+ return 'claude';
+}
+
+export function normalizeHookEvent(event, projectCwd, harness = 'claude') {
+ if (!event || typeof event !== 'object' || harness !== 'cursor') return event;
+
+ const cwd = event.cwd
+ || (Array.isArray(event.workspace_roots) && event.workspace_roots[0])
+ || envProjectDir(projectCwd)
+ || projectCwd;
+ const sessionId = event.session_id || event.conversation_id || 'unknown';
+
+ const ti = event.tool_input && typeof event.tool_input === 'object' ? event.tool_input : {};
+ const filePath = ti.file_path || ti.path || event.file_path;
+ if (filePath) {
+ return {
+ ...event,
+ cwd,
+ session_id: sessionId,
+ tool_input: { ...ti, file_path: filePath },
+ };
+ }
+
+ return { ...event, cwd, session_id: sessionId };
+}
+
+function envProjectDir(fallback) {
+ if (typeof process.env.CURSOR_PROJECT_DIR === 'string' && process.env.CURSOR_PROJECT_DIR) {
+ return process.env.CURSOR_PROJECT_DIR;
+ }
+ return fallback;
+}
+
+// UI components often keep slop in a sibling/co-located stylesheet while the
+// JSX edit is what triggered PostToolUse. Scan those styles too so an App.jsx
+// patch doesn't report "clean" while styles.css still has Inter/bounce/etc.
+const UI_CODE_EXTS = new Set(['.jsx', '.tsx', '.vue', '.svelte', '.astro']);
+const STYLE_EXTS = new Set(['.css', '.scss', '.sass', '.less']);
+const CO_SCAN_STYLE_NAMES = [
+ 'styles.css', 'styles.scss', 'styles.sass', 'styles.less',
+ 'index.css', 'index.scss', 'index.sass', 'index.less',
+ 'global.css', 'global.scss', 'global.sass', 'global.less',
+ 'globals.css', 'globals.scss', 'globals.sass', 'globals.less',
+];
+const MAX_SCAN_TARGETS = 6;
+
+const STATIC_STYLE_IMPORT_RE = /import\s+(?:[\w*{}\s,$]+\s+from\s+)?['"]([^'"]+\.(?:css|scss|sass|less))['"]/gi;
+
+function hasPathTraversal(filePath) {
+ return typeof filePath === 'string' && filePath.includes('..');
+}
+
+function isInsideProject(filePath, projectCwd) {
+ if (!filePath || !projectCwd || hasPathTraversal(filePath)) return false;
+ try {
+ const rel = path.relative(projectCwd, filePath);
+ return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));
+ } catch {
+ return false;
+ }
+}
+
+export function parseStaticStyleImports(content, fromFile, projectCwd) {
+ if (!content || typeof content !== 'string') return [];
+ const dir = path.dirname(fromFile);
+ const out = [];
+ for (const m of content.matchAll(STATIC_STYLE_IMPORT_RE)) {
+ let p = (m[1] || '').trim();
+ if (!p) continue;
+ if (p.startsWith('.')) p = path.resolve(dir, p);
+ else if (!path.isAbsolute(p)) p = path.resolve(projectCwd, p);
+ if (!isInsideProject(p, projectCwd)) continue;
+ out.push(p);
+ }
+ return out;
+}
+
+export function coLocatedStylesheets(filePath) {
+ const dir = path.dirname(filePath);
+ const base = path.basename(filePath, path.extname(filePath));
+ const candidates = new Set([
+ path.join(dir, `${base}.css`),
+ path.join(dir, `${base}.module.css`),
+ path.join(dir, `${base}.scss`),
+ path.join(dir, `${base}.module.scss`),
+ path.join(dir, `${base}.sass`),
+ path.join(dir, `${base}.module.sass`),
+ path.join(dir, `${base}.less`),
+ path.join(dir, `${base}.module.less`),
+ ]);
+ for (const name of CO_SCAN_STYLE_NAMES) {
+ candidates.add(path.join(dir, name));
+ }
+ return [...candidates].filter((p) => fs.existsSync(p));
+}
+
+export function normalizeScanTargets(primaryTargets, projectCwd) {
+ if (!Array.isArray(primaryTargets) || primaryTargets.length === 0) return [];
+ const ordered = [];
+ const seen = new Set();
+ const baseCwd = projectCwd || process.cwd();
+ const normalizeTarget = (p) => {
+ // Preserve literal `..` segments so downstream sensitive-path checks
+ // still fire. path.resolve would collapse `/foo/../etc/passwd`.
+ if (hasPathTraversal(p)) return p;
+ return path.isAbsolute(p) ? p : path.resolve(baseCwd, p);
+ };
+ const add = (p) => {
+ if (ordered.length >= MAX_SCAN_TARGETS) return;
+ const abs = normalizeTarget(p);
+ if (seen.has(abs)) return;
+ seen.add(abs);
+ ordered.push(abs);
+ return abs;
+ };
+
+ for (const p of primaryTargets) add(p);
+ return ordered;
+}
+
+export function expandScanTargets(primaryTargets, projectCwd) {
+ const ordered = normalizeScanTargets(primaryTargets, projectCwd);
+ if (ordered.length === 0) return [];
+ const seen = new Set(ordered);
+ const baseCwd = projectCwd || process.cwd();
+ const add = (p) => {
+ if (ordered.length >= MAX_SCAN_TARGETS) return;
+ const abs = hasPathTraversal(p) ? p : (path.isAbsolute(p) ? p : path.resolve(baseCwd, p));
+ if (seen.has(abs)) return;
+ seen.add(abs);
+ ordered.push(abs);
+ return abs;
+ };
+
+ const normalizedPrimaries = [];
+ for (const p of ordered) normalizedPrimaries.push(p);
+
+ for (const p of normalizedPrimaries) {
+ if (ordered.length >= MAX_SCAN_TARGETS) break;
+ if (!isInsideProject(p, baseCwd)) continue;
+ const ext = path.extname(p).toLowerCase();
+ if (STYLE_EXTS.has(ext) || !UI_CODE_EXTS.has(ext)) continue;
+
+ let content = '';
+ try { content = fs.readFileSync(p, 'utf-8'); } catch { /* unreadable primary */ }
+
+ for (const imp of parseStaticStyleImports(content, p, projectCwd)) {
+ add(imp);
+ if (ordered.length >= MAX_SCAN_TARGETS) break;
+ }
+ for (const col of coLocatedStylesheets(p)) {
+ add(col);
+ if (ordered.length >= MAX_SCAN_TARGETS) break;
+ }
+ }
+
+ return ordered;
+}
+
+export function writeAuditLog(env, entry) {
+ const target = env?.IMPECCABLE_HOOK_LOG;
+ if (!target || typeof target !== 'string') return false;
+ try {
+ const expanded = target.startsWith('~/')
+ ? path.join(process.env.HOME || process.env.USERPROFILE || '.', target.slice(2))
+ : target;
+ fs.mkdirSync(path.dirname(expanded), { recursive: true });
+ const line = JSON.stringify({ ts: new Date().toISOString(), ...entry }) + '\n';
+ fs.appendFileSync(expanded, line);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+const DETECTOR_CANDIDATES = [
+ path.join(__dirname, 'detector', 'detect-antipatterns.mjs'),
+ path.join(__dirname, '..', '..', 'cli', 'engine', 'detect-antipatterns.mjs'),
+ path.join(__dirname, '..', '..', '..', 'cli', 'engine', 'detect-antipatterns.mjs'),
+];
+
+let detectorCache = null;
+export async function loadDetector(candidates = DETECTOR_CANDIDATES) {
+ if (detectorCache) return detectorCache;
+ const found = candidates.find((c) => fs.existsSync(c));
+ if (!found) return null;
+ const mod = await import(pathToFileURL(found));
+ detectorCache = { detectText: mod.detectText, detectHtml: mod.detectHtml };
+ return detectorCache;
+}
+
+// For tests: allow injecting a detector implementation.
+export function setDetectorForTesting(impl) {
+ detectorCache = impl;
+}
+
+// ────────────────────────────────────────────────────────────────────────
+// Nudge/steer messages for the no-silent-fires policy.
+//
+// The hook is designed to be a conversational presence: every fire that
+// actually scans a file emits a developer-role message into the model's
+// next turn. Three states map to three templates:
+//
+// 1. **Fresh findings** → `renderTemplate` (existing, imperative).
+// 2. **Pending findings** → `renderPendingAck` (re-nudge for issues the
+// model was already told about in this
+// session but hasn't fixed yet).
+// 3. **Truly clean** → `renderCleanAck` (short positive nudge that
+// keeps the design discipline in context).
+//
+// All three are short (≤ ~40 tokens each) so the cumulative cost stays
+// bounded across a long active editing session. Users who explicitly want
+// silence-on-clean can set `IMPECCABLE_HOOK_QUIET=1` — runHook checks that
+// env before emitting #2 or #3.
+//
+// Why not stay silent on dedup-clean? Earlier versions did. The model
+// quickly forgets the prior reminder once tool output scrolls past it, so
+// re-nudging on the same file with a short "still pending" line keeps the
+// pressure on. The wording deliberately points back to "earlier this
+// session" so the model knows it's a re-mind, not a new finding.
+// ────────────────────────────────────────────────────────────────────────
+
+const STEER_LINE = 'Keep typography hierarchy, spacing rhythm, and color contrast intentional on the next change.';
+
+export function renderCleanAck(filePath, opts = {}) {
+ const cwd = opts.cwd || process.cwd();
+ const display = relativize(filePath, cwd);
+ return `${ENVELOPE_PREFIX} Design hook scanned ${display}. No anti-patterns. ${STEER_LINE}`;
+}
+
+export function renderPendingAck(filePath, knownFindings, opts = {}) {
+ const cwd = opts.cwd || process.cwd();
+ const display = relativize(filePath, cwd);
+ const count = knownFindings.length;
+ // `knownFindings` here are the cache strings like "side-tab:3".
+ const sample = knownFindings.slice(0, 3).join(', ');
+ const more = count > 3 ? `, +${count - 3} more` : '';
+ return `${ENVELOPE_PREFIX} Design hook scanned ${display}. Still has ${count} issue(s) flagged earlier this session (${sample}${more}). Address them before finalizing — the previous reminder still applies.`;
+}
+
+export function shouldEmitAckForFile(filePath) {
+ return ACK_EXTS.has(path.extname(String(filePath || '')).toLowerCase());
+}
+
+// The directive footer is the part of the hook output that steers model
+// behavior. Three intentional moves:
+// 1. **Imperative, not advisory.** "Fix these..." beats "Consider
+// revising..." which the model treats as a soft suggestion it can
+// override when the user asked for any kind of throwaway / demo UI.
+// 2. **Explicit exception clause.** Without it, the model will try to
+// "fix" intentional bad fixtures, anti-pattern examples in docs, or
+// test cases. Naming the exception inline beats hoping the model
+// infers it from context.
+// 3. **Acknowledgement instruction.** Hook output is injected as
+// developer-role context, not a chat turn, so the user never sees the
+// raw envelope. Asking the model to surface the fix in its reply is
+// the cheapest way to make the feedback loop visible to the user.
+function directiveFooter(display, opts = {}) {
+ const ignoreFileCommand = `/impeccable hooks ignore-file ${quoteCommandArg(display)}`;
+ const fileIgnoreGuidance = opts.grouped
+ ? 'run `/impeccable hooks ignore-file <path>` for the specific file'
+ : `run \`${ignoreFileCommand}\``;
+ return [
+ 'Fix these in your next reply before finalizing. Acknowledge what you changed so the user sees the correction.',
+ '',
+ 'Skip the fix only if the user explicitly asked for an intentionally bad UI, an anti-pattern example, a test fixture, or documentation of bad design. In that case, say so and continue.',
+ '',
+ `Do not add source comments such as \`impeccable: ignore\`; those pollute the code and do not suppress hook findings. Do not add hook ignores unless the user explicitly confirms the finding is intentional. Prefer the narrowest persisted exception: run the exact \`/impeccable hooks ignore-value ... --shared\` command shown next to a value-specific finding. For \`overused-font\`, use \`ignore-value\` for a specific font and use \`/impeccable hooks ignore-rule overused-font --all-values\` only when the user asks to ignore overused fonts generally. For file-specific findings without an ignore-value command, ${fileIgnoreGuidance}; use \`/impeccable hooks ignore-rule <id>\` only when the user asks to suppress the whole non-value-specific rule. Run /impeccable audit for the full pass.`,
+ ].join('\n');
+}
+
+/**
+ * Run the hook with explicit dependencies. Returns a result object:
+ * { exitCode, stdout, audit, reason? }
+ *
+ * Never throws. All errors are converted to `exitCode: 0` + audit entry.
+ */
+export async function runHook({ stdinJson, env = {}, cwd = process.cwd(), now = Date.now, detector } = {}) {
+ const audit = { ts: new Date(now()).toISOString(), event: 'PostToolUse' };
+ const result = (extra) => ({ exitCode: 0, stdout: '', audit: { ...audit, ...extra } });
+
+ try {
+ // Re-entrancy guard.
+ if (depthIsSet(env.IMPECCABLE_HOOK_DEPTH) || depthIsSet(env.CLAUDE_HOOK_DEPTH)) {
+ return result({ reentrant: true, durationMs: 0 });
+ }
+
+ if (truthy(env.IMPECCABLE_HOOK_DISABLED)) {
+ return result({ skipped: 'env-disabled', durationMs: 0 });
+ }
+
+ const started = Date.now();
+
+ let event;
+ try {
+ event = typeof stdinJson === 'string' ? JSON.parse(stdinJson) : stdinJson;
+ } catch {
+ return result({ skipped: 'stdin-malformed', durationMs: Date.now() - started });
+ }
+ if (!event || typeof event !== 'object') {
+ return result({ skipped: 'stdin-empty', durationMs: Date.now() - started });
+ }
+
+ const harness = resolveHarness(env, event);
+ event = normalizeHookEvent(event, cwd, harness);
+ audit.harness = harness;
+
+ const projectCwd = event.cwd || cwd;
+ const primaryFiles = normalizeScanTargets(resolveTargetFiles(event, projectCwd), projectCwd);
+ const primaryFileSet = new Set(primaryFiles);
+ const targetFiles = expandScanTargets(primaryFiles, projectCwd);
+ audit.session = event.session_id || null;
+ if (event.tool_name) audit.tool = event.tool_name;
+
+ if (targetFiles.length === 0) {
+ return result({ skipped: 'no-file-path', durationMs: Date.now() - started });
+ }
+
+ const config = readConfig(projectCwd);
+ if (config.enabled === false) {
+ return result({ skipped: 'config-disabled', durationMs: Date.now() - started });
+ }
+
+ const cache = readCache(projectCwd);
+ const sessionId = event.session_id || 'unknown';
+ const det = detector || await loadDetector();
+ if (!det || typeof det.detectText !== 'function') {
+ persistCache(projectCwd, cache);
+ return result({ skipped: 'detector-missing', durationMs: Date.now() - started });
+ }
+
+ let pendingWinner = null;
+ let cleanWinner = null;
+ const freshGroups = [];
+ let suppressionWinner = null;
+ let detectorThrewAny = false;
+ let lastSkip = 'no-scannable-file';
+ let suppressedHit = false;
+
+ for (const filePath of targetFiles) {
+ audit.file = filePath;
+
+ if (hasPathTraversal(filePath) || SENSITIVE_PATH.test(filePath)) {
+ lastSkip = 'sensitive';
+ continue;
+ }
+ if (GENERATED_PATH.test(filePath)) {
+ lastSkip = 'generated';
+ continue;
+ }
+
+ const ext = path.extname(filePath).toLowerCase();
+ audit.ext = ext;
+ if (!ALLOWED_EXTS.has(ext)) {
+ lastSkip = 'extension';
+ continue;
+ }
+
+ const relForMatch = relativize(filePath, projectCwd);
+ if (matchesAnyGlob(relForMatch, config.ignoreFiles) || matchesAnyGlob(filePath, config.ignoreFiles)) {
+ lastSkip = 'config-ignore-file';
+ continue;
+ }
+ if (!fs.existsSync(filePath)) {
+ lastSkip = 'file-missing';
+ continue;
+ }
+
+ if (primaryFileSet.has(filePath)) {
+ const editCount = bumpEditCount(cache, sessionId, filePath);
+ audit.editCount = editCount;
+
+ if (editCount > EDIT_COUNT_THRESHOLD) {
+ const wasJustCrossed = editCount === EDIT_COUNT_THRESHOLD + 1;
+ if (wasJustCrossed && !suppressionWinner) {
+ suppressionWinner = { filePath };
+ }
+ lastSkip = 'suppressed';
+ suppressedHit = true;
+ continue;
+ }
+ }
+
+ const content = fs.readFileSync(filePath, 'utf-8');
+ let findings;
+ let detectorThrew = false;
+ if ((ext === '.html' || ext === '.htm') && typeof det.detectHtml === 'function') {
+ try { findings = await det.detectHtml(filePath); } catch { findings = []; detectorThrew = true; }
+ } else {
+ try { findings = await det.detectText(content, filePath); } catch { findings = []; detectorThrew = true; }
+ }
+
+ const filtered = filterFindings(findings || [], content, ext, config);
+ const fresh = dedupeAgainstCache(filtered, cache, sessionId, filePath);
+ audit.findings = (findings || []).length;
+ audit.freshFindings = fresh.length;
+
+ if (fresh.length > 0) {
+ rememberFindings(cache, sessionId, filePath, fresh);
+ freshGroups.push({ filePath, findings: fresh });
+ continue;
+ }
+
+ if (detectorThrew) {
+ detectorThrewAny = true;
+ continue;
+ }
+
+ if (filtered.length > 0 && !pendingWinner) {
+ const known = (ensureFile(cache, sessionId, filePath).findings || []).slice();
+ pendingWinner = { filePath, known };
+ } else if (filtered.length === 0 && !cleanWinner) {
+ cleanWinner = { filePath };
+ }
+ }
+
+ persistCache(projectCwd, cache);
+
+ if (freshGroups.length > 0) {
+ const firstGroup = freshGroups[0];
+ const text = renderGroupedTemplate(freshGroups, config, { cwd: projectCwd });
+ const allFindings = freshGroups.flatMap((group) => group.findings);
+ return {
+ exitCode: 0,
+ stdout: payload(text, 'PostToolUse', harness),
+ emission: {
+ kind: 'fresh',
+ file: firstGroup.filePath,
+ findings: firstGroup.findings,
+ groups: freshGroups,
+ },
+ audit: {
+ ...audit,
+ file: firstGroup.filePath,
+ emitted: true,
+ freshFiles: freshGroups.length,
+ freshFindings: allFindings.length,
+ chars: text.length,
+ durationMs: Date.now() - started,
+ },
+ };
+ }
+
+ if (detectorThrewAny && !pendingWinner && !cleanWinner) {
+ return result({ emitted: false, error: 'detector-threw', durationMs: Date.now() - started });
+ }
+
+ if (truthy(env.IMPECCABLE_HOOK_QUIET)) {
+ return result({ emitted: false, quiet: true, durationMs: Date.now() - started });
+ }
+
+ if (pendingWinner && shouldEmitAckForFile(pendingWinner.filePath)) {
+ const text = renderPendingAck(pendingWinner.filePath, pendingWinner.known, { cwd: projectCwd });
+ return {
+ exitCode: 0,
+ stdout: payload(text, 'PostToolUse', harness),
+ emission: { kind: 'pending', file: pendingWinner.filePath, known: pendingWinner.known },
+ audit: {
+ ...audit,
+ file: pendingWinner.filePath,
+ emitted: true,
+ kind: 'pending',
+ pending: pendingWinner.known.length,
+ chars: text.length,
+ durationMs: Date.now() - started,
+ },
+ };
+ }
+
+ if (suppressionWinner) {
+ const text = suppressionNotice(relativize(suppressionWinner.filePath, projectCwd));
+ return {
+ exitCode: 0,
+ stdout: payload(text, 'PostToolUse', harness),
+ emission: { kind: 'suppression', file: suppressionWinner.filePath },
+ audit: {
+ ...audit,
+ file: suppressionWinner.filePath,
+ suppressed: true,
+ emitted: true,
+ durationMs: Date.now() - started,
+ },
+ };
+ }
+
+ if (cleanWinner && shouldEmitAckForFile(cleanWinner.filePath)) {
+ const text = renderCleanAck(cleanWinner.filePath, { cwd: projectCwd });
+ return {
+ exitCode: 0,
+ stdout: payload(text, 'PostToolUse', harness),
+ emission: { kind: 'clean', file: cleanWinner.filePath },
+ audit: {
+ ...audit,
+ file: cleanWinner.filePath,
+ emitted: true,
+ kind: 'clean',
+ chars: text.length,
+ durationMs: Date.now() - started,
+ },
+ };
+ }
+
+ if (pendingWinner || cleanWinner) {
+ return result({ emitted: false, skipped: 'non-ui-ack', durationMs: Date.now() - started });
+ }
+
+ if (suppressedHit) {
+ return result({ suppressed: true, emitted: false, durationMs: Date.now() - started });
+ }
+
+ return result({ skipped: lastSkip, durationMs: Date.now() - started });
+ } catch (err) {
+ return {
+ exitCode: 0,
+ stdout: '',
+ audit: { ...audit, error: String(err && err.message ? err.message : err) },
+ };
+ }
+}
+
+export function payload(text, eventName = 'PostToolUse', harness = 'claude') {
+ if (harness === 'cursor') {
+ return JSON.stringify({ additional_context: text });
+ }
+ return JSON.stringify({
+ hookSpecificOutput: { hookEventName: eventName, additionalContext: text },
+ });
+}
diff --git a/.qoder/skills/impeccable/scripts/hook.mjs b/.qoder/skills/impeccable/scripts/hook.mjs
new file mode 100644
index 000000000..b862f8033
--- /dev/null
+++ b/.qoder/skills/impeccable/scripts/hook.mjs
@@ -0,0 +1,61 @@
+#!/usr/bin/env node
+/**
+ * Impeccable design hook — PostToolUse entry point.
+ *
+ * Reads the Claude Code / Codex / Cursor hook event from stdin, runs the design
+ * detector against the touched file, and emits a system reminder via
+ * `hookSpecificOutput.additionalContext` when findings exist.
+ *
+ * Contract: never break a turn. Always exit 0. Clean files emit a small ack
+ * unless quiet mode is enabled.
+ *
+ * Most logic lives in `hook-lib.mjs` so it is unit-testable without a
+ * subprocess. This file is the thin stdin/stdout adapter.
+ */
+
+import { runHook, 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');
+}
+
+async function main() {
+ // Snapshot the inherited env FIRST so the re-entrancy guard checks the
+ // parent's value, not the value we are about to export for any child
+ // processes the hook might ever spawn.
+ const inheritedEnv = { ...process.env };
+ process.env.IMPECCABLE_HOOK_DEPTH = process.env.IMPECCABLE_HOOK_DEPTH || '1';
+
+ let stdinJson = '';
+ try { stdinJson = await readStdin(); } catch { /* fall through */ }
+
+ const result = await runHook({
+ stdinJson,
+ env: inheritedEnv,
+ cwd: process.cwd(),
+ });
+
+ writeAuditLog(process.env, result.audit);
+
+ if (result.stdout) process.stdout.write(result.stdout);
+ process.exit(result.exitCode || 0);
+}
+
+main().catch((err) => {
+ // Last-ditch: never break the agent's turn even if something we did not
+ // anticipate goes wrong. Audit-log the failure if logging is enabled.
+ try {
+ writeAuditLog(process.env, {
+ ts: new Date().toISOString(),
+ event: 'PostToolUse',
+ error: String(err && err.message ? err.message : err),
+ });
+ } catch { /* swallow */ }
+ if (process.env.IMPECCABLE_HOOK_DEBUG) {
+ process.stderr.write(`[impeccable-hook] ${err}\n`);
+ }
+ process.exit(0);
+});
diff --git a/.qoder/skills/impeccable/scripts/live-inject.mjs b/.qoder/skills/impeccable/scripts/live-inject.mjs
index 4e5c5dc0a..69ce530c1 100644
--- a/.qoder/skills/impeccable/scripts/live-inject.mjs
+++ b/.qoder/skills/impeccable/scripts/live-inject.mjs
@@ -32,6 +32,8 @@ const IGNORE_MARKER_CLOSE = '# impeccable-live-ignore-end';
export const LIVE_IGNORE_PATTERNS = Object.freeze([
'.impeccable/hook.cache.json',
+ '.impeccable/hook.pending.json',
+ '.impeccable/hook.local.json',
'.impeccable/live/server.json',
'.impeccable/live/sessions/',
'.impeccable/live/previews/',
diff --git a/.rovodev/skills/impeccable/SKILL.md b/.rovodev/skills/impeccable/SKILL.md
index 85feec207..d36116d63 100644
--- a/.rovodev/skills/impeccable/SKILL.md
+++ b/.rovodev/skills/impeccable/SKILL.md
@@ -126,7 +126,7 @@ If someone could look at this interface and say "AI made that" without doubt, it
| `optimize [target]` | Fix | Diagnose and fix UI performance | [reference/optimize.md](reference/optimize.md) |
| `live` | Iterate | Visual variant mode: pick elements in the browser, generate alternatives | [reference/live.md](reference/live.md) |
-Plus two management commands: `pin <command>` and `unpin <command>`, detailed below.
+Plus three management commands: `pin <command>`, `unpin <command>`, and `hooks <on|off|status|...>`, detailed below.
### Routing rules
@@ -143,7 +143,7 @@ Plus two management commands: `pin <command>` and `unpin <command>`, detailed be
**If `scan.targets` is non-empty, run `node .rovodev/skills/impeccable/scripts/detect.mjs --json <scan.targets joined by spaces>` once** (the bundled detector over local files: no network, no npx). `scan.via` tells you what they are: `git-changes` (the markup/style files in your dirty tree, the most relevant set), `source-dir` (e.g. `src`, `app`), `html`, or `root`. Fold the hits into your picks: many quality / contrast hits → `audit` or `polish`; a specific slop family → the matching command (gradient text or eyebrows → `quieter` / `typeset`, flat or gray palette → `colorize`, and so on). It's a real, current signal that beats guessing. If detect errors or the tree is large and slow, skip it and recommend the user run `audit` themselves; never block the suggestion on it.
Keep it to 2-3 pointed picks with the exact command to type. The menu stays the fallback; the recommendation is the lede.
-2. **First word matches a command**: load its reference file and follow its instructions. Everything after the command name is the target.
+2. **First word matches a command** (table above OR `pin` / `unpin` / `hooks`): load its reference file and follow its instructions. Everything after the command name is the target.
3. **First word doesn't match, but the intent clearly maps to one command** (e.g. "fix the spacing" → `layout`, "rewrite this error message" → `clarify`, "the colors feel flat" → `colorize`): load that command's reference and proceed as if invoked. If two commands could fit, ask once which.
4. **No clear command match**: general design invocation. Apply the setup steps, the General rules, and the loaded register reference, using the full argument as context.
@@ -161,4 +161,8 @@ If the first word is `craft`, setup still runs first, but [reference/craft.md](r
node .rovodev/skills/impeccable/scripts/pin.mjs <pin|unpin> <command>
```
-Valid `<command>` is any command from the table above. Report the script's result concisely. Confirm the new shortcut on success, relay stderr verbatim on error.
\ No newline at end of file
+Valid `<command>` is any command from the table above. Report the script's result concisely. Confirm the new shortcut on success, relay stderr verbatim on error.
+
+## Hooks
+
+`/impeccable hooks <on|off|status|ignore-rule|ignore-file|ignore-value|reset>` manages the design detector hook for this project. The hook auto-runs the detector after direct UI file edits and surfaces findings as system reminders. Full flow is in [reference/hooks.md](reference/hooks.md); load it when the user invokes `/impeccable hooks` with any argument.
\ No newline at end of file
diff --git a/.rovodev/skills/impeccable/reference/hooks.md b/.rovodev/skills/impeccable/reference/hooks.md
new file mode 100644
index 000000000..1a6a54caa
--- /dev/null
+++ b/.rovodev/skills/impeccable/reference/hooks.md
@@ -0,0 +1,82 @@
+# /impeccable hooks
+
+Manage the **design detector hook** for the current project.
+
+The hook runs the impeccable design detector on direct file edits to design-relevant files (`.tsx`, `.jsx`, `.html`, `.vue`, `.svelte`, `.astro`, `.css`, `.scss`, `.sass`, `.less`, `.ts`, `.js`). Claude Code and Codex use `PostToolUse` and push a short system reminder into the agent's context after the edit; findings get a correction prompt, pending issues get a re-nudge, and clean UI-ish files get a short ack unless `IMPECCABLE_HOOK_QUIET=1` is set. Plain `.ts` and `.js` files are still scanned, but stay quiet unless the detector finds something. Cursor uses `preToolUse` to block bad proposed writes before they land and stays silent when it allows a clean write.
+
+This command toggles the hook **per project** by editing `.impeccable/hook.json`. Local-only ignore policy lives in `.impeccable/hook.local.json`, which is gitignored. To disable globally, set `IMPECCABLE_HOOK_DISABLED=1` in your shell environment.
+
+Supported harnesses: Claude Code (`.claude/settings.json` in the project), Codex (`.codex/hooks.json` in the project), and Cursor (`.cursor/hooks.json` in the project).
+
+On **Cursor**, `preToolUse` checks proposed Write/Edit/Shell write content and denies only when the real detector finds an issue. The denial message is visible to the agent as the tool error, so the agent can reconsider before the bad write lands.
+
+## Routing
+
+The first argument is the action. Defaults to `status`.
+
+| Action | What it does |
+|---|---|
+| `status` | Print current state, shared/local config paths, ignored rules / files / values, env override. |
+| `on` | Set `enabled: true` in `.impeccable/hook.json`. |
+| `off` | Set `enabled: false` in `.impeccable/hook.json`. |
+| `ignore-rule <id>` | Append `<id>` to `ignoreRules`; for `overused-font`, requires `--all-values`. |
+| `ignore-file <glob>` | Append `<glob>` to `ignoreFiles`. |
+| `ignore-value <id> <value> [--shared] [--reason "..."]` | Append a rule/value suppression to shared `.impeccable/hook.json`. |
+| `ignore-value <id> <value> --local [--reason "..."]` | Append a private rule/value suppression to `.impeccable/hook.local.json`. |
+| `reset` | Delete the project config, dedup cache, and Cursor pending queue. |
+
+## Flow
+
+1. Resolve the action from the user's argument. If no action was given, default to `status`.
+2. Invoke the admin script and pass the user's output through verbatim:
+
+ ```bash
+ node .rovodev/skills/impeccable/scripts/hook-admin.mjs <action> [args...]
+ ```
+
+3. If `<action>` is `off`, follow up with a one-line note: "Done. New edits will not trigger the design hook in this project until you run `/impeccable hooks on`."
+4. If `<action>` is `on`, follow up with: "Done. The design hook will fire after the next Edit/Write/MultiEdit on a UI file."
+5. If `<action>` is `ignore-value`, `ignore-file`, or `ignore-rule`, just print the script output. The default scope is shared `.impeccable/hook.json`; add `--local` only when the user explicitly asks for a private exception.
+6. If `<action>` is `status`, just print the script output. Do not add commentary unless the user asked a follow-up question.
+
+## Intentional findings
+
+The hook itself never writes ignore config. Persist an exception only after the user explicitly confirms the flagged issue is intentional, and always go through `hook-admin.mjs`.
+
+Prefer the narrowest exception:
+
+- If the finding line shows an exact `ignore-value` command, run that command. This writes shared `.impeccable/hook.json` by default.
+- For `overused-font`, use `ignore-value` when the user confirms a specific font. Do not use `ignore-rule overused-font` for a specific font.
+- If the finding has no value-specific command, such as `side-tab`, prefer `ignore-file <path>` for the current file.
+- Use `ignore-rule <id>` only when the user asks to suppress that whole rule across the project. For broad overused-font suppression, use `ignore-rule overused-font --all-values` only when the user asks to ignore overused fonts generally.
+- Do not add source comments such as `impeccable: ignore`; inline comments pollute code and are not a supported suppression mechanism.
+
+Example value-specific exception:
+
+```bash
+node .rovodev/skills/impeccable/scripts/hook-admin.mjs ignore-value overused-font Inter --shared --reason "User confirmed Inter is intentional"
+```
+
+Example whole-rule font exception:
+
+```bash
+node .rovodev/skills/impeccable/scripts/hook-admin.mjs ignore-rule overused-font --all-values --reason "User asked to ignore overused fonts generally"
+```
+
+Example file-scoped exception:
+
+```bash
+node .rovodev/skills/impeccable/scripts/hook-admin.mjs ignore-file "src/legacy/Card.tsx"
+```
+
+## Constraints
+
+- Never modify `.impeccable/hook.json` or `.impeccable/hook.local.json` by hand from this command. Always go through `hook-admin.mjs` so writes stay validated and the file shape stays consistent.
+- Do not edit the hook scripts themselves (`hook.mjs`, `hook-lib.mjs`, `hook-before-edit.mjs`) from this flow. Those are skill plumbing.
+- Cursor can block a proposed write when the detector finds a real issue. Claude Code and Codex do not block the edit; they emit a post-edit reminder instead. Disabling stops both blocking and reminders.
+- The hook is bundled with the Impeccable skill and installed through project-local manifests: `.claude/settings.json`, `.codex/hooks.json`, and `.cursor/hooks.json`. On Codex, the user must approve the hook via `/hooks` the first time. On Cursor, confirm hooks are enabled under Settings -> Hooks.
+
+## Failure modes
+
+- If `.impeccable/hook.json` or `.impeccable/hook.local.json` is unreadable or malformed, the hook ignores that file and uses the remaining valid config/defaults. `hook-admin.mjs status` will show malformed files as ignored.
+- If the user asks to "disable the hook" globally, suggest both options: `IMPECCABLE_HOOK_DISABLED=1` env var (one-shot, follows the shell), and `/impeccable hooks off` (persistent for this project, committable).
diff --git a/.rovodev/skills/impeccable/scripts/detector/engines/regex/detect-text.mjs b/.rovodev/skills/impeccable/scripts/detector/engines/regex/detect-text.mjs
index fd0d9c73f..4c0777c93 100644
--- a/.rovodev/skills/impeccable/scripts/detector/engines/regex/detect-text.mjs
+++ b/.rovodev/skills/impeccable/scripts/detector/engines/regex/detect-text.mjs
@@ -446,7 +446,7 @@ function detectText(content, filePath, options = {}) {
// Run regex matchers on the full file content (catches Tailwind classes, inline styles)
// Enable block context for CSS files where related properties span multiple lines
- const cssLike = new Set(['.css', '.scss', '.less']);
+ const cssLike = new Set(['.css', '.scss', '.sass', '.less']);
findings.push(...runRegexMatchers(lines, filePath, 0, cssLike.has(ext) || null, {
profile,
phase: 'source',
diff --git a/.rovodev/skills/impeccable/scripts/detector/node/file-system.mjs b/.rovodev/skills/impeccable/scripts/detector/node/file-system.mjs
index a80250a0e..aaa8c6df7 100644
--- a/.rovodev/skills/impeccable/scripts/detector/node/file-system.mjs
+++ b/.rovodev/skills/impeccable/scripts/detector/node/file-system.mjs
@@ -11,7 +11,7 @@ const SKIP_DIRS = new Set([
]);
const SCANNABLE_EXTENSIONS = new Set([
- '.html', '.htm', '.css', '.scss', '.less',
+ '.html', '.htm', '.css', '.scss', '.sass', '.less',
'.jsx', '.tsx', '.js', '.ts',
'.vue', '.svelte', '.astro',
]);
diff --git a/.rovodev/skills/impeccable/scripts/hook-admin.mjs b/.rovodev/skills/impeccable/scripts/hook-admin.mjs
new file mode 100644
index 000000000..86fcfa909
--- /dev/null
+++ b/.rovodev/skills/impeccable/scripts/hook-admin.mjs
@@ -0,0 +1,300 @@
+#!/usr/bin/env node
+/**
+ * `/impeccable hooks <on|off|status|reset>` — manage the design hook
+ * via .impeccable/hook.json and .impeccable/hook.local.json in the current
+ * project.
+ *
+ * Usage:
+ * node hook-admin.mjs status # print current state
+ * node hook-admin.mjs on # set enabled: true
+ * node hook-admin.mjs off # set enabled: false
+ * node hook-admin.mjs ignore-rule <rule-id> # append to ignoreRules
+ * node hook-admin.mjs ignore-rule overused-font --all-values
+ * node hook-admin.mjs ignore-file <glob> # append to ignoreFiles
+ * node hook-admin.mjs ignore-value <rule> <value> # append to shared ignoreValues
+ * node hook-admin.mjs ignore-value <rule> <value> --local
+ * node hook-admin.mjs reset # remove all config + cache
+ *
+ * Designed to be invoked by the LLM from the reference/hooks.md flow.
+ * Output is human-readable; the harness will pass it back to the user.
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+
+import {
+ getConfigPath,
+ getLocalConfigPath,
+ getCachePath,
+ getPendingPath,
+ readConfig,
+ DEFAULT_CONFIG,
+ ensureHookGitExcludes,
+ normalizeIgnoreValue,
+ normalizeIgnoreValueEntries,
+} from './hook-lib.mjs';
+
+const ACTIONS = new Set(['status', 'on', 'off', 'ignore-rule', 'ignore-file', 'ignore-value', 'reset']);
+
+function readRawConfigFile(filePath) {
+ if (!fs.existsSync(filePath)) return { exists: false, malformed: false, raw: null };
+ try {
+ return { exists: true, malformed: false, raw: JSON.parse(fs.readFileSync(filePath, 'utf-8')) };
+ } catch {
+ return { exists: true, malformed: true, raw: null };
+ }
+}
+
+function readRawConfig(cwd, opts = {}) {
+ const filePath = opts.local ? getLocalConfigPath(cwd) : getConfigPath(cwd);
+ return readRawConfigFile(filePath).raw;
+}
+
+function writeConfig(cwd, config, opts = {}) {
+ const filePath = opts.local ? getLocalConfigPath(cwd) : getConfigPath(cwd);
+ if (opts.local) ensureHookGitExcludes(cwd);
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
+ fs.writeFileSync(filePath, JSON.stringify(config, null, 2) + '\n');
+ return filePath;
+}
+
+function mergeConfig(existing) {
+ // Persist the full shape so /impeccable hooks edits leave a complete file
+ // for the user to see, not an unhelpful `{"enabled":false}`.
+ const base = existing && typeof existing === 'object' ? existing : {};
+ return {
+ enabled: base.enabled === false ? false : true,
+ ignoreRules: Array.isArray(base.ignoreRules) ? Array.from(new Set(base.ignoreRules.map(String))) : [],
+ ignoreFiles: Array.isArray(base.ignoreFiles) ? Array.from(new Set(base.ignoreFiles.map(String))) : [],
+ ignoreValues: normalizeIgnoreValueEntries(base.ignoreValues || []),
+ limits: {
+ maxFindings: Number.isFinite(base?.limits?.maxFindings) ? base.limits.maxFindings : DEFAULT_CONFIG.limits.maxFindings,
+ maxChars: Number.isFinite(base?.limits?.maxChars) ? base.limits.maxChars : DEFAULT_CONFIG.limits.maxChars,
+ },
+ };
+}
+
+function mergeLocalConfig(existing) {
+ const base = existing && typeof existing === 'object' ? existing : {};
+ const out = {};
+ if (Object.prototype.hasOwnProperty.call(base, 'enabled')) {
+ out.enabled = base.enabled === false ? false : true;
+ }
+ if (Array.isArray(base.ignoreRules)) {
+ out.ignoreRules = Array.from(new Set(base.ignoreRules.map(String)));
+ }
+ if (Array.isArray(base.ignoreFiles)) {
+ out.ignoreFiles = Array.from(new Set(base.ignoreFiles.map(String)));
+ }
+ out.ignoreValues = normalizeIgnoreValueEntries(base.ignoreValues || []);
+ if (base.limits && typeof base.limits === 'object') {
+ const limits = {};
+ if (Number.isFinite(base.limits.maxFindings)) limits.maxFindings = base.limits.maxFindings;
+ if (Number.isFinite(base.limits.maxChars)) limits.maxChars = base.limits.maxChars;
+ if (Object.keys(limits).length) out.limits = limits;
+ }
+ return out;
+}
+
+function statusReport(cwd) {
+ const shared = readRawConfigFile(getConfigPath(cwd));
+ const local = readRawConfigFile(getLocalConfigPath(cwd));
+ const cfg = readConfig(cwd);
+ const envKill = process.env.IMPECCABLE_HOOK_DISABLED;
+ const envState = envKill ? `IMPECCABLE_HOOK_DISABLED=${envKill}` : 'unset';
+ const cfgPath = path.relative(cwd, getConfigPath(cwd)) || '.impeccable/hook.json';
+ const localPath = path.relative(cwd, getLocalConfigPath(cwd)) || '.impeccable/hook.local.json';
+ const cachePath = path.relative(cwd, getCachePath(cwd)) || '.impeccable/hook.cache.json';
+ const fileState = (info, relPath, absent) => {
+ if (info.malformed) return `${relPath} (malformed; ignored)`;
+ if (info.exists) return relPath;
+ return `${relPath} (${absent})`;
+ };
+ const ignoreValues = cfg.ignoreValues.map((entry) => `${entry.rule}=${entry.value}`);
+
+ const lines = [
+ `Impeccable design hook`,
+ ` state: ${cfg.enabled ? 'enabled' : 'disabled'}`,
+ ` shared file: ${fileState(shared, cfgPath, 'using defaults; file not present')}`,
+ ` local file: ${fileState(local, localPath, 'not present')}`,
+ ` ignoreRules: ${cfg.ignoreRules.length ? cfg.ignoreRules.join(', ') : '(none)'}`,
+ ` ignoreFiles: ${cfg.ignoreFiles.length ? cfg.ignoreFiles.join(', ') : '(none)'}`,
+ ` ignoreValues: ${ignoreValues.length ? ignoreValues.join(', ') : '(none)'}`,
+ ` maxFindings: ${cfg.limits.maxFindings}`,
+ ` maxChars: ${cfg.limits.maxChars}`,
+ ` env override: ${envState}`,
+ ` cache file: ${fs.existsSync(getCachePath(cwd)) ? cachePath : `${cachePath} (not present)`}`,
+ ];
+ return lines.join('\n');
+}
+
+function setEnabled(cwd, value) {
+ const config = mergeConfig(readRawConfig(cwd));
+ config.enabled = value;
+ const target = writeConfig(cwd, config);
+ return `Design hook ${value ? 'enabled' : 'disabled'} for this project (wrote ${path.relative(cwd, target) || target}).`;
+}
+
+function normalizeRuleId(rule) {
+ return String(rule || '').trim().toLowerCase();
+}
+
+function parseIgnoreRuleArgs(args) {
+ const positionals = [];
+ let allValues = false;
+
+ for (let i = 0; i < args.length; i++) {
+ const arg = String(args[i] || '');
+ if (arg === '--all-values') {
+ allValues = true;
+ } else if (arg === '--reason') {
+ while (i + 1 < args.length && !String(args[i + 1]).startsWith('--')) i++;
+ } else if (arg.startsWith('--reason=')) {
+ // Accepted for command symmetry; ignoreRules stores rule ids only.
+ } else if (arg.startsWith('--')) {
+ throw new Error(`Unknown ignore-rule flag: ${arg}`);
+ } else {
+ positionals.push(arg);
+ }
+ }
+
+ return {
+ rule: normalizeRuleId(positionals[0]),
+ allValues,
+ };
+}
+
+function addIgnoreRule(cwd, args) {
+ const parsed = parseIgnoreRuleArgs(args);
+ const rule = parsed.rule;
+ if (!rule) throw new Error('Pass a rule id, e.g. /impeccable hooks ignore-rule side-tab');
+ if (rule === 'overused-font' && !parsed.allValues) {
+ throw new Error('overused-font is value-specific by default. Use /impeccable hooks ignore-value overused-font <font> for a confirmed font, or /impeccable hooks ignore-rule overused-font --all-values only when the user asked to ignore overused fonts generally.');
+ }
+ const config = mergeConfig(readRawConfig(cwd));
+ if (!config.ignoreRules.includes(rule)) config.ignoreRules.push(rule);
+ writeConfig(cwd, config);
+ return `Added "${rule}" to ignoreRules. Current: ${config.ignoreRules.join(', ')}`;
+}
+
+function addIgnoreFile(cwd, glob) {
+ if (!glob) throw new Error('Pass a glob, e.g. /impeccable hooks ignore-file "src/legacy/**"');
+ const config = mergeConfig(readRawConfig(cwd));
+ if (!config.ignoreFiles.includes(glob)) config.ignoreFiles.push(glob);
+ writeConfig(cwd, config);
+ return `Added "${glob}" to ignoreFiles. Current: ${config.ignoreFiles.join(', ')}`;
+}
+
+function parseIgnoreValueArgs(args) {
+ const positionals = [];
+ let shared = false;
+ let local = false;
+ let reason = '';
+
+ for (let i = 0; i < args.length; i++) {
+ const arg = args[i];
+ if (arg === '--shared') {
+ shared = true;
+ } else if (arg === '--local') {
+ local = true;
+ } else if (arg === '--reason') {
+ const chunks = [];
+ while (i + 1 < args.length && !String(args[i + 1]).startsWith('--')) {
+ chunks.push(args[++i]);
+ }
+ reason = chunks.join(' ').trim();
+ } else if (String(arg).startsWith('--reason=')) {
+ reason = String(arg).slice('--reason='.length).trim();
+ } else {
+ positionals.push(arg);
+ }
+ }
+
+ const [rule, ...valueParts] = positionals;
+ return {
+ rule: String(rule || '').trim().toLowerCase(),
+ value: normalizeIgnoreValue(valueParts.join(' ')),
+ shared,
+ local,
+ reason,
+ };
+}
+
+function addIgnoreValue(cwd, args) {
+ const parsed = parseIgnoreValueArgs(args);
+ if (!parsed.rule || !parsed.value) {
+ throw new Error('Pass a rule id and value, e.g. /impeccable hooks ignore-value overused-font Inter');
+ }
+
+ if (parsed.shared && parsed.local) {
+ throw new Error('Pass only one scope flag: --shared or --local');
+ }
+
+ const local = parsed.local;
+ const config = local
+ ? mergeLocalConfig(readRawConfig(cwd, { local: true }))
+ : mergeConfig(readRawConfig(cwd, { local: false }));
+ const key = `${parsed.rule}\0${parsed.value}`;
+ const existing = config.ignoreValues.find((entry) => `${entry.rule}\0${entry.value}` === key);
+
+ if (existing) {
+ if (parsed.reason) existing.reason = parsed.reason;
+ } else {
+ const entry = {
+ rule: parsed.rule,
+ value: parsed.value,
+ createdAt: new Date().toISOString(),
+ };
+ if (parsed.reason) entry.reason = parsed.reason;
+ config.ignoreValues.push(entry);
+ }
+
+ const target = writeConfig(cwd, config, { local });
+ const scope = local ? 'local ignoreValues' : 'shared ignoreValues';
+ return `Added ${parsed.rule}=${parsed.value} to ${scope} (${path.relative(cwd, target) || target}).`;
+}
+
+function reset(cwd) {
+ const removed = [];
+ for (const filePath of [getConfigPath(cwd), getLocalConfigPath(cwd), getCachePath(cwd), getPendingPath(cwd)]) {
+ try {
+ if (fs.existsSync(filePath)) {
+ fs.unlinkSync(filePath);
+ removed.push(path.relative(cwd, filePath) || filePath);
+ }
+ } catch { /* ignore */ }
+ }
+ return removed.length
+ ? `Reset design hook config and cache (removed: ${removed.join(', ')}).`
+ : 'No hook config or cache to remove. Already at defaults.';
+}
+
+function main() {
+ const [, , actionArg, ...rest] = process.argv;
+ const action = (actionArg || 'status').toLowerCase();
+ const cwd = process.cwd();
+
+ if (!ACTIONS.has(action)) {
+ process.stderr.write(`Unknown action: ${action}\nValid: ${Array.from(ACTIONS).join(', ')}\n`);
+ process.exit(1);
+ }
+
+ try {
+ let out = '';
+ switch (action) {
+ case 'status': out = statusReport(cwd); break;
+ case 'on': out = setEnabled(cwd, true); break;
+ case 'off': out = setEnabled(cwd, false); break;
+ case 'ignore-rule': out = addIgnoreRule(cwd, rest); break;
+ case 'ignore-file': out = addIgnoreFile(cwd, rest[0]); break;
+ case 'ignore-value': out = addIgnoreValue(cwd, rest); break;
+ case 'reset': out = reset(cwd); break;
+ }
+ process.stdout.write(out + '\n');
+ } catch (err) {
+ process.stderr.write(`Error: ${err.message || err}\n`);
+ process.exit(1);
+ }
+}
+
+main();
diff --git a/.rovodev/skills/impeccable/scripts/hook-before-edit.mjs b/.rovodev/skills/impeccable/scripts/hook-before-edit.mjs
new file mode 100644
index 000000000..54b2709d2
--- /dev/null
+++ b/.rovodev/skills/impeccable/scripts/hook-before-edit.mjs
@@ -0,0 +1,408 @@
+#!/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 shellContent = shellHereDocContent(shellCommand(input));
+ if (shellContent) return shellContent;
+ const copiedContent = shellCopiedFileContent(shellCommand(input), 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 || '';
+}
+
+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 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' });
+});
diff --git a/.rovodev/skills/impeccable/scripts/hook-lib.mjs b/.rovodev/skills/impeccable/scripts/hook-lib.mjs
new file mode 100644
index 000000000..02199f530
--- /dev/null
+++ b/.rovodev/skills/impeccable/scripts/hook-lib.mjs
@@ -0,0 +1,1232 @@
+/**
+ * Shared library for the Impeccable design hook.
+ *
+ * Pure-ish helpers split out from `hook.mjs` so unit tests can exercise
+ * config parsing, finding filtering, dedup, render, and cache logic without
+ * spawning a subprocess. `hook.mjs` itself is the thin stdin/stdout shim.
+ *
+ * Public surface (everything exported is part of the contract):
+ * ENVELOPE_PREFIX, ALLOWED_EXTS, ACK_EXTS, SENSITIVE_PATH, GENERATED_PATH, TRUTHY
+ * truthy(value)
+ * readConfig(cwd) / DEFAULT_CONFIG / getConfigPath(cwd) / getLocalConfigPath(cwd)
+ * normalizeIgnoreValue(value)
+ * readCache(cwd) / persistCache(cwd, cache)
+ * bumpEditCount(cache, sessionId, filePath) -> number
+ * suppressionNotice(filePath)
+ * filterFindings(findings, content, ext, config)
+ * dedupeAgainstCache(findings, cache, sessionId, filePath)
+ * renderTemplate(findings, filePath, config, opts)
+ * renderCleanAck(filePath, opts) / renderPendingAck(filePath, known, opts)
+ * shouldEmitAckForFile(filePath)
+ * writeAuditLog(env, entry)
+ * loadDetector() -> Promise<{ detectText, detectHtml }>
+ * matchesAnyGlob(filePath, globs)
+ * normalizeScanTargets(primaryTargets, projectCwd)
+ * runHook(deps) -> { exitCode, stdout, audit, reason? }
+ *
+ * Design notes:
+ * - All errors are swallowed at the runHook seam. The detector throwing must
+ * never break a turn. See PRD §5 "Failure modes".
+ * - Cache shape is JSON-friendly; we gc the oldest sessions when there are
+ * more than 8 to keep file size predictable across long-lived projects.
+ * - The detector loader looks for `detector/detect-antipatterns.mjs` next to
+ * this file first (built skill layout) and falls back to the repo root's
+ * `cli/engine/detect-antipatterns.mjs` (running from source).
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+import { pathToFileURL, fileURLToPath } from 'node:url';
+
+const __filename = fileURLToPath(import.meta.url);
+const __dirname = path.dirname(__filename);
+
+export const ENVELOPE_PREFIX = '[impeccable@1]';
+
+export const ALLOWED_EXTS = new Set([
+ '.tsx', '.jsx', '.html', '.htm', '.vue', '.svelte', '.astro',
+ '.css', '.scss', '.sass', '.less', '.ts', '.js',
+]);
+
+export const ACK_EXTS = new Set([
+ '.tsx', '.jsx', '.html', '.htm', '.vue', '.svelte', '.astro',
+ '.css', '.scss', '.sass', '.less',
+]);
+
+// Hard-skip regex for sensitive files. Cannot be turned off via config.
+// Match tokenized secret/credential filenames, not UI names such as
+// CredentialForm.tsx, SecretPage.jsx, or secretary-dashboard.vue.
+export const SENSITIVE_PATH = new RegExp([
+ String.raw`(?:^|[/\\])\.env(?:\.|$)`,
+ String.raw`(?:^|[/\\])\.git(?:[/\\]|$)`,
+ String.raw`(?:^|[/\\])id_rsa(?:$|[._-])[^/\\]*$`,
+ String.raw`(?:^|[/\\])[^/\\]*\.pem$`,
+ String.raw`(?:^|[/\\])(?:[^/\\]*[._-])?(?:secret|secrets|credential|credentials)(?=[._-])[^/\\]*\.(?:json|ya?ml|toml|ini|conf|config|env|txt|key|cert|crt|pem|js|ts)$`,
+].join('|'), 'i');
+
+// Hard-skip regex for generated, lock, minified, and build-output paths.
+export const GENERATED_PATH = /(?:\.generated\.[a-z]+$|\.d\.ts$|\.min\.[a-z]+$|[/\\]node_modules[/\\]|[/\\](?:dist|build|out|\.next|\.cache|coverage)[/\\]|[/\\]?[^/\\]+\.lock(?:\.json)?$)/i;
+
+export const TRUTHY = /^(1|true|yes|on)$/i;
+
+export const DEFAULT_CONFIG = Object.freeze({
+ enabled: true,
+ ignoreRules: [],
+ ignoreFiles: [],
+ ignoreValues: [],
+ limits: { maxFindings: 5, maxChars: 8000 },
+});
+
+export const HOOK_LOCAL_IGNORE_PATTERNS = Object.freeze([
+ '.impeccable/hook.cache.json',
+ '.impeccable/hook.pending.json',
+ '.impeccable/hook.local.json',
+]);
+
+const HOOK_IGNORE_MARKER_OPEN = '# impeccable-hook-ignore-start';
+const HOOK_IGNORE_MARKER_CLOSE = '# impeccable-hook-ignore-end';
+const CACHE_MAX_SESSIONS = 8;
+export const EDIT_COUNT_THRESHOLD = 6;
+
+export function truthy(value) {
+ return typeof value === 'string' && TRUTHY.test(value);
+}
+
+function depthIsSet(value) {
+ if (value === undefined || value === null) return false;
+ const text = String(value).trim();
+ if (!text) return false;
+ if (TRUTHY.test(text)) return true;
+ return /^\d+$/.test(text) && Number(text) > 0;
+}
+
+function safeReadJson(filePath) {
+ try {
+ return JSON.parse(fs.readFileSync(filePath, 'utf-8'));
+ } catch {
+ return null;
+ }
+}
+
+export function getConfigPath(cwd) {
+ return path.join(cwd, '.impeccable', 'hook.json');
+}
+
+export function getLocalConfigPath(cwd) {
+ return path.join(cwd, '.impeccable', 'hook.local.json');
+}
+
+export function getCachePath(cwd) {
+ return path.join(cwd, '.impeccable', 'hook.cache.json');
+}
+
+export function getPendingPath(cwd) {
+ return path.join(cwd, '.impeccable', 'hook.pending.json');
+}
+
+export function resolveProjectCwd(event, fallback = process.cwd()) {
+ return event?.cwd
+ || (Array.isArray(event?.workspace_roots) && event.workspace_roots[0])
+ || envProjectDir(fallback)
+ || fallback;
+}
+
+export function readConfig(cwd) {
+ const config = cloneDefaultConfig();
+ applyConfigSource(config, safeReadJson(getConfigPath(cwd)));
+ applyConfigSource(config, safeReadJson(getLocalConfigPath(cwd)));
+ return config;
+}
+
+function numberOr(value, fallback) {
+ return Number.isFinite(value) && value > 0 ? value : fallback;
+}
+
+function cloneDefaultConfig() {
+ return {
+ ...DEFAULT_CONFIG,
+ ignoreRules: [],
+ ignoreFiles: [],
+ ignoreValues: [],
+ limits: { ...DEFAULT_CONFIG.limits },
+ };
+}
+
+function applyConfigSource(config, raw) {
+ if (!raw || typeof raw !== 'object') return config;
+ if (Object.prototype.hasOwnProperty.call(raw, 'enabled')) {
+ config.enabled = raw.enabled === false ? false : true;
+ }
+ if (Array.isArray(raw.ignoreRules)) {
+ config.ignoreRules = uniqueStrings([...config.ignoreRules, ...raw.ignoreRules]);
+ }
+ if (Array.isArray(raw.ignoreFiles)) {
+ config.ignoreFiles = uniqueStrings([...config.ignoreFiles, ...raw.ignoreFiles]);
+ }
+ if (Array.isArray(raw.ignoreValues)) {
+ config.ignoreValues = mergeIgnoreValues(config.ignoreValues, raw.ignoreValues);
+ }
+ if (raw.limits && typeof raw.limits === 'object') {
+ config.limits = {
+ maxFindings: numberOr(raw.limits.maxFindings, config.limits.maxFindings),
+ maxChars: numberOr(raw.limits.maxChars, config.limits.maxChars),
+ };
+ }
+ return config;
+}
+
+function uniqueStrings(values) {
+ return Array.from(new Set(values.map(String)));
+}
+
+export function normalizeIgnoreValue(value) {
+ return String(value || '')
+ .trim()
+ .replace(/^["']|["']$/g, '')
+ .replace(/\+/g, ' ')
+ .replace(/\s+/g, ' ')
+ .toLowerCase();
+}
+
+function normalizeIgnoreRule(rule) {
+ return String(rule || '').trim().toLowerCase();
+}
+
+export function normalizeIgnoreValueEntries(entries) {
+ if (!Array.isArray(entries)) return [];
+ const out = [];
+ for (const entry of entries) {
+ if (!entry || typeof entry !== 'object') continue;
+ const rule = normalizeIgnoreRule(entry.rule);
+ const value = normalizeIgnoreValue(entry.value);
+ if (!rule || !value) continue;
+ const normalized = { rule, value };
+ if (typeof entry.reason === 'string' && entry.reason.trim()) {
+ normalized.reason = entry.reason.trim();
+ }
+ if (typeof entry.createdAt === 'string' && entry.createdAt.trim()) {
+ normalized.createdAt = entry.createdAt.trim();
+ }
+ out.push(normalized);
+ }
+ return out;
+}
+
+function mergeIgnoreValues(existing, incoming) {
+ const map = new Map();
+ for (const entry of normalizeIgnoreValueEntries(existing)) {
+ map.set(`${entry.rule}\0${entry.value}`, entry);
+ }
+ for (const entry of normalizeIgnoreValueEntries(incoming)) {
+ map.set(`${entry.rule}\0${entry.value}`, entry);
+ }
+ return Array.from(map.values());
+}
+
+export function readCache(cwd) {
+ const raw = safeReadJson(getCachePath(cwd));
+ if (!raw || typeof raw !== 'object' || raw.version !== 1) {
+ return { version: 1, sessions: {} };
+ }
+ return {
+ version: 1,
+ sessions: raw.sessions && typeof raw.sessions === 'object' ? raw.sessions : {},
+ };
+}
+
+export function persistCache(cwd, cache) {
+ const sessions = cache.sessions || {};
+ const ids = Object.keys(sessions);
+ if (ids.length > CACHE_MAX_SESSIONS) {
+ // Garbage-collect oldest sessions by updatedAt.
+ const ordered = ids
+ .map((id) => [id, sessions[id]?.updatedAt || 0])
+ .sort((a, b) => b[1] - a[1])
+ .slice(0, CACHE_MAX_SESSIONS);
+ const next = {};
+ for (const [id] of ordered) next[id] = sessions[id];
+ cache = { ...cache, sessions: next };
+ }
+ const target = getCachePath(cwd);
+ try {
+ ensureHookGitExcludes(cwd);
+ fs.mkdirSync(path.dirname(target), { recursive: true });
+ fs.writeFileSync(target, JSON.stringify(cache));
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+export function ensureHookGitExcludes(cwd = process.cwd()) {
+ try {
+ const target = resolveHookGitExcludeTarget(cwd);
+ if (!target) {
+ return { mode: 'none', changed: false, patterns: [...HOOK_LOCAL_IGNORE_PATTERNS] };
+ }
+
+ const patterns = target.patternPrefix
+ ? HOOK_LOCAL_IGNORE_PATTERNS.map((pattern) => `${target.patternPrefix}/${pattern}`)
+ : [...HOOK_LOCAL_IGNORE_PATTERNS];
+ const markerSuffix = target.patternPrefix || '.';
+ const markerOpen = `${HOOK_IGNORE_MARKER_OPEN} ${markerSuffix}`;
+ const markerClose = `${HOOK_IGNORE_MARKER_CLOSE} ${markerSuffix}`;
+ const existing = fs.existsSync(target.path) ? fs.readFileSync(target.path, 'utf-8') : '';
+ const block = [markerOpen, ...patterns, markerClose].join('\n');
+ const markerRe = new RegExp(`${escapeRegExp(markerOpen)}[\\s\\S]*?${escapeRegExp(markerClose)}`);
+
+ let updated;
+ if (markerRe.test(existing)) {
+ updated = existing.replace(markerRe, block);
+ } else {
+ const prefix = existing.length === 0 ? '' : existing.endsWith('\n') ? existing : `${existing}\n`;
+ updated = `${prefix}${prefix.endsWith('\n\n') || prefix === '' ? '' : '\n'}${block}\n`;
+ }
+
+ if (updated !== existing) {
+ fs.mkdirSync(path.dirname(target.path), { recursive: true });
+ fs.writeFileSync(target.path, updated, 'utf-8');
+ }
+
+ return {
+ mode: 'git-info-exclude',
+ file: path.relative(path.resolve(cwd), target.path).split(path.sep).join('/'),
+ changed: updated !== existing,
+ patterns,
+ };
+ } catch {
+ return { mode: 'error', changed: false, patterns: [...HOOK_LOCAL_IGNORE_PATTERNS] };
+ }
+}
+
+function resolveHookGitExcludeTarget(cwd) {
+ const start = path.resolve(cwd);
+ let dir = start;
+ while (true) {
+ const dotGit = path.join(dir, '.git');
+ if (fs.existsSync(dotGit)) {
+ const gitDir = resolveGitDir(dotGit, dir);
+ if (!gitDir) return null;
+ const relPrefix = path.relative(dir, start).split(path.sep).join('/');
+ return {
+ path: path.join(gitDir, 'info', 'exclude'),
+ patternPrefix: relPrefix && relPrefix !== '.' ? relPrefix : '',
+ };
+ }
+ const parent = path.dirname(dir);
+ if (parent === dir) return null;
+ dir = parent;
+ }
+}
+
+function resolveGitDir(dotGit, worktreeDir) {
+ const stat = fs.statSync(dotGit);
+ if (stat.isDirectory()) return dotGit;
+ if (!stat.isFile()) return null;
+
+ const body = fs.readFileSync(dotGit, 'utf-8').trim();
+ const match = body.match(/^gitdir:\s*(.+)$/i);
+ if (!match) return null;
+ return path.isAbsolute(match[1]) ? match[1] : path.resolve(worktreeDir, match[1]);
+}
+
+function escapeRegExp(value) {
+ return String(value).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+}
+
+function ensureSession(cache, sessionId) {
+ if (!cache.sessions[sessionId]) {
+ cache.sessions[sessionId] = { updatedAt: Date.now(), files: {} };
+ }
+ return cache.sessions[sessionId];
+}
+
+function ensureFile(cache, sessionId, filePath) {
+ const session = ensureSession(cache, sessionId);
+ if (!session.files[filePath]) {
+ session.files[filePath] = { editCount: 0, findings: [] };
+ }
+ return session.files[filePath];
+}
+
+export function bumpEditCount(cache, sessionId, filePath) {
+ const fileEntry = ensureFile(cache, sessionId, filePath);
+ fileEntry.editCount = (fileEntry.editCount || 0) + 1;
+ ensureSession(cache, sessionId).updatedAt = Date.now();
+ return fileEntry.editCount;
+}
+
+export function suppressionNotice(filePath) {
+ return `${ENVELOPE_PREFIX} Suppressing further design hints on ${filePath}. More than ${EDIT_COUNT_THRESHOLD} edits in this session reached. Run /impeccable audit to revisit.`;
+}
+
+// Glob → RegExp. Supports `**`, `*`, `?`, and `{a,b}` alternation.
+function globToRegex(glob) {
+ let re = '^';
+ let i = 0;
+ while (i < glob.length) {
+ const c = glob[i];
+ if (c === '*') {
+ if (glob[i + 1] === '*') {
+ re += '.*';
+ i += 2;
+ if (glob[i] === '/') i += 1;
+ } else {
+ re += '[^/]*';
+ i += 1;
+ }
+ } else if (c === '?') {
+ re += '[^/]';
+ i += 1;
+ } else if (c === '{') {
+ const end = glob.indexOf('}', i);
+ if (end === -1) { re += '\\{'; i += 1; continue; }
+ const parts = glob.slice(i + 1, end).split(',').map((p) => p.replace(/[.+^$()|[\]\\]/g, '\\$&'));
+ re += `(?:${parts.join('|')})`;
+ i = end + 1;
+ } else if (/[.+^$()|[\]\\]/.test(c)) {
+ re += `\\${c}`;
+ i += 1;
+ } else {
+ re += c;
+ i += 1;
+ }
+ }
+ re += '$';
+ return new RegExp(re);
+}
+
+export function matchesAnyGlob(filePath, globs) {
+ if (!Array.isArray(globs) || globs.length === 0) return false;
+ const normalized = filePath.split(path.sep).join('/');
+ for (const glob of globs) {
+ try {
+ const re = globToRegex(String(glob));
+ if (re.test(normalized)) return true;
+ // Match against basename too for convenience: `*.generated.tsx` should
+ // catch `src/foo.generated.tsx` without requiring `**/`.
+ const base = normalized.split('/').pop();
+ if (re.test(base)) return true;
+ } catch {
+ /* malformed glob, skip */
+ }
+ }
+ return false;
+}
+
+export function filterFindings(findings, _content, _ext, config) {
+ if (!Array.isArray(findings) || findings.length === 0) return [];
+ const ignoreRules = new Set((config.ignoreRules || []).map((rule) => normalizeIgnoreRule(rule)));
+ const ignoreValues = normalizeIgnoreValueEntries(config.ignoreValues || []);
+ return findings.filter((f) => {
+ if (!f || typeof f !== 'object') return false;
+ if (ignoreRules.has(normalizeIgnoreRule(f.antipattern))) return false;
+ if (isIgnoredFindingValue(f, ignoreValues)) return false;
+ return true;
+ });
+}
+
+function isIgnoredFindingValue(finding, ignoreValues) {
+ if (!Array.isArray(ignoreValues) || ignoreValues.length === 0) return false;
+ const rule = normalizeIgnoreRule(finding.antipattern);
+ const value = extractFindingIgnoreValue(finding);
+ if (!rule || !value) return false;
+ return ignoreValues.some((entry) => entry.rule === rule && entry.value === value);
+}
+
+export function extractFindingIgnoreValue(finding) {
+ if (!finding || typeof finding !== 'object') return '';
+ const rule = normalizeIgnoreRule(finding.antipattern);
+ if (rule !== 'overused-font') return '';
+ return normalizeIgnoreValue(extractFindingIgnoreValueRaw(finding));
+}
+
+function extractFindingIgnoreValueRaw(finding) {
+ const direct = cleanIgnoreValueDisplay(finding.ignoreValue || finding.value || '');
+ if (direct) return direct;
+
+ const candidates = [finding.detail, finding.snippet].filter((v) => typeof v === 'string' && v);
+ for (const text of candidates) {
+ const primary = text.match(/Primary font:\s*([^()\n;]+)/i);
+ if (primary) return cleanIgnoreValueDisplay(primary[1]);
+
+ const family = text.match(/font-family\s*:\s*["']?([^'",;\n]+)/i);
+ if (family) return cleanIgnoreValueDisplay(family[1]);
+
+ const google = text.match(/[?&]family=([^&:;\n]+)/i);
+ if (google) {
+ try {
+ return cleanIgnoreValueDisplay(decodeURIComponent(google[1]));
+ } catch {
+ return cleanIgnoreValueDisplay(google[1]);
+ }
+ }
+ }
+
+ return '';
+}
+
+function cleanIgnoreValueDisplay(value) {
+ return String(value || '')
+ .trim()
+ .replace(/^["']|["']$/g, '')
+ .replace(/\+/g, ' ')
+ .replace(/\s+/g, ' ');
+}
+
+export function dedupeAgainstCache(findings, cache, sessionId, filePath) {
+ if (!Array.isArray(findings) || findings.length === 0) return [];
+ const fileEntry = ensureFile(cache, sessionId, filePath);
+ const known = new Set(fileEntry.findings || []);
+ const fresh = [];
+ for (const f of findings) {
+ const key = `${f.antipattern}:${f.line || 0}`;
+ if (known.has(key)) continue;
+ known.add(key);
+ fresh.push(f);
+ }
+ return fresh;
+}
+
+export function rememberFindings(cache, sessionId, filePath, findings) {
+ const fileEntry = ensureFile(cache, sessionId, filePath);
+ const known = new Set(fileEntry.findings || []);
+ for (const f of findings) known.add(`${f.antipattern}:${f.line || 0}`);
+ fileEntry.findings = Array.from(known);
+ ensureSession(cache, sessionId).updatedAt = Date.now();
+}
+
+export function renderTemplate(findings, filePath, config, opts = {}) {
+ if (!Array.isArray(findings) || findings.length === 0) return '';
+ const limits = config?.limits || DEFAULT_CONFIG.limits;
+ const cap = Math.max(1, limits.maxFindings || DEFAULT_CONFIG.limits.maxFindings);
+ const maxChars = Math.max(500, limits.maxChars || DEFAULT_CONFIG.limits.maxChars);
+
+ const cwd = opts.cwd || process.cwd();
+ const display = relativize(filePath, cwd);
+ const total = findings.length;
+ const shown = findings.slice(0, cap);
+ const remaining = total - shown.length;
+
+ const header = `${ENVELOPE_PREFIX} Required design corrections in ${display} (${total} issue(s)):`;
+ const lines = shown.map((f) => formatFindingLine(f));
+ const more = remaining > 0
+ ? `... and ${remaining} more (see /impeccable audit).`
+ : null;
+ const footer = directiveFooter(display);
+
+ const blocks = [header, ...lines];
+ if (more) blocks.push(more);
+ blocks.push('');
+ blocks.push(footer);
+ let text = blocks.join('\n');
+
+ if (text.length > maxChars) {
+ text = clampToBudget(header, lines, more, footer, maxChars);
+ }
+ return text;
+}
+
+function renderGroupedTemplate(groups, config, opts = {}) {
+ const realGroups = groups.filter((group) => Array.isArray(group.findings) && group.findings.length > 0);
+ if (realGroups.length === 0) return '';
+ if (realGroups.length === 1) {
+ const [group] = realGroups;
+ return renderTemplate(group.findings, group.filePath, config, opts);
+ }
+
+ const limits = config?.limits || DEFAULT_CONFIG.limits;
+ const cap = Math.max(1, limits.maxFindings || DEFAULT_CONFIG.limits.maxFindings);
+ const maxChars = Math.max(500, limits.maxChars || DEFAULT_CONFIG.limits.maxChars);
+ const cwd = opts.cwd || process.cwd();
+ const total = realGroups.reduce((sum, group) => sum + group.findings.length, 0);
+ const header = `${ENVELOPE_PREFIX} Required design corrections across ${realGroups.length} files (${total} issue(s)):`;
+ const lines = [];
+ let shownCount = 0;
+
+ for (const group of realGroups) {
+ const display = relativize(group.filePath, cwd);
+ lines.push(`${display} (${group.findings.length} issue(s)):`);
+ const remainingCap = Math.max(0, cap - shownCount);
+ const shown = group.findings.slice(0, remainingCap);
+ for (const finding of shown) {
+ lines.push(formatFindingLine(finding));
+ }
+ shownCount += shown.length;
+ const hidden = group.findings.length - shown.length;
+ if (hidden > 0) {
+ lines.push(`- ... ${hidden} more in ${display} (see /impeccable audit).`);
+ }
+ }
+
+ const footer = directiveFooter('the affected files', { grouped: true });
+ let text = [header, ...lines, '', footer].join('\n');
+ if (text.length > maxChars) {
+ text = clampGroupedToBudget(header, lines, footer, maxChars);
+ }
+ return text;
+}
+
+function clampGroupedToBudget(header, lines, footer, maxChars) {
+ const assemble = (linesArr, omitted) => [
+ header,
+ ...linesArr,
+ ...(omitted ? ['... and more (see /impeccable audit).'] : []),
+ '',
+ footer,
+ ].join('\n');
+
+ let working = lines.slice();
+ let omitted = false;
+ let assembled = assemble(working, omitted);
+ while (assembled.length > maxChars && working.length > 1) {
+ working.pop();
+ omitted = true;
+ assembled = assemble(working, omitted);
+ }
+ if (assembled.length > maxChars) {
+ assembled = `${assembled.slice(0, maxChars - 1)}…`;
+ }
+ return assembled;
+}
+
+function clampToBudget(header, lines, more, footer, maxChars) {
+ const assemble = (linesArr, moreText) => {
+ const blocks = [header, ...linesArr];
+ if (moreText) blocks.push(moreText);
+ blocks.push('');
+ blocks.push(footer);
+ return blocks.join('\n');
+ };
+
+ let working = lines.slice();
+ let moreText = more;
+ let assembled = assemble(working, moreText);
+ while (assembled.length > maxChars && working.length > 1) {
+ working.pop();
+ moreText = '... and more (see /impeccable audit).';
+ assembled = assemble(working, moreText);
+ }
+ if (assembled.length > maxChars) {
+ assembled = `${assembled.slice(0, maxChars - 1)}…`;
+ }
+ return assembled;
+}
+
+function formatFindingLine(f) {
+ const prefix = f.line && f.line > 0 ? `- L${f.line}` : '-';
+ const desc = (f.description || '').trim();
+ const name = (f.name || '').trim();
+ // Description from the registry already ends in punctuation; join with a
+ // single space. `name` may have a trailing period already, keep it clean.
+ const nameSegment = name ? `${name.replace(/\.+\s*$/, '')}.` : '';
+ const ignoreCommand = formatFindingIgnoreCommand(f);
+ const ignoreSegment = ignoreCommand
+ ? ` If the user explicitly confirms this value is intentional: \`${ignoreCommand}\`.`
+ : '';
+ return `${prefix} [${f.antipattern}] ${nameSegment} ${desc}${ignoreSegment}`.replace(/\s+/g, ' ').trim();
+}
+
+function formatFindingIgnoreCommand(finding) {
+ if (!finding || typeof finding !== 'object') return '';
+ const rule = normalizeIgnoreRule(finding.antipattern);
+ if (!rule) return '';
+ const normalizedValue = extractFindingIgnoreValue(finding);
+ if (!normalizedValue) return '';
+ const value = extractFindingIgnoreValueRaw(finding);
+ const valueArg = quoteCommandArg(value);
+ const reason = quoteCommandArg(`User confirmed ${value} is intentional`);
+ return `/impeccable hooks ignore-value ${rule} ${valueArg} --shared --reason ${reason}`;
+}
+
+function quoteCommandArg(value) {
+ const text = String(value || '').trim();
+ if (/^[A-Za-z0-9._:-]+$/.test(text)) return text;
+ return `"${text.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
+}
+
+function relativize(filePath, cwd) {
+ try {
+ const rel = path.relative(cwd, filePath);
+ if (!rel || rel.startsWith('..')) return filePath;
+ return rel.split(path.sep).join('/');
+ } catch {
+ return filePath;
+ }
+}
+
+// Codex `apply_patch` exposes the raw patch in `tool_input.command`, not
+// `tool_input.file_path`. Claude Code may send both; parse the patch body
+// so we can scan the file(s) the tool actually touched.
+// https://developers.openai.com/codex/hooks#posttooluse
+const APPLY_PATCH_FILE_RE = /^\*\*\* (?:Update|Add) File: (.+)$/gm;
+
+export function parseApplyPatchPaths(command, projectCwd) {
+ if (!command || typeof command !== 'string') return [];
+ const out = [];
+ for (const m of command.matchAll(APPLY_PATCH_FILE_RE)) {
+ let p = (m[1] || '').trim();
+ if (!p) continue;
+ if (!path.isAbsolute(p)) p = path.resolve(projectCwd, p);
+ out.push(p);
+ }
+ return out;
+}
+
+export function resolveTargetFiles(event, projectCwd) {
+ const ti = event?.tool_input;
+ const out = [];
+ const add = (filePath) => {
+ if (typeof filePath !== 'string' || !filePath) return;
+ if (!out.includes(filePath)) out.push(filePath);
+ };
+
+ if (event?.tool_name === 'apply_patch' && ti && typeof ti.command === 'string') {
+ for (const filePath of parseApplyPatchPaths(ti.command, projectCwd)) add(filePath);
+ }
+ if (ti && typeof ti.file_path === 'string' && ti.file_path) {
+ add(ti.file_path);
+ }
+ // Cursor Write / StrReplace use `path`, not `file_path`.
+ if (ti && typeof ti.path === 'string' && ti.path) {
+ add(ti.path);
+ }
+ if (typeof event?.file_path === 'string' && event.file_path) {
+ add(event.file_path);
+ }
+ return out;
+}
+
+export function resolveHarness(env = {}, event = null) {
+ const explicit = env?.IMPECCABLE_HOOK_HARNESS;
+ if (explicit === 'cursor') return 'cursor';
+ if (explicit === 'claude' || explicit === 'codex') return 'claude';
+ if (typeof event?.conversation_id === 'string' && event.conversation_id) return 'cursor';
+ return 'claude';
+}
+
+export function normalizeHookEvent(event, projectCwd, harness = 'claude') {
+ if (!event || typeof event !== 'object' || harness !== 'cursor') return event;
+
+ const cwd = event.cwd
+ || (Array.isArray(event.workspace_roots) && event.workspace_roots[0])
+ || envProjectDir(projectCwd)
+ || projectCwd;
+ const sessionId = event.session_id || event.conversation_id || 'unknown';
+
+ const ti = event.tool_input && typeof event.tool_input === 'object' ? event.tool_input : {};
+ const filePath = ti.file_path || ti.path || event.file_path;
+ if (filePath) {
+ return {
+ ...event,
+ cwd,
+ session_id: sessionId,
+ tool_input: { ...ti, file_path: filePath },
+ };
+ }
+
+ return { ...event, cwd, session_id: sessionId };
+}
+
+function envProjectDir(fallback) {
+ if (typeof process.env.CURSOR_PROJECT_DIR === 'string' && process.env.CURSOR_PROJECT_DIR) {
+ return process.env.CURSOR_PROJECT_DIR;
+ }
+ return fallback;
+}
+
+// UI components often keep slop in a sibling/co-located stylesheet while the
+// JSX edit is what triggered PostToolUse. Scan those styles too so an App.jsx
+// patch doesn't report "clean" while styles.css still has Inter/bounce/etc.
+const UI_CODE_EXTS = new Set(['.jsx', '.tsx', '.vue', '.svelte', '.astro']);
+const STYLE_EXTS = new Set(['.css', '.scss', '.sass', '.less']);
+const CO_SCAN_STYLE_NAMES = [
+ 'styles.css', 'styles.scss', 'styles.sass', 'styles.less',
+ 'index.css', 'index.scss', 'index.sass', 'index.less',
+ 'global.css', 'global.scss', 'global.sass', 'global.less',
+ 'globals.css', 'globals.scss', 'globals.sass', 'globals.less',
+];
+const MAX_SCAN_TARGETS = 6;
+
+const STATIC_STYLE_IMPORT_RE = /import\s+(?:[\w*{}\s,$]+\s+from\s+)?['"]([^'"]+\.(?:css|scss|sass|less))['"]/gi;
+
+function hasPathTraversal(filePath) {
+ return typeof filePath === 'string' && filePath.includes('..');
+}
+
+function isInsideProject(filePath, projectCwd) {
+ if (!filePath || !projectCwd || hasPathTraversal(filePath)) return false;
+ try {
+ const rel = path.relative(projectCwd, filePath);
+ return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));
+ } catch {
+ return false;
+ }
+}
+
+export function parseStaticStyleImports(content, fromFile, projectCwd) {
+ if (!content || typeof content !== 'string') return [];
+ const dir = path.dirname(fromFile);
+ const out = [];
+ for (const m of content.matchAll(STATIC_STYLE_IMPORT_RE)) {
+ let p = (m[1] || '').trim();
+ if (!p) continue;
+ if (p.startsWith('.')) p = path.resolve(dir, p);
+ else if (!path.isAbsolute(p)) p = path.resolve(projectCwd, p);
+ if (!isInsideProject(p, projectCwd)) continue;
+ out.push(p);
+ }
+ return out;
+}
+
+export function coLocatedStylesheets(filePath) {
+ const dir = path.dirname(filePath);
+ const base = path.basename(filePath, path.extname(filePath));
+ const candidates = new Set([
+ path.join(dir, `${base}.css`),
+ path.join(dir, `${base}.module.css`),
+ path.join(dir, `${base}.scss`),
+ path.join(dir, `${base}.module.scss`),
+ path.join(dir, `${base}.sass`),
+ path.join(dir, `${base}.module.sass`),
+ path.join(dir, `${base}.less`),
+ path.join(dir, `${base}.module.less`),
+ ]);
+ for (const name of CO_SCAN_STYLE_NAMES) {
+ candidates.add(path.join(dir, name));
+ }
+ return [...candidates].filter((p) => fs.existsSync(p));
+}
+
+export function normalizeScanTargets(primaryTargets, projectCwd) {
+ if (!Array.isArray(primaryTargets) || primaryTargets.length === 0) return [];
+ const ordered = [];
+ const seen = new Set();
+ const baseCwd = projectCwd || process.cwd();
+ const normalizeTarget = (p) => {
+ // Preserve literal `..` segments so downstream sensitive-path checks
+ // still fire. path.resolve would collapse `/foo/../etc/passwd`.
+ if (hasPathTraversal(p)) return p;
+ return path.isAbsolute(p) ? p : path.resolve(baseCwd, p);
+ };
+ const add = (p) => {
+ if (ordered.length >= MAX_SCAN_TARGETS) return;
+ const abs = normalizeTarget(p);
+ if (seen.has(abs)) return;
+ seen.add(abs);
+ ordered.push(abs);
+ return abs;
+ };
+
+ for (const p of primaryTargets) add(p);
+ return ordered;
+}
+
+export function expandScanTargets(primaryTargets, projectCwd) {
+ const ordered = normalizeScanTargets(primaryTargets, projectCwd);
+ if (ordered.length === 0) return [];
+ const seen = new Set(ordered);
+ const baseCwd = projectCwd || process.cwd();
+ const add = (p) => {
+ if (ordered.length >= MAX_SCAN_TARGETS) return;
+ const abs = hasPathTraversal(p) ? p : (path.isAbsolute(p) ? p : path.resolve(baseCwd, p));
+ if (seen.has(abs)) return;
+ seen.add(abs);
+ ordered.push(abs);
+ return abs;
+ };
+
+ const normalizedPrimaries = [];
+ for (const p of ordered) normalizedPrimaries.push(p);
+
+ for (const p of normalizedPrimaries) {
+ if (ordered.length >= MAX_SCAN_TARGETS) break;
+ if (!isInsideProject(p, baseCwd)) continue;
+ const ext = path.extname(p).toLowerCase();
+ if (STYLE_EXTS.has(ext) || !UI_CODE_EXTS.has(ext)) continue;
+
+ let content = '';
+ try { content = fs.readFileSync(p, 'utf-8'); } catch { /* unreadable primary */ }
+
+ for (const imp of parseStaticStyleImports(content, p, projectCwd)) {
+ add(imp);
+ if (ordered.length >= MAX_SCAN_TARGETS) break;
+ }
+ for (const col of coLocatedStylesheets(p)) {
+ add(col);
+ if (ordered.length >= MAX_SCAN_TARGETS) break;
+ }
+ }
+
+ return ordered;
+}
+
+export function writeAuditLog(env, entry) {
+ const target = env?.IMPECCABLE_HOOK_LOG;
+ if (!target || typeof target !== 'string') return false;
+ try {
+ const expanded = target.startsWith('~/')
+ ? path.join(process.env.HOME || process.env.USERPROFILE || '.', target.slice(2))
+ : target;
+ fs.mkdirSync(path.dirname(expanded), { recursive: true });
+ const line = JSON.stringify({ ts: new Date().toISOString(), ...entry }) + '\n';
+ fs.appendFileSync(expanded, line);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+const DETECTOR_CANDIDATES = [
+ path.join(__dirname, 'detector', 'detect-antipatterns.mjs'),
+ path.join(__dirname, '..', '..', 'cli', 'engine', 'detect-antipatterns.mjs'),
+ path.join(__dirname, '..', '..', '..', 'cli', 'engine', 'detect-antipatterns.mjs'),
+];
+
+let detectorCache = null;
+export async function loadDetector(candidates = DETECTOR_CANDIDATES) {
+ if (detectorCache) return detectorCache;
+ const found = candidates.find((c) => fs.existsSync(c));
+ if (!found) return null;
+ const mod = await import(pathToFileURL(found));
+ detectorCache = { detectText: mod.detectText, detectHtml: mod.detectHtml };
+ return detectorCache;
+}
+
+// For tests: allow injecting a detector implementation.
+export function setDetectorForTesting(impl) {
+ detectorCache = impl;
+}
+
+// ────────────────────────────────────────────────────────────────────────
+// Nudge/steer messages for the no-silent-fires policy.
+//
+// The hook is designed to be a conversational presence: every fire that
+// actually scans a file emits a developer-role message into the model's
+// next turn. Three states map to three templates:
+//
+// 1. **Fresh findings** → `renderTemplate` (existing, imperative).
+// 2. **Pending findings** → `renderPendingAck` (re-nudge for issues the
+// model was already told about in this
+// session but hasn't fixed yet).
+// 3. **Truly clean** → `renderCleanAck` (short positive nudge that
+// keeps the design discipline in context).
+//
+// All three are short (≤ ~40 tokens each) so the cumulative cost stays
+// bounded across a long active editing session. Users who explicitly want
+// silence-on-clean can set `IMPECCABLE_HOOK_QUIET=1` — runHook checks that
+// env before emitting #2 or #3.
+//
+// Why not stay silent on dedup-clean? Earlier versions did. The model
+// quickly forgets the prior reminder once tool output scrolls past it, so
+// re-nudging on the same file with a short "still pending" line keeps the
+// pressure on. The wording deliberately points back to "earlier this
+// session" so the model knows it's a re-mind, not a new finding.
+// ────────────────────────────────────────────────────────────────────────
+
+const STEER_LINE = 'Keep typography hierarchy, spacing rhythm, and color contrast intentional on the next change.';
+
+export function renderCleanAck(filePath, opts = {}) {
+ const cwd = opts.cwd || process.cwd();
+ const display = relativize(filePath, cwd);
+ return `${ENVELOPE_PREFIX} Design hook scanned ${display}. No anti-patterns. ${STEER_LINE}`;
+}
+
+export function renderPendingAck(filePath, knownFindings, opts = {}) {
+ const cwd = opts.cwd || process.cwd();
+ const display = relativize(filePath, cwd);
+ const count = knownFindings.length;
+ // `knownFindings` here are the cache strings like "side-tab:3".
+ const sample = knownFindings.slice(0, 3).join(', ');
+ const more = count > 3 ? `, +${count - 3} more` : '';
+ return `${ENVELOPE_PREFIX} Design hook scanned ${display}. Still has ${count} issue(s) flagged earlier this session (${sample}${more}). Address them before finalizing — the previous reminder still applies.`;
+}
+
+export function shouldEmitAckForFile(filePath) {
+ return ACK_EXTS.has(path.extname(String(filePath || '')).toLowerCase());
+}
+
+// The directive footer is the part of the hook output that steers model
+// behavior. Three intentional moves:
+// 1. **Imperative, not advisory.** "Fix these..." beats "Consider
+// revising..." which the model treats as a soft suggestion it can
+// override when the user asked for any kind of throwaway / demo UI.
+// 2. **Explicit exception clause.** Without it, the model will try to
+// "fix" intentional bad fixtures, anti-pattern examples in docs, or
+// test cases. Naming the exception inline beats hoping the model
+// infers it from context.
+// 3. **Acknowledgement instruction.** Hook output is injected as
+// developer-role context, not a chat turn, so the user never sees the
+// raw envelope. Asking the model to surface the fix in its reply is
+// the cheapest way to make the feedback loop visible to the user.
+function directiveFooter(display, opts = {}) {
+ const ignoreFileCommand = `/impeccable hooks ignore-file ${quoteCommandArg(display)}`;
+ const fileIgnoreGuidance = opts.grouped
+ ? 'run `/impeccable hooks ignore-file <path>` for the specific file'
+ : `run \`${ignoreFileCommand}\``;
+ return [
+ 'Fix these in your next reply before finalizing. Acknowledge what you changed so the user sees the correction.',
+ '',
+ 'Skip the fix only if the user explicitly asked for an intentionally bad UI, an anti-pattern example, a test fixture, or documentation of bad design. In that case, say so and continue.',
+ '',
+ `Do not add source comments such as \`impeccable: ignore\`; those pollute the code and do not suppress hook findings. Do not add hook ignores unless the user explicitly confirms the finding is intentional. Prefer the narrowest persisted exception: run the exact \`/impeccable hooks ignore-value ... --shared\` command shown next to a value-specific finding. For \`overused-font\`, use \`ignore-value\` for a specific font and use \`/impeccable hooks ignore-rule overused-font --all-values\` only when the user asks to ignore overused fonts generally. For file-specific findings without an ignore-value command, ${fileIgnoreGuidance}; use \`/impeccable hooks ignore-rule <id>\` only when the user asks to suppress the whole non-value-specific rule. Run /impeccable audit for the full pass.`,
+ ].join('\n');
+}
+
+/**
+ * Run the hook with explicit dependencies. Returns a result object:
+ * { exitCode, stdout, audit, reason? }
+ *
+ * Never throws. All errors are converted to `exitCode: 0` + audit entry.
+ */
+export async function runHook({ stdinJson, env = {}, cwd = process.cwd(), now = Date.now, detector } = {}) {
+ const audit = { ts: new Date(now()).toISOString(), event: 'PostToolUse' };
+ const result = (extra) => ({ exitCode: 0, stdout: '', audit: { ...audit, ...extra } });
+
+ try {
+ // Re-entrancy guard.
+ if (depthIsSet(env.IMPECCABLE_HOOK_DEPTH) || depthIsSet(env.CLAUDE_HOOK_DEPTH)) {
+ return result({ reentrant: true, durationMs: 0 });
+ }
+
+ if (truthy(env.IMPECCABLE_HOOK_DISABLED)) {
+ return result({ skipped: 'env-disabled', durationMs: 0 });
+ }
+
+ const started = Date.now();
+
+ let event;
+ try {
+ event = typeof stdinJson === 'string' ? JSON.parse(stdinJson) : stdinJson;
+ } catch {
+ return result({ skipped: 'stdin-malformed', durationMs: Date.now() - started });
+ }
+ if (!event || typeof event !== 'object') {
+ return result({ skipped: 'stdin-empty', durationMs: Date.now() - started });
+ }
+
+ const harness = resolveHarness(env, event);
+ event = normalizeHookEvent(event, cwd, harness);
+ audit.harness = harness;
+
+ const projectCwd = event.cwd || cwd;
+ const primaryFiles = normalizeScanTargets(resolveTargetFiles(event, projectCwd), projectCwd);
+ const primaryFileSet = new Set(primaryFiles);
+ const targetFiles = expandScanTargets(primaryFiles, projectCwd);
+ audit.session = event.session_id || null;
+ if (event.tool_name) audit.tool = event.tool_name;
+
+ if (targetFiles.length === 0) {
+ return result({ skipped: 'no-file-path', durationMs: Date.now() - started });
+ }
+
+ const config = readConfig(projectCwd);
+ if (config.enabled === false) {
+ return result({ skipped: 'config-disabled', durationMs: Date.now() - started });
+ }
+
+ const cache = readCache(projectCwd);
+ const sessionId = event.session_id || 'unknown';
+ const det = detector || await loadDetector();
+ if (!det || typeof det.detectText !== 'function') {
+ persistCache(projectCwd, cache);
+ return result({ skipped: 'detector-missing', durationMs: Date.now() - started });
+ }
+
+ let pendingWinner = null;
+ let cleanWinner = null;
+ const freshGroups = [];
+ let suppressionWinner = null;
+ let detectorThrewAny = false;
+ let lastSkip = 'no-scannable-file';
+ let suppressedHit = false;
+
+ for (const filePath of targetFiles) {
+ audit.file = filePath;
+
+ if (hasPathTraversal(filePath) || SENSITIVE_PATH.test(filePath)) {
+ lastSkip = 'sensitive';
+ continue;
+ }
+ if (GENERATED_PATH.test(filePath)) {
+ lastSkip = 'generated';
+ continue;
+ }
+
+ const ext = path.extname(filePath).toLowerCase();
+ audit.ext = ext;
+ if (!ALLOWED_EXTS.has(ext)) {
+ lastSkip = 'extension';
+ continue;
+ }
+
+ const relForMatch = relativize(filePath, projectCwd);
+ if (matchesAnyGlob(relForMatch, config.ignoreFiles) || matchesAnyGlob(filePath, config.ignoreFiles)) {
+ lastSkip = 'config-ignore-file';
+ continue;
+ }
+ if (!fs.existsSync(filePath)) {
+ lastSkip = 'file-missing';
+ continue;
+ }
+
+ if (primaryFileSet.has(filePath)) {
+ const editCount = bumpEditCount(cache, sessionId, filePath);
+ audit.editCount = editCount;
+
+ if (editCount > EDIT_COUNT_THRESHOLD) {
+ const wasJustCrossed = editCount === EDIT_COUNT_THRESHOLD + 1;
+ if (wasJustCrossed && !suppressionWinner) {
+ suppressionWinner = { filePath };
+ }
+ lastSkip = 'suppressed';
+ suppressedHit = true;
+ continue;
+ }
+ }
+
+ const content = fs.readFileSync(filePath, 'utf-8');
+ let findings;
+ let detectorThrew = false;
+ if ((ext === '.html' || ext === '.htm') && typeof det.detectHtml === 'function') {
+ try { findings = await det.detectHtml(filePath); } catch { findings = []; detectorThrew = true; }
+ } else {
+ try { findings = await det.detectText(content, filePath); } catch { findings = []; detectorThrew = true; }
+ }
+
+ const filtered = filterFindings(findings || [], content, ext, config);
+ const fresh = dedupeAgainstCache(filtered, cache, sessionId, filePath);
+ audit.findings = (findings || []).length;
+ audit.freshFindings = fresh.length;
+
+ if (fresh.length > 0) {
+ rememberFindings(cache, sessionId, filePath, fresh);
+ freshGroups.push({ filePath, findings: fresh });
+ continue;
+ }
+
+ if (detectorThrew) {
+ detectorThrewAny = true;
+ continue;
+ }
+
+ if (filtered.length > 0 && !pendingWinner) {
+ const known = (ensureFile(cache, sessionId, filePath).findings || []).slice();
+ pendingWinner = { filePath, known };
+ } else if (filtered.length === 0 && !cleanWinner) {
+ cleanWinner = { filePath };
+ }
+ }
+
+ persistCache(projectCwd, cache);
+
+ if (freshGroups.length > 0) {
+ const firstGroup = freshGroups[0];
+ const text = renderGroupedTemplate(freshGroups, config, { cwd: projectCwd });
+ const allFindings = freshGroups.flatMap((group) => group.findings);
+ return {
+ exitCode: 0,
+ stdout: payload(text, 'PostToolUse', harness),
+ emission: {
+ kind: 'fresh',
+ file: firstGroup.filePath,
+ findings: firstGroup.findings,
+ groups: freshGroups,
+ },
+ audit: {
+ ...audit,
+ file: firstGroup.filePath,
+ emitted: true,
+ freshFiles: freshGroups.length,
+ freshFindings: allFindings.length,
+ chars: text.length,
+ durationMs: Date.now() - started,
+ },
+ };
+ }
+
+ if (detectorThrewAny && !pendingWinner && !cleanWinner) {
+ return result({ emitted: false, error: 'detector-threw', durationMs: Date.now() - started });
+ }
+
+ if (truthy(env.IMPECCABLE_HOOK_QUIET)) {
+ return result({ emitted: false, quiet: true, durationMs: Date.now() - started });
+ }
+
+ if (pendingWinner && shouldEmitAckForFile(pendingWinner.filePath)) {
+ const text = renderPendingAck(pendingWinner.filePath, pendingWinner.known, { cwd: projectCwd });
+ return {
+ exitCode: 0,
+ stdout: payload(text, 'PostToolUse', harness),
+ emission: { kind: 'pending', file: pendingWinner.filePath, known: pendingWinner.known },
+ audit: {
+ ...audit,
+ file: pendingWinner.filePath,
+ emitted: true,
+ kind: 'pending',
+ pending: pendingWinner.known.length,
+ chars: text.length,
+ durationMs: Date.now() - started,
+ },
+ };
+ }
+
+ if (suppressionWinner) {
+ const text = suppressionNotice(relativize(suppressionWinner.filePath, projectCwd));
+ return {
+ exitCode: 0,
+ stdout: payload(text, 'PostToolUse', harness),
+ emission: { kind: 'suppression', file: suppressionWinner.filePath },
+ audit: {
+ ...audit,
+ file: suppressionWinner.filePath,
+ suppressed: true,
+ emitted: true,
+ durationMs: Date.now() - started,
+ },
+ };
+ }
+
+ if (cleanWinner && shouldEmitAckForFile(cleanWinner.filePath)) {
+ const text = renderCleanAck(cleanWinner.filePath, { cwd: projectCwd });
+ return {
+ exitCode: 0,
+ stdout: payload(text, 'PostToolUse', harness),
+ emission: { kind: 'clean', file: cleanWinner.filePath },
+ audit: {
+ ...audit,
+ file: cleanWinner.filePath,
+ emitted: true,
+ kind: 'clean',
+ chars: text.length,
+ durationMs: Date.now() - started,
+ },
+ };
+ }
+
+ if (pendingWinner || cleanWinner) {
+ return result({ emitted: false, skipped: 'non-ui-ack', durationMs: Date.now() - started });
+ }
+
+ if (suppressedHit) {
+ return result({ suppressed: true, emitted: false, durationMs: Date.now() - started });
+ }
+
+ return result({ skipped: lastSkip, durationMs: Date.now() - started });
+ } catch (err) {
+ return {
+ exitCode: 0,
+ stdout: '',
+ audit: { ...audit, error: String(err && err.message ? err.message : err) },
+ };
+ }
+}
+
+export function payload(text, eventName = 'PostToolUse', harness = 'claude') {
+ if (harness === 'cursor') {
+ return JSON.stringify({ additional_context: text });
+ }
+ return JSON.stringify({
+ hookSpecificOutput: { hookEventName: eventName, additionalContext: text },
+ });
+}
diff --git a/.rovodev/skills/impeccable/scripts/hook.mjs b/.rovodev/skills/impeccable/scripts/hook.mjs
new file mode 100644
index 000000000..b862f8033
--- /dev/null
+++ b/.rovodev/skills/impeccable/scripts/hook.mjs
@@ -0,0 +1,61 @@
+#!/usr/bin/env node
+/**
+ * Impeccable design hook — PostToolUse entry point.
+ *
+ * Reads the Claude Code / Codex / Cursor hook event from stdin, runs the design
+ * detector against the touched file, and emits a system reminder via
+ * `hookSpecificOutput.additionalContext` when findings exist.
+ *
+ * Contract: never break a turn. Always exit 0. Clean files emit a small ack
+ * unless quiet mode is enabled.
+ *
+ * Most logic lives in `hook-lib.mjs` so it is unit-testable without a
+ * subprocess. This file is the thin stdin/stdout adapter.
+ */
+
+import { runHook, 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');
+}
+
+async function main() {
+ // Snapshot the inherited env FIRST so the re-entrancy guard checks the
+ // parent's value, not the value we are about to export for any child
+ // processes the hook might ever spawn.
+ const inheritedEnv = { ...process.env };
+ process.env.IMPECCABLE_HOOK_DEPTH = process.env.IMPECCABLE_HOOK_DEPTH || '1';
+
+ let stdinJson = '';
+ try { stdinJson = await readStdin(); } catch { /* fall through */ }
+
+ const result = await runHook({
+ stdinJson,
+ env: inheritedEnv,
+ cwd: process.cwd(),
+ });
+
+ writeAuditLog(process.env, result.audit);
+
+ if (result.stdout) process.stdout.write(result.stdout);
+ process.exit(result.exitCode || 0);
+}
+
+main().catch((err) => {
+ // Last-ditch: never break the agent's turn even if something we did not
+ // anticipate goes wrong. Audit-log the failure if logging is enabled.
+ try {
+ writeAuditLog(process.env, {
+ ts: new Date().toISOString(),
+ event: 'PostToolUse',
+ error: String(err && err.message ? err.message : err),
+ });
+ } catch { /* swallow */ }
+ if (process.env.IMPECCABLE_HOOK_DEBUG) {
+ process.stderr.write(`[impeccable-hook] ${err}\n`);
+ }
+ process.exit(0);
+});
diff --git a/.rovodev/skills/impeccable/scripts/live-inject.mjs b/.rovodev/skills/impeccable/scripts/live-inject.mjs
index 4e5c5dc0a..69ce530c1 100644
--- a/.rovodev/skills/impeccable/scripts/live-inject.mjs
+++ b/.rovodev/skills/impeccable/scripts/live-inject.mjs
@@ -32,6 +32,8 @@ const IGNORE_MARKER_CLOSE = '# impeccable-live-ignore-end';
export const LIVE_IGNORE_PATTERNS = Object.freeze([
'.impeccable/hook.cache.json',
+ '.impeccable/hook.pending.json',
+ '.impeccable/hook.local.json',
'.impeccable/live/server.json',
'.impeccable/live/sessions/',
'.impeccable/live/previews/',
diff --git a/.trae-cn/skills/impeccable/SKILL.md b/.trae-cn/skills/impeccable/SKILL.md
index df1bce67f..187455c1b 100644
--- a/.trae-cn/skills/impeccable/SKILL.md
+++ b/.trae-cn/skills/impeccable/SKILL.md
@@ -124,7 +124,7 @@ If someone could look at this interface and say "AI made that" without doubt, it
| `optimize [target]` | Fix | Diagnose and fix UI performance | [reference/optimize.md](reference/optimize.md) |
| `live` | Iterate | Visual variant mode: pick elements in the browser, generate alternatives | [reference/live.md](reference/live.md) |
-Plus two management commands: `pin <command>` and `unpin <command>`, detailed below.
+Plus three management commands: `pin <command>`, `unpin <command>`, and `hooks <on|off|status|...>`, detailed below.
### Routing rules
@@ -141,7 +141,7 @@ Plus two management commands: `pin <command>` and `unpin <command>`, detailed be
**If `scan.targets` is non-empty, run `node .trae-cn/skills/impeccable/scripts/detect.mjs --json <scan.targets joined by spaces>` once** (the bundled detector over local files: no network, no npx). `scan.via` tells you what they are: `git-changes` (the markup/style files in your dirty tree, the most relevant set), `source-dir` (e.g. `src`, `app`), `html`, or `root`. Fold the hits into your picks: many quality / contrast hits → `audit` or `polish`; a specific slop family → the matching command (gradient text or eyebrows → `quieter` / `typeset`, flat or gray palette → `colorize`, and so on). It's a real, current signal that beats guessing. If detect errors or the tree is large and slow, skip it and recommend the user run `audit` themselves; never block the suggestion on it.
Keep it to 2-3 pointed picks with the exact command to type. The menu stays the fallback; the recommendation is the lede.
-2. **First word matches a command**: load its reference file and follow its instructions. Everything after the command name is the target.
+2. **First word matches a command** (table above OR `pin` / `unpin` / `hooks`): load its reference file and follow its instructions. Everything after the command name is the target.
3. **First word doesn't match, but the intent clearly maps to one command** (e.g. "fix the spacing" → `layout`, "rewrite this error message" → `clarify`, "the colors feel flat" → `colorize`): load that command's reference and proceed as if invoked. If two commands could fit, ask once which.
4. **No clear command match**: general design invocation. Apply the setup steps, the General rules, and the loaded register reference, using the full argument as context.
@@ -159,4 +159,8 @@ If the first word is `craft`, setup still runs first, but [reference/craft.md](r
node .trae-cn/skills/impeccable/scripts/pin.mjs <pin|unpin> <command>
```
-Valid `<command>` is any command from the table above. Report the script's result concisely. Confirm the new shortcut on success, relay stderr verbatim on error.
\ No newline at end of file
+Valid `<command>` is any command from the table above. Report the script's result concisely. Confirm the new shortcut on success, relay stderr verbatim on error.
+
+## Hooks
+
+`/impeccable hooks <on|off|status|ignore-rule|ignore-file|ignore-value|reset>` manages the design detector hook for this project. The hook auto-runs the detector after direct UI file edits and surfaces findings as system reminders. Full flow is in [reference/hooks.md](reference/hooks.md); load it when the user invokes `/impeccable hooks` with any argument.
\ No newline at end of file
diff --git a/.trae-cn/skills/impeccable/reference/hooks.md b/.trae-cn/skills/impeccable/reference/hooks.md
new file mode 100644
index 000000000..b3da5d0f4
--- /dev/null
+++ b/.trae-cn/skills/impeccable/reference/hooks.md
@@ -0,0 +1,82 @@
+# /impeccable hooks
+
+Manage the **design detector hook** for the current project.
+
+The hook runs the impeccable design detector on direct file edits to design-relevant files (`.tsx`, `.jsx`, `.html`, `.vue`, `.svelte`, `.astro`, `.css`, `.scss`, `.sass`, `.less`, `.ts`, `.js`). Claude Code and Codex use `PostToolUse` and push a short system reminder into the agent's context after the edit; findings get a correction prompt, pending issues get a re-nudge, and clean UI-ish files get a short ack unless `IMPECCABLE_HOOK_QUIET=1` is set. Plain `.ts` and `.js` files are still scanned, but stay quiet unless the detector finds something. Cursor uses `preToolUse` to block bad proposed writes before they land and stays silent when it allows a clean write.
+
+This command toggles the hook **per project** by editing `.impeccable/hook.json`. Local-only ignore policy lives in `.impeccable/hook.local.json`, which is gitignored. To disable globally, set `IMPECCABLE_HOOK_DISABLED=1` in your shell environment.
+
+Supported harnesses: Claude Code (`.claude/settings.json` in the project), Codex (`.codex/hooks.json` in the project), and Cursor (`.cursor/hooks.json` in the project).
+
+On **Cursor**, `preToolUse` checks proposed Write/Edit/Shell write content and denies only when the real detector finds an issue. The denial message is visible to the agent as the tool error, so the agent can reconsider before the bad write lands.
+
+## Routing
+
+The first argument is the action. Defaults to `status`.
+
+| Action | What it does |
+|---|---|
+| `status` | Print current state, shared/local config paths, ignored rules / files / values, env override. |
+| `on` | Set `enabled: true` in `.impeccable/hook.json`. |
+| `off` | Set `enabled: false` in `.impeccable/hook.json`. |
+| `ignore-rule <id>` | Append `<id>` to `ignoreRules`; for `overused-font`, requires `--all-values`. |
+| `ignore-file <glob>` | Append `<glob>` to `ignoreFiles`. |
+| `ignore-value <id> <value> [--shared] [--reason "..."]` | Append a rule/value suppression to shared `.impeccable/hook.json`. |
+| `ignore-value <id> <value> --local [--reason "..."]` | Append a private rule/value suppression to `.impeccable/hook.local.json`. |
+| `reset` | Delete the project config, dedup cache, and Cursor pending queue. |
+
+## Flow
+
+1. Resolve the action from the user's argument. If no action was given, default to `status`.
+2. Invoke the admin script and pass the user's output through verbatim:
+
+ ```bash
+ node .trae-cn/skills/impeccable/scripts/hook-admin.mjs <action> [args...]
+ ```
+
+3. If `<action>` is `off`, follow up with a one-line note: "Done. New edits will not trigger the design hook in this project until you run `/impeccable hooks on`."
+4. If `<action>` is `on`, follow up with: "Done. The design hook will fire after the next Edit/Write/MultiEdit on a UI file."
+5. If `<action>` is `ignore-value`, `ignore-file`, or `ignore-rule`, just print the script output. The default scope is shared `.impeccable/hook.json`; add `--local` only when the user explicitly asks for a private exception.
+6. If `<action>` is `status`, just print the script output. Do not add commentary unless the user asked a follow-up question.
+
+## Intentional findings
+
+The hook itself never writes ignore config. Persist an exception only after the user explicitly confirms the flagged issue is intentional, and always go through `hook-admin.mjs`.
+
+Prefer the narrowest exception:
+
+- If the finding line shows an exact `ignore-value` command, run that command. This writes shared `.impeccable/hook.json` by default.
+- For `overused-font`, use `ignore-value` when the user confirms a specific font. Do not use `ignore-rule overused-font` for a specific font.
+- If the finding has no value-specific command, such as `side-tab`, prefer `ignore-file <path>` for the current file.
+- Use `ignore-rule <id>` only when the user asks to suppress that whole rule across the project. For broad overused-font suppression, use `ignore-rule overused-font --all-values` only when the user asks to ignore overused fonts generally.
+- Do not add source comments such as `impeccable: ignore`; inline comments pollute code and are not a supported suppression mechanism.
+
+Example value-specific exception:
+
+```bash
+node .trae-cn/skills/impeccable/scripts/hook-admin.mjs ignore-value overused-font Inter --shared --reason "User confirmed Inter is intentional"
+```
+
+Example whole-rule font exception:
+
+```bash
+node .trae-cn/skills/impeccable/scripts/hook-admin.mjs ignore-rule overused-font --all-values --reason "User asked to ignore overused fonts generally"
+```
+
+Example file-scoped exception:
+
+```bash
+node .trae-cn/skills/impeccable/scripts/hook-admin.mjs ignore-file "src/legacy/Card.tsx"
+```
+
+## Constraints
+
+- Never modify `.impeccable/hook.json` or `.impeccable/hook.local.json` by hand from this command. Always go through `hook-admin.mjs` so writes stay validated and the file shape stays consistent.
+- Do not edit the hook scripts themselves (`hook.mjs`, `hook-lib.mjs`, `hook-before-edit.mjs`) from this flow. Those are skill plumbing.
+- Cursor can block a proposed write when the detector finds a real issue. Claude Code and Codex do not block the edit; they emit a post-edit reminder instead. Disabling stops both blocking and reminders.
+- The hook is bundled with the Impeccable skill and installed through project-local manifests: `.claude/settings.json`, `.codex/hooks.json`, and `.cursor/hooks.json`. On Codex, the user must approve the hook via `/hooks` the first time. On Cursor, confirm hooks are enabled under Settings -> Hooks.
+
+## Failure modes
+
+- If `.impeccable/hook.json` or `.impeccable/hook.local.json` is unreadable or malformed, the hook ignores that file and uses the remaining valid config/defaults. `hook-admin.mjs status` will show malformed files as ignored.
+- If the user asks to "disable the hook" globally, suggest both options: `IMPECCABLE_HOOK_DISABLED=1` env var (one-shot, follows the shell), and `/impeccable hooks off` (persistent for this project, committable).
diff --git a/.trae-cn/skills/impeccable/scripts/detector/engines/regex/detect-text.mjs b/.trae-cn/skills/impeccable/scripts/detector/engines/regex/detect-text.mjs
index fd0d9c73f..4c0777c93 100644
--- a/.trae-cn/skills/impeccable/scripts/detector/engines/regex/detect-text.mjs
+++ b/.trae-cn/skills/impeccable/scripts/detector/engines/regex/detect-text.mjs
@@ -446,7 +446,7 @@ function detectText(content, filePath, options = {}) {
// Run regex matchers on the full file content (catches Tailwind classes, inline styles)
// Enable block context for CSS files where related properties span multiple lines
- const cssLike = new Set(['.css', '.scss', '.less']);
+ const cssLike = new Set(['.css', '.scss', '.sass', '.less']);
findings.push(...runRegexMatchers(lines, filePath, 0, cssLike.has(ext) || null, {
profile,
phase: 'source',
diff --git a/.trae-cn/skills/impeccable/scripts/detector/node/file-system.mjs b/.trae-cn/skills/impeccable/scripts/detector/node/file-system.mjs
index a80250a0e..aaa8c6df7 100644
--- a/.trae-cn/skills/impeccable/scripts/detector/node/file-system.mjs
+++ b/.trae-cn/skills/impeccable/scripts/detector/node/file-system.mjs
@@ -11,7 +11,7 @@ const SKIP_DIRS = new Set([
]);
const SCANNABLE_EXTENSIONS = new Set([
- '.html', '.htm', '.css', '.scss', '.less',
+ '.html', '.htm', '.css', '.scss', '.sass', '.less',
'.jsx', '.tsx', '.js', '.ts',
'.vue', '.svelte', '.astro',
]);
diff --git a/.trae-cn/skills/impeccable/scripts/hook-admin.mjs b/.trae-cn/skills/impeccable/scripts/hook-admin.mjs
new file mode 100644
index 000000000..86fcfa909
--- /dev/null
+++ b/.trae-cn/skills/impeccable/scripts/hook-admin.mjs
@@ -0,0 +1,300 @@
+#!/usr/bin/env node
+/**
+ * `/impeccable hooks <on|off|status|reset>` — manage the design hook
+ * via .impeccable/hook.json and .impeccable/hook.local.json in the current
+ * project.
+ *
+ * Usage:
+ * node hook-admin.mjs status # print current state
+ * node hook-admin.mjs on # set enabled: true
+ * node hook-admin.mjs off # set enabled: false
+ * node hook-admin.mjs ignore-rule <rule-id> # append to ignoreRules
+ * node hook-admin.mjs ignore-rule overused-font --all-values
+ * node hook-admin.mjs ignore-file <glob> # append to ignoreFiles
+ * node hook-admin.mjs ignore-value <rule> <value> # append to shared ignoreValues
+ * node hook-admin.mjs ignore-value <rule> <value> --local
+ * node hook-admin.mjs reset # remove all config + cache
+ *
+ * Designed to be invoked by the LLM from the reference/hooks.md flow.
+ * Output is human-readable; the harness will pass it back to the user.
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+
+import {
+ getConfigPath,
+ getLocalConfigPath,
+ getCachePath,
+ getPendingPath,
+ readConfig,
+ DEFAULT_CONFIG,
+ ensureHookGitExcludes,
+ normalizeIgnoreValue,
+ normalizeIgnoreValueEntries,
+} from './hook-lib.mjs';
+
+const ACTIONS = new Set(['status', 'on', 'off', 'ignore-rule', 'ignore-file', 'ignore-value', 'reset']);
+
+function readRawConfigFile(filePath) {
+ if (!fs.existsSync(filePath)) return { exists: false, malformed: false, raw: null };
+ try {
+ return { exists: true, malformed: false, raw: JSON.parse(fs.readFileSync(filePath, 'utf-8')) };
+ } catch {
+ return { exists: true, malformed: true, raw: null };
+ }
+}
+
+function readRawConfig(cwd, opts = {}) {
+ const filePath = opts.local ? getLocalConfigPath(cwd) : getConfigPath(cwd);
+ return readRawConfigFile(filePath).raw;
+}
+
+function writeConfig(cwd, config, opts = {}) {
+ const filePath = opts.local ? getLocalConfigPath(cwd) : getConfigPath(cwd);
+ if (opts.local) ensureHookGitExcludes(cwd);
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
+ fs.writeFileSync(filePath, JSON.stringify(config, null, 2) + '\n');
+ return filePath;
+}
+
+function mergeConfig(existing) {
+ // Persist the full shape so /impeccable hooks edits leave a complete file
+ // for the user to see, not an unhelpful `{"enabled":false}`.
+ const base = existing && typeof existing === 'object' ? existing : {};
+ return {
+ enabled: base.enabled === false ? false : true,
+ ignoreRules: Array.isArray(base.ignoreRules) ? Array.from(new Set(base.ignoreRules.map(String))) : [],
+ ignoreFiles: Array.isArray(base.ignoreFiles) ? Array.from(new Set(base.ignoreFiles.map(String))) : [],
+ ignoreValues: normalizeIgnoreValueEntries(base.ignoreValues || []),
+ limits: {
+ maxFindings: Number.isFinite(base?.limits?.maxFindings) ? base.limits.maxFindings : DEFAULT_CONFIG.limits.maxFindings,
+ maxChars: Number.isFinite(base?.limits?.maxChars) ? base.limits.maxChars : DEFAULT_CONFIG.limits.maxChars,
+ },
+ };
+}
+
+function mergeLocalConfig(existing) {
+ const base = existing && typeof existing === 'object' ? existing : {};
+ const out = {};
+ if (Object.prototype.hasOwnProperty.call(base, 'enabled')) {
+ out.enabled = base.enabled === false ? false : true;
+ }
+ if (Array.isArray(base.ignoreRules)) {
+ out.ignoreRules = Array.from(new Set(base.ignoreRules.map(String)));
+ }
+ if (Array.isArray(base.ignoreFiles)) {
+ out.ignoreFiles = Array.from(new Set(base.ignoreFiles.map(String)));
+ }
+ out.ignoreValues = normalizeIgnoreValueEntries(base.ignoreValues || []);
+ if (base.limits && typeof base.limits === 'object') {
+ const limits = {};
+ if (Number.isFinite(base.limits.maxFindings)) limits.maxFindings = base.limits.maxFindings;
+ if (Number.isFinite(base.limits.maxChars)) limits.maxChars = base.limits.maxChars;
+ if (Object.keys(limits).length) out.limits = limits;
+ }
+ return out;
+}
+
+function statusReport(cwd) {
+ const shared = readRawConfigFile(getConfigPath(cwd));
+ const local = readRawConfigFile(getLocalConfigPath(cwd));
+ const cfg = readConfig(cwd);
+ const envKill = process.env.IMPECCABLE_HOOK_DISABLED;
+ const envState = envKill ? `IMPECCABLE_HOOK_DISABLED=${envKill}` : 'unset';
+ const cfgPath = path.relative(cwd, getConfigPath(cwd)) || '.impeccable/hook.json';
+ const localPath = path.relative(cwd, getLocalConfigPath(cwd)) || '.impeccable/hook.local.json';
+ const cachePath = path.relative(cwd, getCachePath(cwd)) || '.impeccable/hook.cache.json';
+ const fileState = (info, relPath, absent) => {
+ if (info.malformed) return `${relPath} (malformed; ignored)`;
+ if (info.exists) return relPath;
+ return `${relPath} (${absent})`;
+ };
+ const ignoreValues = cfg.ignoreValues.map((entry) => `${entry.rule}=${entry.value}`);
+
+ const lines = [
+ `Impeccable design hook`,
+ ` state: ${cfg.enabled ? 'enabled' : 'disabled'}`,
+ ` shared file: ${fileState(shared, cfgPath, 'using defaults; file not present')}`,
+ ` local file: ${fileState(local, localPath, 'not present')}`,
+ ` ignoreRules: ${cfg.ignoreRules.length ? cfg.ignoreRules.join(', ') : '(none)'}`,
+ ` ignoreFiles: ${cfg.ignoreFiles.length ? cfg.ignoreFiles.join(', ') : '(none)'}`,
+ ` ignoreValues: ${ignoreValues.length ? ignoreValues.join(', ') : '(none)'}`,
+ ` maxFindings: ${cfg.limits.maxFindings}`,
+ ` maxChars: ${cfg.limits.maxChars}`,
+ ` env override: ${envState}`,
+ ` cache file: ${fs.existsSync(getCachePath(cwd)) ? cachePath : `${cachePath} (not present)`}`,
+ ];
+ return lines.join('\n');
+}
+
+function setEnabled(cwd, value) {
+ const config = mergeConfig(readRawConfig(cwd));
+ config.enabled = value;
+ const target = writeConfig(cwd, config);
+ return `Design hook ${value ? 'enabled' : 'disabled'} for this project (wrote ${path.relative(cwd, target) || target}).`;
+}
+
+function normalizeRuleId(rule) {
+ return String(rule || '').trim().toLowerCase();
+}
+
+function parseIgnoreRuleArgs(args) {
+ const positionals = [];
+ let allValues = false;
+
+ for (let i = 0; i < args.length; i++) {
+ const arg = String(args[i] || '');
+ if (arg === '--all-values') {
+ allValues = true;
+ } else if (arg === '--reason') {
+ while (i + 1 < args.length && !String(args[i + 1]).startsWith('--')) i++;
+ } else if (arg.startsWith('--reason=')) {
+ // Accepted for command symmetry; ignoreRules stores rule ids only.
+ } else if (arg.startsWith('--')) {
+ throw new Error(`Unknown ignore-rule flag: ${arg}`);
+ } else {
+ positionals.push(arg);
+ }
+ }
+
+ return {
+ rule: normalizeRuleId(positionals[0]),
+ allValues,
+ };
+}
+
+function addIgnoreRule(cwd, args) {
+ const parsed = parseIgnoreRuleArgs(args);
+ const rule = parsed.rule;
+ if (!rule) throw new Error('Pass a rule id, e.g. /impeccable hooks ignore-rule side-tab');
+ if (rule === 'overused-font' && !parsed.allValues) {
+ throw new Error('overused-font is value-specific by default. Use /impeccable hooks ignore-value overused-font <font> for a confirmed font, or /impeccable hooks ignore-rule overused-font --all-values only when the user asked to ignore overused fonts generally.');
+ }
+ const config = mergeConfig(readRawConfig(cwd));
+ if (!config.ignoreRules.includes(rule)) config.ignoreRules.push(rule);
+ writeConfig(cwd, config);
+ return `Added "${rule}" to ignoreRules. Current: ${config.ignoreRules.join(', ')}`;
+}
+
+function addIgnoreFile(cwd, glob) {
+ if (!glob) throw new Error('Pass a glob, e.g. /impeccable hooks ignore-file "src/legacy/**"');
+ const config = mergeConfig(readRawConfig(cwd));
+ if (!config.ignoreFiles.includes(glob)) config.ignoreFiles.push(glob);
+ writeConfig(cwd, config);
+ return `Added "${glob}" to ignoreFiles. Current: ${config.ignoreFiles.join(', ')}`;
+}
+
+function parseIgnoreValueArgs(args) {
+ const positionals = [];
+ let shared = false;
+ let local = false;
+ let reason = '';
+
+ for (let i = 0; i < args.length; i++) {
+ const arg = args[i];
+ if (arg === '--shared') {
+ shared = true;
+ } else if (arg === '--local') {
+ local = true;
+ } else if (arg === '--reason') {
+ const chunks = [];
+ while (i + 1 < args.length && !String(args[i + 1]).startsWith('--')) {
+ chunks.push(args[++i]);
+ }
+ reason = chunks.join(' ').trim();
+ } else if (String(arg).startsWith('--reason=')) {
+ reason = String(arg).slice('--reason='.length).trim();
+ } else {
+ positionals.push(arg);
+ }
+ }
+
+ const [rule, ...valueParts] = positionals;
+ return {
+ rule: String(rule || '').trim().toLowerCase(),
+ value: normalizeIgnoreValue(valueParts.join(' ')),
+ shared,
+ local,
+ reason,
+ };
+}
+
+function addIgnoreValue(cwd, args) {
+ const parsed = parseIgnoreValueArgs(args);
+ if (!parsed.rule || !parsed.value) {
+ throw new Error('Pass a rule id and value, e.g. /impeccable hooks ignore-value overused-font Inter');
+ }
+
+ if (parsed.shared && parsed.local) {
+ throw new Error('Pass only one scope flag: --shared or --local');
+ }
+
+ const local = parsed.local;
+ const config = local
+ ? mergeLocalConfig(readRawConfig(cwd, { local: true }))
+ : mergeConfig(readRawConfig(cwd, { local: false }));
+ const key = `${parsed.rule}\0${parsed.value}`;
+ const existing = config.ignoreValues.find((entry) => `${entry.rule}\0${entry.value}` === key);
+
+ if (existing) {
+ if (parsed.reason) existing.reason = parsed.reason;
+ } else {
+ const entry = {
+ rule: parsed.rule,
+ value: parsed.value,
+ createdAt: new Date().toISOString(),
+ };
+ if (parsed.reason) entry.reason = parsed.reason;
+ config.ignoreValues.push(entry);
+ }
+
+ const target = writeConfig(cwd, config, { local });
+ const scope = local ? 'local ignoreValues' : 'shared ignoreValues';
+ return `Added ${parsed.rule}=${parsed.value} to ${scope} (${path.relative(cwd, target) || target}).`;
+}
+
+function reset(cwd) {
+ const removed = [];
+ for (const filePath of [getConfigPath(cwd), getLocalConfigPath(cwd), getCachePath(cwd), getPendingPath(cwd)]) {
+ try {
+ if (fs.existsSync(filePath)) {
+ fs.unlinkSync(filePath);
+ removed.push(path.relative(cwd, filePath) || filePath);
+ }
+ } catch { /* ignore */ }
+ }
+ return removed.length
+ ? `Reset design hook config and cache (removed: ${removed.join(', ')}).`
+ : 'No hook config or cache to remove. Already at defaults.';
+}
+
+function main() {
+ const [, , actionArg, ...rest] = process.argv;
+ const action = (actionArg || 'status').toLowerCase();
+ const cwd = process.cwd();
+
+ if (!ACTIONS.has(action)) {
+ process.stderr.write(`Unknown action: ${action}\nValid: ${Array.from(ACTIONS).join(', ')}\n`);
+ process.exit(1);
+ }
+
+ try {
+ let out = '';
+ switch (action) {
+ case 'status': out = statusReport(cwd); break;
+ case 'on': out = setEnabled(cwd, true); break;
+ case 'off': out = setEnabled(cwd, false); break;
+ case 'ignore-rule': out = addIgnoreRule(cwd, rest); break;
+ case 'ignore-file': out = addIgnoreFile(cwd, rest[0]); break;
+ case 'ignore-value': out = addIgnoreValue(cwd, rest); break;
+ case 'reset': out = reset(cwd); break;
+ }
+ process.stdout.write(out + '\n');
+ } catch (err) {
+ process.stderr.write(`Error: ${err.message || err}\n`);
+ process.exit(1);
+ }
+}
+
+main();
diff --git a/.trae-cn/skills/impeccable/scripts/hook-before-edit.mjs b/.trae-cn/skills/impeccable/scripts/hook-before-edit.mjs
new file mode 100644
index 000000000..54b2709d2
--- /dev/null
+++ b/.trae-cn/skills/impeccable/scripts/hook-before-edit.mjs
@@ -0,0 +1,408 @@
+#!/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 shellContent = shellHereDocContent(shellCommand(input));
+ if (shellContent) return shellContent;
+ const copiedContent = shellCopiedFileContent(shellCommand(input), 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 || '';
+}
+
+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 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' });
+});
diff --git a/.trae-cn/skills/impeccable/scripts/hook-lib.mjs b/.trae-cn/skills/impeccable/scripts/hook-lib.mjs
new file mode 100644
index 000000000..02199f530
--- /dev/null
+++ b/.trae-cn/skills/impeccable/scripts/hook-lib.mjs
@@ -0,0 +1,1232 @@
+/**
+ * Shared library for the Impeccable design hook.
+ *
+ * Pure-ish helpers split out from `hook.mjs` so unit tests can exercise
+ * config parsing, finding filtering, dedup, render, and cache logic without
+ * spawning a subprocess. `hook.mjs` itself is the thin stdin/stdout shim.
+ *
+ * Public surface (everything exported is part of the contract):
+ * ENVELOPE_PREFIX, ALLOWED_EXTS, ACK_EXTS, SENSITIVE_PATH, GENERATED_PATH, TRUTHY
+ * truthy(value)
+ * readConfig(cwd) / DEFAULT_CONFIG / getConfigPath(cwd) / getLocalConfigPath(cwd)
+ * normalizeIgnoreValue(value)
+ * readCache(cwd) / persistCache(cwd, cache)
+ * bumpEditCount(cache, sessionId, filePath) -> number
+ * suppressionNotice(filePath)
+ * filterFindings(findings, content, ext, config)
+ * dedupeAgainstCache(findings, cache, sessionId, filePath)
+ * renderTemplate(findings, filePath, config, opts)
+ * renderCleanAck(filePath, opts) / renderPendingAck(filePath, known, opts)
+ * shouldEmitAckForFile(filePath)
+ * writeAuditLog(env, entry)
+ * loadDetector() -> Promise<{ detectText, detectHtml }>
+ * matchesAnyGlob(filePath, globs)
+ * normalizeScanTargets(primaryTargets, projectCwd)
+ * runHook(deps) -> { exitCode, stdout, audit, reason? }
+ *
+ * Design notes:
+ * - All errors are swallowed at the runHook seam. The detector throwing must
+ * never break a turn. See PRD §5 "Failure modes".
+ * - Cache shape is JSON-friendly; we gc the oldest sessions when there are
+ * more than 8 to keep file size predictable across long-lived projects.
+ * - The detector loader looks for `detector/detect-antipatterns.mjs` next to
+ * this file first (built skill layout) and falls back to the repo root's
+ * `cli/engine/detect-antipatterns.mjs` (running from source).
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+import { pathToFileURL, fileURLToPath } from 'node:url';
+
+const __filename = fileURLToPath(import.meta.url);
+const __dirname = path.dirname(__filename);
+
+export const ENVELOPE_PREFIX = '[impeccable@1]';
+
+export const ALLOWED_EXTS = new Set([
+ '.tsx', '.jsx', '.html', '.htm', '.vue', '.svelte', '.astro',
+ '.css', '.scss', '.sass', '.less', '.ts', '.js',
+]);
+
+export const ACK_EXTS = new Set([
+ '.tsx', '.jsx', '.html', '.htm', '.vue', '.svelte', '.astro',
+ '.css', '.scss', '.sass', '.less',
+]);
+
+// Hard-skip regex for sensitive files. Cannot be turned off via config.
+// Match tokenized secret/credential filenames, not UI names such as
+// CredentialForm.tsx, SecretPage.jsx, or secretary-dashboard.vue.
+export const SENSITIVE_PATH = new RegExp([
+ String.raw`(?:^|[/\\])\.env(?:\.|$)`,
+ String.raw`(?:^|[/\\])\.git(?:[/\\]|$)`,
+ String.raw`(?:^|[/\\])id_rsa(?:$|[._-])[^/\\]*$`,
+ String.raw`(?:^|[/\\])[^/\\]*\.pem$`,
+ String.raw`(?:^|[/\\])(?:[^/\\]*[._-])?(?:secret|secrets|credential|credentials)(?=[._-])[^/\\]*\.(?:json|ya?ml|toml|ini|conf|config|env|txt|key|cert|crt|pem|js|ts)$`,
+].join('|'), 'i');
+
+// Hard-skip regex for generated, lock, minified, and build-output paths.
+export const GENERATED_PATH = /(?:\.generated\.[a-z]+$|\.d\.ts$|\.min\.[a-z]+$|[/\\]node_modules[/\\]|[/\\](?:dist|build|out|\.next|\.cache|coverage)[/\\]|[/\\]?[^/\\]+\.lock(?:\.json)?$)/i;
+
+export const TRUTHY = /^(1|true|yes|on)$/i;
+
+export const DEFAULT_CONFIG = Object.freeze({
+ enabled: true,
+ ignoreRules: [],
+ ignoreFiles: [],
+ ignoreValues: [],
+ limits: { maxFindings: 5, maxChars: 8000 },
+});
+
+export const HOOK_LOCAL_IGNORE_PATTERNS = Object.freeze([
+ '.impeccable/hook.cache.json',
+ '.impeccable/hook.pending.json',
+ '.impeccable/hook.local.json',
+]);
+
+const HOOK_IGNORE_MARKER_OPEN = '# impeccable-hook-ignore-start';
+const HOOK_IGNORE_MARKER_CLOSE = '# impeccable-hook-ignore-end';
+const CACHE_MAX_SESSIONS = 8;
+export const EDIT_COUNT_THRESHOLD = 6;
+
+export function truthy(value) {
+ return typeof value === 'string' && TRUTHY.test(value);
+}
+
+function depthIsSet(value) {
+ if (value === undefined || value === null) return false;
+ const text = String(value).trim();
+ if (!text) return false;
+ if (TRUTHY.test(text)) return true;
+ return /^\d+$/.test(text) && Number(text) > 0;
+}
+
+function safeReadJson(filePath) {
+ try {
+ return JSON.parse(fs.readFileSync(filePath, 'utf-8'));
+ } catch {
+ return null;
+ }
+}
+
+export function getConfigPath(cwd) {
+ return path.join(cwd, '.impeccable', 'hook.json');
+}
+
+export function getLocalConfigPath(cwd) {
+ return path.join(cwd, '.impeccable', 'hook.local.json');
+}
+
+export function getCachePath(cwd) {
+ return path.join(cwd, '.impeccable', 'hook.cache.json');
+}
+
+export function getPendingPath(cwd) {
+ return path.join(cwd, '.impeccable', 'hook.pending.json');
+}
+
+export function resolveProjectCwd(event, fallback = process.cwd()) {
+ return event?.cwd
+ || (Array.isArray(event?.workspace_roots) && event.workspace_roots[0])
+ || envProjectDir(fallback)
+ || fallback;
+}
+
+export function readConfig(cwd) {
+ const config = cloneDefaultConfig();
+ applyConfigSource(config, safeReadJson(getConfigPath(cwd)));
+ applyConfigSource(config, safeReadJson(getLocalConfigPath(cwd)));
+ return config;
+}
+
+function numberOr(value, fallback) {
+ return Number.isFinite(value) && value > 0 ? value : fallback;
+}
+
+function cloneDefaultConfig() {
+ return {
+ ...DEFAULT_CONFIG,
+ ignoreRules: [],
+ ignoreFiles: [],
+ ignoreValues: [],
+ limits: { ...DEFAULT_CONFIG.limits },
+ };
+}
+
+function applyConfigSource(config, raw) {
+ if (!raw || typeof raw !== 'object') return config;
+ if (Object.prototype.hasOwnProperty.call(raw, 'enabled')) {
+ config.enabled = raw.enabled === false ? false : true;
+ }
+ if (Array.isArray(raw.ignoreRules)) {
+ config.ignoreRules = uniqueStrings([...config.ignoreRules, ...raw.ignoreRules]);
+ }
+ if (Array.isArray(raw.ignoreFiles)) {
+ config.ignoreFiles = uniqueStrings([...config.ignoreFiles, ...raw.ignoreFiles]);
+ }
+ if (Array.isArray(raw.ignoreValues)) {
+ config.ignoreValues = mergeIgnoreValues(config.ignoreValues, raw.ignoreValues);
+ }
+ if (raw.limits && typeof raw.limits === 'object') {
+ config.limits = {
+ maxFindings: numberOr(raw.limits.maxFindings, config.limits.maxFindings),
+ maxChars: numberOr(raw.limits.maxChars, config.limits.maxChars),
+ };
+ }
+ return config;
+}
+
+function uniqueStrings(values) {
+ return Array.from(new Set(values.map(String)));
+}
+
+export function normalizeIgnoreValue(value) {
+ return String(value || '')
+ .trim()
+ .replace(/^["']|["']$/g, '')
+ .replace(/\+/g, ' ')
+ .replace(/\s+/g, ' ')
+ .toLowerCase();
+}
+
+function normalizeIgnoreRule(rule) {
+ return String(rule || '').trim().toLowerCase();
+}
+
+export function normalizeIgnoreValueEntries(entries) {
+ if (!Array.isArray(entries)) return [];
+ const out = [];
+ for (const entry of entries) {
+ if (!entry || typeof entry !== 'object') continue;
+ const rule = normalizeIgnoreRule(entry.rule);
+ const value = normalizeIgnoreValue(entry.value);
+ if (!rule || !value) continue;
+ const normalized = { rule, value };
+ if (typeof entry.reason === 'string' && entry.reason.trim()) {
+ normalized.reason = entry.reason.trim();
+ }
+ if (typeof entry.createdAt === 'string' && entry.createdAt.trim()) {
+ normalized.createdAt = entry.createdAt.trim();
+ }
+ out.push(normalized);
+ }
+ return out;
+}
+
+function mergeIgnoreValues(existing, incoming) {
+ const map = new Map();
+ for (const entry of normalizeIgnoreValueEntries(existing)) {
+ map.set(`${entry.rule}\0${entry.value}`, entry);
+ }
+ for (const entry of normalizeIgnoreValueEntries(incoming)) {
+ map.set(`${entry.rule}\0${entry.value}`, entry);
+ }
+ return Array.from(map.values());
+}
+
+export function readCache(cwd) {
+ const raw = safeReadJson(getCachePath(cwd));
+ if (!raw || typeof raw !== 'object' || raw.version !== 1) {
+ return { version: 1, sessions: {} };
+ }
+ return {
+ version: 1,
+ sessions: raw.sessions && typeof raw.sessions === 'object' ? raw.sessions : {},
+ };
+}
+
+export function persistCache(cwd, cache) {
+ const sessions = cache.sessions || {};
+ const ids = Object.keys(sessions);
+ if (ids.length > CACHE_MAX_SESSIONS) {
+ // Garbage-collect oldest sessions by updatedAt.
+ const ordered = ids
+ .map((id) => [id, sessions[id]?.updatedAt || 0])
+ .sort((a, b) => b[1] - a[1])
+ .slice(0, CACHE_MAX_SESSIONS);
+ const next = {};
+ for (const [id] of ordered) next[id] = sessions[id];
+ cache = { ...cache, sessions: next };
+ }
+ const target = getCachePath(cwd);
+ try {
+ ensureHookGitExcludes(cwd);
+ fs.mkdirSync(path.dirname(target), { recursive: true });
+ fs.writeFileSync(target, JSON.stringify(cache));
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+export function ensureHookGitExcludes(cwd = process.cwd()) {
+ try {
+ const target = resolveHookGitExcludeTarget(cwd);
+ if (!target) {
+ return { mode: 'none', changed: false, patterns: [...HOOK_LOCAL_IGNORE_PATTERNS] };
+ }
+
+ const patterns = target.patternPrefix
+ ? HOOK_LOCAL_IGNORE_PATTERNS.map((pattern) => `${target.patternPrefix}/${pattern}`)
+ : [...HOOK_LOCAL_IGNORE_PATTERNS];
+ const markerSuffix = target.patternPrefix || '.';
+ const markerOpen = `${HOOK_IGNORE_MARKER_OPEN} ${markerSuffix}`;
+ const markerClose = `${HOOK_IGNORE_MARKER_CLOSE} ${markerSuffix}`;
+ const existing = fs.existsSync(target.path) ? fs.readFileSync(target.path, 'utf-8') : '';
+ const block = [markerOpen, ...patterns, markerClose].join('\n');
+ const markerRe = new RegExp(`${escapeRegExp(markerOpen)}[\\s\\S]*?${escapeRegExp(markerClose)}`);
+
+ let updated;
+ if (markerRe.test(existing)) {
+ updated = existing.replace(markerRe, block);
+ } else {
+ const prefix = existing.length === 0 ? '' : existing.endsWith('\n') ? existing : `${existing}\n`;
+ updated = `${prefix}${prefix.endsWith('\n\n') || prefix === '' ? '' : '\n'}${block}\n`;
+ }
+
+ if (updated !== existing) {
+ fs.mkdirSync(path.dirname(target.path), { recursive: true });
+ fs.writeFileSync(target.path, updated, 'utf-8');
+ }
+
+ return {
+ mode: 'git-info-exclude',
+ file: path.relative(path.resolve(cwd), target.path).split(path.sep).join('/'),
+ changed: updated !== existing,
+ patterns,
+ };
+ } catch {
+ return { mode: 'error', changed: false, patterns: [...HOOK_LOCAL_IGNORE_PATTERNS] };
+ }
+}
+
+function resolveHookGitExcludeTarget(cwd) {
+ const start = path.resolve(cwd);
+ let dir = start;
+ while (true) {
+ const dotGit = path.join(dir, '.git');
+ if (fs.existsSync(dotGit)) {
+ const gitDir = resolveGitDir(dotGit, dir);
+ if (!gitDir) return null;
+ const relPrefix = path.relative(dir, start).split(path.sep).join('/');
+ return {
+ path: path.join(gitDir, 'info', 'exclude'),
+ patternPrefix: relPrefix && relPrefix !== '.' ? relPrefix : '',
+ };
+ }
+ const parent = path.dirname(dir);
+ if (parent === dir) return null;
+ dir = parent;
+ }
+}
+
+function resolveGitDir(dotGit, worktreeDir) {
+ const stat = fs.statSync(dotGit);
+ if (stat.isDirectory()) return dotGit;
+ if (!stat.isFile()) return null;
+
+ const body = fs.readFileSync(dotGit, 'utf-8').trim();
+ const match = body.match(/^gitdir:\s*(.+)$/i);
+ if (!match) return null;
+ return path.isAbsolute(match[1]) ? match[1] : path.resolve(worktreeDir, match[1]);
+}
+
+function escapeRegExp(value) {
+ return String(value).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+}
+
+function ensureSession(cache, sessionId) {
+ if (!cache.sessions[sessionId]) {
+ cache.sessions[sessionId] = { updatedAt: Date.now(), files: {} };
+ }
+ return cache.sessions[sessionId];
+}
+
+function ensureFile(cache, sessionId, filePath) {
+ const session = ensureSession(cache, sessionId);
+ if (!session.files[filePath]) {
+ session.files[filePath] = { editCount: 0, findings: [] };
+ }
+ return session.files[filePath];
+}
+
+export function bumpEditCount(cache, sessionId, filePath) {
+ const fileEntry = ensureFile(cache, sessionId, filePath);
+ fileEntry.editCount = (fileEntry.editCount || 0) + 1;
+ ensureSession(cache, sessionId).updatedAt = Date.now();
+ return fileEntry.editCount;
+}
+
+export function suppressionNotice(filePath) {
+ return `${ENVELOPE_PREFIX} Suppressing further design hints on ${filePath}. More than ${EDIT_COUNT_THRESHOLD} edits in this session reached. Run /impeccable audit to revisit.`;
+}
+
+// Glob → RegExp. Supports `**`, `*`, `?`, and `{a,b}` alternation.
+function globToRegex(glob) {
+ let re = '^';
+ let i = 0;
+ while (i < glob.length) {
+ const c = glob[i];
+ if (c === '*') {
+ if (glob[i + 1] === '*') {
+ re += '.*';
+ i += 2;
+ if (glob[i] === '/') i += 1;
+ } else {
+ re += '[^/]*';
+ i += 1;
+ }
+ } else if (c === '?') {
+ re += '[^/]';
+ i += 1;
+ } else if (c === '{') {
+ const end = glob.indexOf('}', i);
+ if (end === -1) { re += '\\{'; i += 1; continue; }
+ const parts = glob.slice(i + 1, end).split(',').map((p) => p.replace(/[.+^$()|[\]\\]/g, '\\$&'));
+ re += `(?:${parts.join('|')})`;
+ i = end + 1;
+ } else if (/[.+^$()|[\]\\]/.test(c)) {
+ re += `\\${c}`;
+ i += 1;
+ } else {
+ re += c;
+ i += 1;
+ }
+ }
+ re += '$';
+ return new RegExp(re);
+}
+
+export function matchesAnyGlob(filePath, globs) {
+ if (!Array.isArray(globs) || globs.length === 0) return false;
+ const normalized = filePath.split(path.sep).join('/');
+ for (const glob of globs) {
+ try {
+ const re = globToRegex(String(glob));
+ if (re.test(normalized)) return true;
+ // Match against basename too for convenience: `*.generated.tsx` should
+ // catch `src/foo.generated.tsx` without requiring `**/`.
+ const base = normalized.split('/').pop();
+ if (re.test(base)) return true;
+ } catch {
+ /* malformed glob, skip */
+ }
+ }
+ return false;
+}
+
+export function filterFindings(findings, _content, _ext, config) {
+ if (!Array.isArray(findings) || findings.length === 0) return [];
+ const ignoreRules = new Set((config.ignoreRules || []).map((rule) => normalizeIgnoreRule(rule)));
+ const ignoreValues = normalizeIgnoreValueEntries(config.ignoreValues || []);
+ return findings.filter((f) => {
+ if (!f || typeof f !== 'object') return false;
+ if (ignoreRules.has(normalizeIgnoreRule(f.antipattern))) return false;
+ if (isIgnoredFindingValue(f, ignoreValues)) return false;
+ return true;
+ });
+}
+
+function isIgnoredFindingValue(finding, ignoreValues) {
+ if (!Array.isArray(ignoreValues) || ignoreValues.length === 0) return false;
+ const rule = normalizeIgnoreRule(finding.antipattern);
+ const value = extractFindingIgnoreValue(finding);
+ if (!rule || !value) return false;
+ return ignoreValues.some((entry) => entry.rule === rule && entry.value === value);
+}
+
+export function extractFindingIgnoreValue(finding) {
+ if (!finding || typeof finding !== 'object') return '';
+ const rule = normalizeIgnoreRule(finding.antipattern);
+ if (rule !== 'overused-font') return '';
+ return normalizeIgnoreValue(extractFindingIgnoreValueRaw(finding));
+}
+
+function extractFindingIgnoreValueRaw(finding) {
+ const direct = cleanIgnoreValueDisplay(finding.ignoreValue || finding.value || '');
+ if (direct) return direct;
+
+ const candidates = [finding.detail, finding.snippet].filter((v) => typeof v === 'string' && v);
+ for (const text of candidates) {
+ const primary = text.match(/Primary font:\s*([^()\n;]+)/i);
+ if (primary) return cleanIgnoreValueDisplay(primary[1]);
+
+ const family = text.match(/font-family\s*:\s*["']?([^'",;\n]+)/i);
+ if (family) return cleanIgnoreValueDisplay(family[1]);
+
+ const google = text.match(/[?&]family=([^&:;\n]+)/i);
+ if (google) {
+ try {
+ return cleanIgnoreValueDisplay(decodeURIComponent(google[1]));
+ } catch {
+ return cleanIgnoreValueDisplay(google[1]);
+ }
+ }
+ }
+
+ return '';
+}
+
+function cleanIgnoreValueDisplay(value) {
+ return String(value || '')
+ .trim()
+ .replace(/^["']|["']$/g, '')
+ .replace(/\+/g, ' ')
+ .replace(/\s+/g, ' ');
+}
+
+export function dedupeAgainstCache(findings, cache, sessionId, filePath) {
+ if (!Array.isArray(findings) || findings.length === 0) return [];
+ const fileEntry = ensureFile(cache, sessionId, filePath);
+ const known = new Set(fileEntry.findings || []);
+ const fresh = [];
+ for (const f of findings) {
+ const key = `${f.antipattern}:${f.line || 0}`;
+ if (known.has(key)) continue;
+ known.add(key);
+ fresh.push(f);
+ }
+ return fresh;
+}
+
+export function rememberFindings(cache, sessionId, filePath, findings) {
+ const fileEntry = ensureFile(cache, sessionId, filePath);
+ const known = new Set(fileEntry.findings || []);
+ for (const f of findings) known.add(`${f.antipattern}:${f.line || 0}`);
+ fileEntry.findings = Array.from(known);
+ ensureSession(cache, sessionId).updatedAt = Date.now();
+}
+
+export function renderTemplate(findings, filePath, config, opts = {}) {
+ if (!Array.isArray(findings) || findings.length === 0) return '';
+ const limits = config?.limits || DEFAULT_CONFIG.limits;
+ const cap = Math.max(1, limits.maxFindings || DEFAULT_CONFIG.limits.maxFindings);
+ const maxChars = Math.max(500, limits.maxChars || DEFAULT_CONFIG.limits.maxChars);
+
+ const cwd = opts.cwd || process.cwd();
+ const display = relativize(filePath, cwd);
+ const total = findings.length;
+ const shown = findings.slice(0, cap);
+ const remaining = total - shown.length;
+
+ const header = `${ENVELOPE_PREFIX} Required design corrections in ${display} (${total} issue(s)):`;
+ const lines = shown.map((f) => formatFindingLine(f));
+ const more = remaining > 0
+ ? `... and ${remaining} more (see /impeccable audit).`
+ : null;
+ const footer = directiveFooter(display);
+
+ const blocks = [header, ...lines];
+ if (more) blocks.push(more);
+ blocks.push('');
+ blocks.push(footer);
+ let text = blocks.join('\n');
+
+ if (text.length > maxChars) {
+ text = clampToBudget(header, lines, more, footer, maxChars);
+ }
+ return text;
+}
+
+function renderGroupedTemplate(groups, config, opts = {}) {
+ const realGroups = groups.filter((group) => Array.isArray(group.findings) && group.findings.length > 0);
+ if (realGroups.length === 0) return '';
+ if (realGroups.length === 1) {
+ const [group] = realGroups;
+ return renderTemplate(group.findings, group.filePath, config, opts);
+ }
+
+ const limits = config?.limits || DEFAULT_CONFIG.limits;
+ const cap = Math.max(1, limits.maxFindings || DEFAULT_CONFIG.limits.maxFindings);
+ const maxChars = Math.max(500, limits.maxChars || DEFAULT_CONFIG.limits.maxChars);
+ const cwd = opts.cwd || process.cwd();
+ const total = realGroups.reduce((sum, group) => sum + group.findings.length, 0);
+ const header = `${ENVELOPE_PREFIX} Required design corrections across ${realGroups.length} files (${total} issue(s)):`;
+ const lines = [];
+ let shownCount = 0;
+
+ for (const group of realGroups) {
+ const display = relativize(group.filePath, cwd);
+ lines.push(`${display} (${group.findings.length} issue(s)):`);
+ const remainingCap = Math.max(0, cap - shownCount);
+ const shown = group.findings.slice(0, remainingCap);
+ for (const finding of shown) {
+ lines.push(formatFindingLine(finding));
+ }
+ shownCount += shown.length;
+ const hidden = group.findings.length - shown.length;
+ if (hidden > 0) {
+ lines.push(`- ... ${hidden} more in ${display} (see /impeccable audit).`);
+ }
+ }
+
+ const footer = directiveFooter('the affected files', { grouped: true });
+ let text = [header, ...lines, '', footer].join('\n');
+ if (text.length > maxChars) {
+ text = clampGroupedToBudget(header, lines, footer, maxChars);
+ }
+ return text;
+}
+
+function clampGroupedToBudget(header, lines, footer, maxChars) {
+ const assemble = (linesArr, omitted) => [
+ header,
+ ...linesArr,
+ ...(omitted ? ['... and more (see /impeccable audit).'] : []),
+ '',
+ footer,
+ ].join('\n');
+
+ let working = lines.slice();
+ let omitted = false;
+ let assembled = assemble(working, omitted);
+ while (assembled.length > maxChars && working.length > 1) {
+ working.pop();
+ omitted = true;
+ assembled = assemble(working, omitted);
+ }
+ if (assembled.length > maxChars) {
+ assembled = `${assembled.slice(0, maxChars - 1)}…`;
+ }
+ return assembled;
+}
+
+function clampToBudget(header, lines, more, footer, maxChars) {
+ const assemble = (linesArr, moreText) => {
+ const blocks = [header, ...linesArr];
+ if (moreText) blocks.push(moreText);
+ blocks.push('');
+ blocks.push(footer);
+ return blocks.join('\n');
+ };
+
+ let working = lines.slice();
+ let moreText = more;
+ let assembled = assemble(working, moreText);
+ while (assembled.length > maxChars && working.length > 1) {
+ working.pop();
+ moreText = '... and more (see /impeccable audit).';
+ assembled = assemble(working, moreText);
+ }
+ if (assembled.length > maxChars) {
+ assembled = `${assembled.slice(0, maxChars - 1)}…`;
+ }
+ return assembled;
+}
+
+function formatFindingLine(f) {
+ const prefix = f.line && f.line > 0 ? `- L${f.line}` : '-';
+ const desc = (f.description || '').trim();
+ const name = (f.name || '').trim();
+ // Description from the registry already ends in punctuation; join with a
+ // single space. `name` may have a trailing period already, keep it clean.
+ const nameSegment = name ? `${name.replace(/\.+\s*$/, '')}.` : '';
+ const ignoreCommand = formatFindingIgnoreCommand(f);
+ const ignoreSegment = ignoreCommand
+ ? ` If the user explicitly confirms this value is intentional: \`${ignoreCommand}\`.`
+ : '';
+ return `${prefix} [${f.antipattern}] ${nameSegment} ${desc}${ignoreSegment}`.replace(/\s+/g, ' ').trim();
+}
+
+function formatFindingIgnoreCommand(finding) {
+ if (!finding || typeof finding !== 'object') return '';
+ const rule = normalizeIgnoreRule(finding.antipattern);
+ if (!rule) return '';
+ const normalizedValue = extractFindingIgnoreValue(finding);
+ if (!normalizedValue) return '';
+ const value = extractFindingIgnoreValueRaw(finding);
+ const valueArg = quoteCommandArg(value);
+ const reason = quoteCommandArg(`User confirmed ${value} is intentional`);
+ return `/impeccable hooks ignore-value ${rule} ${valueArg} --shared --reason ${reason}`;
+}
+
+function quoteCommandArg(value) {
+ const text = String(value || '').trim();
+ if (/^[A-Za-z0-9._:-]+$/.test(text)) return text;
+ return `"${text.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
+}
+
+function relativize(filePath, cwd) {
+ try {
+ const rel = path.relative(cwd, filePath);
+ if (!rel || rel.startsWith('..')) return filePath;
+ return rel.split(path.sep).join('/');
+ } catch {
+ return filePath;
+ }
+}
+
+// Codex `apply_patch` exposes the raw patch in `tool_input.command`, not
+// `tool_input.file_path`. Claude Code may send both; parse the patch body
+// so we can scan the file(s) the tool actually touched.
+// https://developers.openai.com/codex/hooks#posttooluse
+const APPLY_PATCH_FILE_RE = /^\*\*\* (?:Update|Add) File: (.+)$/gm;
+
+export function parseApplyPatchPaths(command, projectCwd) {
+ if (!command || typeof command !== 'string') return [];
+ const out = [];
+ for (const m of command.matchAll(APPLY_PATCH_FILE_RE)) {
+ let p = (m[1] || '').trim();
+ if (!p) continue;
+ if (!path.isAbsolute(p)) p = path.resolve(projectCwd, p);
+ out.push(p);
+ }
+ return out;
+}
+
+export function resolveTargetFiles(event, projectCwd) {
+ const ti = event?.tool_input;
+ const out = [];
+ const add = (filePath) => {
+ if (typeof filePath !== 'string' || !filePath) return;
+ if (!out.includes(filePath)) out.push(filePath);
+ };
+
+ if (event?.tool_name === 'apply_patch' && ti && typeof ti.command === 'string') {
+ for (const filePath of parseApplyPatchPaths(ti.command, projectCwd)) add(filePath);
+ }
+ if (ti && typeof ti.file_path === 'string' && ti.file_path) {
+ add(ti.file_path);
+ }
+ // Cursor Write / StrReplace use `path`, not `file_path`.
+ if (ti && typeof ti.path === 'string' && ti.path) {
+ add(ti.path);
+ }
+ if (typeof event?.file_path === 'string' && event.file_path) {
+ add(event.file_path);
+ }
+ return out;
+}
+
+export function resolveHarness(env = {}, event = null) {
+ const explicit = env?.IMPECCABLE_HOOK_HARNESS;
+ if (explicit === 'cursor') return 'cursor';
+ if (explicit === 'claude' || explicit === 'codex') return 'claude';
+ if (typeof event?.conversation_id === 'string' && event.conversation_id) return 'cursor';
+ return 'claude';
+}
+
+export function normalizeHookEvent(event, projectCwd, harness = 'claude') {
+ if (!event || typeof event !== 'object' || harness !== 'cursor') return event;
+
+ const cwd = event.cwd
+ || (Array.isArray(event.workspace_roots) && event.workspace_roots[0])
+ || envProjectDir(projectCwd)
+ || projectCwd;
+ const sessionId = event.session_id || event.conversation_id || 'unknown';
+
+ const ti = event.tool_input && typeof event.tool_input === 'object' ? event.tool_input : {};
+ const filePath = ti.file_path || ti.path || event.file_path;
+ if (filePath) {
+ return {
+ ...event,
+ cwd,
+ session_id: sessionId,
+ tool_input: { ...ti, file_path: filePath },
+ };
+ }
+
+ return { ...event, cwd, session_id: sessionId };
+}
+
+function envProjectDir(fallback) {
+ if (typeof process.env.CURSOR_PROJECT_DIR === 'string' && process.env.CURSOR_PROJECT_DIR) {
+ return process.env.CURSOR_PROJECT_DIR;
+ }
+ return fallback;
+}
+
+// UI components often keep slop in a sibling/co-located stylesheet while the
+// JSX edit is what triggered PostToolUse. Scan those styles too so an App.jsx
+// patch doesn't report "clean" while styles.css still has Inter/bounce/etc.
+const UI_CODE_EXTS = new Set(['.jsx', '.tsx', '.vue', '.svelte', '.astro']);
+const STYLE_EXTS = new Set(['.css', '.scss', '.sass', '.less']);
+const CO_SCAN_STYLE_NAMES = [
+ 'styles.css', 'styles.scss', 'styles.sass', 'styles.less',
+ 'index.css', 'index.scss', 'index.sass', 'index.less',
+ 'global.css', 'global.scss', 'global.sass', 'global.less',
+ 'globals.css', 'globals.scss', 'globals.sass', 'globals.less',
+];
+const MAX_SCAN_TARGETS = 6;
+
+const STATIC_STYLE_IMPORT_RE = /import\s+(?:[\w*{}\s,$]+\s+from\s+)?['"]([^'"]+\.(?:css|scss|sass|less))['"]/gi;
+
+function hasPathTraversal(filePath) {
+ return typeof filePath === 'string' && filePath.includes('..');
+}
+
+function isInsideProject(filePath, projectCwd) {
+ if (!filePath || !projectCwd || hasPathTraversal(filePath)) return false;
+ try {
+ const rel = path.relative(projectCwd, filePath);
+ return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));
+ } catch {
+ return false;
+ }
+}
+
+export function parseStaticStyleImports(content, fromFile, projectCwd) {
+ if (!content || typeof content !== 'string') return [];
+ const dir = path.dirname(fromFile);
+ const out = [];
+ for (const m of content.matchAll(STATIC_STYLE_IMPORT_RE)) {
+ let p = (m[1] || '').trim();
+ if (!p) continue;
+ if (p.startsWith('.')) p = path.resolve(dir, p);
+ else if (!path.isAbsolute(p)) p = path.resolve(projectCwd, p);
+ if (!isInsideProject(p, projectCwd)) continue;
+ out.push(p);
+ }
+ return out;
+}
+
+export function coLocatedStylesheets(filePath) {
+ const dir = path.dirname(filePath);
+ const base = path.basename(filePath, path.extname(filePath));
+ const candidates = new Set([
+ path.join(dir, `${base}.css`),
+ path.join(dir, `${base}.module.css`),
+ path.join(dir, `${base}.scss`),
+ path.join(dir, `${base}.module.scss`),
+ path.join(dir, `${base}.sass`),
+ path.join(dir, `${base}.module.sass`),
+ path.join(dir, `${base}.less`),
+ path.join(dir, `${base}.module.less`),
+ ]);
+ for (const name of CO_SCAN_STYLE_NAMES) {
+ candidates.add(path.join(dir, name));
+ }
+ return [...candidates].filter((p) => fs.existsSync(p));
+}
+
+export function normalizeScanTargets(primaryTargets, projectCwd) {
+ if (!Array.isArray(primaryTargets) || primaryTargets.length === 0) return [];
+ const ordered = [];
+ const seen = new Set();
+ const baseCwd = projectCwd || process.cwd();
+ const normalizeTarget = (p) => {
+ // Preserve literal `..` segments so downstream sensitive-path checks
+ // still fire. path.resolve would collapse `/foo/../etc/passwd`.
+ if (hasPathTraversal(p)) return p;
+ return path.isAbsolute(p) ? p : path.resolve(baseCwd, p);
+ };
+ const add = (p) => {
+ if (ordered.length >= MAX_SCAN_TARGETS) return;
+ const abs = normalizeTarget(p);
+ if (seen.has(abs)) return;
+ seen.add(abs);
+ ordered.push(abs);
+ return abs;
+ };
+
+ for (const p of primaryTargets) add(p);
+ return ordered;
+}
+
+export function expandScanTargets(primaryTargets, projectCwd) {
+ const ordered = normalizeScanTargets(primaryTargets, projectCwd);
+ if (ordered.length === 0) return [];
+ const seen = new Set(ordered);
+ const baseCwd = projectCwd || process.cwd();
+ const add = (p) => {
+ if (ordered.length >= MAX_SCAN_TARGETS) return;
+ const abs = hasPathTraversal(p) ? p : (path.isAbsolute(p) ? p : path.resolve(baseCwd, p));
+ if (seen.has(abs)) return;
+ seen.add(abs);
+ ordered.push(abs);
+ return abs;
+ };
+
+ const normalizedPrimaries = [];
+ for (const p of ordered) normalizedPrimaries.push(p);
+
+ for (const p of normalizedPrimaries) {
+ if (ordered.length >= MAX_SCAN_TARGETS) break;
+ if (!isInsideProject(p, baseCwd)) continue;
+ const ext = path.extname(p).toLowerCase();
+ if (STYLE_EXTS.has(ext) || !UI_CODE_EXTS.has(ext)) continue;
+
+ let content = '';
+ try { content = fs.readFileSync(p, 'utf-8'); } catch { /* unreadable primary */ }
+
+ for (const imp of parseStaticStyleImports(content, p, projectCwd)) {
+ add(imp);
+ if (ordered.length >= MAX_SCAN_TARGETS) break;
+ }
+ for (const col of coLocatedStylesheets(p)) {
+ add(col);
+ if (ordered.length >= MAX_SCAN_TARGETS) break;
+ }
+ }
+
+ return ordered;
+}
+
+export function writeAuditLog(env, entry) {
+ const target = env?.IMPECCABLE_HOOK_LOG;
+ if (!target || typeof target !== 'string') return false;
+ try {
+ const expanded = target.startsWith('~/')
+ ? path.join(process.env.HOME || process.env.USERPROFILE || '.', target.slice(2))
+ : target;
+ fs.mkdirSync(path.dirname(expanded), { recursive: true });
+ const line = JSON.stringify({ ts: new Date().toISOString(), ...entry }) + '\n';
+ fs.appendFileSync(expanded, line);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+const DETECTOR_CANDIDATES = [
+ path.join(__dirname, 'detector', 'detect-antipatterns.mjs'),
+ path.join(__dirname, '..', '..', 'cli', 'engine', 'detect-antipatterns.mjs'),
+ path.join(__dirname, '..', '..', '..', 'cli', 'engine', 'detect-antipatterns.mjs'),
+];
+
+let detectorCache = null;
+export async function loadDetector(candidates = DETECTOR_CANDIDATES) {
+ if (detectorCache) return detectorCache;
+ const found = candidates.find((c) => fs.existsSync(c));
+ if (!found) return null;
+ const mod = await import(pathToFileURL(found));
+ detectorCache = { detectText: mod.detectText, detectHtml: mod.detectHtml };
+ return detectorCache;
+}
+
+// For tests: allow injecting a detector implementation.
+export function setDetectorForTesting(impl) {
+ detectorCache = impl;
+}
+
+// ────────────────────────────────────────────────────────────────────────
+// Nudge/steer messages for the no-silent-fires policy.
+//
+// The hook is designed to be a conversational presence: every fire that
+// actually scans a file emits a developer-role message into the model's
+// next turn. Three states map to three templates:
+//
+// 1. **Fresh findings** → `renderTemplate` (existing, imperative).
+// 2. **Pending findings** → `renderPendingAck` (re-nudge for issues the
+// model was already told about in this
+// session but hasn't fixed yet).
+// 3. **Truly clean** → `renderCleanAck` (short positive nudge that
+// keeps the design discipline in context).
+//
+// All three are short (≤ ~40 tokens each) so the cumulative cost stays
+// bounded across a long active editing session. Users who explicitly want
+// silence-on-clean can set `IMPECCABLE_HOOK_QUIET=1` — runHook checks that
+// env before emitting #2 or #3.
+//
+// Why not stay silent on dedup-clean? Earlier versions did. The model
+// quickly forgets the prior reminder once tool output scrolls past it, so
+// re-nudging on the same file with a short "still pending" line keeps the
+// pressure on. The wording deliberately points back to "earlier this
+// session" so the model knows it's a re-mind, not a new finding.
+// ────────────────────────────────────────────────────────────────────────
+
+const STEER_LINE = 'Keep typography hierarchy, spacing rhythm, and color contrast intentional on the next change.';
+
+export function renderCleanAck(filePath, opts = {}) {
+ const cwd = opts.cwd || process.cwd();
+ const display = relativize(filePath, cwd);
+ return `${ENVELOPE_PREFIX} Design hook scanned ${display}. No anti-patterns. ${STEER_LINE}`;
+}
+
+export function renderPendingAck(filePath, knownFindings, opts = {}) {
+ const cwd = opts.cwd || process.cwd();
+ const display = relativize(filePath, cwd);
+ const count = knownFindings.length;
+ // `knownFindings` here are the cache strings like "side-tab:3".
+ const sample = knownFindings.slice(0, 3).join(', ');
+ const more = count > 3 ? `, +${count - 3} more` : '';
+ return `${ENVELOPE_PREFIX} Design hook scanned ${display}. Still has ${count} issue(s) flagged earlier this session (${sample}${more}). Address them before finalizing — the previous reminder still applies.`;
+}
+
+export function shouldEmitAckForFile(filePath) {
+ return ACK_EXTS.has(path.extname(String(filePath || '')).toLowerCase());
+}
+
+// The directive footer is the part of the hook output that steers model
+// behavior. Three intentional moves:
+// 1. **Imperative, not advisory.** "Fix these..." beats "Consider
+// revising..." which the model treats as a soft suggestion it can
+// override when the user asked for any kind of throwaway / demo UI.
+// 2. **Explicit exception clause.** Without it, the model will try to
+// "fix" intentional bad fixtures, anti-pattern examples in docs, or
+// test cases. Naming the exception inline beats hoping the model
+// infers it from context.
+// 3. **Acknowledgement instruction.** Hook output is injected as
+// developer-role context, not a chat turn, so the user never sees the
+// raw envelope. Asking the model to surface the fix in its reply is
+// the cheapest way to make the feedback loop visible to the user.
+function directiveFooter(display, opts = {}) {
+ const ignoreFileCommand = `/impeccable hooks ignore-file ${quoteCommandArg(display)}`;
+ const fileIgnoreGuidance = opts.grouped
+ ? 'run `/impeccable hooks ignore-file <path>` for the specific file'
+ : `run \`${ignoreFileCommand}\``;
+ return [
+ 'Fix these in your next reply before finalizing. Acknowledge what you changed so the user sees the correction.',
+ '',
+ 'Skip the fix only if the user explicitly asked for an intentionally bad UI, an anti-pattern example, a test fixture, or documentation of bad design. In that case, say so and continue.',
+ '',
+ `Do not add source comments such as \`impeccable: ignore\`; those pollute the code and do not suppress hook findings. Do not add hook ignores unless the user explicitly confirms the finding is intentional. Prefer the narrowest persisted exception: run the exact \`/impeccable hooks ignore-value ... --shared\` command shown next to a value-specific finding. For \`overused-font\`, use \`ignore-value\` for a specific font and use \`/impeccable hooks ignore-rule overused-font --all-values\` only when the user asks to ignore overused fonts generally. For file-specific findings without an ignore-value command, ${fileIgnoreGuidance}; use \`/impeccable hooks ignore-rule <id>\` only when the user asks to suppress the whole non-value-specific rule. Run /impeccable audit for the full pass.`,
+ ].join('\n');
+}
+
+/**
+ * Run the hook with explicit dependencies. Returns a result object:
+ * { exitCode, stdout, audit, reason? }
+ *
+ * Never throws. All errors are converted to `exitCode: 0` + audit entry.
+ */
+export async function runHook({ stdinJson, env = {}, cwd = process.cwd(), now = Date.now, detector } = {}) {
+ const audit = { ts: new Date(now()).toISOString(), event: 'PostToolUse' };
+ const result = (extra) => ({ exitCode: 0, stdout: '', audit: { ...audit, ...extra } });
+
+ try {
+ // Re-entrancy guard.
+ if (depthIsSet(env.IMPECCABLE_HOOK_DEPTH) || depthIsSet(env.CLAUDE_HOOK_DEPTH)) {
+ return result({ reentrant: true, durationMs: 0 });
+ }
+
+ if (truthy(env.IMPECCABLE_HOOK_DISABLED)) {
+ return result({ skipped: 'env-disabled', durationMs: 0 });
+ }
+
+ const started = Date.now();
+
+ let event;
+ try {
+ event = typeof stdinJson === 'string' ? JSON.parse(stdinJson) : stdinJson;
+ } catch {
+ return result({ skipped: 'stdin-malformed', durationMs: Date.now() - started });
+ }
+ if (!event || typeof event !== 'object') {
+ return result({ skipped: 'stdin-empty', durationMs: Date.now() - started });
+ }
+
+ const harness = resolveHarness(env, event);
+ event = normalizeHookEvent(event, cwd, harness);
+ audit.harness = harness;
+
+ const projectCwd = event.cwd || cwd;
+ const primaryFiles = normalizeScanTargets(resolveTargetFiles(event, projectCwd), projectCwd);
+ const primaryFileSet = new Set(primaryFiles);
+ const targetFiles = expandScanTargets(primaryFiles, projectCwd);
+ audit.session = event.session_id || null;
+ if (event.tool_name) audit.tool = event.tool_name;
+
+ if (targetFiles.length === 0) {
+ return result({ skipped: 'no-file-path', durationMs: Date.now() - started });
+ }
+
+ const config = readConfig(projectCwd);
+ if (config.enabled === false) {
+ return result({ skipped: 'config-disabled', durationMs: Date.now() - started });
+ }
+
+ const cache = readCache(projectCwd);
+ const sessionId = event.session_id || 'unknown';
+ const det = detector || await loadDetector();
+ if (!det || typeof det.detectText !== 'function') {
+ persistCache(projectCwd, cache);
+ return result({ skipped: 'detector-missing', durationMs: Date.now() - started });
+ }
+
+ let pendingWinner = null;
+ let cleanWinner = null;
+ const freshGroups = [];
+ let suppressionWinner = null;
+ let detectorThrewAny = false;
+ let lastSkip = 'no-scannable-file';
+ let suppressedHit = false;
+
+ for (const filePath of targetFiles) {
+ audit.file = filePath;
+
+ if (hasPathTraversal(filePath) || SENSITIVE_PATH.test(filePath)) {
+ lastSkip = 'sensitive';
+ continue;
+ }
+ if (GENERATED_PATH.test(filePath)) {
+ lastSkip = 'generated';
+ continue;
+ }
+
+ const ext = path.extname(filePath).toLowerCase();
+ audit.ext = ext;
+ if (!ALLOWED_EXTS.has(ext)) {
+ lastSkip = 'extension';
+ continue;
+ }
+
+ const relForMatch = relativize(filePath, projectCwd);
+ if (matchesAnyGlob(relForMatch, config.ignoreFiles) || matchesAnyGlob(filePath, config.ignoreFiles)) {
+ lastSkip = 'config-ignore-file';
+ continue;
+ }
+ if (!fs.existsSync(filePath)) {
+ lastSkip = 'file-missing';
+ continue;
+ }
+
+ if (primaryFileSet.has(filePath)) {
+ const editCount = bumpEditCount(cache, sessionId, filePath);
+ audit.editCount = editCount;
+
+ if (editCount > EDIT_COUNT_THRESHOLD) {
+ const wasJustCrossed = editCount === EDIT_COUNT_THRESHOLD + 1;
+ if (wasJustCrossed && !suppressionWinner) {
+ suppressionWinner = { filePath };
+ }
+ lastSkip = 'suppressed';
+ suppressedHit = true;
+ continue;
+ }
+ }
+
+ const content = fs.readFileSync(filePath, 'utf-8');
+ let findings;
+ let detectorThrew = false;
+ if ((ext === '.html' || ext === '.htm') && typeof det.detectHtml === 'function') {
+ try { findings = await det.detectHtml(filePath); } catch { findings = []; detectorThrew = true; }
+ } else {
+ try { findings = await det.detectText(content, filePath); } catch { findings = []; detectorThrew = true; }
+ }
+
+ const filtered = filterFindings(findings || [], content, ext, config);
+ const fresh = dedupeAgainstCache(filtered, cache, sessionId, filePath);
+ audit.findings = (findings || []).length;
+ audit.freshFindings = fresh.length;
+
+ if (fresh.length > 0) {
+ rememberFindings(cache, sessionId, filePath, fresh);
+ freshGroups.push({ filePath, findings: fresh });
+ continue;
+ }
+
+ if (detectorThrew) {
+ detectorThrewAny = true;
+ continue;
+ }
+
+ if (filtered.length > 0 && !pendingWinner) {
+ const known = (ensureFile(cache, sessionId, filePath).findings || []).slice();
+ pendingWinner = { filePath, known };
+ } else if (filtered.length === 0 && !cleanWinner) {
+ cleanWinner = { filePath };
+ }
+ }
+
+ persistCache(projectCwd, cache);
+
+ if (freshGroups.length > 0) {
+ const firstGroup = freshGroups[0];
+ const text = renderGroupedTemplate(freshGroups, config, { cwd: projectCwd });
+ const allFindings = freshGroups.flatMap((group) => group.findings);
+ return {
+ exitCode: 0,
+ stdout: payload(text, 'PostToolUse', harness),
+ emission: {
+ kind: 'fresh',
+ file: firstGroup.filePath,
+ findings: firstGroup.findings,
+ groups: freshGroups,
+ },
+ audit: {
+ ...audit,
+ file: firstGroup.filePath,
+ emitted: true,
+ freshFiles: freshGroups.length,
+ freshFindings: allFindings.length,
+ chars: text.length,
+ durationMs: Date.now() - started,
+ },
+ };
+ }
+
+ if (detectorThrewAny && !pendingWinner && !cleanWinner) {
+ return result({ emitted: false, error: 'detector-threw', durationMs: Date.now() - started });
+ }
+
+ if (truthy(env.IMPECCABLE_HOOK_QUIET)) {
+ return result({ emitted: false, quiet: true, durationMs: Date.now() - started });
+ }
+
+ if (pendingWinner && shouldEmitAckForFile(pendingWinner.filePath)) {
+ const text = renderPendingAck(pendingWinner.filePath, pendingWinner.known, { cwd: projectCwd });
+ return {
+ exitCode: 0,
+ stdout: payload(text, 'PostToolUse', harness),
+ emission: { kind: 'pending', file: pendingWinner.filePath, known: pendingWinner.known },
+ audit: {
+ ...audit,
+ file: pendingWinner.filePath,
+ emitted: true,
+ kind: 'pending',
+ pending: pendingWinner.known.length,
+ chars: text.length,
+ durationMs: Date.now() - started,
+ },
+ };
+ }
+
+ if (suppressionWinner) {
+ const text = suppressionNotice(relativize(suppressionWinner.filePath, projectCwd));
+ return {
+ exitCode: 0,
+ stdout: payload(text, 'PostToolUse', harness),
+ emission: { kind: 'suppression', file: suppressionWinner.filePath },
+ audit: {
+ ...audit,
+ file: suppressionWinner.filePath,
+ suppressed: true,
+ emitted: true,
+ durationMs: Date.now() - started,
+ },
+ };
+ }
+
+ if (cleanWinner && shouldEmitAckForFile(cleanWinner.filePath)) {
+ const text = renderCleanAck(cleanWinner.filePath, { cwd: projectCwd });
+ return {
+ exitCode: 0,
+ stdout: payload(text, 'PostToolUse', harness),
+ emission: { kind: 'clean', file: cleanWinner.filePath },
+ audit: {
+ ...audit,
+ file: cleanWinner.filePath,
+ emitted: true,
+ kind: 'clean',
+ chars: text.length,
+ durationMs: Date.now() - started,
+ },
+ };
+ }
+
+ if (pendingWinner || cleanWinner) {
+ return result({ emitted: false, skipped: 'non-ui-ack', durationMs: Date.now() - started });
+ }
+
+ if (suppressedHit) {
+ return result({ suppressed: true, emitted: false, durationMs: Date.now() - started });
+ }
+
+ return result({ skipped: lastSkip, durationMs: Date.now() - started });
+ } catch (err) {
+ return {
+ exitCode: 0,
+ stdout: '',
+ audit: { ...audit, error: String(err && err.message ? err.message : err) },
+ };
+ }
+}
+
+export function payload(text, eventName = 'PostToolUse', harness = 'claude') {
+ if (harness === 'cursor') {
+ return JSON.stringify({ additional_context: text });
+ }
+ return JSON.stringify({
+ hookSpecificOutput: { hookEventName: eventName, additionalContext: text },
+ });
+}
diff --git a/.trae-cn/skills/impeccable/scripts/hook.mjs b/.trae-cn/skills/impeccable/scripts/hook.mjs
new file mode 100644
index 000000000..b862f8033
--- /dev/null
+++ b/.trae-cn/skills/impeccable/scripts/hook.mjs
@@ -0,0 +1,61 @@
+#!/usr/bin/env node
+/**
+ * Impeccable design hook — PostToolUse entry point.
+ *
+ * Reads the Claude Code / Codex / Cursor hook event from stdin, runs the design
+ * detector against the touched file, and emits a system reminder via
+ * `hookSpecificOutput.additionalContext` when findings exist.
+ *
+ * Contract: never break a turn. Always exit 0. Clean files emit a small ack
+ * unless quiet mode is enabled.
+ *
+ * Most logic lives in `hook-lib.mjs` so it is unit-testable without a
+ * subprocess. This file is the thin stdin/stdout adapter.
+ */
+
+import { runHook, 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');
+}
+
+async function main() {
+ // Snapshot the inherited env FIRST so the re-entrancy guard checks the
+ // parent's value, not the value we are about to export for any child
+ // processes the hook might ever spawn.
+ const inheritedEnv = { ...process.env };
+ process.env.IMPECCABLE_HOOK_DEPTH = process.env.IMPECCABLE_HOOK_DEPTH || '1';
+
+ let stdinJson = '';
+ try { stdinJson = await readStdin(); } catch { /* fall through */ }
+
+ const result = await runHook({
+ stdinJson,
+ env: inheritedEnv,
+ cwd: process.cwd(),
+ });
+
+ writeAuditLog(process.env, result.audit);
+
+ if (result.stdout) process.stdout.write(result.stdout);
+ process.exit(result.exitCode || 0);
+}
+
+main().catch((err) => {
+ // Last-ditch: never break the agent's turn even if something we did not
+ // anticipate goes wrong. Audit-log the failure if logging is enabled.
+ try {
+ writeAuditLog(process.env, {
+ ts: new Date().toISOString(),
+ event: 'PostToolUse',
+ error: String(err && err.message ? err.message : err),
+ });
+ } catch { /* swallow */ }
+ if (process.env.IMPECCABLE_HOOK_DEBUG) {
+ process.stderr.write(`[impeccable-hook] ${err}\n`);
+ }
+ process.exit(0);
+});
diff --git a/.trae-cn/skills/impeccable/scripts/live-inject.mjs b/.trae-cn/skills/impeccable/scripts/live-inject.mjs
index 4e5c5dc0a..69ce530c1 100644
--- a/.trae-cn/skills/impeccable/scripts/live-inject.mjs
+++ b/.trae-cn/skills/impeccable/scripts/live-inject.mjs
@@ -32,6 +32,8 @@ const IGNORE_MARKER_CLOSE = '# impeccable-live-ignore-end';
export const LIVE_IGNORE_PATTERNS = Object.freeze([
'.impeccable/hook.cache.json',
+ '.impeccable/hook.pending.json',
+ '.impeccable/hook.local.json',
'.impeccable/live/server.json',
'.impeccable/live/sessions/',
'.impeccable/live/previews/',
diff --git a/.trae/skills/impeccable/SKILL.md b/.trae/skills/impeccable/SKILL.md
index 0e4a2b49c..d36c0e8a8 100644
--- a/.trae/skills/impeccable/SKILL.md
+++ b/.trae/skills/impeccable/SKILL.md
@@ -124,7 +124,7 @@ If someone could look at this interface and say "AI made that" without doubt, it
| `optimize [target]` | Fix | Diagnose and fix UI performance | [reference/optimize.md](reference/optimize.md) |
| `live` | Iterate | Visual variant mode: pick elements in the browser, generate alternatives | [reference/live.md](reference/live.md) |
-Plus two management commands: `pin <command>` and `unpin <command>`, detailed below.
+Plus three management commands: `pin <command>`, `unpin <command>`, and `hooks <on|off|status|...>`, detailed below.
### Routing rules
@@ -141,7 +141,7 @@ Plus two management commands: `pin <command>` and `unpin <command>`, detailed be
**If `scan.targets` is non-empty, run `node .trae/skills/impeccable/scripts/detect.mjs --json <scan.targets joined by spaces>` once** (the bundled detector over local files: no network, no npx). `scan.via` tells you what they are: `git-changes` (the markup/style files in your dirty tree, the most relevant set), `source-dir` (e.g. `src`, `app`), `html`, or `root`. Fold the hits into your picks: many quality / contrast hits → `audit` or `polish`; a specific slop family → the matching command (gradient text or eyebrows → `quieter` / `typeset`, flat or gray palette → `colorize`, and so on). It's a real, current signal that beats guessing. If detect errors or the tree is large and slow, skip it and recommend the user run `audit` themselves; never block the suggestion on it.
Keep it to 2-3 pointed picks with the exact command to type. The menu stays the fallback; the recommendation is the lede.
-2. **First word matches a command**: load its reference file and follow its instructions. Everything after the command name is the target.
+2. **First word matches a command** (table above OR `pin` / `unpin` / `hooks`): load its reference file and follow its instructions. Everything after the command name is the target.
3. **First word doesn't match, but the intent clearly maps to one command** (e.g. "fix the spacing" → `layout`, "rewrite this error message" → `clarify`, "the colors feel flat" → `colorize`): load that command's reference and proceed as if invoked. If two commands could fit, ask once which.
4. **No clear command match**: general design invocation. Apply the setup steps, the General rules, and the loaded register reference, using the full argument as context.
@@ -159,4 +159,8 @@ If the first word is `craft`, setup still runs first, but [reference/craft.md](r
node .trae/skills/impeccable/scripts/pin.mjs <pin|unpin> <command>
```
-Valid `<command>` is any command from the table above. Report the script's result concisely. Confirm the new shortcut on success, relay stderr verbatim on error.
\ No newline at end of file
+Valid `<command>` is any command from the table above. Report the script's result concisely. Confirm the new shortcut on success, relay stderr verbatim on error.
+
+## Hooks
+
+`/impeccable hooks <on|off|status|ignore-rule|ignore-file|ignore-value|reset>` manages the design detector hook for this project. The hook auto-runs the detector after direct UI file edits and surfaces findings as system reminders. Full flow is in [reference/hooks.md](reference/hooks.md); load it when the user invokes `/impeccable hooks` with any argument.
\ No newline at end of file
diff --git a/.trae/skills/impeccable/reference/hooks.md b/.trae/skills/impeccable/reference/hooks.md
new file mode 100644
index 000000000..5aba0af26
--- /dev/null
+++ b/.trae/skills/impeccable/reference/hooks.md
@@ -0,0 +1,82 @@
+# /impeccable hooks
+
+Manage the **design detector hook** for the current project.
+
+The hook runs the impeccable design detector on direct file edits to design-relevant files (`.tsx`, `.jsx`, `.html`, `.vue`, `.svelte`, `.astro`, `.css`, `.scss`, `.sass`, `.less`, `.ts`, `.js`). Claude Code and Codex use `PostToolUse` and push a short system reminder into the agent's context after the edit; findings get a correction prompt, pending issues get a re-nudge, and clean UI-ish files get a short ack unless `IMPECCABLE_HOOK_QUIET=1` is set. Plain `.ts` and `.js` files are still scanned, but stay quiet unless the detector finds something. Cursor uses `preToolUse` to block bad proposed writes before they land and stays silent when it allows a clean write.
+
+This command toggles the hook **per project** by editing `.impeccable/hook.json`. Local-only ignore policy lives in `.impeccable/hook.local.json`, which is gitignored. To disable globally, set `IMPECCABLE_HOOK_DISABLED=1` in your shell environment.
+
+Supported harnesses: Claude Code (`.claude/settings.json` in the project), Codex (`.codex/hooks.json` in the project), and Cursor (`.cursor/hooks.json` in the project).
+
+On **Cursor**, `preToolUse` checks proposed Write/Edit/Shell write content and denies only when the real detector finds an issue. The denial message is visible to the agent as the tool error, so the agent can reconsider before the bad write lands.
+
+## Routing
+
+The first argument is the action. Defaults to `status`.
+
+| Action | What it does |
+|---|---|
+| `status` | Print current state, shared/local config paths, ignored rules / files / values, env override. |
+| `on` | Set `enabled: true` in `.impeccable/hook.json`. |
+| `off` | Set `enabled: false` in `.impeccable/hook.json`. |
+| `ignore-rule <id>` | Append `<id>` to `ignoreRules`; for `overused-font`, requires `--all-values`. |
+| `ignore-file <glob>` | Append `<glob>` to `ignoreFiles`. |
+| `ignore-value <id> <value> [--shared] [--reason "..."]` | Append a rule/value suppression to shared `.impeccable/hook.json`. |
+| `ignore-value <id> <value> --local [--reason "..."]` | Append a private rule/value suppression to `.impeccable/hook.local.json`. |
+| `reset` | Delete the project config, dedup cache, and Cursor pending queue. |
+
+## Flow
+
+1. Resolve the action from the user's argument. If no action was given, default to `status`.
+2. Invoke the admin script and pass the user's output through verbatim:
+
+ ```bash
+ node .trae/skills/impeccable/scripts/hook-admin.mjs <action> [args...]
+ ```
+
+3. If `<action>` is `off`, follow up with a one-line note: "Done. New edits will not trigger the design hook in this project until you run `/impeccable hooks on`."
+4. If `<action>` is `on`, follow up with: "Done. The design hook will fire after the next Edit/Write/MultiEdit on a UI file."
+5. If `<action>` is `ignore-value`, `ignore-file`, or `ignore-rule`, just print the script output. The default scope is shared `.impeccable/hook.json`; add `--local` only when the user explicitly asks for a private exception.
+6. If `<action>` is `status`, just print the script output. Do not add commentary unless the user asked a follow-up question.
+
+## Intentional findings
+
+The hook itself never writes ignore config. Persist an exception only after the user explicitly confirms the flagged issue is intentional, and always go through `hook-admin.mjs`.
+
+Prefer the narrowest exception:
+
+- If the finding line shows an exact `ignore-value` command, run that command. This writes shared `.impeccable/hook.json` by default.
+- For `overused-font`, use `ignore-value` when the user confirms a specific font. Do not use `ignore-rule overused-font` for a specific font.
+- If the finding has no value-specific command, such as `side-tab`, prefer `ignore-file <path>` for the current file.
+- Use `ignore-rule <id>` only when the user asks to suppress that whole rule across the project. For broad overused-font suppression, use `ignore-rule overused-font --all-values` only when the user asks to ignore overused fonts generally.
+- Do not add source comments such as `impeccable: ignore`; inline comments pollute code and are not a supported suppression mechanism.
+
+Example value-specific exception:
+
+```bash
+node .trae/skills/impeccable/scripts/hook-admin.mjs ignore-value overused-font Inter --shared --reason "User confirmed Inter is intentional"
+```
+
+Example whole-rule font exception:
+
+```bash
+node .trae/skills/impeccable/scripts/hook-admin.mjs ignore-rule overused-font --all-values --reason "User asked to ignore overused fonts generally"
+```
+
+Example file-scoped exception:
+
+```bash
+node .trae/skills/impeccable/scripts/hook-admin.mjs ignore-file "src/legacy/Card.tsx"
+```
+
+## Constraints
+
+- Never modify `.impeccable/hook.json` or `.impeccable/hook.local.json` by hand from this command. Always go through `hook-admin.mjs` so writes stay validated and the file shape stays consistent.
+- Do not edit the hook scripts themselves (`hook.mjs`, `hook-lib.mjs`, `hook-before-edit.mjs`) from this flow. Those are skill plumbing.
+- Cursor can block a proposed write when the detector finds a real issue. Claude Code and Codex do not block the edit; they emit a post-edit reminder instead. Disabling stops both blocking and reminders.
+- The hook is bundled with the Impeccable skill and installed through project-local manifests: `.claude/settings.json`, `.codex/hooks.json`, and `.cursor/hooks.json`. On Codex, the user must approve the hook via `/hooks` the first time. On Cursor, confirm hooks are enabled under Settings -> Hooks.
+
+## Failure modes
+
+- If `.impeccable/hook.json` or `.impeccable/hook.local.json` is unreadable or malformed, the hook ignores that file and uses the remaining valid config/defaults. `hook-admin.mjs status` will show malformed files as ignored.
+- If the user asks to "disable the hook" globally, suggest both options: `IMPECCABLE_HOOK_DISABLED=1` env var (one-shot, follows the shell), and `/impeccable hooks off` (persistent for this project, committable).
diff --git a/.trae/skills/impeccable/scripts/detector/engines/regex/detect-text.mjs b/.trae/skills/impeccable/scripts/detector/engines/regex/detect-text.mjs
index fd0d9c73f..4c0777c93 100644
--- a/.trae/skills/impeccable/scripts/detector/engines/regex/detect-text.mjs
+++ b/.trae/skills/impeccable/scripts/detector/engines/regex/detect-text.mjs
@@ -446,7 +446,7 @@ function detectText(content, filePath, options = {}) {
// Run regex matchers on the full file content (catches Tailwind classes, inline styles)
// Enable block context for CSS files where related properties span multiple lines
- const cssLike = new Set(['.css', '.scss', '.less']);
+ const cssLike = new Set(['.css', '.scss', '.sass', '.less']);
findings.push(...runRegexMatchers(lines, filePath, 0, cssLike.has(ext) || null, {
profile,
phase: 'source',
diff --git a/.trae/skills/impeccable/scripts/detector/node/file-system.mjs b/.trae/skills/impeccable/scripts/detector/node/file-system.mjs
index a80250a0e..aaa8c6df7 100644
--- a/.trae/skills/impeccable/scripts/detector/node/file-system.mjs
+++ b/.trae/skills/impeccable/scripts/detector/node/file-system.mjs
@@ -11,7 +11,7 @@ const SKIP_DIRS = new Set([
]);
const SCANNABLE_EXTENSIONS = new Set([
- '.html', '.htm', '.css', '.scss', '.less',
+ '.html', '.htm', '.css', '.scss', '.sass', '.less',
'.jsx', '.tsx', '.js', '.ts',
'.vue', '.svelte', '.astro',
]);
diff --git a/.trae/skills/impeccable/scripts/hook-admin.mjs b/.trae/skills/impeccable/scripts/hook-admin.mjs
new file mode 100644
index 000000000..86fcfa909
--- /dev/null
+++ b/.trae/skills/impeccable/scripts/hook-admin.mjs
@@ -0,0 +1,300 @@
+#!/usr/bin/env node
+/**
+ * `/impeccable hooks <on|off|status|reset>` — manage the design hook
+ * via .impeccable/hook.json and .impeccable/hook.local.json in the current
+ * project.
+ *
+ * Usage:
+ * node hook-admin.mjs status # print current state
+ * node hook-admin.mjs on # set enabled: true
+ * node hook-admin.mjs off # set enabled: false
+ * node hook-admin.mjs ignore-rule <rule-id> # append to ignoreRules
+ * node hook-admin.mjs ignore-rule overused-font --all-values
+ * node hook-admin.mjs ignore-file <glob> # append to ignoreFiles
+ * node hook-admin.mjs ignore-value <rule> <value> # append to shared ignoreValues
+ * node hook-admin.mjs ignore-value <rule> <value> --local
+ * node hook-admin.mjs reset # remove all config + cache
+ *
+ * Designed to be invoked by the LLM from the reference/hooks.md flow.
+ * Output is human-readable; the harness will pass it back to the user.
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+
+import {
+ getConfigPath,
+ getLocalConfigPath,
+ getCachePath,
+ getPendingPath,
+ readConfig,
+ DEFAULT_CONFIG,
+ ensureHookGitExcludes,
+ normalizeIgnoreValue,
+ normalizeIgnoreValueEntries,
+} from './hook-lib.mjs';
+
+const ACTIONS = new Set(['status', 'on', 'off', 'ignore-rule', 'ignore-file', 'ignore-value', 'reset']);
+
+function readRawConfigFile(filePath) {
+ if (!fs.existsSync(filePath)) return { exists: false, malformed: false, raw: null };
+ try {
+ return { exists: true, malformed: false, raw: JSON.parse(fs.readFileSync(filePath, 'utf-8')) };
+ } catch {
+ return { exists: true, malformed: true, raw: null };
+ }
+}
+
+function readRawConfig(cwd, opts = {}) {
+ const filePath = opts.local ? getLocalConfigPath(cwd) : getConfigPath(cwd);
+ return readRawConfigFile(filePath).raw;
+}
+
+function writeConfig(cwd, config, opts = {}) {
+ const filePath = opts.local ? getLocalConfigPath(cwd) : getConfigPath(cwd);
+ if (opts.local) ensureHookGitExcludes(cwd);
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
+ fs.writeFileSync(filePath, JSON.stringify(config, null, 2) + '\n');
+ return filePath;
+}
+
+function mergeConfig(existing) {
+ // Persist the full shape so /impeccable hooks edits leave a complete file
+ // for the user to see, not an unhelpful `{"enabled":false}`.
+ const base = existing && typeof existing === 'object' ? existing : {};
+ return {
+ enabled: base.enabled === false ? false : true,
+ ignoreRules: Array.isArray(base.ignoreRules) ? Array.from(new Set(base.ignoreRules.map(String))) : [],
+ ignoreFiles: Array.isArray(base.ignoreFiles) ? Array.from(new Set(base.ignoreFiles.map(String))) : [],
+ ignoreValues: normalizeIgnoreValueEntries(base.ignoreValues || []),
+ limits: {
+ maxFindings: Number.isFinite(base?.limits?.maxFindings) ? base.limits.maxFindings : DEFAULT_CONFIG.limits.maxFindings,
+ maxChars: Number.isFinite(base?.limits?.maxChars) ? base.limits.maxChars : DEFAULT_CONFIG.limits.maxChars,
+ },
+ };
+}
+
+function mergeLocalConfig(existing) {
+ const base = existing && typeof existing === 'object' ? existing : {};
+ const out = {};
+ if (Object.prototype.hasOwnProperty.call(base, 'enabled')) {
+ out.enabled = base.enabled === false ? false : true;
+ }
+ if (Array.isArray(base.ignoreRules)) {
+ out.ignoreRules = Array.from(new Set(base.ignoreRules.map(String)));
+ }
+ if (Array.isArray(base.ignoreFiles)) {
+ out.ignoreFiles = Array.from(new Set(base.ignoreFiles.map(String)));
+ }
+ out.ignoreValues = normalizeIgnoreValueEntries(base.ignoreValues || []);
+ if (base.limits && typeof base.limits === 'object') {
+ const limits = {};
+ if (Number.isFinite(base.limits.maxFindings)) limits.maxFindings = base.limits.maxFindings;
+ if (Number.isFinite(base.limits.maxChars)) limits.maxChars = base.limits.maxChars;
+ if (Object.keys(limits).length) out.limits = limits;
+ }
+ return out;
+}
+
+function statusReport(cwd) {
+ const shared = readRawConfigFile(getConfigPath(cwd));
+ const local = readRawConfigFile(getLocalConfigPath(cwd));
+ const cfg = readConfig(cwd);
+ const envKill = process.env.IMPECCABLE_HOOK_DISABLED;
+ const envState = envKill ? `IMPECCABLE_HOOK_DISABLED=${envKill}` : 'unset';
+ const cfgPath = path.relative(cwd, getConfigPath(cwd)) || '.impeccable/hook.json';
+ const localPath = path.relative(cwd, getLocalConfigPath(cwd)) || '.impeccable/hook.local.json';
+ const cachePath = path.relative(cwd, getCachePath(cwd)) || '.impeccable/hook.cache.json';
+ const fileState = (info, relPath, absent) => {
+ if (info.malformed) return `${relPath} (malformed; ignored)`;
+ if (info.exists) return relPath;
+ return `${relPath} (${absent})`;
+ };
+ const ignoreValues = cfg.ignoreValues.map((entry) => `${entry.rule}=${entry.value}`);
+
+ const lines = [
+ `Impeccable design hook`,
+ ` state: ${cfg.enabled ? 'enabled' : 'disabled'}`,
+ ` shared file: ${fileState(shared, cfgPath, 'using defaults; file not present')}`,
+ ` local file: ${fileState(local, localPath, 'not present')}`,
+ ` ignoreRules: ${cfg.ignoreRules.length ? cfg.ignoreRules.join(', ') : '(none)'}`,
+ ` ignoreFiles: ${cfg.ignoreFiles.length ? cfg.ignoreFiles.join(', ') : '(none)'}`,
+ ` ignoreValues: ${ignoreValues.length ? ignoreValues.join(', ') : '(none)'}`,
+ ` maxFindings: ${cfg.limits.maxFindings}`,
+ ` maxChars: ${cfg.limits.maxChars}`,
+ ` env override: ${envState}`,
+ ` cache file: ${fs.existsSync(getCachePath(cwd)) ? cachePath : `${cachePath} (not present)`}`,
+ ];
+ return lines.join('\n');
+}
+
+function setEnabled(cwd, value) {
+ const config = mergeConfig(readRawConfig(cwd));
+ config.enabled = value;
+ const target = writeConfig(cwd, config);
+ return `Design hook ${value ? 'enabled' : 'disabled'} for this project (wrote ${path.relative(cwd, target) || target}).`;
+}
+
+function normalizeRuleId(rule) {
+ return String(rule || '').trim().toLowerCase();
+}
+
+function parseIgnoreRuleArgs(args) {
+ const positionals = [];
+ let allValues = false;
+
+ for (let i = 0; i < args.length; i++) {
+ const arg = String(args[i] || '');
+ if (arg === '--all-values') {
+ allValues = true;
+ } else if (arg === '--reason') {
+ while (i + 1 < args.length && !String(args[i + 1]).startsWith('--')) i++;
+ } else if (arg.startsWith('--reason=')) {
+ // Accepted for command symmetry; ignoreRules stores rule ids only.
+ } else if (arg.startsWith('--')) {
+ throw new Error(`Unknown ignore-rule flag: ${arg}`);
+ } else {
+ positionals.push(arg);
+ }
+ }
+
+ return {
+ rule: normalizeRuleId(positionals[0]),
+ allValues,
+ };
+}
+
+function addIgnoreRule(cwd, args) {
+ const parsed = parseIgnoreRuleArgs(args);
+ const rule = parsed.rule;
+ if (!rule) throw new Error('Pass a rule id, e.g. /impeccable hooks ignore-rule side-tab');
+ if (rule === 'overused-font' && !parsed.allValues) {
+ throw new Error('overused-font is value-specific by default. Use /impeccable hooks ignore-value overused-font <font> for a confirmed font, or /impeccable hooks ignore-rule overused-font --all-values only when the user asked to ignore overused fonts generally.');
+ }
+ const config = mergeConfig(readRawConfig(cwd));
+ if (!config.ignoreRules.includes(rule)) config.ignoreRules.push(rule);
+ writeConfig(cwd, config);
+ return `Added "${rule}" to ignoreRules. Current: ${config.ignoreRules.join(', ')}`;
+}
+
+function addIgnoreFile(cwd, glob) {
+ if (!glob) throw new Error('Pass a glob, e.g. /impeccable hooks ignore-file "src/legacy/**"');
+ const config = mergeConfig(readRawConfig(cwd));
+ if (!config.ignoreFiles.includes(glob)) config.ignoreFiles.push(glob);
+ writeConfig(cwd, config);
+ return `Added "${glob}" to ignoreFiles. Current: ${config.ignoreFiles.join(', ')}`;
+}
+
+function parseIgnoreValueArgs(args) {
+ const positionals = [];
+ let shared = false;
+ let local = false;
+ let reason = '';
+
+ for (let i = 0; i < args.length; i++) {
+ const arg = args[i];
+ if (arg === '--shared') {
+ shared = true;
+ } else if (arg === '--local') {
+ local = true;
+ } else if (arg === '--reason') {
+ const chunks = [];
+ while (i + 1 < args.length && !String(args[i + 1]).startsWith('--')) {
+ chunks.push(args[++i]);
+ }
+ reason = chunks.join(' ').trim();
+ } else if (String(arg).startsWith('--reason=')) {
+ reason = String(arg).slice('--reason='.length).trim();
+ } else {
+ positionals.push(arg);
+ }
+ }
+
+ const [rule, ...valueParts] = positionals;
+ return {
+ rule: String(rule || '').trim().toLowerCase(),
+ value: normalizeIgnoreValue(valueParts.join(' ')),
+ shared,
+ local,
+ reason,
+ };
+}
+
+function addIgnoreValue(cwd, args) {
+ const parsed = parseIgnoreValueArgs(args);
+ if (!parsed.rule || !parsed.value) {
+ throw new Error('Pass a rule id and value, e.g. /impeccable hooks ignore-value overused-font Inter');
+ }
+
+ if (parsed.shared && parsed.local) {
+ throw new Error('Pass only one scope flag: --shared or --local');
+ }
+
+ const local = parsed.local;
+ const config = local
+ ? mergeLocalConfig(readRawConfig(cwd, { local: true }))
+ : mergeConfig(readRawConfig(cwd, { local: false }));
+ const key = `${parsed.rule}\0${parsed.value}`;
+ const existing = config.ignoreValues.find((entry) => `${entry.rule}\0${entry.value}` === key);
+
+ if (existing) {
+ if (parsed.reason) existing.reason = parsed.reason;
+ } else {
+ const entry = {
+ rule: parsed.rule,
+ value: parsed.value,
+ createdAt: new Date().toISOString(),
+ };
+ if (parsed.reason) entry.reason = parsed.reason;
+ config.ignoreValues.push(entry);
+ }
+
+ const target = writeConfig(cwd, config, { local });
+ const scope = local ? 'local ignoreValues' : 'shared ignoreValues';
+ return `Added ${parsed.rule}=${parsed.value} to ${scope} (${path.relative(cwd, target) || target}).`;
+}
+
+function reset(cwd) {
+ const removed = [];
+ for (const filePath of [getConfigPath(cwd), getLocalConfigPath(cwd), getCachePath(cwd), getPendingPath(cwd)]) {
+ try {
+ if (fs.existsSync(filePath)) {
+ fs.unlinkSync(filePath);
+ removed.push(path.relative(cwd, filePath) || filePath);
+ }
+ } catch { /* ignore */ }
+ }
+ return removed.length
+ ? `Reset design hook config and cache (removed: ${removed.join(', ')}).`
+ : 'No hook config or cache to remove. Already at defaults.';
+}
+
+function main() {
+ const [, , actionArg, ...rest] = process.argv;
+ const action = (actionArg || 'status').toLowerCase();
+ const cwd = process.cwd();
+
+ if (!ACTIONS.has(action)) {
+ process.stderr.write(`Unknown action: ${action}\nValid: ${Array.from(ACTIONS).join(', ')}\n`);
+ process.exit(1);
+ }
+
+ try {
+ let out = '';
+ switch (action) {
+ case 'status': out = statusReport(cwd); break;
+ case 'on': out = setEnabled(cwd, true); break;
+ case 'off': out = setEnabled(cwd, false); break;
+ case 'ignore-rule': out = addIgnoreRule(cwd, rest); break;
+ case 'ignore-file': out = addIgnoreFile(cwd, rest[0]); break;
+ case 'ignore-value': out = addIgnoreValue(cwd, rest); break;
+ case 'reset': out = reset(cwd); break;
+ }
+ process.stdout.write(out + '\n');
+ } catch (err) {
+ process.stderr.write(`Error: ${err.message || err}\n`);
+ process.exit(1);
+ }
+}
+
+main();
diff --git a/.trae/skills/impeccable/scripts/hook-before-edit.mjs b/.trae/skills/impeccable/scripts/hook-before-edit.mjs
new file mode 100644
index 000000000..54b2709d2
--- /dev/null
+++ b/.trae/skills/impeccable/scripts/hook-before-edit.mjs
@@ -0,0 +1,408 @@
+#!/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 shellContent = shellHereDocContent(shellCommand(input));
+ if (shellContent) return shellContent;
+ const copiedContent = shellCopiedFileContent(shellCommand(input), 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 || '';
+}
+
+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 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' });
+});
diff --git a/.trae/skills/impeccable/scripts/hook-lib.mjs b/.trae/skills/impeccable/scripts/hook-lib.mjs
new file mode 100644
index 000000000..02199f530
--- /dev/null
+++ b/.trae/skills/impeccable/scripts/hook-lib.mjs
@@ -0,0 +1,1232 @@
+/**
+ * Shared library for the Impeccable design hook.
+ *
+ * Pure-ish helpers split out from `hook.mjs` so unit tests can exercise
+ * config parsing, finding filtering, dedup, render, and cache logic without
+ * spawning a subprocess. `hook.mjs` itself is the thin stdin/stdout shim.
+ *
+ * Public surface (everything exported is part of the contract):
+ * ENVELOPE_PREFIX, ALLOWED_EXTS, ACK_EXTS, SENSITIVE_PATH, GENERATED_PATH, TRUTHY
+ * truthy(value)
+ * readConfig(cwd) / DEFAULT_CONFIG / getConfigPath(cwd) / getLocalConfigPath(cwd)
+ * normalizeIgnoreValue(value)
+ * readCache(cwd) / persistCache(cwd, cache)
+ * bumpEditCount(cache, sessionId, filePath) -> number
+ * suppressionNotice(filePath)
+ * filterFindings(findings, content, ext, config)
+ * dedupeAgainstCache(findings, cache, sessionId, filePath)
+ * renderTemplate(findings, filePath, config, opts)
+ * renderCleanAck(filePath, opts) / renderPendingAck(filePath, known, opts)
+ * shouldEmitAckForFile(filePath)
+ * writeAuditLog(env, entry)
+ * loadDetector() -> Promise<{ detectText, detectHtml }>
+ * matchesAnyGlob(filePath, globs)
+ * normalizeScanTargets(primaryTargets, projectCwd)
+ * runHook(deps) -> { exitCode, stdout, audit, reason? }
+ *
+ * Design notes:
+ * - All errors are swallowed at the runHook seam. The detector throwing must
+ * never break a turn. See PRD §5 "Failure modes".
+ * - Cache shape is JSON-friendly; we gc the oldest sessions when there are
+ * more than 8 to keep file size predictable across long-lived projects.
+ * - The detector loader looks for `detector/detect-antipatterns.mjs` next to
+ * this file first (built skill layout) and falls back to the repo root's
+ * `cli/engine/detect-antipatterns.mjs` (running from source).
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+import { pathToFileURL, fileURLToPath } from 'node:url';
+
+const __filename = fileURLToPath(import.meta.url);
+const __dirname = path.dirname(__filename);
+
+export const ENVELOPE_PREFIX = '[impeccable@1]';
+
+export const ALLOWED_EXTS = new Set([
+ '.tsx', '.jsx', '.html', '.htm', '.vue', '.svelte', '.astro',
+ '.css', '.scss', '.sass', '.less', '.ts', '.js',
+]);
+
+export const ACK_EXTS = new Set([
+ '.tsx', '.jsx', '.html', '.htm', '.vue', '.svelte', '.astro',
+ '.css', '.scss', '.sass', '.less',
+]);
+
+// Hard-skip regex for sensitive files. Cannot be turned off via config.
+// Match tokenized secret/credential filenames, not UI names such as
+// CredentialForm.tsx, SecretPage.jsx, or secretary-dashboard.vue.
+export const SENSITIVE_PATH = new RegExp([
+ String.raw`(?:^|[/\\])\.env(?:\.|$)`,
+ String.raw`(?:^|[/\\])\.git(?:[/\\]|$)`,
+ String.raw`(?:^|[/\\])id_rsa(?:$|[._-])[^/\\]*$`,
+ String.raw`(?:^|[/\\])[^/\\]*\.pem$`,
+ String.raw`(?:^|[/\\])(?:[^/\\]*[._-])?(?:secret|secrets|credential|credentials)(?=[._-])[^/\\]*\.(?:json|ya?ml|toml|ini|conf|config|env|txt|key|cert|crt|pem|js|ts)$`,
+].join('|'), 'i');
+
+// Hard-skip regex for generated, lock, minified, and build-output paths.
+export const GENERATED_PATH = /(?:\.generated\.[a-z]+$|\.d\.ts$|\.min\.[a-z]+$|[/\\]node_modules[/\\]|[/\\](?:dist|build|out|\.next|\.cache|coverage)[/\\]|[/\\]?[^/\\]+\.lock(?:\.json)?$)/i;
+
+export const TRUTHY = /^(1|true|yes|on)$/i;
+
+export const DEFAULT_CONFIG = Object.freeze({
+ enabled: true,
+ ignoreRules: [],
+ ignoreFiles: [],
+ ignoreValues: [],
+ limits: { maxFindings: 5, maxChars: 8000 },
+});
+
+export const HOOK_LOCAL_IGNORE_PATTERNS = Object.freeze([
+ '.impeccable/hook.cache.json',
+ '.impeccable/hook.pending.json',
+ '.impeccable/hook.local.json',
+]);
+
+const HOOK_IGNORE_MARKER_OPEN = '# impeccable-hook-ignore-start';
+const HOOK_IGNORE_MARKER_CLOSE = '# impeccable-hook-ignore-end';
+const CACHE_MAX_SESSIONS = 8;
+export const EDIT_COUNT_THRESHOLD = 6;
+
+export function truthy(value) {
+ return typeof value === 'string' && TRUTHY.test(value);
+}
+
+function depthIsSet(value) {
+ if (value === undefined || value === null) return false;
+ const text = String(value).trim();
+ if (!text) return false;
+ if (TRUTHY.test(text)) return true;
+ return /^\d+$/.test(text) && Number(text) > 0;
+}
+
+function safeReadJson(filePath) {
+ try {
+ return JSON.parse(fs.readFileSync(filePath, 'utf-8'));
+ } catch {
+ return null;
+ }
+}
+
+export function getConfigPath(cwd) {
+ return path.join(cwd, '.impeccable', 'hook.json');
+}
+
+export function getLocalConfigPath(cwd) {
+ return path.join(cwd, '.impeccable', 'hook.local.json');
+}
+
+export function getCachePath(cwd) {
+ return path.join(cwd, '.impeccable', 'hook.cache.json');
+}
+
+export function getPendingPath(cwd) {
+ return path.join(cwd, '.impeccable', 'hook.pending.json');
+}
+
+export function resolveProjectCwd(event, fallback = process.cwd()) {
+ return event?.cwd
+ || (Array.isArray(event?.workspace_roots) && event.workspace_roots[0])
+ || envProjectDir(fallback)
+ || fallback;
+}
+
+export function readConfig(cwd) {
+ const config = cloneDefaultConfig();
+ applyConfigSource(config, safeReadJson(getConfigPath(cwd)));
+ applyConfigSource(config, safeReadJson(getLocalConfigPath(cwd)));
+ return config;
+}
+
+function numberOr(value, fallback) {
+ return Number.isFinite(value) && value > 0 ? value : fallback;
+}
+
+function cloneDefaultConfig() {
+ return {
+ ...DEFAULT_CONFIG,
+ ignoreRules: [],
+ ignoreFiles: [],
+ ignoreValues: [],
+ limits: { ...DEFAULT_CONFIG.limits },
+ };
+}
+
+function applyConfigSource(config, raw) {
+ if (!raw || typeof raw !== 'object') return config;
+ if (Object.prototype.hasOwnProperty.call(raw, 'enabled')) {
+ config.enabled = raw.enabled === false ? false : true;
+ }
+ if (Array.isArray(raw.ignoreRules)) {
+ config.ignoreRules = uniqueStrings([...config.ignoreRules, ...raw.ignoreRules]);
+ }
+ if (Array.isArray(raw.ignoreFiles)) {
+ config.ignoreFiles = uniqueStrings([...config.ignoreFiles, ...raw.ignoreFiles]);
+ }
+ if (Array.isArray(raw.ignoreValues)) {
+ config.ignoreValues = mergeIgnoreValues(config.ignoreValues, raw.ignoreValues);
+ }
+ if (raw.limits && typeof raw.limits === 'object') {
+ config.limits = {
+ maxFindings: numberOr(raw.limits.maxFindings, config.limits.maxFindings),
+ maxChars: numberOr(raw.limits.maxChars, config.limits.maxChars),
+ };
+ }
+ return config;
+}
+
+function uniqueStrings(values) {
+ return Array.from(new Set(values.map(String)));
+}
+
+export function normalizeIgnoreValue(value) {
+ return String(value || '')
+ .trim()
+ .replace(/^["']|["']$/g, '')
+ .replace(/\+/g, ' ')
+ .replace(/\s+/g, ' ')
+ .toLowerCase();
+}
+
+function normalizeIgnoreRule(rule) {
+ return String(rule || '').trim().toLowerCase();
+}
+
+export function normalizeIgnoreValueEntries(entries) {
+ if (!Array.isArray(entries)) return [];
+ const out = [];
+ for (const entry of entries) {
+ if (!entry || typeof entry !== 'object') continue;
+ const rule = normalizeIgnoreRule(entry.rule);
+ const value = normalizeIgnoreValue(entry.value);
+ if (!rule || !value) continue;
+ const normalized = { rule, value };
+ if (typeof entry.reason === 'string' && entry.reason.trim()) {
+ normalized.reason = entry.reason.trim();
+ }
+ if (typeof entry.createdAt === 'string' && entry.createdAt.trim()) {
+ normalized.createdAt = entry.createdAt.trim();
+ }
+ out.push(normalized);
+ }
+ return out;
+}
+
+function mergeIgnoreValues(existing, incoming) {
+ const map = new Map();
+ for (const entry of normalizeIgnoreValueEntries(existing)) {
+ map.set(`${entry.rule}\0${entry.value}`, entry);
+ }
+ for (const entry of normalizeIgnoreValueEntries(incoming)) {
+ map.set(`${entry.rule}\0${entry.value}`, entry);
+ }
+ return Array.from(map.values());
+}
+
+export function readCache(cwd) {
+ const raw = safeReadJson(getCachePath(cwd));
+ if (!raw || typeof raw !== 'object' || raw.version !== 1) {
+ return { version: 1, sessions: {} };
+ }
+ return {
+ version: 1,
+ sessions: raw.sessions && typeof raw.sessions === 'object' ? raw.sessions : {},
+ };
+}
+
+export function persistCache(cwd, cache) {
+ const sessions = cache.sessions || {};
+ const ids = Object.keys(sessions);
+ if (ids.length > CACHE_MAX_SESSIONS) {
+ // Garbage-collect oldest sessions by updatedAt.
+ const ordered = ids
+ .map((id) => [id, sessions[id]?.updatedAt || 0])
+ .sort((a, b) => b[1] - a[1])
+ .slice(0, CACHE_MAX_SESSIONS);
+ const next = {};
+ for (const [id] of ordered) next[id] = sessions[id];
+ cache = { ...cache, sessions: next };
+ }
+ const target = getCachePath(cwd);
+ try {
+ ensureHookGitExcludes(cwd);
+ fs.mkdirSync(path.dirname(target), { recursive: true });
+ fs.writeFileSync(target, JSON.stringify(cache));
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+export function ensureHookGitExcludes(cwd = process.cwd()) {
+ try {
+ const target = resolveHookGitExcludeTarget(cwd);
+ if (!target) {
+ return { mode: 'none', changed: false, patterns: [...HOOK_LOCAL_IGNORE_PATTERNS] };
+ }
+
+ const patterns = target.patternPrefix
+ ? HOOK_LOCAL_IGNORE_PATTERNS.map((pattern) => `${target.patternPrefix}/${pattern}`)
+ : [...HOOK_LOCAL_IGNORE_PATTERNS];
+ const markerSuffix = target.patternPrefix || '.';
+ const markerOpen = `${HOOK_IGNORE_MARKER_OPEN} ${markerSuffix}`;
+ const markerClose = `${HOOK_IGNORE_MARKER_CLOSE} ${markerSuffix}`;
+ const existing = fs.existsSync(target.path) ? fs.readFileSync(target.path, 'utf-8') : '';
+ const block = [markerOpen, ...patterns, markerClose].join('\n');
+ const markerRe = new RegExp(`${escapeRegExp(markerOpen)}[\\s\\S]*?${escapeRegExp(markerClose)}`);
+
+ let updated;
+ if (markerRe.test(existing)) {
+ updated = existing.replace(markerRe, block);
+ } else {
+ const prefix = existing.length === 0 ? '' : existing.endsWith('\n') ? existing : `${existing}\n`;
+ updated = `${prefix}${prefix.endsWith('\n\n') || prefix === '' ? '' : '\n'}${block}\n`;
+ }
+
+ if (updated !== existing) {
+ fs.mkdirSync(path.dirname(target.path), { recursive: true });
+ fs.writeFileSync(target.path, updated, 'utf-8');
+ }
+
+ return {
+ mode: 'git-info-exclude',
+ file: path.relative(path.resolve(cwd), target.path).split(path.sep).join('/'),
+ changed: updated !== existing,
+ patterns,
+ };
+ } catch {
+ return { mode: 'error', changed: false, patterns: [...HOOK_LOCAL_IGNORE_PATTERNS] };
+ }
+}
+
+function resolveHookGitExcludeTarget(cwd) {
+ const start = path.resolve(cwd);
+ let dir = start;
+ while (true) {
+ const dotGit = path.join(dir, '.git');
+ if (fs.existsSync(dotGit)) {
+ const gitDir = resolveGitDir(dotGit, dir);
+ if (!gitDir) return null;
+ const relPrefix = path.relative(dir, start).split(path.sep).join('/');
+ return {
+ path: path.join(gitDir, 'info', 'exclude'),
+ patternPrefix: relPrefix && relPrefix !== '.' ? relPrefix : '',
+ };
+ }
+ const parent = path.dirname(dir);
+ if (parent === dir) return null;
+ dir = parent;
+ }
+}
+
+function resolveGitDir(dotGit, worktreeDir) {
+ const stat = fs.statSync(dotGit);
+ if (stat.isDirectory()) return dotGit;
+ if (!stat.isFile()) return null;
+
+ const body = fs.readFileSync(dotGit, 'utf-8').trim();
+ const match = body.match(/^gitdir:\s*(.+)$/i);
+ if (!match) return null;
+ return path.isAbsolute(match[1]) ? match[1] : path.resolve(worktreeDir, match[1]);
+}
+
+function escapeRegExp(value) {
+ return String(value).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+}
+
+function ensureSession(cache, sessionId) {
+ if (!cache.sessions[sessionId]) {
+ cache.sessions[sessionId] = { updatedAt: Date.now(), files: {} };
+ }
+ return cache.sessions[sessionId];
+}
+
+function ensureFile(cache, sessionId, filePath) {
+ const session = ensureSession(cache, sessionId);
+ if (!session.files[filePath]) {
+ session.files[filePath] = { editCount: 0, findings: [] };
+ }
+ return session.files[filePath];
+}
+
+export function bumpEditCount(cache, sessionId, filePath) {
+ const fileEntry = ensureFile(cache, sessionId, filePath);
+ fileEntry.editCount = (fileEntry.editCount || 0) + 1;
+ ensureSession(cache, sessionId).updatedAt = Date.now();
+ return fileEntry.editCount;
+}
+
+export function suppressionNotice(filePath) {
+ return `${ENVELOPE_PREFIX} Suppressing further design hints on ${filePath}. More than ${EDIT_COUNT_THRESHOLD} edits in this session reached. Run /impeccable audit to revisit.`;
+}
+
+// Glob → RegExp. Supports `**`, `*`, `?`, and `{a,b}` alternation.
+function globToRegex(glob) {
+ let re = '^';
+ let i = 0;
+ while (i < glob.length) {
+ const c = glob[i];
+ if (c === '*') {
+ if (glob[i + 1] === '*') {
+ re += '.*';
+ i += 2;
+ if (glob[i] === '/') i += 1;
+ } else {
+ re += '[^/]*';
+ i += 1;
+ }
+ } else if (c === '?') {
+ re += '[^/]';
+ i += 1;
+ } else if (c === '{') {
+ const end = glob.indexOf('}', i);
+ if (end === -1) { re += '\\{'; i += 1; continue; }
+ const parts = glob.slice(i + 1, end).split(',').map((p) => p.replace(/[.+^$()|[\]\\]/g, '\\$&'));
+ re += `(?:${parts.join('|')})`;
+ i = end + 1;
+ } else if (/[.+^$()|[\]\\]/.test(c)) {
+ re += `\\${c}`;
+ i += 1;
+ } else {
+ re += c;
+ i += 1;
+ }
+ }
+ re += '$';
+ return new RegExp(re);
+}
+
+export function matchesAnyGlob(filePath, globs) {
+ if (!Array.isArray(globs) || globs.length === 0) return false;
+ const normalized = filePath.split(path.sep).join('/');
+ for (const glob of globs) {
+ try {
+ const re = globToRegex(String(glob));
+ if (re.test(normalized)) return true;
+ // Match against basename too for convenience: `*.generated.tsx` should
+ // catch `src/foo.generated.tsx` without requiring `**/`.
+ const base = normalized.split('/').pop();
+ if (re.test(base)) return true;
+ } catch {
+ /* malformed glob, skip */
+ }
+ }
+ return false;
+}
+
+export function filterFindings(findings, _content, _ext, config) {
+ if (!Array.isArray(findings) || findings.length === 0) return [];
+ const ignoreRules = new Set((config.ignoreRules || []).map((rule) => normalizeIgnoreRule(rule)));
+ const ignoreValues = normalizeIgnoreValueEntries(config.ignoreValues || []);
+ return findings.filter((f) => {
+ if (!f || typeof f !== 'object') return false;
+ if (ignoreRules.has(normalizeIgnoreRule(f.antipattern))) return false;
+ if (isIgnoredFindingValue(f, ignoreValues)) return false;
+ return true;
+ });
+}
+
+function isIgnoredFindingValue(finding, ignoreValues) {
+ if (!Array.isArray(ignoreValues) || ignoreValues.length === 0) return false;
+ const rule = normalizeIgnoreRule(finding.antipattern);
+ const value = extractFindingIgnoreValue(finding);
+ if (!rule || !value) return false;
+ return ignoreValues.some((entry) => entry.rule === rule && entry.value === value);
+}
+
+export function extractFindingIgnoreValue(finding) {
+ if (!finding || typeof finding !== 'object') return '';
+ const rule = normalizeIgnoreRule(finding.antipattern);
+ if (rule !== 'overused-font') return '';
+ return normalizeIgnoreValue(extractFindingIgnoreValueRaw(finding));
+}
+
+function extractFindingIgnoreValueRaw(finding) {
+ const direct = cleanIgnoreValueDisplay(finding.ignoreValue || finding.value || '');
+ if (direct) return direct;
+
+ const candidates = [finding.detail, finding.snippet].filter((v) => typeof v === 'string' && v);
+ for (const text of candidates) {
+ const primary = text.match(/Primary font:\s*([^()\n;]+)/i);
+ if (primary) return cleanIgnoreValueDisplay(primary[1]);
+
+ const family = text.match(/font-family\s*:\s*["']?([^'",;\n]+)/i);
+ if (family) return cleanIgnoreValueDisplay(family[1]);
+
+ const google = text.match(/[?&]family=([^&:;\n]+)/i);
+ if (google) {
+ try {
+ return cleanIgnoreValueDisplay(decodeURIComponent(google[1]));
+ } catch {
+ return cleanIgnoreValueDisplay(google[1]);
+ }
+ }
+ }
+
+ return '';
+}
+
+function cleanIgnoreValueDisplay(value) {
+ return String(value || '')
+ .trim()
+ .replace(/^["']|["']$/g, '')
+ .replace(/\+/g, ' ')
+ .replace(/\s+/g, ' ');
+}
+
+export function dedupeAgainstCache(findings, cache, sessionId, filePath) {
+ if (!Array.isArray(findings) || findings.length === 0) return [];
+ const fileEntry = ensureFile(cache, sessionId, filePath);
+ const known = new Set(fileEntry.findings || []);
+ const fresh = [];
+ for (const f of findings) {
+ const key = `${f.antipattern}:${f.line || 0}`;
+ if (known.has(key)) continue;
+ known.add(key);
+ fresh.push(f);
+ }
+ return fresh;
+}
+
+export function rememberFindings(cache, sessionId, filePath, findings) {
+ const fileEntry = ensureFile(cache, sessionId, filePath);
+ const known = new Set(fileEntry.findings || []);
+ for (const f of findings) known.add(`${f.antipattern}:${f.line || 0}`);
+ fileEntry.findings = Array.from(known);
+ ensureSession(cache, sessionId).updatedAt = Date.now();
+}
+
+export function renderTemplate(findings, filePath, config, opts = {}) {
+ if (!Array.isArray(findings) || findings.length === 0) return '';
+ const limits = config?.limits || DEFAULT_CONFIG.limits;
+ const cap = Math.max(1, limits.maxFindings || DEFAULT_CONFIG.limits.maxFindings);
+ const maxChars = Math.max(500, limits.maxChars || DEFAULT_CONFIG.limits.maxChars);
+
+ const cwd = opts.cwd || process.cwd();
+ const display = relativize(filePath, cwd);
+ const total = findings.length;
+ const shown = findings.slice(0, cap);
+ const remaining = total - shown.length;
+
+ const header = `${ENVELOPE_PREFIX} Required design corrections in ${display} (${total} issue(s)):`;
+ const lines = shown.map((f) => formatFindingLine(f));
+ const more = remaining > 0
+ ? `... and ${remaining} more (see /impeccable audit).`
+ : null;
+ const footer = directiveFooter(display);
+
+ const blocks = [header, ...lines];
+ if (more) blocks.push(more);
+ blocks.push('');
+ blocks.push(footer);
+ let text = blocks.join('\n');
+
+ if (text.length > maxChars) {
+ text = clampToBudget(header, lines, more, footer, maxChars);
+ }
+ return text;
+}
+
+function renderGroupedTemplate(groups, config, opts = {}) {
+ const realGroups = groups.filter((group) => Array.isArray(group.findings) && group.findings.length > 0);
+ if (realGroups.length === 0) return '';
+ if (realGroups.length === 1) {
+ const [group] = realGroups;
+ return renderTemplate(group.findings, group.filePath, config, opts);
+ }
+
+ const limits = config?.limits || DEFAULT_CONFIG.limits;
+ const cap = Math.max(1, limits.maxFindings || DEFAULT_CONFIG.limits.maxFindings);
+ const maxChars = Math.max(500, limits.maxChars || DEFAULT_CONFIG.limits.maxChars);
+ const cwd = opts.cwd || process.cwd();
+ const total = realGroups.reduce((sum, group) => sum + group.findings.length, 0);
+ const header = `${ENVELOPE_PREFIX} Required design corrections across ${realGroups.length} files (${total} issue(s)):`;
+ const lines = [];
+ let shownCount = 0;
+
+ for (const group of realGroups) {
+ const display = relativize(group.filePath, cwd);
+ lines.push(`${display} (${group.findings.length} issue(s)):`);
+ const remainingCap = Math.max(0, cap - shownCount);
+ const shown = group.findings.slice(0, remainingCap);
+ for (const finding of shown) {
+ lines.push(formatFindingLine(finding));
+ }
+ shownCount += shown.length;
+ const hidden = group.findings.length - shown.length;
+ if (hidden > 0) {
+ lines.push(`- ... ${hidden} more in ${display} (see /impeccable audit).`);
+ }
+ }
+
+ const footer = directiveFooter('the affected files', { grouped: true });
+ let text = [header, ...lines, '', footer].join('\n');
+ if (text.length > maxChars) {
+ text = clampGroupedToBudget(header, lines, footer, maxChars);
+ }
+ return text;
+}
+
+function clampGroupedToBudget(header, lines, footer, maxChars) {
+ const assemble = (linesArr, omitted) => [
+ header,
+ ...linesArr,
+ ...(omitted ? ['... and more (see /impeccable audit).'] : []),
+ '',
+ footer,
+ ].join('\n');
+
+ let working = lines.slice();
+ let omitted = false;
+ let assembled = assemble(working, omitted);
+ while (assembled.length > maxChars && working.length > 1) {
+ working.pop();
+ omitted = true;
+ assembled = assemble(working, omitted);
+ }
+ if (assembled.length > maxChars) {
+ assembled = `${assembled.slice(0, maxChars - 1)}…`;
+ }
+ return assembled;
+}
+
+function clampToBudget(header, lines, more, footer, maxChars) {
+ const assemble = (linesArr, moreText) => {
+ const blocks = [header, ...linesArr];
+ if (moreText) blocks.push(moreText);
+ blocks.push('');
+ blocks.push(footer);
+ return blocks.join('\n');
+ };
+
+ let working = lines.slice();
+ let moreText = more;
+ let assembled = assemble(working, moreText);
+ while (assembled.length > maxChars && working.length > 1) {
+ working.pop();
+ moreText = '... and more (see /impeccable audit).';
+ assembled = assemble(working, moreText);
+ }
+ if (assembled.length > maxChars) {
+ assembled = `${assembled.slice(0, maxChars - 1)}…`;
+ }
+ return assembled;
+}
+
+function formatFindingLine(f) {
+ const prefix = f.line && f.line > 0 ? `- L${f.line}` : '-';
+ const desc = (f.description || '').trim();
+ const name = (f.name || '').trim();
+ // Description from the registry already ends in punctuation; join with a
+ // single space. `name` may have a trailing period already, keep it clean.
+ const nameSegment = name ? `${name.replace(/\.+\s*$/, '')}.` : '';
+ const ignoreCommand = formatFindingIgnoreCommand(f);
+ const ignoreSegment = ignoreCommand
+ ? ` If the user explicitly confirms this value is intentional: \`${ignoreCommand}\`.`
+ : '';
+ return `${prefix} [${f.antipattern}] ${nameSegment} ${desc}${ignoreSegment}`.replace(/\s+/g, ' ').trim();
+}
+
+function formatFindingIgnoreCommand(finding) {
+ if (!finding || typeof finding !== 'object') return '';
+ const rule = normalizeIgnoreRule(finding.antipattern);
+ if (!rule) return '';
+ const normalizedValue = extractFindingIgnoreValue(finding);
+ if (!normalizedValue) return '';
+ const value = extractFindingIgnoreValueRaw(finding);
+ const valueArg = quoteCommandArg(value);
+ const reason = quoteCommandArg(`User confirmed ${value} is intentional`);
+ return `/impeccable hooks ignore-value ${rule} ${valueArg} --shared --reason ${reason}`;
+}
+
+function quoteCommandArg(value) {
+ const text = String(value || '').trim();
+ if (/^[A-Za-z0-9._:-]+$/.test(text)) return text;
+ return `"${text.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
+}
+
+function relativize(filePath, cwd) {
+ try {
+ const rel = path.relative(cwd, filePath);
+ if (!rel || rel.startsWith('..')) return filePath;
+ return rel.split(path.sep).join('/');
+ } catch {
+ return filePath;
+ }
+}
+
+// Codex `apply_patch` exposes the raw patch in `tool_input.command`, not
+// `tool_input.file_path`. Claude Code may send both; parse the patch body
+// so we can scan the file(s) the tool actually touched.
+// https://developers.openai.com/codex/hooks#posttooluse
+const APPLY_PATCH_FILE_RE = /^\*\*\* (?:Update|Add) File: (.+)$/gm;
+
+export function parseApplyPatchPaths(command, projectCwd) {
+ if (!command || typeof command !== 'string') return [];
+ const out = [];
+ for (const m of command.matchAll(APPLY_PATCH_FILE_RE)) {
+ let p = (m[1] || '').trim();
+ if (!p) continue;
+ if (!path.isAbsolute(p)) p = path.resolve(projectCwd, p);
+ out.push(p);
+ }
+ return out;
+}
+
+export function resolveTargetFiles(event, projectCwd) {
+ const ti = event?.tool_input;
+ const out = [];
+ const add = (filePath) => {
+ if (typeof filePath !== 'string' || !filePath) return;
+ if (!out.includes(filePath)) out.push(filePath);
+ };
+
+ if (event?.tool_name === 'apply_patch' && ti && typeof ti.command === 'string') {
+ for (const filePath of parseApplyPatchPaths(ti.command, projectCwd)) add(filePath);
+ }
+ if (ti && typeof ti.file_path === 'string' && ti.file_path) {
+ add(ti.file_path);
+ }
+ // Cursor Write / StrReplace use `path`, not `file_path`.
+ if (ti && typeof ti.path === 'string' && ti.path) {
+ add(ti.path);
+ }
+ if (typeof event?.file_path === 'string' && event.file_path) {
+ add(event.file_path);
+ }
+ return out;
+}
+
+export function resolveHarness(env = {}, event = null) {
+ const explicit = env?.IMPECCABLE_HOOK_HARNESS;
+ if (explicit === 'cursor') return 'cursor';
+ if (explicit === 'claude' || explicit === 'codex') return 'claude';
+ if (typeof event?.conversation_id === 'string' && event.conversation_id) return 'cursor';
+ return 'claude';
+}
+
+export function normalizeHookEvent(event, projectCwd, harness = 'claude') {
+ if (!event || typeof event !== 'object' || harness !== 'cursor') return event;
+
+ const cwd = event.cwd
+ || (Array.isArray(event.workspace_roots) && event.workspace_roots[0])
+ || envProjectDir(projectCwd)
+ || projectCwd;
+ const sessionId = event.session_id || event.conversation_id || 'unknown';
+
+ const ti = event.tool_input && typeof event.tool_input === 'object' ? event.tool_input : {};
+ const filePath = ti.file_path || ti.path || event.file_path;
+ if (filePath) {
+ return {
+ ...event,
+ cwd,
+ session_id: sessionId,
+ tool_input: { ...ti, file_path: filePath },
+ };
+ }
+
+ return { ...event, cwd, session_id: sessionId };
+}
+
+function envProjectDir(fallback) {
+ if (typeof process.env.CURSOR_PROJECT_DIR === 'string' && process.env.CURSOR_PROJECT_DIR) {
+ return process.env.CURSOR_PROJECT_DIR;
+ }
+ return fallback;
+}
+
+// UI components often keep slop in a sibling/co-located stylesheet while the
+// JSX edit is what triggered PostToolUse. Scan those styles too so an App.jsx
+// patch doesn't report "clean" while styles.css still has Inter/bounce/etc.
+const UI_CODE_EXTS = new Set(['.jsx', '.tsx', '.vue', '.svelte', '.astro']);
+const STYLE_EXTS = new Set(['.css', '.scss', '.sass', '.less']);
+const CO_SCAN_STYLE_NAMES = [
+ 'styles.css', 'styles.scss', 'styles.sass', 'styles.less',
+ 'index.css', 'index.scss', 'index.sass', 'index.less',
+ 'global.css', 'global.scss', 'global.sass', 'global.less',
+ 'globals.css', 'globals.scss', 'globals.sass', 'globals.less',
+];
+const MAX_SCAN_TARGETS = 6;
+
+const STATIC_STYLE_IMPORT_RE = /import\s+(?:[\w*{}\s,$]+\s+from\s+)?['"]([^'"]+\.(?:css|scss|sass|less))['"]/gi;
+
+function hasPathTraversal(filePath) {
+ return typeof filePath === 'string' && filePath.includes('..');
+}
+
+function isInsideProject(filePath, projectCwd) {
+ if (!filePath || !projectCwd || hasPathTraversal(filePath)) return false;
+ try {
+ const rel = path.relative(projectCwd, filePath);
+ return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));
+ } catch {
+ return false;
+ }
+}
+
+export function parseStaticStyleImports(content, fromFile, projectCwd) {
+ if (!content || typeof content !== 'string') return [];
+ const dir = path.dirname(fromFile);
+ const out = [];
+ for (const m of content.matchAll(STATIC_STYLE_IMPORT_RE)) {
+ let p = (m[1] || '').trim();
+ if (!p) continue;
+ if (p.startsWith('.')) p = path.resolve(dir, p);
+ else if (!path.isAbsolute(p)) p = path.resolve(projectCwd, p);
+ if (!isInsideProject(p, projectCwd)) continue;
+ out.push(p);
+ }
+ return out;
+}
+
+export function coLocatedStylesheets(filePath) {
+ const dir = path.dirname(filePath);
+ const base = path.basename(filePath, path.extname(filePath));
+ const candidates = new Set([
+ path.join(dir, `${base}.css`),
+ path.join(dir, `${base}.module.css`),
+ path.join(dir, `${base}.scss`),
+ path.join(dir, `${base}.module.scss`),
+ path.join(dir, `${base}.sass`),
+ path.join(dir, `${base}.module.sass`),
+ path.join(dir, `${base}.less`),
+ path.join(dir, `${base}.module.less`),
+ ]);
+ for (const name of CO_SCAN_STYLE_NAMES) {
+ candidates.add(path.join(dir, name));
+ }
+ return [...candidates].filter((p) => fs.existsSync(p));
+}
+
+export function normalizeScanTargets(primaryTargets, projectCwd) {
+ if (!Array.isArray(primaryTargets) || primaryTargets.length === 0) return [];
+ const ordered = [];
+ const seen = new Set();
+ const baseCwd = projectCwd || process.cwd();
+ const normalizeTarget = (p) => {
+ // Preserve literal `..` segments so downstream sensitive-path checks
+ // still fire. path.resolve would collapse `/foo/../etc/passwd`.
+ if (hasPathTraversal(p)) return p;
+ return path.isAbsolute(p) ? p : path.resolve(baseCwd, p);
+ };
+ const add = (p) => {
+ if (ordered.length >= MAX_SCAN_TARGETS) return;
+ const abs = normalizeTarget(p);
+ if (seen.has(abs)) return;
+ seen.add(abs);
+ ordered.push(abs);
+ return abs;
+ };
+
+ for (const p of primaryTargets) add(p);
+ return ordered;
+}
+
+export function expandScanTargets(primaryTargets, projectCwd) {
+ const ordered = normalizeScanTargets(primaryTargets, projectCwd);
+ if (ordered.length === 0) return [];
+ const seen = new Set(ordered);
+ const baseCwd = projectCwd || process.cwd();
+ const add = (p) => {
+ if (ordered.length >= MAX_SCAN_TARGETS) return;
+ const abs = hasPathTraversal(p) ? p : (path.isAbsolute(p) ? p : path.resolve(baseCwd, p));
+ if (seen.has(abs)) return;
+ seen.add(abs);
+ ordered.push(abs);
+ return abs;
+ };
+
+ const normalizedPrimaries = [];
+ for (const p of ordered) normalizedPrimaries.push(p);
+
+ for (const p of normalizedPrimaries) {
+ if (ordered.length >= MAX_SCAN_TARGETS) break;
+ if (!isInsideProject(p, baseCwd)) continue;
+ const ext = path.extname(p).toLowerCase();
+ if (STYLE_EXTS.has(ext) || !UI_CODE_EXTS.has(ext)) continue;
+
+ let content = '';
+ try { content = fs.readFileSync(p, 'utf-8'); } catch { /* unreadable primary */ }
+
+ for (const imp of parseStaticStyleImports(content, p, projectCwd)) {
+ add(imp);
+ if (ordered.length >= MAX_SCAN_TARGETS) break;
+ }
+ for (const col of coLocatedStylesheets(p)) {
+ add(col);
+ if (ordered.length >= MAX_SCAN_TARGETS) break;
+ }
+ }
+
+ return ordered;
+}
+
+export function writeAuditLog(env, entry) {
+ const target = env?.IMPECCABLE_HOOK_LOG;
+ if (!target || typeof target !== 'string') return false;
+ try {
+ const expanded = target.startsWith('~/')
+ ? path.join(process.env.HOME || process.env.USERPROFILE || '.', target.slice(2))
+ : target;
+ fs.mkdirSync(path.dirname(expanded), { recursive: true });
+ const line = JSON.stringify({ ts: new Date().toISOString(), ...entry }) + '\n';
+ fs.appendFileSync(expanded, line);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+const DETECTOR_CANDIDATES = [
+ path.join(__dirname, 'detector', 'detect-antipatterns.mjs'),
+ path.join(__dirname, '..', '..', 'cli', 'engine', 'detect-antipatterns.mjs'),
+ path.join(__dirname, '..', '..', '..', 'cli', 'engine', 'detect-antipatterns.mjs'),
+];
+
+let detectorCache = null;
+export async function loadDetector(candidates = DETECTOR_CANDIDATES) {
+ if (detectorCache) return detectorCache;
+ const found = candidates.find((c) => fs.existsSync(c));
+ if (!found) return null;
+ const mod = await import(pathToFileURL(found));
+ detectorCache = { detectText: mod.detectText, detectHtml: mod.detectHtml };
+ return detectorCache;
+}
+
+// For tests: allow injecting a detector implementation.
+export function setDetectorForTesting(impl) {
+ detectorCache = impl;
+}
+
+// ────────────────────────────────────────────────────────────────────────
+// Nudge/steer messages for the no-silent-fires policy.
+//
+// The hook is designed to be a conversational presence: every fire that
+// actually scans a file emits a developer-role message into the model's
+// next turn. Three states map to three templates:
+//
+// 1. **Fresh findings** → `renderTemplate` (existing, imperative).
+// 2. **Pending findings** → `renderPendingAck` (re-nudge for issues the
+// model was already told about in this
+// session but hasn't fixed yet).
+// 3. **Truly clean** → `renderCleanAck` (short positive nudge that
+// keeps the design discipline in context).
+//
+// All three are short (≤ ~40 tokens each) so the cumulative cost stays
+// bounded across a long active editing session. Users who explicitly want
+// silence-on-clean can set `IMPECCABLE_HOOK_QUIET=1` — runHook checks that
+// env before emitting #2 or #3.
+//
+// Why not stay silent on dedup-clean? Earlier versions did. The model
+// quickly forgets the prior reminder once tool output scrolls past it, so
+// re-nudging on the same file with a short "still pending" line keeps the
+// pressure on. The wording deliberately points back to "earlier this
+// session" so the model knows it's a re-mind, not a new finding.
+// ────────────────────────────────────────────────────────────────────────
+
+const STEER_LINE = 'Keep typography hierarchy, spacing rhythm, and color contrast intentional on the next change.';
+
+export function renderCleanAck(filePath, opts = {}) {
+ const cwd = opts.cwd || process.cwd();
+ const display = relativize(filePath, cwd);
+ return `${ENVELOPE_PREFIX} Design hook scanned ${display}. No anti-patterns. ${STEER_LINE}`;
+}
+
+export function renderPendingAck(filePath, knownFindings, opts = {}) {
+ const cwd = opts.cwd || process.cwd();
+ const display = relativize(filePath, cwd);
+ const count = knownFindings.length;
+ // `knownFindings` here are the cache strings like "side-tab:3".
+ const sample = knownFindings.slice(0, 3).join(', ');
+ const more = count > 3 ? `, +${count - 3} more` : '';
+ return `${ENVELOPE_PREFIX} Design hook scanned ${display}. Still has ${count} issue(s) flagged earlier this session (${sample}${more}). Address them before finalizing — the previous reminder still applies.`;
+}
+
+export function shouldEmitAckForFile(filePath) {
+ return ACK_EXTS.has(path.extname(String(filePath || '')).toLowerCase());
+}
+
+// The directive footer is the part of the hook output that steers model
+// behavior. Three intentional moves:
+// 1. **Imperative, not advisory.** "Fix these..." beats "Consider
+// revising..." which the model treats as a soft suggestion it can
+// override when the user asked for any kind of throwaway / demo UI.
+// 2. **Explicit exception clause.** Without it, the model will try to
+// "fix" intentional bad fixtures, anti-pattern examples in docs, or
+// test cases. Naming the exception inline beats hoping the model
+// infers it from context.
+// 3. **Acknowledgement instruction.** Hook output is injected as
+// developer-role context, not a chat turn, so the user never sees the
+// raw envelope. Asking the model to surface the fix in its reply is
+// the cheapest way to make the feedback loop visible to the user.
+function directiveFooter(display, opts = {}) {
+ const ignoreFileCommand = `/impeccable hooks ignore-file ${quoteCommandArg(display)}`;
+ const fileIgnoreGuidance = opts.grouped
+ ? 'run `/impeccable hooks ignore-file <path>` for the specific file'
+ : `run \`${ignoreFileCommand}\``;
+ return [
+ 'Fix these in your next reply before finalizing. Acknowledge what you changed so the user sees the correction.',
+ '',
+ 'Skip the fix only if the user explicitly asked for an intentionally bad UI, an anti-pattern example, a test fixture, or documentation of bad design. In that case, say so and continue.',
+ '',
+ `Do not add source comments such as \`impeccable: ignore\`; those pollute the code and do not suppress hook findings. Do not add hook ignores unless the user explicitly confirms the finding is intentional. Prefer the narrowest persisted exception: run the exact \`/impeccable hooks ignore-value ... --shared\` command shown next to a value-specific finding. For \`overused-font\`, use \`ignore-value\` for a specific font and use \`/impeccable hooks ignore-rule overused-font --all-values\` only when the user asks to ignore overused fonts generally. For file-specific findings without an ignore-value command, ${fileIgnoreGuidance}; use \`/impeccable hooks ignore-rule <id>\` only when the user asks to suppress the whole non-value-specific rule. Run /impeccable audit for the full pass.`,
+ ].join('\n');
+}
+
+/**
+ * Run the hook with explicit dependencies. Returns a result object:
+ * { exitCode, stdout, audit, reason? }
+ *
+ * Never throws. All errors are converted to `exitCode: 0` + audit entry.
+ */
+export async function runHook({ stdinJson, env = {}, cwd = process.cwd(), now = Date.now, detector } = {}) {
+ const audit = { ts: new Date(now()).toISOString(), event: 'PostToolUse' };
+ const result = (extra) => ({ exitCode: 0, stdout: '', audit: { ...audit, ...extra } });
+
+ try {
+ // Re-entrancy guard.
+ if (depthIsSet(env.IMPECCABLE_HOOK_DEPTH) || depthIsSet(env.CLAUDE_HOOK_DEPTH)) {
+ return result({ reentrant: true, durationMs: 0 });
+ }
+
+ if (truthy(env.IMPECCABLE_HOOK_DISABLED)) {
+ return result({ skipped: 'env-disabled', durationMs: 0 });
+ }
+
+ const started = Date.now();
+
+ let event;
+ try {
+ event = typeof stdinJson === 'string' ? JSON.parse(stdinJson) : stdinJson;
+ } catch {
+ return result({ skipped: 'stdin-malformed', durationMs: Date.now() - started });
+ }
+ if (!event || typeof event !== 'object') {
+ return result({ skipped: 'stdin-empty', durationMs: Date.now() - started });
+ }
+
+ const harness = resolveHarness(env, event);
+ event = normalizeHookEvent(event, cwd, harness);
+ audit.harness = harness;
+
+ const projectCwd = event.cwd || cwd;
+ const primaryFiles = normalizeScanTargets(resolveTargetFiles(event, projectCwd), projectCwd);
+ const primaryFileSet = new Set(primaryFiles);
+ const targetFiles = expandScanTargets(primaryFiles, projectCwd);
+ audit.session = event.session_id || null;
+ if (event.tool_name) audit.tool = event.tool_name;
+
+ if (targetFiles.length === 0) {
+ return result({ skipped: 'no-file-path', durationMs: Date.now() - started });
+ }
+
+ const config = readConfig(projectCwd);
+ if (config.enabled === false) {
+ return result({ skipped: 'config-disabled', durationMs: Date.now() - started });
+ }
+
+ const cache = readCache(projectCwd);
+ const sessionId = event.session_id || 'unknown';
+ const det = detector || await loadDetector();
+ if (!det || typeof det.detectText !== 'function') {
+ persistCache(projectCwd, cache);
+ return result({ skipped: 'detector-missing', durationMs: Date.now() - started });
+ }
+
+ let pendingWinner = null;
+ let cleanWinner = null;
+ const freshGroups = [];
+ let suppressionWinner = null;
+ let detectorThrewAny = false;
+ let lastSkip = 'no-scannable-file';
+ let suppressedHit = false;
+
+ for (const filePath of targetFiles) {
+ audit.file = filePath;
+
+ if (hasPathTraversal(filePath) || SENSITIVE_PATH.test(filePath)) {
+ lastSkip = 'sensitive';
+ continue;
+ }
+ if (GENERATED_PATH.test(filePath)) {
+ lastSkip = 'generated';
+ continue;
+ }
+
+ const ext = path.extname(filePath).toLowerCase();
+ audit.ext = ext;
+ if (!ALLOWED_EXTS.has(ext)) {
+ lastSkip = 'extension';
+ continue;
+ }
+
+ const relForMatch = relativize(filePath, projectCwd);
+ if (matchesAnyGlob(relForMatch, config.ignoreFiles) || matchesAnyGlob(filePath, config.ignoreFiles)) {
+ lastSkip = 'config-ignore-file';
+ continue;
+ }
+ if (!fs.existsSync(filePath)) {
+ lastSkip = 'file-missing';
+ continue;
+ }
+
+ if (primaryFileSet.has(filePath)) {
+ const editCount = bumpEditCount(cache, sessionId, filePath);
+ audit.editCount = editCount;
+
+ if (editCount > EDIT_COUNT_THRESHOLD) {
+ const wasJustCrossed = editCount === EDIT_COUNT_THRESHOLD + 1;
+ if (wasJustCrossed && !suppressionWinner) {
+ suppressionWinner = { filePath };
+ }
+ lastSkip = 'suppressed';
+ suppressedHit = true;
+ continue;
+ }
+ }
+
+ const content = fs.readFileSync(filePath, 'utf-8');
+ let findings;
+ let detectorThrew = false;
+ if ((ext === '.html' || ext === '.htm') && typeof det.detectHtml === 'function') {
+ try { findings = await det.detectHtml(filePath); } catch { findings = []; detectorThrew = true; }
+ } else {
+ try { findings = await det.detectText(content, filePath); } catch { findings = []; detectorThrew = true; }
+ }
+
+ const filtered = filterFindings(findings || [], content, ext, config);
+ const fresh = dedupeAgainstCache(filtered, cache, sessionId, filePath);
+ audit.findings = (findings || []).length;
+ audit.freshFindings = fresh.length;
+
+ if (fresh.length > 0) {
+ rememberFindings(cache, sessionId, filePath, fresh);
+ freshGroups.push({ filePath, findings: fresh });
+ continue;
+ }
+
+ if (detectorThrew) {
+ detectorThrewAny = true;
+ continue;
+ }
+
+ if (filtered.length > 0 && !pendingWinner) {
+ const known = (ensureFile(cache, sessionId, filePath).findings || []).slice();
+ pendingWinner = { filePath, known };
+ } else if (filtered.length === 0 && !cleanWinner) {
+ cleanWinner = { filePath };
+ }
+ }
+
+ persistCache(projectCwd, cache);
+
+ if (freshGroups.length > 0) {
+ const firstGroup = freshGroups[0];
+ const text = renderGroupedTemplate(freshGroups, config, { cwd: projectCwd });
+ const allFindings = freshGroups.flatMap((group) => group.findings);
+ return {
+ exitCode: 0,
+ stdout: payload(text, 'PostToolUse', harness),
+ emission: {
+ kind: 'fresh',
+ file: firstGroup.filePath,
+ findings: firstGroup.findings,
+ groups: freshGroups,
+ },
+ audit: {
+ ...audit,
+ file: firstGroup.filePath,
+ emitted: true,
+ freshFiles: freshGroups.length,
+ freshFindings: allFindings.length,
+ chars: text.length,
+ durationMs: Date.now() - started,
+ },
+ };
+ }
+
+ if (detectorThrewAny && !pendingWinner && !cleanWinner) {
+ return result({ emitted: false, error: 'detector-threw', durationMs: Date.now() - started });
+ }
+
+ if (truthy(env.IMPECCABLE_HOOK_QUIET)) {
+ return result({ emitted: false, quiet: true, durationMs: Date.now() - started });
+ }
+
+ if (pendingWinner && shouldEmitAckForFile(pendingWinner.filePath)) {
+ const text = renderPendingAck(pendingWinner.filePath, pendingWinner.known, { cwd: projectCwd });
+ return {
+ exitCode: 0,
+ stdout: payload(text, 'PostToolUse', harness),
+ emission: { kind: 'pending', file: pendingWinner.filePath, known: pendingWinner.known },
+ audit: {
+ ...audit,
+ file: pendingWinner.filePath,
+ emitted: true,
+ kind: 'pending',
+ pending: pendingWinner.known.length,
+ chars: text.length,
+ durationMs: Date.now() - started,
+ },
+ };
+ }
+
+ if (suppressionWinner) {
+ const text = suppressionNotice(relativize(suppressionWinner.filePath, projectCwd));
+ return {
+ exitCode: 0,
+ stdout: payload(text, 'PostToolUse', harness),
+ emission: { kind: 'suppression', file: suppressionWinner.filePath },
+ audit: {
+ ...audit,
+ file: suppressionWinner.filePath,
+ suppressed: true,
+ emitted: true,
+ durationMs: Date.now() - started,
+ },
+ };
+ }
+
+ if (cleanWinner && shouldEmitAckForFile(cleanWinner.filePath)) {
+ const text = renderCleanAck(cleanWinner.filePath, { cwd: projectCwd });
+ return {
+ exitCode: 0,
+ stdout: payload(text, 'PostToolUse', harness),
+ emission: { kind: 'clean', file: cleanWinner.filePath },
+ audit: {
+ ...audit,
+ file: cleanWinner.filePath,
+ emitted: true,
+ kind: 'clean',
+ chars: text.length,
+ durationMs: Date.now() - started,
+ },
+ };
+ }
+
+ if (pendingWinner || cleanWinner) {
+ return result({ emitted: false, skipped: 'non-ui-ack', durationMs: Date.now() - started });
+ }
+
+ if (suppressedHit) {
+ return result({ suppressed: true, emitted: false, durationMs: Date.now() - started });
+ }
+
+ return result({ skipped: lastSkip, durationMs: Date.now() - started });
+ } catch (err) {
+ return {
+ exitCode: 0,
+ stdout: '',
+ audit: { ...audit, error: String(err && err.message ? err.message : err) },
+ };
+ }
+}
+
+export function payload(text, eventName = 'PostToolUse', harness = 'claude') {
+ if (harness === 'cursor') {
+ return JSON.stringify({ additional_context: text });
+ }
+ return JSON.stringify({
+ hookSpecificOutput: { hookEventName: eventName, additionalContext: text },
+ });
+}
diff --git a/.trae/skills/impeccable/scripts/hook.mjs b/.trae/skills/impeccable/scripts/hook.mjs
new file mode 100644
index 000000000..b862f8033
--- /dev/null
+++ b/.trae/skills/impeccable/scripts/hook.mjs
@@ -0,0 +1,61 @@
+#!/usr/bin/env node
+/**
+ * Impeccable design hook — PostToolUse entry point.
+ *
+ * Reads the Claude Code / Codex / Cursor hook event from stdin, runs the design
+ * detector against the touched file, and emits a system reminder via
+ * `hookSpecificOutput.additionalContext` when findings exist.
+ *
+ * Contract: never break a turn. Always exit 0. Clean files emit a small ack
+ * unless quiet mode is enabled.
+ *
+ * Most logic lives in `hook-lib.mjs` so it is unit-testable without a
+ * subprocess. This file is the thin stdin/stdout adapter.
+ */
+
+import { runHook, 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');
+}
+
+async function main() {
+ // Snapshot the inherited env FIRST so the re-entrancy guard checks the
+ // parent's value, not the value we are about to export for any child
+ // processes the hook might ever spawn.
+ const inheritedEnv = { ...process.env };
+ process.env.IMPECCABLE_HOOK_DEPTH = process.env.IMPECCABLE_HOOK_DEPTH || '1';
+
+ let stdinJson = '';
+ try { stdinJson = await readStdin(); } catch { /* fall through */ }
+
+ const result = await runHook({
+ stdinJson,
+ env: inheritedEnv,
+ cwd: process.cwd(),
+ });
+
+ writeAuditLog(process.env, result.audit);
+
+ if (result.stdout) process.stdout.write(result.stdout);
+ process.exit(result.exitCode || 0);
+}
+
+main().catch((err) => {
+ // Last-ditch: never break the agent's turn even if something we did not
+ // anticipate goes wrong. Audit-log the failure if logging is enabled.
+ try {
+ writeAuditLog(process.env, {
+ ts: new Date().toISOString(),
+ event: 'PostToolUse',
+ error: String(err && err.message ? err.message : err),
+ });
+ } catch { /* swallow */ }
+ if (process.env.IMPECCABLE_HOOK_DEBUG) {
+ process.stderr.write(`[impeccable-hook] ${err}\n`);
+ }
+ process.exit(0);
+});
diff --git a/.trae/skills/impeccable/scripts/live-inject.mjs b/.trae/skills/impeccable/scripts/live-inject.mjs
index 4e5c5dc0a..69ce530c1 100644
--- a/.trae/skills/impeccable/scripts/live-inject.mjs
+++ b/.trae/skills/impeccable/scripts/live-inject.mjs
@@ -32,6 +32,8 @@ const IGNORE_MARKER_CLOSE = '# impeccable-live-ignore-end';
export const LIVE_IGNORE_PATTERNS = Object.freeze([
'.impeccable/hook.cache.json',
+ '.impeccable/hook.pending.json',
+ '.impeccable/hook.local.json',
'.impeccable/live/server.json',
'.impeccable/live/sessions/',
'.impeccable/live/previews/',
diff --git a/README.md b/README.md
index 2a3514481..cdc42181b 100644
--- a/README.md
+++ b/README.md
@@ -103,9 +103,15 @@ From the root of your project, run:
npx impeccable skills install
```
-This auto-detects your harness and writes the build compiled for it to the right location (`.claude/skills/`, `.cursor/skills/`, etc.). Works with Cursor, Claude Code, Gemini CLI, Codex CLI, and every other supported tool. Reload your harness afterward.
+This auto-detects your harness and writes the build compiled for it to the right location (`.claude/skills/`, `.cursor/skills/`, etc.). On Claude Code, Cursor, and Codex, it also installs the provider-native hook manifest. Works with Cursor, Claude Code, Gemini CLI, Codex CLI, and every other supported tool. Reload your harness afterward.
-Claude Code users can alternatively install the plugin with `/plugin marketplace add pbakaus/impeccable`. The general-purpose `npx skills add pbakaus/impeccable` also works, though it installs one shared build for all harnesses rather than the one compiled for yours.
+To refresh an existing install, run:
+
+```bash
+npx impeccable skills update
+```
+
+Codex users should open `/hooks` after install or update and approve the project hook when prompted. Codex tracks trust by hook definition, so updates that change `.codex/hooks.json` can require approval again.
### Option 2: Git Submodule
@@ -179,13 +185,16 @@ cp -r dist/gemini/.gemini your-project/
```bash
# Project-local
cp -r dist/agents/.agents your-project/
+mkdir -p your-project/.codex
+cp dist/codex/.codex/hooks.json your-project/.codex/hooks.json
-# Or user-wide
+# Or install the skill user-wide. Copy .codex/hooks.json into each project
+# where you want the design hook to run.
mkdir -p ~/.agents/skills
cp -r dist/agents/.agents/skills/* ~/.agents/skills/
```
-> The asset-producer subagent ships nested inside the skill's own `agents/` folder, which Codex auto-discovers. No separate `.codex/agents/` copy is needed.
+> The asset-producer subagent ships nested inside the skill's own `agents/` folder, which Codex auto-discovers. No separate `.codex/agents/` copy is needed. The hook is project-local because Codex discovers hooks from `.codex/hooks.json` next to trusted project config.
**GitHub Copilot:**
```bash
@@ -249,6 +258,31 @@ If you reach for one command often, pin it with `/impeccable pin audit` to get `
**Note:** Codex uses skills here, not `/prompts:` commands. Open `/skills` or type `$impeccable`. Repo-local installs live in `.agents/skills/`; user-wide installs live in `~/.agents/skills/`. GitHub Copilot uses `.github/skills/`. Restart the tool if a newly installed skill does not appear.
+## Design hook
+
+On Claude Code, Codex, and Cursor, `npx impeccable skills install` and `npx impeccable skills update` install a provider-native hook manifest along with the skill payload. The hook runs the Impeccable design detector on direct UI file edits and surfaces findings back into the agent flow. Claude Code and Codex surface findings after the edit. Cursor blocks bad proposed writes before they land.
+
+Installed hook surfaces:
+
+- Claude Code: `.claude/settings.json` runs `${CLAUDE_PROJECT_DIR}/.claude/skills/impeccable/scripts/hook.mjs`.
+- Cursor: `.cursor/hooks.json` runs `.cursor/skills/impeccable/scripts/hook-before-edit.mjs`.
+- Codex: `.codex/hooks.json` runs `.agents/skills/impeccable/scripts/hook.mjs`.
+
+The installer preserves unrelated hook entries and settings. If a hook manifest is malformed, install/update aborts by default; rerun with `--force` to back up the malformed file as `.bak` and replace it.
+
+If you want skills without hook manifests, pass `--no-hooks` to `npx impeccable skills install` or `npx impeccable skills update`.
+
+For debugging, set `IMPECCABLE_HOOK_LOG=/path/to/hook.ndjson` to write one NDJSON line per hook invocation. Leave it unset for normal use.
+
+Codex requires one platform step that Impeccable cannot safely skip: open `/hooks` after install or update and approve the project hook. There is no Codex marketplace/plugin install flow for this hook.
+
+Manual copy commands are fallback/debug instructions. The normal path is:
+
+```bash
+npx impeccable skills install
+npx impeccable skills update
+```
+
## CLI
Impeccable includes a standalone CLI for detecting anti-patterns without an AI harness:
diff --git a/README.npm.md b/README.npm.md
index 2e68ceafc..b20924408 100644
--- a/README.npm.md
+++ b/README.npm.md
@@ -14,6 +14,9 @@ npx impeccable skills install
# Update skills to the latest version
npx impeccable skills update
+# Install or update skills without hook manifests
+npx impeccable skills install --no-hooks
+
# Link skills from a Git submodule checkout
npx impeccable skills link --source=.impeccable --providers=claude,cursor
diff --git a/cli/bin/commands/skills.mjs b/cli/bin/commands/skills.mjs
index 46dfacd7d..ce295fea9 100644
--- a/cli/bin/commands/skills.mjs
+++ b/cli/bin/commands/skills.mjs
@@ -59,6 +59,26 @@ const GLOBAL_HARNESS_HINTS = [
// Last-resort default when nothing is detected: Claude Code + the universal
// (.agents, also Codex) folder, which covers the most common setups.
const DEFAULT_TARGETS = ['.claude', '.agents'];
+const IMPECCABLE_HOOK_COMMAND_MARKERS = [
+ 'skills/impeccable/scripts/hook-probe.mjs',
+ 'skills/impeccable/scripts/hook.mjs',
+ 'skills/impeccable/scripts/hook-before-edit.mjs',
+ 'skills/impeccable/scripts/hook-after-edit.mjs',
+ 'skills/impeccable/scripts/hook-stop.mjs',
+];
+const PROVIDER_HOOK_ARTIFACTS = {
+ '.claude': [
+ { sourceProvider: '.claude', rel: 'settings.json', destProvider: '.claude' },
+ ],
+ '.cursor': [
+ { sourceProvider: '.cursor', rel: 'hooks.json', destProvider: '.cursor' },
+ ],
+ // Codex reads skills from `.agents/skills`, but project hooks from
+ // `.codex/hooks.json`, so the `.agents` install target owns this sidecar.
+ '.agents': [
+ { sourceProvider: '.codex', rel: 'hooks.json', destProvider: '.codex' },
+ ],
+};
function ask(question) {
const rl = createInterface({ input: process.stdin, output: process.stdout });
@@ -392,26 +412,140 @@ function copyProviderSkills(bundleDir, root, targets) {
let written = 0;
for (const provider of targets) {
const srcDir = join(bundleDir, provider, 'skills');
- if (!existsSync(srcDir)) continue;
- const localSkillsDir = join(root, provider, 'skills');
- // A previous `npx skills` install may have left this provider's skills dir
- // as a symlink to another provider's canonical copy. Drop the link so we
- // write a real, provider-specific directory instead of writing through it.
- try {
- if (lstatSync(localSkillsDir).isSymbolicLink()) unlinkSync(localSkillsDir);
- } catch {}
- for (const skill of readdirSync(srcDir, { withFileTypes: true })) {
- if (!skill.isDirectory()) continue;
- const src = join(srcDir, skill.name);
- const dest = join(localSkillsDir, skill.name);
- rmSync(dest, { recursive: true, force: true });
- copyDirSync(src, dest);
- written++;
+ if (existsSync(srcDir)) {
+ const localSkillsDir = join(root, provider, 'skills');
+ // A previous `npx skills` install may have left this provider's skills dir
+ // as a symlink to another provider's canonical copy. Drop the link so we
+ // write a real, provider-specific directory instead of writing through it.
+ try {
+ if (lstatSync(localSkillsDir).isSymbolicLink()) unlinkSync(localSkillsDir);
+ } catch {}
+ for (const skill of readdirSync(srcDir, { withFileTypes: true })) {
+ if (!skill.isDirectory()) continue;
+ const src = join(srcDir, skill.name);
+ const dest = join(localSkillsDir, skill.name);
+ rmSync(dest, { recursive: true, force: true });
+ copyDirSync(src, dest);
+ written++;
+ }
}
}
return written;
}
+function hookArtifactsForProvider(bundleDir, root, provider) {
+ return (PROVIDER_HOOK_ARTIFACTS[provider] || []).map(({ sourceProvider, rel, destProvider }) => ({
+ src: join(bundleDir, sourceProvider, rel),
+ dest: join(root, destProvider, rel),
+ }));
+}
+
+function expectedHookDests(root, providers) {
+ const targets = Array.isArray(providers) ? providers : [providers];
+ return targets.flatMap(provider =>
+ (PROVIDER_HOOK_ARTIFACTS[provider] || []).map(({ rel, destProvider }) => join(root, destProvider, rel))
+ );
+}
+
+function valueHasImpeccableHookMarker(value) {
+ if (typeof value === 'string') {
+ return IMPECCABLE_HOOK_COMMAND_MARKERS.some(marker => value.includes(marker));
+ }
+ if (Array.isArray(value)) return value.some(valueHasImpeccableHookMarker);
+ if (value && typeof value === 'object') {
+ return Object.values(value).some(valueHasImpeccableHookMarker);
+ }
+ return false;
+}
+
+function stripImpeccableHookEntry(entry) {
+ if (!entry || typeof entry !== 'object') return entry;
+ if (valueHasImpeccableHookMarker(entry.command) || valueHasImpeccableHookMarker(entry.args)) {
+ return null;
+ }
+ if (!Array.isArray(entry.hooks)) return entry;
+
+ const strippedHooks = entry.hooks
+ .map(stripImpeccableHookEntry)
+ .filter(Boolean);
+
+ if (strippedHooks.length === 0 && entry.hooks.some(valueHasImpeccableHookMarker)) {
+ return null;
+ }
+
+ return { ...entry, hooks: strippedHooks };
+}
+
+function stripImpeccableHookEntries(entries) {
+ if (!Array.isArray(entries)) return [];
+ return entries
+ .map(stripImpeccableHookEntry)
+ .filter(Boolean);
+}
+
+function mergeHookManifests(existing, fresh) {
+ const existingObject = existing && typeof existing === 'object' && !Array.isArray(existing) ? existing : {};
+ const freshObject = fresh && typeof fresh === 'object' && !Array.isArray(fresh) ? fresh : {};
+ const existingHooks = existingObject.hooks && typeof existingObject.hooks === 'object' && !Array.isArray(existingObject.hooks)
+ ? existingObject.hooks
+ : {};
+ const freshHooks = freshObject.hooks && typeof freshObject.hooks === 'object' && !Array.isArray(freshObject.hooks)
+ ? freshObject.hooks
+ : {};
+
+ const merged = { ...existingObject, hooks: {} };
+ if (freshObject.version !== undefined) merged.version = freshObject.version;
+ if (freshObject.description !== undefined) merged.description = freshObject.description;
+
+ const hookEvents = new Set([...Object.keys(existingHooks), ...Object.keys(freshHooks)]);
+ for (const event of hookEvents) {
+ const preserved = stripImpeccableHookEntries(existingHooks[event]);
+ const added = Array.isArray(freshHooks[event]) ? freshHooks[event] : [];
+ const mergedEntries = [...preserved, ...added];
+ if (mergedEntries.length > 0) merged.hooks[event] = mergedEntries;
+ }
+
+ return merged;
+}
+
+function readJsonFile(filePath, description) {
+ try {
+ return JSON.parse(readFileSync(filePath, 'utf-8'));
+ } catch (e) {
+ throw new Error(`${description} is not valid JSON: ${filePath}. ${e.message}`);
+ }
+}
+
+function copyProviderHooks(bundleDir, root, providers, { force = false } = {}) {
+ const targets = Array.isArray(providers) ? providers : [providers];
+ const written = [];
+ for (const provider of targets) {
+ for (const { src, dest } of hookArtifactsForProvider(bundleDir, root, provider)) {
+ if (!existsSync(src)) continue;
+ const fresh = readJsonFile(src, 'Bundled hook manifest');
+ let next = fresh;
+
+ if (existsSync(dest)) {
+ try {
+ const existing = JSON.parse(readFileSync(dest, 'utf-8'));
+ next = mergeHookManifests(existing, fresh);
+ } catch {
+ if (!force) {
+ throw new Error(`Existing hook manifest is not valid JSON: ${dest}. Re-run with --force to replace it.`);
+ }
+ writeFileSync(`${dest}.bak`, readFileSync(dest));
+ next = fresh;
+ }
+ }
+
+ mkdirSync(dirname(dest), { recursive: true });
+ writeFileSync(dest, `${JSON.stringify(next, null, 2)}\n`);
+ written.push(provider);
+ }
+ }
+ return [...new Set(written)];
+}
+
function resolveLinkSource(sourceValue, root) {
const sourcePath = sourceValue || '.impeccable';
const checkoutRoot = isAbsolute(sourcePath) ? sourcePath : resolve(root, sourcePath);
@@ -549,12 +683,30 @@ async function link(flags) {
async function install(flags) {
const force = flags.includes('--force');
const yes = flags.includes('-y') || flags.includes('--yes');
+ const installHooks = !flags.includes('--no-hooks');
const providersValue = getFlagValue(flags, '--providers');
const root = findProjectRoot();
const existing = isAlreadyInstalled(root);
if (existing && !force) {
console.log(`Impeccable skills are already installed (found in ${existing}/).`);
+ const targets = providersValue ? resolveInstallTargets(root, providersValue) : findInstalledProviders(root);
+ const missingHookDests = installHooks
+ ? expectedHookDests(root, targets).filter(dest => !existsSync(dest))
+ : [];
+ if (missingHookDests.length > 0) {
+ let bundleDir;
+ try {
+ bundleDir = await downloadAndExtractBundle();
+ const hookTargets = copyProviderHooks(bundleDir, root, targets);
+ if (hookTargets.length > 0) console.log(`Installed hooks into: ${hookTargets.join(', ')}`);
+ } catch (e) {
+ console.error(`Hook install failed: ${e.message}`);
+ process.exit(1);
+ } finally {
+ if (bundleDir) rmSync(bundleDir, { recursive: true, force: true });
+ }
+ }
console.log('Run with --force to reinstall.\n');
process.exit(0);
}
@@ -594,8 +746,10 @@ async function install(flags) {
migrateUnprefixImpeccable(root);
let written = 0;
+ let hookTargets = [];
try {
written = copyProviderSkills(bundleDir, root, targets);
+ hookTargets = installHooks ? copyProviderHooks(bundleDir, root, targets, { force }) : [];
} catch (e) {
rmSync(bundleDir, { recursive: true, force: true });
console.error(`Install failed: ${e.message}`);
@@ -608,6 +762,7 @@ async function install(flags) {
process.exit(1);
}
console.log(`Installed impeccable into: ${targets.join(', ')}`);
+ if (hookTargets.length > 0) console.log(`Installed hooks into: ${hookTargets.join(', ')}`);
console.log('\nDone! Run /impeccable init in your AI harness to set up design context.\n');
}
@@ -692,6 +847,8 @@ function downloadFile(url, dest) {
async function update(flags = []) {
const yes = flags.includes('-y') || flags.includes('--yes');
+ const force = flags.includes('--force');
+ const installHooks = !flags.includes('--no-hooks');
// Download the latest skills directly from impeccable.style.
// We skip `npx skills update` because it has a known upstream bug
@@ -726,10 +883,19 @@ async function update(flags = []) {
// Compare local vs remote -- skip if already up to date
if (isUpToDate(root, copyProviders, tmpDir)) {
- rmSync(tmpDir, { recursive: true, force: true });
- const v = getSkillsVersion(root);
- console.log(`Skills are up to date${v ? ` (v${v})` : ''}. Nothing to do.`);
- process.exit(0);
+ try {
+ const hookTargets = installHooks ? copyProviderHooks(tmpDir, root, copyProviders, { force }) : [];
+ rmSync(tmpDir, { recursive: true, force: true });
+ const v = getSkillsVersion(root);
+ console.log(`Skills are up to date${v ? ` (v${v})` : ''}.`);
+ if (hookTargets.length > 0) console.log(`Installed hooks into: ${hookTargets.join(', ')}`);
+ console.log('Nothing else to do.');
+ process.exit(0);
+ } catch (e) {
+ rmSync(tmpDir, { recursive: true, force: true });
+ console.error(`Update failed: ${e.message}`);
+ process.exit(1);
+ }
}
console.log(`Found skills in: ${copyProviders.join(', ')}`);
@@ -769,11 +935,13 @@ async function update(flags = []) {
updated++;
}
}
+ const hookTargets = installHooks ? copyProviderHooks(tmpDir, root, providers, { force }) : [];
rmSync(tmpDir, { recursive: true, force: true });
const v = getSkillsVersion(root);
console.log(`Updated ${updated} skill(s)${v ? ` to v${v}` : ''}.`);
+ if (hookTargets.length > 0) console.log(`Installed hooks into: ${hookTargets.join(', ')}`);
console.log('Done!\n');
} catch (e) {
console.error(`Update failed: ${e.message}`);
@@ -798,7 +966,16 @@ function copyDirSync(src, dest) {
// ─── Test surface ───────────────────────────────────────────────────────────
// Exported so the test suite exercises the real implementation rather than a
// reimplementation in a helper script (which is how bugs slip through).
-export { migrateUnprefixImpeccable, linkProviderSkills, resolveLinkSource };
+export {
+ copyProviderHooks,
+ copyProviderSkills,
+ expectedHookDests,
+ linkProviderSkills,
+ mergeHookManifests,
+ migrateUnprefixImpeccable,
+ resolveInstallTargets,
+ resolveLinkSource,
+};
// ─── Router ───────────────────────────────────────────────────────────────────
diff --git a/cli/engine/engines/regex/detect-text.mjs b/cli/engine/engines/regex/detect-text.mjs
index fd0d9c73f..4c0777c93 100644
--- a/cli/engine/engines/regex/detect-text.mjs
+++ b/cli/engine/engines/regex/detect-text.mjs
@@ -446,7 +446,7 @@ function detectText(content, filePath, options = {}) {
// Run regex matchers on the full file content (catches Tailwind classes, inline styles)
// Enable block context for CSS files where related properties span multiple lines
- const cssLike = new Set(['.css', '.scss', '.less']);
+ const cssLike = new Set(['.css', '.scss', '.sass', '.less']);
findings.push(...runRegexMatchers(lines, filePath, 0, cssLike.has(ext) || null, {
profile,
phase: 'source',
diff --git a/cli/engine/node/file-system.mjs b/cli/engine/node/file-system.mjs
index a80250a0e..aaa8c6df7 100644
--- a/cli/engine/node/file-system.mjs
+++ b/cli/engine/node/file-system.mjs
@@ -11,7 +11,7 @@ const SKIP_DIRS = new Set([
]);
const SCANNABLE_EXTENSIONS = new Set([
- '.html', '.htm', '.css', '.scss', '.less',
+ '.html', '.htm', '.css', '.scss', '.sass', '.less',
'.jsx', '.tsx', '.js', '.ts',
'.vue', '.svelte', '.astro',
]);
diff --git a/docs/HARNESSES.md b/docs/HARNESSES.md
index d84475639..f7e43c0cb 100644
--- a/docs/HARNESSES.md
+++ b/docs/HARNESSES.md
@@ -46,14 +46,24 @@ Fields marked with * are spec-standard. Others are provider extensions.
| `effort` | Yes | No | No | No | No | No | No | No | No | No |
| `context` | Yes | No | No | No | No | No | No | No | No | No |
| `agent` | Yes | No | No | No | No | No | Yes | No | No | No |
-| `hooks` | Yes | No | No | No | No | No | No | No | No | No |
+| `hooks` | Yes | No | No | Yes | No | No | No | No | No | No |
Notes:
- Gemini CLI validates only `name` and `description`; other spec fields are parsed but ignored.
- Codex CLI uses a separate `agents/openai.yaml` sidecar for skill metadata (icons, branding, MCP tools, invocation control). Codex also auto-discovers subagents bundled inside an installed skill's `agents/` folder (TOML), which is how Impeccable ships its asset-producer. Standalone custom agents can still live under `.codex/agents/` or `~/.codex/agents/`, but Impeccable no longer installs anything there.
+- Codex CLI hooks ship under `[features].hooks = true` (still flagged), require `/hooks` trust ceremony per-update, and are disabled on Windows.
- Kiro recognizes `user-invocable` and `disable-model-invocation` per community reports but does not formally document them.
- Unknown fields are silently ignored by all harnesses.
+## Hook surface used by Impeccable
+
+| Harness | Edit hook | Startup hook | Manifest location | Notes |
+|---------|:---------:|:------------:|-------------------|-------|
+| Claude Code | Yes (`PostToolUse`) | No | `.claude/settings.json` | Project-local settings entry installed by `npx impeccable skills install/update`. Runs `.claude/skills/impeccable/scripts/hook.mjs`. |
+| Codex CLI | Yes (`PostToolUse`) | No | `.codex/hooks.json` | Project-local manifest installed with the `.agents/skills/impeccable` payload. Runs `.agents/skills/impeccable/scripts/hook.mjs` from the git root. Requires normal `/hooks` trust approval. |
+| Cursor | Yes (`preToolUse`) | No | `.cursor/hooks.json` | Project-level manifest installed with `.cursor/skills/impeccable`. Runs `hook-before-edit.mjs` to block bad proposed writes before they land. Reloads on save; restart Cursor if hooks do not pick up. |
+| All other harnesses | No | No | n/a | No documented hook surface today. Skill and commands still ship. |
+
## Skill Directory Structure
| Harness | Native directory | Also reads |
diff --git a/package.json b/package.json
index 851eca3bf..4484adc2f 100644
--- a/package.json
+++ b/package.json
@@ -65,6 +65,7 @@
"test:live-e2e-agent": "node scripts/run-tests.mjs live-e2e-agent",
"test:skill-behavior": "node scripts/run-tests.mjs skill-behavior",
"test:live-svelte-adapter-deepseek": "node scripts/run-tests.mjs live-svelte-adapter-deepseek",
+ "smoke:hooks": "node scripts/smoke-provider-hooks.mjs",
"bench:detector": "node scripts/benchmark-detector.mjs",
"bench:detector:browser": "node scripts/benchmark-detector.mjs --browser",
"audit": "bun audit --audit-level=moderate",
diff --git a/plugin/skills/impeccable/SKILL.md b/plugin/skills/impeccable/SKILL.md
index 341179949..73a27c46e 100644
--- a/plugin/skills/impeccable/SKILL.md
+++ b/plugin/skills/impeccable/SKILL.md
@@ -126,7 +126,7 @@ If someone could look at this interface and say "AI made that" without doubt, it
| `optimize [target]` | Fix | Diagnose and fix UI performance | [reference/optimize.md](reference/optimize.md) |
| `live` | Iterate | Visual variant mode: pick elements in the browser, generate alternatives | [reference/live.md](reference/live.md) |
-Plus two management commands: `pin <command>` and `unpin <command>`, detailed below.
+Plus three management commands: `pin <command>`, `unpin <command>`, and `hooks <on|off|status|...>`, detailed below.
### Routing rules
@@ -143,7 +143,7 @@ Plus two management commands: `pin <command>` and `unpin <command>`, detailed be
**If `scan.targets` is non-empty, run `node .claude/skills/impeccable/scripts/detect.mjs --json <scan.targets joined by spaces>` once** (the bundled detector over local files: no network, no npx). `scan.via` tells you what they are: `git-changes` (the markup/style files in your dirty tree, the most relevant set), `source-dir` (e.g. `src`, `app`), `html`, or `root`. Fold the hits into your picks: many quality / contrast hits → `audit` or `polish`; a specific slop family → the matching command (gradient text or eyebrows → `quieter` / `typeset`, flat or gray palette → `colorize`, and so on). It's a real, current signal that beats guessing. If detect errors or the tree is large and slow, skip it and recommend the user run `audit` themselves; never block the suggestion on it.
Keep it to 2-3 pointed picks with the exact command to type. The menu stays the fallback; the recommendation is the lede.
-2. **First word matches a command**: load its reference file and follow its instructions. Everything after the command name is the target.
+2. **First word matches a command** (table above OR `pin` / `unpin` / `hooks`): load its reference file and follow its instructions. Everything after the command name is the target.
3. **First word doesn't match, but the intent clearly maps to one command** (e.g. "fix the spacing" → `layout`, "rewrite this error message" → `clarify`, "the colors feel flat" → `colorize`): load that command's reference and proceed as if invoked. If two commands could fit, ask once which.
4. **No clear command match**: general design invocation. Apply the setup steps, the General rules, and the loaded register reference, using the full argument as context.
@@ -161,4 +161,8 @@ If the first word is `craft`, setup still runs first, but [reference/craft.md](r
node .claude/skills/impeccable/scripts/pin.mjs <pin|unpin> <command>
```
-Valid `<command>` is any command from the table above. Report the script's result concisely. Confirm the new shortcut on success, relay stderr verbatim on error.
\ No newline at end of file
+Valid `<command>` is any command from the table above. Report the script's result concisely. Confirm the new shortcut on success, relay stderr verbatim on error.
+
+## Hooks
+
+`/impeccable hooks <on|off|status|ignore-rule|ignore-file|ignore-value|reset>` manages the design detector hook for this project. The hook auto-runs the detector after direct UI file edits and surfaces findings as system reminders. Full flow is in [reference/hooks.md](reference/hooks.md); load it when the user invokes `/impeccable hooks` with any argument.
\ No newline at end of file
diff --git a/plugin/skills/impeccable/reference/hooks.md b/plugin/skills/impeccable/reference/hooks.md
new file mode 100644
index 000000000..caadaa603
--- /dev/null
+++ b/plugin/skills/impeccable/reference/hooks.md
@@ -0,0 +1,82 @@
+# /impeccable hooks
+
+Manage the **design detector hook** for the current project.
+
+The hook runs the impeccable design detector on direct file edits to design-relevant files (`.tsx`, `.jsx`, `.html`, `.vue`, `.svelte`, `.astro`, `.css`, `.scss`, `.sass`, `.less`, `.ts`, `.js`). Claude Code and Codex use `PostToolUse` and push a short system reminder into the agent's context after the edit; findings get a correction prompt, pending issues get a re-nudge, and clean UI-ish files get a short ack unless `IMPECCABLE_HOOK_QUIET=1` is set. Plain `.ts` and `.js` files are still scanned, but stay quiet unless the detector finds something. Cursor uses `preToolUse` to block bad proposed writes before they land and stays silent when it allows a clean write.
+
+This command toggles the hook **per project** by editing `.impeccable/hook.json`. Local-only ignore policy lives in `.impeccable/hook.local.json`, which is gitignored. To disable globally, set `IMPECCABLE_HOOK_DISABLED=1` in your shell environment.
+
+Supported harnesses: Claude Code (`.claude/settings.json` in the project), Codex (`.codex/hooks.json` in the project), and Cursor (`.cursor/hooks.json` in the project).
+
+On **Cursor**, `preToolUse` checks proposed Write/Edit/Shell write content and denies only when the real detector finds an issue. The denial message is visible to the agent as the tool error, so the agent can reconsider before the bad write lands.
+
+## Routing
+
+The first argument is the action. Defaults to `status`.
+
+| Action | What it does |
+|---|---|
+| `status` | Print current state, shared/local config paths, ignored rules / files / values, env override. |
+| `on` | Set `enabled: true` in `.impeccable/hook.json`. |
+| `off` | Set `enabled: false` in `.impeccable/hook.json`. |
+| `ignore-rule <id>` | Append `<id>` to `ignoreRules`; for `overused-font`, requires `--all-values`. |
+| `ignore-file <glob>` | Append `<glob>` to `ignoreFiles`. |
+| `ignore-value <id> <value> [--shared] [--reason "..."]` | Append a rule/value suppression to shared `.impeccable/hook.json`. |
+| `ignore-value <id> <value> --local [--reason "..."]` | Append a private rule/value suppression to `.impeccable/hook.local.json`. |
+| `reset` | Delete the project config, dedup cache, and Cursor pending queue. |
+
+## Flow
+
+1. Resolve the action from the user's argument. If no action was given, default to `status`.
+2. Invoke the admin script and pass the user's output through verbatim:
+
+ ```bash
+ node .claude/skills/impeccable/scripts/hook-admin.mjs <action> [args...]
+ ```
+
+3. If `<action>` is `off`, follow up with a one-line note: "Done. New edits will not trigger the design hook in this project until you run `/impeccable hooks on`."
+4. If `<action>` is `on`, follow up with: "Done. The design hook will fire after the next Edit/Write/MultiEdit on a UI file."
+5. If `<action>` is `ignore-value`, `ignore-file`, or `ignore-rule`, just print the script output. The default scope is shared `.impeccable/hook.json`; add `--local` only when the user explicitly asks for a private exception.
+6. If `<action>` is `status`, just print the script output. Do not add commentary unless the user asked a follow-up question.
+
+## Intentional findings
+
+The hook itself never writes ignore config. Persist an exception only after the user explicitly confirms the flagged issue is intentional, and always go through `hook-admin.mjs`.
+
+Prefer the narrowest exception:
+
+- If the finding line shows an exact `ignore-value` command, run that command. This writes shared `.impeccable/hook.json` by default.
+- For `overused-font`, use `ignore-value` when the user confirms a specific font. Do not use `ignore-rule overused-font` for a specific font.
+- If the finding has no value-specific command, such as `side-tab`, prefer `ignore-file <path>` for the current file.
+- Use `ignore-rule <id>` only when the user asks to suppress that whole rule across the project. For broad overused-font suppression, use `ignore-rule overused-font --all-values` only when the user asks to ignore overused fonts generally.
+- Do not add source comments such as `impeccable: ignore`; inline comments pollute code and are not a supported suppression mechanism.
+
+Example value-specific exception:
+
+```bash
+node .claude/skills/impeccable/scripts/hook-admin.mjs ignore-value overused-font Inter --shared --reason "User confirmed Inter is intentional"
+```
+
+Example whole-rule font exception:
+
+```bash
+node .claude/skills/impeccable/scripts/hook-admin.mjs ignore-rule overused-font --all-values --reason "User asked to ignore overused fonts generally"
+```
+
+Example file-scoped exception:
+
+```bash
+node .claude/skills/impeccable/scripts/hook-admin.mjs ignore-file "src/legacy/Card.tsx"
+```
+
+## Constraints
+
+- Never modify `.impeccable/hook.json` or `.impeccable/hook.local.json` by hand from this command. Always go through `hook-admin.mjs` so writes stay validated and the file shape stays consistent.
+- Do not edit the hook scripts themselves (`hook.mjs`, `hook-lib.mjs`, `hook-before-edit.mjs`) from this flow. Those are skill plumbing.
+- Cursor can block a proposed write when the detector finds a real issue. Claude Code and Codex do not block the edit; they emit a post-edit reminder instead. Disabling stops both blocking and reminders.
+- The hook is bundled with the Impeccable skill and installed through project-local manifests: `.claude/settings.json`, `.codex/hooks.json`, and `.cursor/hooks.json`. On Codex, the user must approve the hook via `/hooks` the first time. On Cursor, confirm hooks are enabled under Settings -> Hooks.
+
+## Failure modes
+
+- If `.impeccable/hook.json` or `.impeccable/hook.local.json` is unreadable or malformed, the hook ignores that file and uses the remaining valid config/defaults. `hook-admin.mjs status` will show malformed files as ignored.
+- If the user asks to "disable the hook" globally, suggest both options: `IMPECCABLE_HOOK_DISABLED=1` env var (one-shot, follows the shell), and `/impeccable hooks off` (persistent for this project, committable).
diff --git a/plugin/skills/impeccable/scripts/detector/engines/regex/detect-text.mjs b/plugin/skills/impeccable/scripts/detector/engines/regex/detect-text.mjs
index fd0d9c73f..4c0777c93 100644
--- a/plugin/skills/impeccable/scripts/detector/engines/regex/detect-text.mjs
+++ b/plugin/skills/impeccable/scripts/detector/engines/regex/detect-text.mjs
@@ -446,7 +446,7 @@ function detectText(content, filePath, options = {}) {
// Run regex matchers on the full file content (catches Tailwind classes, inline styles)
// Enable block context for CSS files where related properties span multiple lines
- const cssLike = new Set(['.css', '.scss', '.less']);
+ const cssLike = new Set(['.css', '.scss', '.sass', '.less']);
findings.push(...runRegexMatchers(lines, filePath, 0, cssLike.has(ext) || null, {
profile,
phase: 'source',
diff --git a/plugin/skills/impeccable/scripts/detector/node/file-system.mjs b/plugin/skills/impeccable/scripts/detector/node/file-system.mjs
index a80250a0e..aaa8c6df7 100644
--- a/plugin/skills/impeccable/scripts/detector/node/file-system.mjs
+++ b/plugin/skills/impeccable/scripts/detector/node/file-system.mjs
@@ -11,7 +11,7 @@ const SKIP_DIRS = new Set([
]);
const SCANNABLE_EXTENSIONS = new Set([
- '.html', '.htm', '.css', '.scss', '.less',
+ '.html', '.htm', '.css', '.scss', '.sass', '.less',
'.jsx', '.tsx', '.js', '.ts',
'.vue', '.svelte', '.astro',
]);
diff --git a/plugin/skills/impeccable/scripts/hook-admin.mjs b/plugin/skills/impeccable/scripts/hook-admin.mjs
new file mode 100644
index 000000000..86fcfa909
--- /dev/null
+++ b/plugin/skills/impeccable/scripts/hook-admin.mjs
@@ -0,0 +1,300 @@
+#!/usr/bin/env node
+/**
+ * `/impeccable hooks <on|off|status|reset>` — manage the design hook
+ * via .impeccable/hook.json and .impeccable/hook.local.json in the current
+ * project.
+ *
+ * Usage:
+ * node hook-admin.mjs status # print current state
+ * node hook-admin.mjs on # set enabled: true
+ * node hook-admin.mjs off # set enabled: false
+ * node hook-admin.mjs ignore-rule <rule-id> # append to ignoreRules
+ * node hook-admin.mjs ignore-rule overused-font --all-values
+ * node hook-admin.mjs ignore-file <glob> # append to ignoreFiles
+ * node hook-admin.mjs ignore-value <rule> <value> # append to shared ignoreValues
+ * node hook-admin.mjs ignore-value <rule> <value> --local
+ * node hook-admin.mjs reset # remove all config + cache
+ *
+ * Designed to be invoked by the LLM from the reference/hooks.md flow.
+ * Output is human-readable; the harness will pass it back to the user.
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+
+import {
+ getConfigPath,
+ getLocalConfigPath,
+ getCachePath,
+ getPendingPath,
+ readConfig,
+ DEFAULT_CONFIG,
+ ensureHookGitExcludes,
+ normalizeIgnoreValue,
+ normalizeIgnoreValueEntries,
+} from './hook-lib.mjs';
+
+const ACTIONS = new Set(['status', 'on', 'off', 'ignore-rule', 'ignore-file', 'ignore-value', 'reset']);
+
+function readRawConfigFile(filePath) {
+ if (!fs.existsSync(filePath)) return { exists: false, malformed: false, raw: null };
+ try {
+ return { exists: true, malformed: false, raw: JSON.parse(fs.readFileSync(filePath, 'utf-8')) };
+ } catch {
+ return { exists: true, malformed: true, raw: null };
+ }
+}
+
+function readRawConfig(cwd, opts = {}) {
+ const filePath = opts.local ? getLocalConfigPath(cwd) : getConfigPath(cwd);
+ return readRawConfigFile(filePath).raw;
+}
+
+function writeConfig(cwd, config, opts = {}) {
+ const filePath = opts.local ? getLocalConfigPath(cwd) : getConfigPath(cwd);
+ if (opts.local) ensureHookGitExcludes(cwd);
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
+ fs.writeFileSync(filePath, JSON.stringify(config, null, 2) + '\n');
+ return filePath;
+}
+
+function mergeConfig(existing) {
+ // Persist the full shape so /impeccable hooks edits leave a complete file
+ // for the user to see, not an unhelpful `{"enabled":false}`.
+ const base = existing && typeof existing === 'object' ? existing : {};
+ return {
+ enabled: base.enabled === false ? false : true,
+ ignoreRules: Array.isArray(base.ignoreRules) ? Array.from(new Set(base.ignoreRules.map(String))) : [],
+ ignoreFiles: Array.isArray(base.ignoreFiles) ? Array.from(new Set(base.ignoreFiles.map(String))) : [],
+ ignoreValues: normalizeIgnoreValueEntries(base.ignoreValues || []),
+ limits: {
+ maxFindings: Number.isFinite(base?.limits?.maxFindings) ? base.limits.maxFindings : DEFAULT_CONFIG.limits.maxFindings,
+ maxChars: Number.isFinite(base?.limits?.maxChars) ? base.limits.maxChars : DEFAULT_CONFIG.limits.maxChars,
+ },
+ };
+}
+
+function mergeLocalConfig(existing) {
+ const base = existing && typeof existing === 'object' ? existing : {};
+ const out = {};
+ if (Object.prototype.hasOwnProperty.call(base, 'enabled')) {
+ out.enabled = base.enabled === false ? false : true;
+ }
+ if (Array.isArray(base.ignoreRules)) {
+ out.ignoreRules = Array.from(new Set(base.ignoreRules.map(String)));
+ }
+ if (Array.isArray(base.ignoreFiles)) {
+ out.ignoreFiles = Array.from(new Set(base.ignoreFiles.map(String)));
+ }
+ out.ignoreValues = normalizeIgnoreValueEntries(base.ignoreValues || []);
+ if (base.limits && typeof base.limits === 'object') {
+ const limits = {};
+ if (Number.isFinite(base.limits.maxFindings)) limits.maxFindings = base.limits.maxFindings;
+ if (Number.isFinite(base.limits.maxChars)) limits.maxChars = base.limits.maxChars;
+ if (Object.keys(limits).length) out.limits = limits;
+ }
+ return out;
+}
+
+function statusReport(cwd) {
+ const shared = readRawConfigFile(getConfigPath(cwd));
+ const local = readRawConfigFile(getLocalConfigPath(cwd));
+ const cfg = readConfig(cwd);
+ const envKill = process.env.IMPECCABLE_HOOK_DISABLED;
+ const envState = envKill ? `IMPECCABLE_HOOK_DISABLED=${envKill}` : 'unset';
+ const cfgPath = path.relative(cwd, getConfigPath(cwd)) || '.impeccable/hook.json';
+ const localPath = path.relative(cwd, getLocalConfigPath(cwd)) || '.impeccable/hook.local.json';
+ const cachePath = path.relative(cwd, getCachePath(cwd)) || '.impeccable/hook.cache.json';
+ const fileState = (info, relPath, absent) => {
+ if (info.malformed) return `${relPath} (malformed; ignored)`;
+ if (info.exists) return relPath;
+ return `${relPath} (${absent})`;
+ };
+ const ignoreValues = cfg.ignoreValues.map((entry) => `${entry.rule}=${entry.value}`);
+
+ const lines = [
+ `Impeccable design hook`,
+ ` state: ${cfg.enabled ? 'enabled' : 'disabled'}`,
+ ` shared file: ${fileState(shared, cfgPath, 'using defaults; file not present')}`,
+ ` local file: ${fileState(local, localPath, 'not present')}`,
+ ` ignoreRules: ${cfg.ignoreRules.length ? cfg.ignoreRules.join(', ') : '(none)'}`,
+ ` ignoreFiles: ${cfg.ignoreFiles.length ? cfg.ignoreFiles.join(', ') : '(none)'}`,
+ ` ignoreValues: ${ignoreValues.length ? ignoreValues.join(', ') : '(none)'}`,
+ ` maxFindings: ${cfg.limits.maxFindings}`,
+ ` maxChars: ${cfg.limits.maxChars}`,
+ ` env override: ${envState}`,
+ ` cache file: ${fs.existsSync(getCachePath(cwd)) ? cachePath : `${cachePath} (not present)`}`,
+ ];
+ return lines.join('\n');
+}
+
+function setEnabled(cwd, value) {
+ const config = mergeConfig(readRawConfig(cwd));
+ config.enabled = value;
+ const target = writeConfig(cwd, config);
+ return `Design hook ${value ? 'enabled' : 'disabled'} for this project (wrote ${path.relative(cwd, target) || target}).`;
+}
+
+function normalizeRuleId(rule) {
+ return String(rule || '').trim().toLowerCase();
+}
+
+function parseIgnoreRuleArgs(args) {
+ const positionals = [];
+ let allValues = false;
+
+ for (let i = 0; i < args.length; i++) {
+ const arg = String(args[i] || '');
+ if (arg === '--all-values') {
+ allValues = true;
+ } else if (arg === '--reason') {
+ while (i + 1 < args.length && !String(args[i + 1]).startsWith('--')) i++;
+ } else if (arg.startsWith('--reason=')) {
+ // Accepted for command symmetry; ignoreRules stores rule ids only.
+ } else if (arg.startsWith('--')) {
+ throw new Error(`Unknown ignore-rule flag: ${arg}`);
+ } else {
+ positionals.push(arg);
+ }
+ }
+
+ return {
+ rule: normalizeRuleId(positionals[0]),
+ allValues,
+ };
+}
+
+function addIgnoreRule(cwd, args) {
+ const parsed = parseIgnoreRuleArgs(args);
+ const rule = parsed.rule;
+ if (!rule) throw new Error('Pass a rule id, e.g. /impeccable hooks ignore-rule side-tab');
+ if (rule === 'overused-font' && !parsed.allValues) {
+ throw new Error('overused-font is value-specific by default. Use /impeccable hooks ignore-value overused-font <font> for a confirmed font, or /impeccable hooks ignore-rule overused-font --all-values only when the user asked to ignore overused fonts generally.');
+ }
+ const config = mergeConfig(readRawConfig(cwd));
+ if (!config.ignoreRules.includes(rule)) config.ignoreRules.push(rule);
+ writeConfig(cwd, config);
+ return `Added "${rule}" to ignoreRules. Current: ${config.ignoreRules.join(', ')}`;
+}
+
+function addIgnoreFile(cwd, glob) {
+ if (!glob) throw new Error('Pass a glob, e.g. /impeccable hooks ignore-file "src/legacy/**"');
+ const config = mergeConfig(readRawConfig(cwd));
+ if (!config.ignoreFiles.includes(glob)) config.ignoreFiles.push(glob);
+ writeConfig(cwd, config);
+ return `Added "${glob}" to ignoreFiles. Current: ${config.ignoreFiles.join(', ')}`;
+}
+
+function parseIgnoreValueArgs(args) {
+ const positionals = [];
+ let shared = false;
+ let local = false;
+ let reason = '';
+
+ for (let i = 0; i < args.length; i++) {
+ const arg = args[i];
+ if (arg === '--shared') {
+ shared = true;
+ } else if (arg === '--local') {
+ local = true;
+ } else if (arg === '--reason') {
+ const chunks = [];
+ while (i + 1 < args.length && !String(args[i + 1]).startsWith('--')) {
+ chunks.push(args[++i]);
+ }
+ reason = chunks.join(' ').trim();
+ } else if (String(arg).startsWith('--reason=')) {
+ reason = String(arg).slice('--reason='.length).trim();
+ } else {
+ positionals.push(arg);
+ }
+ }
+
+ const [rule, ...valueParts] = positionals;
+ return {
+ rule: String(rule || '').trim().toLowerCase(),
+ value: normalizeIgnoreValue(valueParts.join(' ')),
+ shared,
+ local,
+ reason,
+ };
+}
+
+function addIgnoreValue(cwd, args) {
+ const parsed = parseIgnoreValueArgs(args);
+ if (!parsed.rule || !parsed.value) {
+ throw new Error('Pass a rule id and value, e.g. /impeccable hooks ignore-value overused-font Inter');
+ }
+
+ if (parsed.shared && parsed.local) {
+ throw new Error('Pass only one scope flag: --shared or --local');
+ }
+
+ const local = parsed.local;
+ const config = local
+ ? mergeLocalConfig(readRawConfig(cwd, { local: true }))
+ : mergeConfig(readRawConfig(cwd, { local: false }));
+ const key = `${parsed.rule}\0${parsed.value}`;
+ const existing = config.ignoreValues.find((entry) => `${entry.rule}\0${entry.value}` === key);
+
+ if (existing) {
+ if (parsed.reason) existing.reason = parsed.reason;
+ } else {
+ const entry = {
+ rule: parsed.rule,
+ value: parsed.value,
+ createdAt: new Date().toISOString(),
+ };
+ if (parsed.reason) entry.reason = parsed.reason;
+ config.ignoreValues.push(entry);
+ }
+
+ const target = writeConfig(cwd, config, { local });
+ const scope = local ? 'local ignoreValues' : 'shared ignoreValues';
+ return `Added ${parsed.rule}=${parsed.value} to ${scope} (${path.relative(cwd, target) || target}).`;
+}
+
+function reset(cwd) {
+ const removed = [];
+ for (const filePath of [getConfigPath(cwd), getLocalConfigPath(cwd), getCachePath(cwd), getPendingPath(cwd)]) {
+ try {
+ if (fs.existsSync(filePath)) {
+ fs.unlinkSync(filePath);
+ removed.push(path.relative(cwd, filePath) || filePath);
+ }
+ } catch { /* ignore */ }
+ }
+ return removed.length
+ ? `Reset design hook config and cache (removed: ${removed.join(', ')}).`
+ : 'No hook config or cache to remove. Already at defaults.';
+}
+
+function main() {
+ const [, , actionArg, ...rest] = process.argv;
+ const action = (actionArg || 'status').toLowerCase();
+ const cwd = process.cwd();
+
+ if (!ACTIONS.has(action)) {
+ process.stderr.write(`Unknown action: ${action}\nValid: ${Array.from(ACTIONS).join(', ')}\n`);
+ process.exit(1);
+ }
+
+ try {
+ let out = '';
+ switch (action) {
+ case 'status': out = statusReport(cwd); break;
+ case 'on': out = setEnabled(cwd, true); break;
+ case 'off': out = setEnabled(cwd, false); break;
+ case 'ignore-rule': out = addIgnoreRule(cwd, rest); break;
+ case 'ignore-file': out = addIgnoreFile(cwd, rest[0]); break;
+ case 'ignore-value': out = addIgnoreValue(cwd, rest); break;
+ case 'reset': out = reset(cwd); break;
+ }
+ process.stdout.write(out + '\n');
+ } catch (err) {
+ process.stderr.write(`Error: ${err.message || err}\n`);
+ process.exit(1);
+ }
+}
+
+main();
diff --git a/plugin/skills/impeccable/scripts/hook-before-edit.mjs b/plugin/skills/impeccable/scripts/hook-before-edit.mjs
new file mode 100644
index 000000000..54b2709d2
--- /dev/null
+++ b/plugin/skills/impeccable/scripts/hook-before-edit.mjs
@@ -0,0 +1,408 @@
+#!/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 shellContent = shellHereDocContent(shellCommand(input));
+ if (shellContent) return shellContent;
+ const copiedContent = shellCopiedFileContent(shellCommand(input), 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 || '';
+}
+
+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 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' });
+});
diff --git a/plugin/skills/impeccable/scripts/hook-lib.mjs b/plugin/skills/impeccable/scripts/hook-lib.mjs
new file mode 100644
index 000000000..02199f530
--- /dev/null
+++ b/plugin/skills/impeccable/scripts/hook-lib.mjs
@@ -0,0 +1,1232 @@
+/**
+ * Shared library for the Impeccable design hook.
+ *
+ * Pure-ish helpers split out from `hook.mjs` so unit tests can exercise
+ * config parsing, finding filtering, dedup, render, and cache logic without
+ * spawning a subprocess. `hook.mjs` itself is the thin stdin/stdout shim.
+ *
+ * Public surface (everything exported is part of the contract):
+ * ENVELOPE_PREFIX, ALLOWED_EXTS, ACK_EXTS, SENSITIVE_PATH, GENERATED_PATH, TRUTHY
+ * truthy(value)
+ * readConfig(cwd) / DEFAULT_CONFIG / getConfigPath(cwd) / getLocalConfigPath(cwd)
+ * normalizeIgnoreValue(value)
+ * readCache(cwd) / persistCache(cwd, cache)
+ * bumpEditCount(cache, sessionId, filePath) -> number
+ * suppressionNotice(filePath)
+ * filterFindings(findings, content, ext, config)
+ * dedupeAgainstCache(findings, cache, sessionId, filePath)
+ * renderTemplate(findings, filePath, config, opts)
+ * renderCleanAck(filePath, opts) / renderPendingAck(filePath, known, opts)
+ * shouldEmitAckForFile(filePath)
+ * writeAuditLog(env, entry)
+ * loadDetector() -> Promise<{ detectText, detectHtml }>
+ * matchesAnyGlob(filePath, globs)
+ * normalizeScanTargets(primaryTargets, projectCwd)
+ * runHook(deps) -> { exitCode, stdout, audit, reason? }
+ *
+ * Design notes:
+ * - All errors are swallowed at the runHook seam. The detector throwing must
+ * never break a turn. See PRD §5 "Failure modes".
+ * - Cache shape is JSON-friendly; we gc the oldest sessions when there are
+ * more than 8 to keep file size predictable across long-lived projects.
+ * - The detector loader looks for `detector/detect-antipatterns.mjs` next to
+ * this file first (built skill layout) and falls back to the repo root's
+ * `cli/engine/detect-antipatterns.mjs` (running from source).
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+import { pathToFileURL, fileURLToPath } from 'node:url';
+
+const __filename = fileURLToPath(import.meta.url);
+const __dirname = path.dirname(__filename);
+
+export const ENVELOPE_PREFIX = '[impeccable@1]';
+
+export const ALLOWED_EXTS = new Set([
+ '.tsx', '.jsx', '.html', '.htm', '.vue', '.svelte', '.astro',
+ '.css', '.scss', '.sass', '.less', '.ts', '.js',
+]);
+
+export const ACK_EXTS = new Set([
+ '.tsx', '.jsx', '.html', '.htm', '.vue', '.svelte', '.astro',
+ '.css', '.scss', '.sass', '.less',
+]);
+
+// Hard-skip regex for sensitive files. Cannot be turned off via config.
+// Match tokenized secret/credential filenames, not UI names such as
+// CredentialForm.tsx, SecretPage.jsx, or secretary-dashboard.vue.
+export const SENSITIVE_PATH = new RegExp([
+ String.raw`(?:^|[/\\])\.env(?:\.|$)`,
+ String.raw`(?:^|[/\\])\.git(?:[/\\]|$)`,
+ String.raw`(?:^|[/\\])id_rsa(?:$|[._-])[^/\\]*$`,
+ String.raw`(?:^|[/\\])[^/\\]*\.pem$`,
+ String.raw`(?:^|[/\\])(?:[^/\\]*[._-])?(?:secret|secrets|credential|credentials)(?=[._-])[^/\\]*\.(?:json|ya?ml|toml|ini|conf|config|env|txt|key|cert|crt|pem|js|ts)$`,
+].join('|'), 'i');
+
+// Hard-skip regex for generated, lock, minified, and build-output paths.
+export const GENERATED_PATH = /(?:\.generated\.[a-z]+$|\.d\.ts$|\.min\.[a-z]+$|[/\\]node_modules[/\\]|[/\\](?:dist|build|out|\.next|\.cache|coverage)[/\\]|[/\\]?[^/\\]+\.lock(?:\.json)?$)/i;
+
+export const TRUTHY = /^(1|true|yes|on)$/i;
+
+export const DEFAULT_CONFIG = Object.freeze({
+ enabled: true,
+ ignoreRules: [],
+ ignoreFiles: [],
+ ignoreValues: [],
+ limits: { maxFindings: 5, maxChars: 8000 },
+});
+
+export const HOOK_LOCAL_IGNORE_PATTERNS = Object.freeze([
+ '.impeccable/hook.cache.json',
+ '.impeccable/hook.pending.json',
+ '.impeccable/hook.local.json',
+]);
+
+const HOOK_IGNORE_MARKER_OPEN = '# impeccable-hook-ignore-start';
+const HOOK_IGNORE_MARKER_CLOSE = '# impeccable-hook-ignore-end';
+const CACHE_MAX_SESSIONS = 8;
+export const EDIT_COUNT_THRESHOLD = 6;
+
+export function truthy(value) {
+ return typeof value === 'string' && TRUTHY.test(value);
+}
+
+function depthIsSet(value) {
+ if (value === undefined || value === null) return false;
+ const text = String(value).trim();
+ if (!text) return false;
+ if (TRUTHY.test(text)) return true;
+ return /^\d+$/.test(text) && Number(text) > 0;
+}
+
+function safeReadJson(filePath) {
+ try {
+ return JSON.parse(fs.readFileSync(filePath, 'utf-8'));
+ } catch {
+ return null;
+ }
+}
+
+export function getConfigPath(cwd) {
+ return path.join(cwd, '.impeccable', 'hook.json');
+}
+
+export function getLocalConfigPath(cwd) {
+ return path.join(cwd, '.impeccable', 'hook.local.json');
+}
+
+export function getCachePath(cwd) {
+ return path.join(cwd, '.impeccable', 'hook.cache.json');
+}
+
+export function getPendingPath(cwd) {
+ return path.join(cwd, '.impeccable', 'hook.pending.json');
+}
+
+export function resolveProjectCwd(event, fallback = process.cwd()) {
+ return event?.cwd
+ || (Array.isArray(event?.workspace_roots) && event.workspace_roots[0])
+ || envProjectDir(fallback)
+ || fallback;
+}
+
+export function readConfig(cwd) {
+ const config = cloneDefaultConfig();
+ applyConfigSource(config, safeReadJson(getConfigPath(cwd)));
+ applyConfigSource(config, safeReadJson(getLocalConfigPath(cwd)));
+ return config;
+}
+
+function numberOr(value, fallback) {
+ return Number.isFinite(value) && value > 0 ? value : fallback;
+}
+
+function cloneDefaultConfig() {
+ return {
+ ...DEFAULT_CONFIG,
+ ignoreRules: [],
+ ignoreFiles: [],
+ ignoreValues: [],
+ limits: { ...DEFAULT_CONFIG.limits },
+ };
+}
+
+function applyConfigSource(config, raw) {
+ if (!raw || typeof raw !== 'object') return config;
+ if (Object.prototype.hasOwnProperty.call(raw, 'enabled')) {
+ config.enabled = raw.enabled === false ? false : true;
+ }
+ if (Array.isArray(raw.ignoreRules)) {
+ config.ignoreRules = uniqueStrings([...config.ignoreRules, ...raw.ignoreRules]);
+ }
+ if (Array.isArray(raw.ignoreFiles)) {
+ config.ignoreFiles = uniqueStrings([...config.ignoreFiles, ...raw.ignoreFiles]);
+ }
+ if (Array.isArray(raw.ignoreValues)) {
+ config.ignoreValues = mergeIgnoreValues(config.ignoreValues, raw.ignoreValues);
+ }
+ if (raw.limits && typeof raw.limits === 'object') {
+ config.limits = {
+ maxFindings: numberOr(raw.limits.maxFindings, config.limits.maxFindings),
+ maxChars: numberOr(raw.limits.maxChars, config.limits.maxChars),
+ };
+ }
+ return config;
+}
+
+function uniqueStrings(values) {
+ return Array.from(new Set(values.map(String)));
+}
+
+export function normalizeIgnoreValue(value) {
+ return String(value || '')
+ .trim()
+ .replace(/^["']|["']$/g, '')
+ .replace(/\+/g, ' ')
+ .replace(/\s+/g, ' ')
+ .toLowerCase();
+}
+
+function normalizeIgnoreRule(rule) {
+ return String(rule || '').trim().toLowerCase();
+}
+
+export function normalizeIgnoreValueEntries(entries) {
+ if (!Array.isArray(entries)) return [];
+ const out = [];
+ for (const entry of entries) {
+ if (!entry || typeof entry !== 'object') continue;
+ const rule = normalizeIgnoreRule(entry.rule);
+ const value = normalizeIgnoreValue(entry.value);
+ if (!rule || !value) continue;
+ const normalized = { rule, value };
+ if (typeof entry.reason === 'string' && entry.reason.trim()) {
+ normalized.reason = entry.reason.trim();
+ }
+ if (typeof entry.createdAt === 'string' && entry.createdAt.trim()) {
+ normalized.createdAt = entry.createdAt.trim();
+ }
+ out.push(normalized);
+ }
+ return out;
+}
+
+function mergeIgnoreValues(existing, incoming) {
+ const map = new Map();
+ for (const entry of normalizeIgnoreValueEntries(existing)) {
+ map.set(`${entry.rule}\0${entry.value}`, entry);
+ }
+ for (const entry of normalizeIgnoreValueEntries(incoming)) {
+ map.set(`${entry.rule}\0${entry.value}`, entry);
+ }
+ return Array.from(map.values());
+}
+
+export function readCache(cwd) {
+ const raw = safeReadJson(getCachePath(cwd));
+ if (!raw || typeof raw !== 'object' || raw.version !== 1) {
+ return { version: 1, sessions: {} };
+ }
+ return {
+ version: 1,
+ sessions: raw.sessions && typeof raw.sessions === 'object' ? raw.sessions : {},
+ };
+}
+
+export function persistCache(cwd, cache) {
+ const sessions = cache.sessions || {};
+ const ids = Object.keys(sessions);
+ if (ids.length > CACHE_MAX_SESSIONS) {
+ // Garbage-collect oldest sessions by updatedAt.
+ const ordered = ids
+ .map((id) => [id, sessions[id]?.updatedAt || 0])
+ .sort((a, b) => b[1] - a[1])
+ .slice(0, CACHE_MAX_SESSIONS);
+ const next = {};
+ for (const [id] of ordered) next[id] = sessions[id];
+ cache = { ...cache, sessions: next };
+ }
+ const target = getCachePath(cwd);
+ try {
+ ensureHookGitExcludes(cwd);
+ fs.mkdirSync(path.dirname(target), { recursive: true });
+ fs.writeFileSync(target, JSON.stringify(cache));
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+export function ensureHookGitExcludes(cwd = process.cwd()) {
+ try {
+ const target = resolveHookGitExcludeTarget(cwd);
+ if (!target) {
+ return { mode: 'none', changed: false, patterns: [...HOOK_LOCAL_IGNORE_PATTERNS] };
+ }
+
+ const patterns = target.patternPrefix
+ ? HOOK_LOCAL_IGNORE_PATTERNS.map((pattern) => `${target.patternPrefix}/${pattern}`)
+ : [...HOOK_LOCAL_IGNORE_PATTERNS];
+ const markerSuffix = target.patternPrefix || '.';
+ const markerOpen = `${HOOK_IGNORE_MARKER_OPEN} ${markerSuffix}`;
+ const markerClose = `${HOOK_IGNORE_MARKER_CLOSE} ${markerSuffix}`;
+ const existing = fs.existsSync(target.path) ? fs.readFileSync(target.path, 'utf-8') : '';
+ const block = [markerOpen, ...patterns, markerClose].join('\n');
+ const markerRe = new RegExp(`${escapeRegExp(markerOpen)}[\\s\\S]*?${escapeRegExp(markerClose)}`);
+
+ let updated;
+ if (markerRe.test(existing)) {
+ updated = existing.replace(markerRe, block);
+ } else {
+ const prefix = existing.length === 0 ? '' : existing.endsWith('\n') ? existing : `${existing}\n`;
+ updated = `${prefix}${prefix.endsWith('\n\n') || prefix === '' ? '' : '\n'}${block}\n`;
+ }
+
+ if (updated !== existing) {
+ fs.mkdirSync(path.dirname(target.path), { recursive: true });
+ fs.writeFileSync(target.path, updated, 'utf-8');
+ }
+
+ return {
+ mode: 'git-info-exclude',
+ file: path.relative(path.resolve(cwd), target.path).split(path.sep).join('/'),
+ changed: updated !== existing,
+ patterns,
+ };
+ } catch {
+ return { mode: 'error', changed: false, patterns: [...HOOK_LOCAL_IGNORE_PATTERNS] };
+ }
+}
+
+function resolveHookGitExcludeTarget(cwd) {
+ const start = path.resolve(cwd);
+ let dir = start;
+ while (true) {
+ const dotGit = path.join(dir, '.git');
+ if (fs.existsSync(dotGit)) {
+ const gitDir = resolveGitDir(dotGit, dir);
+ if (!gitDir) return null;
+ const relPrefix = path.relative(dir, start).split(path.sep).join('/');
+ return {
+ path: path.join(gitDir, 'info', 'exclude'),
+ patternPrefix: relPrefix && relPrefix !== '.' ? relPrefix : '',
+ };
+ }
+ const parent = path.dirname(dir);
+ if (parent === dir) return null;
+ dir = parent;
+ }
+}
+
+function resolveGitDir(dotGit, worktreeDir) {
+ const stat = fs.statSync(dotGit);
+ if (stat.isDirectory()) return dotGit;
+ if (!stat.isFile()) return null;
+
+ const body = fs.readFileSync(dotGit, 'utf-8').trim();
+ const match = body.match(/^gitdir:\s*(.+)$/i);
+ if (!match) return null;
+ return path.isAbsolute(match[1]) ? match[1] : path.resolve(worktreeDir, match[1]);
+}
+
+function escapeRegExp(value) {
+ return String(value).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+}
+
+function ensureSession(cache, sessionId) {
+ if (!cache.sessions[sessionId]) {
+ cache.sessions[sessionId] = { updatedAt: Date.now(), files: {} };
+ }
+ return cache.sessions[sessionId];
+}
+
+function ensureFile(cache, sessionId, filePath) {
+ const session = ensureSession(cache, sessionId);
+ if (!session.files[filePath]) {
+ session.files[filePath] = { editCount: 0, findings: [] };
+ }
+ return session.files[filePath];
+}
+
+export function bumpEditCount(cache, sessionId, filePath) {
+ const fileEntry = ensureFile(cache, sessionId, filePath);
+ fileEntry.editCount = (fileEntry.editCount || 0) + 1;
+ ensureSession(cache, sessionId).updatedAt = Date.now();
+ return fileEntry.editCount;
+}
+
+export function suppressionNotice(filePath) {
+ return `${ENVELOPE_PREFIX} Suppressing further design hints on ${filePath}. More than ${EDIT_COUNT_THRESHOLD} edits in this session reached. Run /impeccable audit to revisit.`;
+}
+
+// Glob → RegExp. Supports `**`, `*`, `?`, and `{a,b}` alternation.
+function globToRegex(glob) {
+ let re = '^';
+ let i = 0;
+ while (i < glob.length) {
+ const c = glob[i];
+ if (c === '*') {
+ if (glob[i + 1] === '*') {
+ re += '.*';
+ i += 2;
+ if (glob[i] === '/') i += 1;
+ } else {
+ re += '[^/]*';
+ i += 1;
+ }
+ } else if (c === '?') {
+ re += '[^/]';
+ i += 1;
+ } else if (c === '{') {
+ const end = glob.indexOf('}', i);
+ if (end === -1) { re += '\\{'; i += 1; continue; }
+ const parts = glob.slice(i + 1, end).split(',').map((p) => p.replace(/[.+^$()|[\]\\]/g, '\\$&'));
+ re += `(?:${parts.join('|')})`;
+ i = end + 1;
+ } else if (/[.+^$()|[\]\\]/.test(c)) {
+ re += `\\${c}`;
+ i += 1;
+ } else {
+ re += c;
+ i += 1;
+ }
+ }
+ re += '$';
+ return new RegExp(re);
+}
+
+export function matchesAnyGlob(filePath, globs) {
+ if (!Array.isArray(globs) || globs.length === 0) return false;
+ const normalized = filePath.split(path.sep).join('/');
+ for (const glob of globs) {
+ try {
+ const re = globToRegex(String(glob));
+ if (re.test(normalized)) return true;
+ // Match against basename too for convenience: `*.generated.tsx` should
+ // catch `src/foo.generated.tsx` without requiring `**/`.
+ const base = normalized.split('/').pop();
+ if (re.test(base)) return true;
+ } catch {
+ /* malformed glob, skip */
+ }
+ }
+ return false;
+}
+
+export function filterFindings(findings, _content, _ext, config) {
+ if (!Array.isArray(findings) || findings.length === 0) return [];
+ const ignoreRules = new Set((config.ignoreRules || []).map((rule) => normalizeIgnoreRule(rule)));
+ const ignoreValues = normalizeIgnoreValueEntries(config.ignoreValues || []);
+ return findings.filter((f) => {
+ if (!f || typeof f !== 'object') return false;
+ if (ignoreRules.has(normalizeIgnoreRule(f.antipattern))) return false;
+ if (isIgnoredFindingValue(f, ignoreValues)) return false;
+ return true;
+ });
+}
+
+function isIgnoredFindingValue(finding, ignoreValues) {
+ if (!Array.isArray(ignoreValues) || ignoreValues.length === 0) return false;
+ const rule = normalizeIgnoreRule(finding.antipattern);
+ const value = extractFindingIgnoreValue(finding);
+ if (!rule || !value) return false;
+ return ignoreValues.some((entry) => entry.rule === rule && entry.value === value);
+}
+
+export function extractFindingIgnoreValue(finding) {
+ if (!finding || typeof finding !== 'object') return '';
+ const rule = normalizeIgnoreRule(finding.antipattern);
+ if (rule !== 'overused-font') return '';
+ return normalizeIgnoreValue(extractFindingIgnoreValueRaw(finding));
+}
+
+function extractFindingIgnoreValueRaw(finding) {
+ const direct = cleanIgnoreValueDisplay(finding.ignoreValue || finding.value || '');
+ if (direct) return direct;
+
+ const candidates = [finding.detail, finding.snippet].filter((v) => typeof v === 'string' && v);
+ for (const text of candidates) {
+ const primary = text.match(/Primary font:\s*([^()\n;]+)/i);
+ if (primary) return cleanIgnoreValueDisplay(primary[1]);
+
+ const family = text.match(/font-family\s*:\s*["']?([^'",;\n]+)/i);
+ if (family) return cleanIgnoreValueDisplay(family[1]);
+
+ const google = text.match(/[?&]family=([^&:;\n]+)/i);
+ if (google) {
+ try {
+ return cleanIgnoreValueDisplay(decodeURIComponent(google[1]));
+ } catch {
+ return cleanIgnoreValueDisplay(google[1]);
+ }
+ }
+ }
+
+ return '';
+}
+
+function cleanIgnoreValueDisplay(value) {
+ return String(value || '')
+ .trim()
+ .replace(/^["']|["']$/g, '')
+ .replace(/\+/g, ' ')
+ .replace(/\s+/g, ' ');
+}
+
+export function dedupeAgainstCache(findings, cache, sessionId, filePath) {
+ if (!Array.isArray(findings) || findings.length === 0) return [];
+ const fileEntry = ensureFile(cache, sessionId, filePath);
+ const known = new Set(fileEntry.findings || []);
+ const fresh = [];
+ for (const f of findings) {
+ const key = `${f.antipattern}:${f.line || 0}`;
+ if (known.has(key)) continue;
+ known.add(key);
+ fresh.push(f);
+ }
+ return fresh;
+}
+
+export function rememberFindings(cache, sessionId, filePath, findings) {
+ const fileEntry = ensureFile(cache, sessionId, filePath);
+ const known = new Set(fileEntry.findings || []);
+ for (const f of findings) known.add(`${f.antipattern}:${f.line || 0}`);
+ fileEntry.findings = Array.from(known);
+ ensureSession(cache, sessionId).updatedAt = Date.now();
+}
+
+export function renderTemplate(findings, filePath, config, opts = {}) {
+ if (!Array.isArray(findings) || findings.length === 0) return '';
+ const limits = config?.limits || DEFAULT_CONFIG.limits;
+ const cap = Math.max(1, limits.maxFindings || DEFAULT_CONFIG.limits.maxFindings);
+ const maxChars = Math.max(500, limits.maxChars || DEFAULT_CONFIG.limits.maxChars);
+
+ const cwd = opts.cwd || process.cwd();
+ const display = relativize(filePath, cwd);
+ const total = findings.length;
+ const shown = findings.slice(0, cap);
+ const remaining = total - shown.length;
+
+ const header = `${ENVELOPE_PREFIX} Required design corrections in ${display} (${total} issue(s)):`;
+ const lines = shown.map((f) => formatFindingLine(f));
+ const more = remaining > 0
+ ? `... and ${remaining} more (see /impeccable audit).`
+ : null;
+ const footer = directiveFooter(display);
+
+ const blocks = [header, ...lines];
+ if (more) blocks.push(more);
+ blocks.push('');
+ blocks.push(footer);
+ let text = blocks.join('\n');
+
+ if (text.length > maxChars) {
+ text = clampToBudget(header, lines, more, footer, maxChars);
+ }
+ return text;
+}
+
+function renderGroupedTemplate(groups, config, opts = {}) {
+ const realGroups = groups.filter((group) => Array.isArray(group.findings) && group.findings.length > 0);
+ if (realGroups.length === 0) return '';
+ if (realGroups.length === 1) {
+ const [group] = realGroups;
+ return renderTemplate(group.findings, group.filePath, config, opts);
+ }
+
+ const limits = config?.limits || DEFAULT_CONFIG.limits;
+ const cap = Math.max(1, limits.maxFindings || DEFAULT_CONFIG.limits.maxFindings);
+ const maxChars = Math.max(500, limits.maxChars || DEFAULT_CONFIG.limits.maxChars);
+ const cwd = opts.cwd || process.cwd();
+ const total = realGroups.reduce((sum, group) => sum + group.findings.length, 0);
+ const header = `${ENVELOPE_PREFIX} Required design corrections across ${realGroups.length} files (${total} issue(s)):`;
+ const lines = [];
+ let shownCount = 0;
+
+ for (const group of realGroups) {
+ const display = relativize(group.filePath, cwd);
+ lines.push(`${display} (${group.findings.length} issue(s)):`);
+ const remainingCap = Math.max(0, cap - shownCount);
+ const shown = group.findings.slice(0, remainingCap);
+ for (const finding of shown) {
+ lines.push(formatFindingLine(finding));
+ }
+ shownCount += shown.length;
+ const hidden = group.findings.length - shown.length;
+ if (hidden > 0) {
+ lines.push(`- ... ${hidden} more in ${display} (see /impeccable audit).`);
+ }
+ }
+
+ const footer = directiveFooter('the affected files', { grouped: true });
+ let text = [header, ...lines, '', footer].join('\n');
+ if (text.length > maxChars) {
+ text = clampGroupedToBudget(header, lines, footer, maxChars);
+ }
+ return text;
+}
+
+function clampGroupedToBudget(header, lines, footer, maxChars) {
+ const assemble = (linesArr, omitted) => [
+ header,
+ ...linesArr,
+ ...(omitted ? ['... and more (see /impeccable audit).'] : []),
+ '',
+ footer,
+ ].join('\n');
+
+ let working = lines.slice();
+ let omitted = false;
+ let assembled = assemble(working, omitted);
+ while (assembled.length > maxChars && working.length > 1) {
+ working.pop();
+ omitted = true;
+ assembled = assemble(working, omitted);
+ }
+ if (assembled.length > maxChars) {
+ assembled = `${assembled.slice(0, maxChars - 1)}…`;
+ }
+ return assembled;
+}
+
+function clampToBudget(header, lines, more, footer, maxChars) {
+ const assemble = (linesArr, moreText) => {
+ const blocks = [header, ...linesArr];
+ if (moreText) blocks.push(moreText);
+ blocks.push('');
+ blocks.push(footer);
+ return blocks.join('\n');
+ };
+
+ let working = lines.slice();
+ let moreText = more;
+ let assembled = assemble(working, moreText);
+ while (assembled.length > maxChars && working.length > 1) {
+ working.pop();
+ moreText = '... and more (see /impeccable audit).';
+ assembled = assemble(working, moreText);
+ }
+ if (assembled.length > maxChars) {
+ assembled = `${assembled.slice(0, maxChars - 1)}…`;
+ }
+ return assembled;
+}
+
+function formatFindingLine(f) {
+ const prefix = f.line && f.line > 0 ? `- L${f.line}` : '-';
+ const desc = (f.description || '').trim();
+ const name = (f.name || '').trim();
+ // Description from the registry already ends in punctuation; join with a
+ // single space. `name` may have a trailing period already, keep it clean.
+ const nameSegment = name ? `${name.replace(/\.+\s*$/, '')}.` : '';
+ const ignoreCommand = formatFindingIgnoreCommand(f);
+ const ignoreSegment = ignoreCommand
+ ? ` If the user explicitly confirms this value is intentional: \`${ignoreCommand}\`.`
+ : '';
+ return `${prefix} [${f.antipattern}] ${nameSegment} ${desc}${ignoreSegment}`.replace(/\s+/g, ' ').trim();
+}
+
+function formatFindingIgnoreCommand(finding) {
+ if (!finding || typeof finding !== 'object') return '';
+ const rule = normalizeIgnoreRule(finding.antipattern);
+ if (!rule) return '';
+ const normalizedValue = extractFindingIgnoreValue(finding);
+ if (!normalizedValue) return '';
+ const value = extractFindingIgnoreValueRaw(finding);
+ const valueArg = quoteCommandArg(value);
+ const reason = quoteCommandArg(`User confirmed ${value} is intentional`);
+ return `/impeccable hooks ignore-value ${rule} ${valueArg} --shared --reason ${reason}`;
+}
+
+function quoteCommandArg(value) {
+ const text = String(value || '').trim();
+ if (/^[A-Za-z0-9._:-]+$/.test(text)) return text;
+ return `"${text.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
+}
+
+function relativize(filePath, cwd) {
+ try {
+ const rel = path.relative(cwd, filePath);
+ if (!rel || rel.startsWith('..')) return filePath;
+ return rel.split(path.sep).join('/');
+ } catch {
+ return filePath;
+ }
+}
+
+// Codex `apply_patch` exposes the raw patch in `tool_input.command`, not
+// `tool_input.file_path`. Claude Code may send both; parse the patch body
+// so we can scan the file(s) the tool actually touched.
+// https://developers.openai.com/codex/hooks#posttooluse
+const APPLY_PATCH_FILE_RE = /^\*\*\* (?:Update|Add) File: (.+)$/gm;
+
+export function parseApplyPatchPaths(command, projectCwd) {
+ if (!command || typeof command !== 'string') return [];
+ const out = [];
+ for (const m of command.matchAll(APPLY_PATCH_FILE_RE)) {
+ let p = (m[1] || '').trim();
+ if (!p) continue;
+ if (!path.isAbsolute(p)) p = path.resolve(projectCwd, p);
+ out.push(p);
+ }
+ return out;
+}
+
+export function resolveTargetFiles(event, projectCwd) {
+ const ti = event?.tool_input;
+ const out = [];
+ const add = (filePath) => {
+ if (typeof filePath !== 'string' || !filePath) return;
+ if (!out.includes(filePath)) out.push(filePath);
+ };
+
+ if (event?.tool_name === 'apply_patch' && ti && typeof ti.command === 'string') {
+ for (const filePath of parseApplyPatchPaths(ti.command, projectCwd)) add(filePath);
+ }
+ if (ti && typeof ti.file_path === 'string' && ti.file_path) {
+ add(ti.file_path);
+ }
+ // Cursor Write / StrReplace use `path`, not `file_path`.
+ if (ti && typeof ti.path === 'string' && ti.path) {
+ add(ti.path);
+ }
+ if (typeof event?.file_path === 'string' && event.file_path) {
+ add(event.file_path);
+ }
+ return out;
+}
+
+export function resolveHarness(env = {}, event = null) {
+ const explicit = env?.IMPECCABLE_HOOK_HARNESS;
+ if (explicit === 'cursor') return 'cursor';
+ if (explicit === 'claude' || explicit === 'codex') return 'claude';
+ if (typeof event?.conversation_id === 'string' && event.conversation_id) return 'cursor';
+ return 'claude';
+}
+
+export function normalizeHookEvent(event, projectCwd, harness = 'claude') {
+ if (!event || typeof event !== 'object' || harness !== 'cursor') return event;
+
+ const cwd = event.cwd
+ || (Array.isArray(event.workspace_roots) && event.workspace_roots[0])
+ || envProjectDir(projectCwd)
+ || projectCwd;
+ const sessionId = event.session_id || event.conversation_id || 'unknown';
+
+ const ti = event.tool_input && typeof event.tool_input === 'object' ? event.tool_input : {};
+ const filePath = ti.file_path || ti.path || event.file_path;
+ if (filePath) {
+ return {
+ ...event,
+ cwd,
+ session_id: sessionId,
+ tool_input: { ...ti, file_path: filePath },
+ };
+ }
+
+ return { ...event, cwd, session_id: sessionId };
+}
+
+function envProjectDir(fallback) {
+ if (typeof process.env.CURSOR_PROJECT_DIR === 'string' && process.env.CURSOR_PROJECT_DIR) {
+ return process.env.CURSOR_PROJECT_DIR;
+ }
+ return fallback;
+}
+
+// UI components often keep slop in a sibling/co-located stylesheet while the
+// JSX edit is what triggered PostToolUse. Scan those styles too so an App.jsx
+// patch doesn't report "clean" while styles.css still has Inter/bounce/etc.
+const UI_CODE_EXTS = new Set(['.jsx', '.tsx', '.vue', '.svelte', '.astro']);
+const STYLE_EXTS = new Set(['.css', '.scss', '.sass', '.less']);
+const CO_SCAN_STYLE_NAMES = [
+ 'styles.css', 'styles.scss', 'styles.sass', 'styles.less',
+ 'index.css', 'index.scss', 'index.sass', 'index.less',
+ 'global.css', 'global.scss', 'global.sass', 'global.less',
+ 'globals.css', 'globals.scss', 'globals.sass', 'globals.less',
+];
+const MAX_SCAN_TARGETS = 6;
+
+const STATIC_STYLE_IMPORT_RE = /import\s+(?:[\w*{}\s,$]+\s+from\s+)?['"]([^'"]+\.(?:css|scss|sass|less))['"]/gi;
+
+function hasPathTraversal(filePath) {
+ return typeof filePath === 'string' && filePath.includes('..');
+}
+
+function isInsideProject(filePath, projectCwd) {
+ if (!filePath || !projectCwd || hasPathTraversal(filePath)) return false;
+ try {
+ const rel = path.relative(projectCwd, filePath);
+ return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));
+ } catch {
+ return false;
+ }
+}
+
+export function parseStaticStyleImports(content, fromFile, projectCwd) {
+ if (!content || typeof content !== 'string') return [];
+ const dir = path.dirname(fromFile);
+ const out = [];
+ for (const m of content.matchAll(STATIC_STYLE_IMPORT_RE)) {
+ let p = (m[1] || '').trim();
+ if (!p) continue;
+ if (p.startsWith('.')) p = path.resolve(dir, p);
+ else if (!path.isAbsolute(p)) p = path.resolve(projectCwd, p);
+ if (!isInsideProject(p, projectCwd)) continue;
+ out.push(p);
+ }
+ return out;
+}
+
+export function coLocatedStylesheets(filePath) {
+ const dir = path.dirname(filePath);
+ const base = path.basename(filePath, path.extname(filePath));
+ const candidates = new Set([
+ path.join(dir, `${base}.css`),
+ path.join(dir, `${base}.module.css`),
+ path.join(dir, `${base}.scss`),
+ path.join(dir, `${base}.module.scss`),
+ path.join(dir, `${base}.sass`),
+ path.join(dir, `${base}.module.sass`),
+ path.join(dir, `${base}.less`),
+ path.join(dir, `${base}.module.less`),
+ ]);
+ for (const name of CO_SCAN_STYLE_NAMES) {
+ candidates.add(path.join(dir, name));
+ }
+ return [...candidates].filter((p) => fs.existsSync(p));
+}
+
+export function normalizeScanTargets(primaryTargets, projectCwd) {
+ if (!Array.isArray(primaryTargets) || primaryTargets.length === 0) return [];
+ const ordered = [];
+ const seen = new Set();
+ const baseCwd = projectCwd || process.cwd();
+ const normalizeTarget = (p) => {
+ // Preserve literal `..` segments so downstream sensitive-path checks
+ // still fire. path.resolve would collapse `/foo/../etc/passwd`.
+ if (hasPathTraversal(p)) return p;
+ return path.isAbsolute(p) ? p : path.resolve(baseCwd, p);
+ };
+ const add = (p) => {
+ if (ordered.length >= MAX_SCAN_TARGETS) return;
+ const abs = normalizeTarget(p);
+ if (seen.has(abs)) return;
+ seen.add(abs);
+ ordered.push(abs);
+ return abs;
+ };
+
+ for (const p of primaryTargets) add(p);
+ return ordered;
+}
+
+export function expandScanTargets(primaryTargets, projectCwd) {
+ const ordered = normalizeScanTargets(primaryTargets, projectCwd);
+ if (ordered.length === 0) return [];
+ const seen = new Set(ordered);
+ const baseCwd = projectCwd || process.cwd();
+ const add = (p) => {
+ if (ordered.length >= MAX_SCAN_TARGETS) return;
+ const abs = hasPathTraversal(p) ? p : (path.isAbsolute(p) ? p : path.resolve(baseCwd, p));
+ if (seen.has(abs)) return;
+ seen.add(abs);
+ ordered.push(abs);
+ return abs;
+ };
+
+ const normalizedPrimaries = [];
+ for (const p of ordered) normalizedPrimaries.push(p);
+
+ for (const p of normalizedPrimaries) {
+ if (ordered.length >= MAX_SCAN_TARGETS) break;
+ if (!isInsideProject(p, baseCwd)) continue;
+ const ext = path.extname(p).toLowerCase();
+ if (STYLE_EXTS.has(ext) || !UI_CODE_EXTS.has(ext)) continue;
+
+ let content = '';
+ try { content = fs.readFileSync(p, 'utf-8'); } catch { /* unreadable primary */ }
+
+ for (const imp of parseStaticStyleImports(content, p, projectCwd)) {
+ add(imp);
+ if (ordered.length >= MAX_SCAN_TARGETS) break;
+ }
+ for (const col of coLocatedStylesheets(p)) {
+ add(col);
+ if (ordered.length >= MAX_SCAN_TARGETS) break;
+ }
+ }
+
+ return ordered;
+}
+
+export function writeAuditLog(env, entry) {
+ const target = env?.IMPECCABLE_HOOK_LOG;
+ if (!target || typeof target !== 'string') return false;
+ try {
+ const expanded = target.startsWith('~/')
+ ? path.join(process.env.HOME || process.env.USERPROFILE || '.', target.slice(2))
+ : target;
+ fs.mkdirSync(path.dirname(expanded), { recursive: true });
+ const line = JSON.stringify({ ts: new Date().toISOString(), ...entry }) + '\n';
+ fs.appendFileSync(expanded, line);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+const DETECTOR_CANDIDATES = [
+ path.join(__dirname, 'detector', 'detect-antipatterns.mjs'),
+ path.join(__dirname, '..', '..', 'cli', 'engine', 'detect-antipatterns.mjs'),
+ path.join(__dirname, '..', '..', '..', 'cli', 'engine', 'detect-antipatterns.mjs'),
+];
+
+let detectorCache = null;
+export async function loadDetector(candidates = DETECTOR_CANDIDATES) {
+ if (detectorCache) return detectorCache;
+ const found = candidates.find((c) => fs.existsSync(c));
+ if (!found) return null;
+ const mod = await import(pathToFileURL(found));
+ detectorCache = { detectText: mod.detectText, detectHtml: mod.detectHtml };
+ return detectorCache;
+}
+
+// For tests: allow injecting a detector implementation.
+export function setDetectorForTesting(impl) {
+ detectorCache = impl;
+}
+
+// ────────────────────────────────────────────────────────────────────────
+// Nudge/steer messages for the no-silent-fires policy.
+//
+// The hook is designed to be a conversational presence: every fire that
+// actually scans a file emits a developer-role message into the model's
+// next turn. Three states map to three templates:
+//
+// 1. **Fresh findings** → `renderTemplate` (existing, imperative).
+// 2. **Pending findings** → `renderPendingAck` (re-nudge for issues the
+// model was already told about in this
+// session but hasn't fixed yet).
+// 3. **Truly clean** → `renderCleanAck` (short positive nudge that
+// keeps the design discipline in context).
+//
+// All three are short (≤ ~40 tokens each) so the cumulative cost stays
+// bounded across a long active editing session. Users who explicitly want
+// silence-on-clean can set `IMPECCABLE_HOOK_QUIET=1` — runHook checks that
+// env before emitting #2 or #3.
+//
+// Why not stay silent on dedup-clean? Earlier versions did. The model
+// quickly forgets the prior reminder once tool output scrolls past it, so
+// re-nudging on the same file with a short "still pending" line keeps the
+// pressure on. The wording deliberately points back to "earlier this
+// session" so the model knows it's a re-mind, not a new finding.
+// ────────────────────────────────────────────────────────────────────────
+
+const STEER_LINE = 'Keep typography hierarchy, spacing rhythm, and color contrast intentional on the next change.';
+
+export function renderCleanAck(filePath, opts = {}) {
+ const cwd = opts.cwd || process.cwd();
+ const display = relativize(filePath, cwd);
+ return `${ENVELOPE_PREFIX} Design hook scanned ${display}. No anti-patterns. ${STEER_LINE}`;
+}
+
+export function renderPendingAck(filePath, knownFindings, opts = {}) {
+ const cwd = opts.cwd || process.cwd();
+ const display = relativize(filePath, cwd);
+ const count = knownFindings.length;
+ // `knownFindings` here are the cache strings like "side-tab:3".
+ const sample = knownFindings.slice(0, 3).join(', ');
+ const more = count > 3 ? `, +${count - 3} more` : '';
+ return `${ENVELOPE_PREFIX} Design hook scanned ${display}. Still has ${count} issue(s) flagged earlier this session (${sample}${more}). Address them before finalizing — the previous reminder still applies.`;
+}
+
+export function shouldEmitAckForFile(filePath) {
+ return ACK_EXTS.has(path.extname(String(filePath || '')).toLowerCase());
+}
+
+// The directive footer is the part of the hook output that steers model
+// behavior. Three intentional moves:
+// 1. **Imperative, not advisory.** "Fix these..." beats "Consider
+// revising..." which the model treats as a soft suggestion it can
+// override when the user asked for any kind of throwaway / demo UI.
+// 2. **Explicit exception clause.** Without it, the model will try to
+// "fix" intentional bad fixtures, anti-pattern examples in docs, or
+// test cases. Naming the exception inline beats hoping the model
+// infers it from context.
+// 3. **Acknowledgement instruction.** Hook output is injected as
+// developer-role context, not a chat turn, so the user never sees the
+// raw envelope. Asking the model to surface the fix in its reply is
+// the cheapest way to make the feedback loop visible to the user.
+function directiveFooter(display, opts = {}) {
+ const ignoreFileCommand = `/impeccable hooks ignore-file ${quoteCommandArg(display)}`;
+ const fileIgnoreGuidance = opts.grouped
+ ? 'run `/impeccable hooks ignore-file <path>` for the specific file'
+ : `run \`${ignoreFileCommand}\``;
+ return [
+ 'Fix these in your next reply before finalizing. Acknowledge what you changed so the user sees the correction.',
+ '',
+ 'Skip the fix only if the user explicitly asked for an intentionally bad UI, an anti-pattern example, a test fixture, or documentation of bad design. In that case, say so and continue.',
+ '',
+ `Do not add source comments such as \`impeccable: ignore\`; those pollute the code and do not suppress hook findings. Do not add hook ignores unless the user explicitly confirms the finding is intentional. Prefer the narrowest persisted exception: run the exact \`/impeccable hooks ignore-value ... --shared\` command shown next to a value-specific finding. For \`overused-font\`, use \`ignore-value\` for a specific font and use \`/impeccable hooks ignore-rule overused-font --all-values\` only when the user asks to ignore overused fonts generally. For file-specific findings without an ignore-value command, ${fileIgnoreGuidance}; use \`/impeccable hooks ignore-rule <id>\` only when the user asks to suppress the whole non-value-specific rule. Run /impeccable audit for the full pass.`,
+ ].join('\n');
+}
+
+/**
+ * Run the hook with explicit dependencies. Returns a result object:
+ * { exitCode, stdout, audit, reason? }
+ *
+ * Never throws. All errors are converted to `exitCode: 0` + audit entry.
+ */
+export async function runHook({ stdinJson, env = {}, cwd = process.cwd(), now = Date.now, detector } = {}) {
+ const audit = { ts: new Date(now()).toISOString(), event: 'PostToolUse' };
+ const result = (extra) => ({ exitCode: 0, stdout: '', audit: { ...audit, ...extra } });
+
+ try {
+ // Re-entrancy guard.
+ if (depthIsSet(env.IMPECCABLE_HOOK_DEPTH) || depthIsSet(env.CLAUDE_HOOK_DEPTH)) {
+ return result({ reentrant: true, durationMs: 0 });
+ }
+
+ if (truthy(env.IMPECCABLE_HOOK_DISABLED)) {
+ return result({ skipped: 'env-disabled', durationMs: 0 });
+ }
+
+ const started = Date.now();
+
+ let event;
+ try {
+ event = typeof stdinJson === 'string' ? JSON.parse(stdinJson) : stdinJson;
+ } catch {
+ return result({ skipped: 'stdin-malformed', durationMs: Date.now() - started });
+ }
+ if (!event || typeof event !== 'object') {
+ return result({ skipped: 'stdin-empty', durationMs: Date.now() - started });
+ }
+
+ const harness = resolveHarness(env, event);
+ event = normalizeHookEvent(event, cwd, harness);
+ audit.harness = harness;
+
+ const projectCwd = event.cwd || cwd;
+ const primaryFiles = normalizeScanTargets(resolveTargetFiles(event, projectCwd), projectCwd);
+ const primaryFileSet = new Set(primaryFiles);
+ const targetFiles = expandScanTargets(primaryFiles, projectCwd);
+ audit.session = event.session_id || null;
+ if (event.tool_name) audit.tool = event.tool_name;
+
+ if (targetFiles.length === 0) {
+ return result({ skipped: 'no-file-path', durationMs: Date.now() - started });
+ }
+
+ const config = readConfig(projectCwd);
+ if (config.enabled === false) {
+ return result({ skipped: 'config-disabled', durationMs: Date.now() - started });
+ }
+
+ const cache = readCache(projectCwd);
+ const sessionId = event.session_id || 'unknown';
+ const det = detector || await loadDetector();
+ if (!det || typeof det.detectText !== 'function') {
+ persistCache(projectCwd, cache);
+ return result({ skipped: 'detector-missing', durationMs: Date.now() - started });
+ }
+
+ let pendingWinner = null;
+ let cleanWinner = null;
+ const freshGroups = [];
+ let suppressionWinner = null;
+ let detectorThrewAny = false;
+ let lastSkip = 'no-scannable-file';
+ let suppressedHit = false;
+
+ for (const filePath of targetFiles) {
+ audit.file = filePath;
+
+ if (hasPathTraversal(filePath) || SENSITIVE_PATH.test(filePath)) {
+ lastSkip = 'sensitive';
+ continue;
+ }
+ if (GENERATED_PATH.test(filePath)) {
+ lastSkip = 'generated';
+ continue;
+ }
+
+ const ext = path.extname(filePath).toLowerCase();
+ audit.ext = ext;
+ if (!ALLOWED_EXTS.has(ext)) {
+ lastSkip = 'extension';
+ continue;
+ }
+
+ const relForMatch = relativize(filePath, projectCwd);
+ if (matchesAnyGlob(relForMatch, config.ignoreFiles) || matchesAnyGlob(filePath, config.ignoreFiles)) {
+ lastSkip = 'config-ignore-file';
+ continue;
+ }
+ if (!fs.existsSync(filePath)) {
+ lastSkip = 'file-missing';
+ continue;
+ }
+
+ if (primaryFileSet.has(filePath)) {
+ const editCount = bumpEditCount(cache, sessionId, filePath);
+ audit.editCount = editCount;
+
+ if (editCount > EDIT_COUNT_THRESHOLD) {
+ const wasJustCrossed = editCount === EDIT_COUNT_THRESHOLD + 1;
+ if (wasJustCrossed && !suppressionWinner) {
+ suppressionWinner = { filePath };
+ }
+ lastSkip = 'suppressed';
+ suppressedHit = true;
+ continue;
+ }
+ }
+
+ const content = fs.readFileSync(filePath, 'utf-8');
+ let findings;
+ let detectorThrew = false;
+ if ((ext === '.html' || ext === '.htm') && typeof det.detectHtml === 'function') {
+ try { findings = await det.detectHtml(filePath); } catch { findings = []; detectorThrew = true; }
+ } else {
+ try { findings = await det.detectText(content, filePath); } catch { findings = []; detectorThrew = true; }
+ }
+
+ const filtered = filterFindings(findings || [], content, ext, config);
+ const fresh = dedupeAgainstCache(filtered, cache, sessionId, filePath);
+ audit.findings = (findings || []).length;
+ audit.freshFindings = fresh.length;
+
+ if (fresh.length > 0) {
+ rememberFindings(cache, sessionId, filePath, fresh);
+ freshGroups.push({ filePath, findings: fresh });
+ continue;
+ }
+
+ if (detectorThrew) {
+ detectorThrewAny = true;
+ continue;
+ }
+
+ if (filtered.length > 0 && !pendingWinner) {
+ const known = (ensureFile(cache, sessionId, filePath).findings || []).slice();
+ pendingWinner = { filePath, known };
+ } else if (filtered.length === 0 && !cleanWinner) {
+ cleanWinner = { filePath };
+ }
+ }
+
+ persistCache(projectCwd, cache);
+
+ if (freshGroups.length > 0) {
+ const firstGroup = freshGroups[0];
+ const text = renderGroupedTemplate(freshGroups, config, { cwd: projectCwd });
+ const allFindings = freshGroups.flatMap((group) => group.findings);
+ return {
+ exitCode: 0,
+ stdout: payload(text, 'PostToolUse', harness),
+ emission: {
+ kind: 'fresh',
+ file: firstGroup.filePath,
+ findings: firstGroup.findings,
+ groups: freshGroups,
+ },
+ audit: {
+ ...audit,
+ file: firstGroup.filePath,
+ emitted: true,
+ freshFiles: freshGroups.length,
+ freshFindings: allFindings.length,
+ chars: text.length,
+ durationMs: Date.now() - started,
+ },
+ };
+ }
+
+ if (detectorThrewAny && !pendingWinner && !cleanWinner) {
+ return result({ emitted: false, error: 'detector-threw', durationMs: Date.now() - started });
+ }
+
+ if (truthy(env.IMPECCABLE_HOOK_QUIET)) {
+ return result({ emitted: false, quiet: true, durationMs: Date.now() - started });
+ }
+
+ if (pendingWinner && shouldEmitAckForFile(pendingWinner.filePath)) {
+ const text = renderPendingAck(pendingWinner.filePath, pendingWinner.known, { cwd: projectCwd });
+ return {
+ exitCode: 0,
+ stdout: payload(text, 'PostToolUse', harness),
+ emission: { kind: 'pending', file: pendingWinner.filePath, known: pendingWinner.known },
+ audit: {
+ ...audit,
+ file: pendingWinner.filePath,
+ emitted: true,
+ kind: 'pending',
+ pending: pendingWinner.known.length,
+ chars: text.length,
+ durationMs: Date.now() - started,
+ },
+ };
+ }
+
+ if (suppressionWinner) {
+ const text = suppressionNotice(relativize(suppressionWinner.filePath, projectCwd));
+ return {
+ exitCode: 0,
+ stdout: payload(text, 'PostToolUse', harness),
+ emission: { kind: 'suppression', file: suppressionWinner.filePath },
+ audit: {
+ ...audit,
+ file: suppressionWinner.filePath,
+ suppressed: true,
+ emitted: true,
+ durationMs: Date.now() - started,
+ },
+ };
+ }
+
+ if (cleanWinner && shouldEmitAckForFile(cleanWinner.filePath)) {
+ const text = renderCleanAck(cleanWinner.filePath, { cwd: projectCwd });
+ return {
+ exitCode: 0,
+ stdout: payload(text, 'PostToolUse', harness),
+ emission: { kind: 'clean', file: cleanWinner.filePath },
+ audit: {
+ ...audit,
+ file: cleanWinner.filePath,
+ emitted: true,
+ kind: 'clean',
+ chars: text.length,
+ durationMs: Date.now() - started,
+ },
+ };
+ }
+
+ if (pendingWinner || cleanWinner) {
+ return result({ emitted: false, skipped: 'non-ui-ack', durationMs: Date.now() - started });
+ }
+
+ if (suppressedHit) {
+ return result({ suppressed: true, emitted: false, durationMs: Date.now() - started });
+ }
+
+ return result({ skipped: lastSkip, durationMs: Date.now() - started });
+ } catch (err) {
+ return {
+ exitCode: 0,
+ stdout: '',
+ audit: { ...audit, error: String(err && err.message ? err.message : err) },
+ };
+ }
+}
+
+export function payload(text, eventName = 'PostToolUse', harness = 'claude') {
+ if (harness === 'cursor') {
+ return JSON.stringify({ additional_context: text });
+ }
+ return JSON.stringify({
+ hookSpecificOutput: { hookEventName: eventName, additionalContext: text },
+ });
+}
diff --git a/plugin/skills/impeccable/scripts/hook.mjs b/plugin/skills/impeccable/scripts/hook.mjs
new file mode 100644
index 000000000..b862f8033
--- /dev/null
+++ b/plugin/skills/impeccable/scripts/hook.mjs
@@ -0,0 +1,61 @@
+#!/usr/bin/env node
+/**
+ * Impeccable design hook — PostToolUse entry point.
+ *
+ * Reads the Claude Code / Codex / Cursor hook event from stdin, runs the design
+ * detector against the touched file, and emits a system reminder via
+ * `hookSpecificOutput.additionalContext` when findings exist.
+ *
+ * Contract: never break a turn. Always exit 0. Clean files emit a small ack
+ * unless quiet mode is enabled.
+ *
+ * Most logic lives in `hook-lib.mjs` so it is unit-testable without a
+ * subprocess. This file is the thin stdin/stdout adapter.
+ */
+
+import { runHook, 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');
+}
+
+async function main() {
+ // Snapshot the inherited env FIRST so the re-entrancy guard checks the
+ // parent's value, not the value we are about to export for any child
+ // processes the hook might ever spawn.
+ const inheritedEnv = { ...process.env };
+ process.env.IMPECCABLE_HOOK_DEPTH = process.env.IMPECCABLE_HOOK_DEPTH || '1';
+
+ let stdinJson = '';
+ try { stdinJson = await readStdin(); } catch { /* fall through */ }
+
+ const result = await runHook({
+ stdinJson,
+ env: inheritedEnv,
+ cwd: process.cwd(),
+ });
+
+ writeAuditLog(process.env, result.audit);
+
+ if (result.stdout) process.stdout.write(result.stdout);
+ process.exit(result.exitCode || 0);
+}
+
+main().catch((err) => {
+ // Last-ditch: never break the agent's turn even if something we did not
+ // anticipate goes wrong. Audit-log the failure if logging is enabled.
+ try {
+ writeAuditLog(process.env, {
+ ts: new Date().toISOString(),
+ event: 'PostToolUse',
+ error: String(err && err.message ? err.message : err),
+ });
+ } catch { /* swallow */ }
+ if (process.env.IMPECCABLE_HOOK_DEBUG) {
+ process.stderr.write(`[impeccable-hook] ${err}\n`);
+ }
+ process.exit(0);
+});
diff --git a/plugin/skills/impeccable/scripts/live-inject.mjs b/plugin/skills/impeccable/scripts/live-inject.mjs
index 4e5c5dc0a..69ce530c1 100644
--- a/plugin/skills/impeccable/scripts/live-inject.mjs
+++ b/plugin/skills/impeccable/scripts/live-inject.mjs
@@ -32,6 +32,8 @@ const IGNORE_MARKER_CLOSE = '# impeccable-live-ignore-end';
export const LIVE_IGNORE_PATTERNS = Object.freeze([
'.impeccable/hook.cache.json',
+ '.impeccable/hook.pending.json',
+ '.impeccable/hook.local.json',
'.impeccable/live/server.json',
'.impeccable/live/sessions/',
'.impeccable/live/previews/',
diff --git a/scripts/build.js b/scripts/build.js
index 6eb6964f8..d8cce4952 100644
--- a/scripts/build.js
+++ b/scripts/build.js
@@ -21,6 +21,7 @@ import { fileURLToPath } from 'url';
import { readSourceFiles, readPatterns, stashPerProjectArtifacts, restorePerProjectArtifacts } from './lib/utils.js';
import { generateApiData } from './lib/api-data.js';
import { createTransformer, PROVIDERS } from './lib/transformers/index.js';
+import { hooksJsonFor } from './lib/transformers/hooks.js';
import { createAllZips } from './lib/zip.js';
import { ANTIPATTERNS } from '../cli/engine/registry/antipatterns.mjs';
// Sub-page generation is now handled by Astro content collections.
@@ -403,6 +404,21 @@ function copyDirSync(src, dest) {
}
}
+function syncRootHookManifests(rootDir) {
+ const synced = [];
+ for (const config of Object.values(PROVIDERS)) {
+ if (!config.emitHooks) continue;
+ const manifest = hooksJsonFor(config.emitHooks);
+ if (!manifest) continue;
+ const rel = config.hooksManifestRel || path.join('hooks', 'hooks.json');
+ const dest = path.join(rootDir, config.configDir, rel);
+ fs.mkdirSync(path.dirname(dest), { recursive: true });
+ fs.writeFileSync(dest, JSON.stringify(manifest, null, 2) + '\n');
+ synced.push(path.join(config.configDir, rel).split(path.sep).join('/'));
+ }
+ return synced;
+}
+
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const ROOT_DIR = path.resolve(__dirname, '..');
@@ -657,6 +673,29 @@ async function build() {
}
}
+ const syncedHooks = syncRootHookManifests(ROOT_DIR);
+ if (syncedHooks.length > 0) {
+ console.log(`🪝 Synced hook manifests to: ${syncedHooks.join(', ')}`);
+ }
+
+ // Remove deprecated skill stubs from local harness dirs. They exist
+ // in dist/ so the cleanup script can redirect users, but they should
+ // not clutter the repo's own skill directories.
+ const deprecatedLocalSkills = [
+ 'frontend-design', 'teach-impeccable',
+ 'arrange', 'normalize', 'onboard', 'extract',
+ // v3.0 consolidation: standalone skills -> /impeccable sub-commands
+ 'adapt', 'animate', 'audit', 'bolder', 'clarify', 'colorize',
+ 'critique', 'delight', 'distill', 'harden', 'layout', 'optimize',
+ 'overdrive', 'polish', 'quieter', 'shape', 'typeset',
+ ];
+ for (const { configDir } of syncConfigs) {
+ for (const name of deprecatedLocalSkills) {
+ const p = path.join(ROOT_DIR, configDir, 'skills', name);
+ if (fs.existsSync(p)) fs.rmSync(p, { recursive: true, force: true });
+ }
+ }
+
console.log(`📋 Synced skills to: ${syncConfigs.map(p => p.configDir).join(', ')}`);
// Build the Claude Code plugin subtree at ./plugin/.
diff --git a/scripts/lib/transformers/factory.js b/scripts/lib/transformers/factory.js
index 62526fcc6..ada60892e 100644
--- a/scripts/lib/transformers/factory.js
+++ b/scripts/lib/transformers/factory.js
@@ -10,6 +10,7 @@ import {
stripRuleMarkers,
} from '../utils.js';
import { SKILL_CATEGORIES, CATEGORY_ORDER } from '../sub-pages-data.js';
+import { hooksJsonFor } from './hooks.js';
/**
* Map from frontmatter field name to extraction spec.
@@ -300,10 +301,26 @@ export function createTransformer(config) {
}
}
+ // Emit the provider hook manifest when the provider opts in.
+ // Claude Code uses `.claude/settings.json`, Codex uses project-local
+ // `.codex/hooks.json`, and Cursor uses `.cursor/hooks.json`.
+ let hooksEmitted = false;
+ if (config.emitHooks) {
+ const manifest = hooksJsonFor(config.emitHooks);
+ if (manifest) {
+ const hooksRel = config.hooksManifestRel || path.join('hooks', 'hooks.json');
+ writeFile(path.join(providerDir, configDir, hooksRel), JSON.stringify(manifest, null, 2) + '\n');
+ hooksEmitted = true;
+ }
+ }
+
const skillWord = skills.length === 1 ? 'skill' : 'skills';
const refInfo = refCount > 0 ? ` (${refCount} reference files)` : '';
const scriptInfo = scriptCount > 0 ? ` (${scriptCount} script files)` : '';
const agentInfo = agentCount > 0 ? ` (${agentCount} agent files)` : '';
- console.log(`✓ ${displayName}: ${skills.length} ${skillWord}${refInfo}${scriptInfo}${agentInfo}`);
+ const hooksInfo = hooksEmitted
+ ? ` (${config.hooksManifestRel || path.join('hooks', 'hooks.json')})`
+ : '';
+ console.log(`✓ ${displayName}: ${skills.length} ${skillWord}${refInfo}${scriptInfo}${agentInfo}${hooksInfo}`);
};
}
diff --git a/scripts/lib/transformers/hooks.js b/scripts/lib/transformers/hooks.js
new file mode 100644
index 000000000..ed041db46
--- /dev/null
+++ b/scripts/lib/transformers/hooks.js
@@ -0,0 +1,86 @@
+/**
+ * Build-pipeline emitters for the Impeccable design hook.
+ *
+ * The hook install path in this PR is project-local:
+ * - Claude Code: `.claude/settings.json`
+ * - Codex: `.codex/hooks.json`
+ * - Cursor: `.cursor/hooks.json`
+ *
+ * No provider marketplace or Codex plugin packaging is emitted here.
+ */
+
+export const IMPECCABLE_HOOK_COMMAND_MARKER = 'skills/impeccable/scripts/hook.mjs';
+
+const TIMEOUT_SECONDS = 5;
+const CLAUDE_PROJECT_HOOK = '${CLAUDE_PROJECT_DIR}/.claude/skills/impeccable/scripts/hook.mjs';
+const CODEX_PROJECT_HOOK = '$(git rev-parse --show-toplevel)/.agents/skills/impeccable/scripts/hook.mjs';
+const CURSOR_BEFORE_EDIT_SCRIPT = '.cursor/skills/impeccable/scripts/hook-before-edit.mjs';
+
+export function buildClaudeSettingsManifest() {
+ return {
+ description: 'Impeccable design detector: runs after Edit/Write/MultiEdit on UI files and surfaces findings as system reminders.',
+ hooks: {
+ PostToolUse: [
+ {
+ matcher: 'Edit|Write|MultiEdit',
+ hooks: [
+ {
+ type: 'command',
+ command: `node "${CLAUDE_PROJECT_HOOK}"`,
+ timeout: TIMEOUT_SECONDS,
+ statusMessage: 'Scanning design',
+ },
+ ],
+ },
+ ],
+ },
+ };
+}
+
+export function buildCodexHooksManifest() {
+ return {
+ description: 'Impeccable design detector: runs after Edit/Write/apply_patch on UI files and surfaces findings as system reminders.',
+ hooks: {
+ PostToolUse: [
+ {
+ matcher: 'Edit|Write|apply_patch',
+ hooks: [
+ {
+ type: 'command',
+ command: `node "${CODEX_PROJECT_HOOK}"`,
+ timeout: TIMEOUT_SECONDS,
+ statusMessage: 'Scanning design',
+ },
+ ],
+ },
+ ],
+ },
+ };
+}
+
+export function buildCursorHooksManifest() {
+ return {
+ version: 1,
+ hooks: {
+ preToolUse: [
+ {
+ command: `node "${CURSOR_BEFORE_EDIT_SCRIPT}"`,
+ timeout: TIMEOUT_SECONDS,
+ },
+ ],
+ },
+ };
+}
+
+export function hooksJsonFor(provider) {
+ switch (provider) {
+ case 'claude':
+ return buildClaudeSettingsManifest();
+ case 'codex':
+ return buildCodexHooksManifest();
+ case 'cursor':
+ return buildCursorHooksManifest();
+ default:
+ return null;
+ }
+}
diff --git a/scripts/lib/transformers/providers.js b/scripts/lib/transformers/providers.js
index 62fc9017f..6c26cbafa 100644
--- a/scripts/lib/transformers/providers.js
+++ b/scripts/lib/transformers/providers.js
@@ -16,6 +16,9 @@ export const PROVIDERS = {
configDir: '.cursor',
displayName: 'Cursor',
frontmatterFields: ['license', 'compatibility', 'metadata'],
+ emitHooks: 'cursor',
+ // Cursor reads `.cursor/hooks.json`, not `.cursor/hooks/hooks.json`.
+ hooksManifestRel: 'hooks.json',
},
'claude-code': {
provider: 'claude-code',
@@ -24,6 +27,9 @@ export const PROVIDERS = {
displayName: 'Claude Code',
frontmatterFields: ['user-invocable', 'argument-hint', 'license', 'compatibility', 'metadata', 'allowed-tools'],
agentFormat: 'claude-md',
+ emitHooks: 'claude',
+ // Project-local Claude Code hooks live in `.claude/settings.json`.
+ hooksManifestRel: 'settings.json',
},
gemini: {
provider: 'gemini',
@@ -43,6 +49,9 @@ export const PROVIDERS = {
// No agentFormat: the Codex subagent ships nested inside the skill's own
// agents/ folder (see CODEX_SKILL_PROVIDERS in factory.js), which Codex
// auto-discovers on install. No top-level .codex/agents/ sidecar is emitted.
+ emitHooks: 'codex',
+ // Codex discovers project-local hooks at `.codex/hooks.json`.
+ hooksManifestRel: 'hooks.json',
},
agents: {
provider: 'agents',
diff --git a/scripts/lib/zip.js b/scripts/lib/zip.js
index 438569b0a..a4351030b 100644
--- a/scripts/lib/zip.js
+++ b/scripts/lib/zip.js
@@ -8,7 +8,9 @@
import path from 'path';
import { createWriteStream, existsSync, statSync } from 'fs';
-import { ZipArchive } from 'archiver';
+import * as archiverModule from 'archiver';
+
+const createArchiver = archiverModule.default || archiverModule.create || archiverModule;
/**
* Create ZIP file for a provider directory
@@ -28,7 +30,7 @@ export async function createProviderZip(providerDir, distDir, providerName) {
try {
await new Promise((resolve, reject) => {
const output = createWriteStream(zipPath);
- const archive = new ZipArchive({ zlib: { level: 9 } });
+ const archive = createArchiver('zip', { zlib: { level: 9 } });
output.on('close', resolve);
archive.on('error', reject);
diff --git a/scripts/smoke-provider-hooks.mjs b/scripts/smoke-provider-hooks.mjs
new file mode 100644
index 000000000..4c7c0758f
--- /dev/null
+++ b/scripts/smoke-provider-hooks.mjs
@@ -0,0 +1,979 @@
+#!/usr/bin/env node
+import { spawnSync } from 'node:child_process';
+import {
+ existsSync,
+ mkdirSync,
+ readFileSync,
+ readdirSync,
+ rmSync,
+ writeFileSync,
+} from 'node:fs';
+import { homedir, tmpdir } from 'node:os';
+import { dirname, join, resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const prRoot = resolve(__dirname, '..');
+const defaultBundle = join(prRoot, 'dist', 'universal.zip');
+const defaultProviders = ['direct', 'claude', 'codex', 'cursor'];
+
+const args = parseArgs(process.argv.slice(2));
+if (args.help || args.h || !args.repo) {
+ const usage = [
+ 'Usage: bun run smoke:hooks -- --repo <target-repo> [--bundle dist/universal.zip] [--providers direct,claude,codex,cursor]',
+ '',
+ 'The target repo must be explicit so this local smoke does not depend on one contributor machine path.',
+ ].join('\n');
+ if (args.help || args.h) {
+ console.log(usage);
+ process.exit(0);
+ }
+ console.error(usage);
+ process.exit(1);
+}
+
+const targetRepo = resolve(args.repo);
+const bundlePath = resolve(args.bundle || defaultBundle);
+const selectedProviders = (args.providers || defaultProviders.join(','))
+ .split(',')
+ .map((provider) => provider.trim().toLowerCase())
+ .filter(Boolean);
+const smokeDir = join(targetRepo, '.impeccable', 'provider-smoke');
+const summaryPath = join(smokeDir, 'summary.json');
+const smokeFiles = {
+ direct: 'src/__impeccable_provider_smoke_direct.html',
+ claude: 'src/__impeccable_provider_smoke_claude.html',
+ codex: 'src/__impeccable_provider_smoke_codex.html',
+ cursor: 'src/__impeccable_provider_smoke_cursor.html',
+ confirmedClaude: 'src/__impeccable_provider_smoke_confirmed_claude.html',
+ confirmedCodex: 'src/__impeccable_provider_smoke_confirmed_codex.html',
+ confirmedCursor: 'src/__impeccable_provider_smoke_confirmed_cursor.html',
+ agentChoiceClaude: 'src/__impeccable_provider_smoke_font_choice_claude.html',
+ agentChoiceCodex: 'src/__impeccable_provider_smoke_font_choice_codex.html',
+ agentChoiceCursor: 'src/__impeccable_provider_smoke_font_choice_cursor.html',
+};
+
+const results = [];
+
+main().catch((error) => {
+ if (!results.some((result) => !result.pass)) {
+ record('fatal', false, String(error?.message || error), 'fatal');
+ }
+ writeSummary();
+ console.error(error?.stack || error);
+ process.exit(1);
+});
+
+async function main() {
+ assertPath(targetRepo, 'target repo');
+ assertPath(bundlePath, 'universal bundle');
+ mkdirSync(smokeDir, { recursive: true });
+ ensureTargetGitExclude();
+
+ cleanSmokeArtifacts();
+ await checked('fresh install/update', 'install shape', reinstallFresh);
+ checked('install shape', 'install shape', verifyInstallShape);
+
+ if (selectedProviders.includes('direct')) checked('direct script contracts', 'direct script failed', runDirectContractChecks);
+ if (selectedProviders.some((provider) => ['claude', 'codex', 'cursor'].includes(provider))) {
+ checked('confirmed exception persistence', 'confirmed exception persistence failed', runConfirmedExceptionPersistenceChecks);
+ checked('agent-chosen font exception', 'agent-chosen font exception failed', runAgentChosenFontExceptionChecks);
+ }
+ if (selectedProviders.includes('claude')) checked('claude provider', 'provider did not fire or did not surface output', runClaudeProviderSmoke);
+ if (selectedProviders.includes('codex')) checked('codex provider', 'provider did not fire or did not surface output', runCodexProviderSmoke);
+ if (selectedProviders.includes('cursor')) checked('cursor provider', 'provider did not fire or did not surface output', runCursorProviderSmoke);
+
+ cleanSmokeFiles();
+ clearRuntimeState();
+ writeSummary();
+
+ const failed = results.filter((result) => !result.pass);
+ if (failed.length > 0) {
+ console.error(`Provider smoke failed: ${failed.map((r) => r.name).join(', ')}`);
+ process.exit(1);
+ }
+ console.log(`Provider smoke passed. Summary: ${summaryPath}`);
+}
+
+async function checked(name, classification, fn) {
+ try {
+ return await fn();
+ } catch (error) {
+ record(name, false, String(error?.message || error), error?.classification || classification);
+ throw error;
+ }
+}
+
+function parseArgs(argv) {
+ const out = {};
+ for (let i = 0; i < argv.length; i++) {
+ const arg = argv[i];
+ if (!arg.startsWith('--')) continue;
+ const eq = arg.indexOf('=');
+ if (eq !== -1) {
+ out[arg.slice(2, eq)] = arg.slice(eq + 1);
+ } else {
+ out[arg.slice(2)] = argv[i + 1] && !argv[i + 1].startsWith('--') ? argv[++i] : 'true';
+ }
+ }
+ return out;
+}
+
+function assertPath(path, label) {
+ if (!existsSync(path)) throw new Error(`${label} does not exist: ${path}`);
+}
+
+function record(name, pass, detail = '', classification = '') {
+ const result = { name, pass, classification, detail };
+ results.push(result);
+ console.log(`${pass ? 'PASS' : 'FAIL'} ${name}${classification ? ` [${classification}]` : ''}${detail ? `: ${detail}` : ''}`);
+}
+
+function writeSummary() {
+ mkdirSync(smokeDir, { recursive: true });
+ writeFileSync(summaryPath, `${JSON.stringify({
+ targetRepo,
+ bundlePath,
+ providers: selectedProviders,
+ results,
+ }, null, 2)}\n`);
+}
+
+function run(cmd, cmdArgs, {
+ cwd = targetRepo,
+ env = {},
+ input = undefined,
+ logName,
+ timeoutMs = 10 * 60 * 1000,
+ allowFailure = false,
+} = {}) {
+ const fallbackPath = '/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Applications/Codex.app/Contents/Resources';
+ const inheritedPath = process.env.PATH || fallbackPath;
+ const fullEnv = {
+ ...process.env,
+ PATH: `${join(homedir(), '.local', 'bin')}:${inheritedPath}:${fallbackPath}`,
+ ...env,
+ };
+ const res = spawnSync(cmd, cmdArgs, {
+ cwd,
+ env: fullEnv,
+ input,
+ encoding: 'utf8',
+ maxBuffer: 50 * 1024 * 1024,
+ timeout: timeoutMs,
+ });
+ const output = [
+ `$ ${cmd} ${cmdArgs.map(shellQuote).join(' ')}`,
+ `exit=${res.status ?? 'null'} signal=${res.signal ?? ''}`,
+ '--- stdout ---',
+ res.stdout || '',
+ '--- stderr ---',
+ res.stderr || '',
+ res.error ? `--- error ---\n${res.error.stack || res.error.message || res.error}` : '',
+ ].join('\n');
+ if (logName) writeFileSync(join(smokeDir, logName), output);
+ if (!allowFailure && (res.error || res.status !== 0)) {
+ const message = res.error
+ ? `${cmd} failed: ${res.error.message}`
+ : `${cmd} exited ${res.status}`;
+ throw Object.assign(new Error(message), { output, status: res.status });
+ }
+ return { ...res, output };
+}
+
+function shellQuote(value) {
+ const s = String(value);
+ return /^[A-Za-z0-9_/:=.,@%+-]+$/.test(s) ? s : JSON.stringify(s);
+}
+
+async function reinstallFresh() {
+ cleanInstalledImpeccable();
+ const packDir = makeTempDir('impeccable-provider-smoke-pack-');
+ const pack = run('npm', ['pack', '--pack-destination', packDir], {
+ cwd: prRoot,
+ logName: 'npm-pack.log',
+ timeoutMs: 2 * 60 * 1000,
+ });
+ const packName = (pack.stdout || '').trim().split('\n').pop();
+ const tarball = join(packDir, packName);
+ assertPath(tarball, 'local npm tarball');
+
+ const env = { IMPECCABLE_BUNDLE_PATH: bundlePath };
+ run('npx', ['--yes', '--package', tarball, 'impeccable', 'skills', 'install', '-y', '--force', '--providers=claude,cursor,codex'], {
+ cwd: targetRepo,
+ env,
+ logName: 'skills-install.log',
+ timeoutMs: 5 * 60 * 1000,
+ });
+ run('npx', ['--yes', '--package', tarball, 'impeccable', 'skills', 'update', '-y'], {
+ cwd: targetRepo,
+ env,
+ logName: 'skills-update.log',
+ timeoutMs: 5 * 60 * 1000,
+ });
+ record('fresh install/update', true, 'installed through local npx + IMPECCABLE_BUNDLE_PATH');
+}
+
+function makeTempDir(prefix) {
+ const dir = join(tmpdir(), `${prefix}${Date.now()}-${Math.random().toString(16).slice(2)}`);
+ mkdirSync(dir, { recursive: true });
+ return dir;
+}
+
+function cleanInstalledImpeccable() {
+ clearRuntimeState();
+ cleanSmokeFiles();
+
+ for (const rel of [
+ '.claude/skills/impeccable',
+ '.cursor/skills/impeccable',
+ '.agents/skills/impeccable',
+ '.claude/hooks/hooks.json',
+ '.agents/hooks',
+ '.agents/plugins/marketplace.json',
+ '.cursor/pre-log.mjs',
+ '.cursor/rules/impeccable-design-hook.mdc',
+ 'plugin-codex',
+ ]) {
+ rmSync(join(targetRepo, rel), { recursive: true, force: true });
+ }
+
+ for (const rel of ['.claude/settings.json', '.cursor/hooks.json', '.codex/hooks.json']) {
+ stripManifest(rel);
+ }
+
+ run('claude', ['plugin', 'uninstall', 'impeccable@impeccable', '--scope', 'user'], {
+ cwd: targetRepo,
+ logName: 'claude-plugin-uninstall.log',
+ allowFailure: true,
+ timeoutMs: 60 * 1000,
+ });
+ run('claude', ['plugin', 'marketplace', 'remove', 'impeccable', '--scope', 'user'], {
+ cwd: targetRepo,
+ logName: 'claude-marketplace-remove.log',
+ allowFailure: true,
+ timeoutMs: 60 * 1000,
+ });
+ run('codex', ['plugin', 'remove', 'impeccable@impeccable'], {
+ cwd: targetRepo,
+ logName: 'codex-plugin-remove.log',
+ allowFailure: true,
+ timeoutMs: 60 * 1000,
+ });
+ run('codex', ['plugin', 'marketplace', 'remove', 'impeccable'], {
+ cwd: targetRepo,
+ logName: 'codex-marketplace-remove.log',
+ allowFailure: true,
+ timeoutMs: 60 * 1000,
+ });
+
+ for (const abs of [
+ join(homedir(), '.claude/plugins/cache/impeccable'),
+ join(homedir(), '.claude/plugins/data/impeccable-impeccable'),
+ join(homedir(), '.codex/plugins/cache/impeccable'),
+ join(homedir(), '.codex/plugins/data/impeccable-impeccable'),
+ ]) {
+ rmSync(abs, { recursive: true, force: true });
+ }
+}
+
+function ensureTargetGitExclude() {
+ const excludePath = join(targetRepo, '.git', 'info', 'exclude');
+ if (!existsSync(dirname(excludePath))) return;
+ const block = [
+ '# impeccable-provider-smoke-start',
+ '.impeccable/provider-smoke/',
+ 'src/__impeccable_provider_smoke_*.html',
+ '# impeccable-provider-smoke-end',
+ ].join('\n');
+ const current = readMaybe(excludePath);
+ const next = current.includes('# impeccable-provider-smoke-start')
+ ? current.replace(/# impeccable-provider-smoke-start[\s\S]*?# impeccable-provider-smoke-end/g, block)
+ : `${current.replace(/\s*$/, '')}\n${block}\n`;
+ if (next !== current) writeFileSync(excludePath, next);
+}
+
+function stripManifest(rel) {
+ const file = join(targetRepo, rel);
+ if (!existsSync(file)) return;
+ let json;
+ try {
+ json = JSON.parse(readFileSync(file, 'utf8'));
+ } catch {
+ rmSync(file, { force: true });
+ return;
+ }
+ const hooks = json.hooks && typeof json.hooks === 'object' && !Array.isArray(json.hooks) ? json.hooks : {};
+ const nextHooks = {};
+ for (const [event, entries] of Object.entries(hooks)) {
+ const preserved = Array.isArray(entries)
+ ? entries.map(stripImpeccableHookEntry).filter(Boolean)
+ : entries;
+ if (Array.isArray(preserved) ? preserved.length > 0 : Boolean(preserved)) nextHooks[event] = preserved;
+ }
+ const next = { ...json, hooks: nextHooks };
+ if (Object.keys(nextHooks).length === 0) {
+ rmSync(file, { force: true });
+ } else {
+ writeFileSync(file, `${JSON.stringify(next, null, 2)}\n`);
+ }
+}
+
+function stripImpeccableHookEntry(entry) {
+ if (!entry || typeof entry !== 'object') return entry;
+ if (containsImpeccableHook(entry)) return null;
+ if (Array.isArray(entry.hooks)) {
+ const hooks = entry.hooks.map(stripImpeccableHookEntry).filter(Boolean);
+ if (hooks.length === 0 && entry.hooks.some(containsImpeccableHook)) return null;
+ return { ...entry, hooks };
+ }
+ return entry;
+}
+
+function containsImpeccableHook(value) {
+ if (typeof value === 'string') return value.includes('skills/impeccable/scripts/hook') || value.includes('.cursor/pre-log.mjs');
+ if (Array.isArray(value)) return value.some(containsImpeccableHook);
+ if (value && typeof value === 'object') return Object.values(value).some(containsImpeccableHook);
+ return false;
+}
+
+function verifyInstallShape() {
+ const claude = readText('.claude/settings.json');
+ const codex = readText('.codex/hooks.json');
+ const cursor = readText('.cursor/hooks.json');
+ assertCount(claude, '.claude/skills/impeccable/scripts/hook.mjs', 1, 'Claude hook.mjs');
+ assertCount(codex, '.agents/skills/impeccable/scripts/hook.mjs', 1, 'Codex hook.mjs');
+ assertCount(cursor, '.cursor/skills/impeccable/scripts/hook-before-edit.mjs', 1, 'Cursor preToolUse');
+ assertCount(cursor, '.cursor/skills/impeccable/scripts/hook-after-edit.mjs', 0, 'Cursor afterFileEdit');
+ assertCount(cursor, '.cursor/skills/impeccable/scripts/hook-stop.mjs', 0, 'Cursor stop');
+ for (const text of [claude, codex, cursor]) {
+ if (text.includes('hook-probe.mjs')) throw new Error('hook-probe.mjs still appears in hook manifests');
+ }
+ for (const rel of [
+ '.claude/skills/impeccable/scripts/hook.mjs',
+ '.claude/skills/impeccable/scripts/hook-lib.mjs',
+ '.claude/skills/impeccable/scripts/detector/cli/main.mjs',
+ '.agents/skills/impeccable/scripts/hook.mjs',
+ '.agents/skills/impeccable/scripts/hook-lib.mjs',
+ '.agents/skills/impeccable/scripts/detector/cli/main.mjs',
+ '.cursor/skills/impeccable/scripts/hook-before-edit.mjs',
+ '.cursor/skills/impeccable/scripts/hook-lib.mjs',
+ '.cursor/skills/impeccable/scripts/detector/cli/main.mjs',
+ ]) {
+ assertPath(join(targetRepo, rel), rel);
+ }
+ for (const rel of [
+ '.cursor/skills/impeccable/scripts/hook-after-edit.mjs',
+ '.cursor/skills/impeccable/scripts/hook-stop.mjs',
+ ]) {
+ if (existsSync(join(targetRepo, rel))) throw new Error(`${rel} should not exist in Cursor payload`);
+ }
+ if (findFiles(['.claude', '.cursor', '.agents'], 'hook-probe.mjs').length > 0) {
+ throw new Error('hook-probe.mjs still exists in installed payloads');
+ }
+ assertNoPluginInstall();
+ record('install shape', true, 'real hook manifests and payloads installed; no probe/plugin leftovers');
+}
+
+function readText(rel) {
+ return readFileSync(join(targetRepo, rel), 'utf8');
+}
+
+function assertCount(text, needle, expected, label) {
+ const actual = text.split(needle).length - 1;
+ if (actual !== expected) throw new Error(`${label}: expected ${expected}, got ${actual}`);
+}
+
+function findFiles(roots, filename) {
+ const found = [];
+ for (const root of roots) {
+ walk(join(targetRepo, root), (file) => {
+ if (file.endsWith(`/${filename}`)) found.push(file);
+ });
+ }
+ return found;
+}
+
+function walk(dir, visit) {
+ if (!existsSync(dir)) return;
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
+ const full = join(dir, entry.name);
+ if (entry.isDirectory()) walk(full, visit);
+ else if (entry.isFile()) visit(full);
+ }
+}
+
+function assertNoPluginInstall() {
+ const claude = run('claude', ['plugin', 'list'], { allowFailure: true, logName: 'claude-plugin-list.log', timeoutMs: 60 * 1000 });
+ const codex = run('codex', ['plugin', 'list'], { allowFailure: true, logName: 'codex-plugin-list.log', timeoutMs: 60 * 1000 });
+ const codexMarket = run('codex', ['plugin', 'marketplace', 'list'], { allowFailure: true, logName: 'codex-marketplace-list.log', timeoutMs: 60 * 1000 });
+ for (const [name, text] of [
+ ['Claude plugin list', `${claude.stdout}\n${claude.stderr}`],
+ ['Codex plugin list', `${codex.stdout}\n${codex.stderr}`],
+ ['Codex marketplace list', `${codexMarket.stdout}\n${codexMarket.stderr}`],
+ ]) {
+ if (/impeccable@impeccable|Marketplace `impeccable`|impeccable-design-hook-impl/.test(text)) {
+ throw new Error(`${name} still contains Impeccable plugin install`);
+ }
+ }
+}
+
+function runDirectContractChecks() {
+ clearRuntimeState();
+ const file = writeBadFixture(smokeFiles.direct);
+ const env = { IMPECCABLE_HOOK_LOG: join(smokeDir, 'direct.ndjson') };
+ const claude = run('node', ['.claude/skills/impeccable/scripts/hook.mjs'], {
+ cwd: targetRepo,
+ env,
+ logName: 'direct-claude.log',
+ input: JSON.stringify(postToolUseEvent('direct-claude', file, 'Edit')),
+ });
+ requireFinding('direct Claude hook', `${claude.stdout}\n${readMaybe(join(smokeDir, 'direct.ndjson'))}`);
+
+ clearRuntimeState();
+ const codex = run('node', ['.agents/skills/impeccable/scripts/hook.mjs'], {
+ cwd: targetRepo,
+ env,
+ logName: 'direct-codex.log',
+ input: JSON.stringify(postToolUseEvent('direct-codex', file, 'apply_patch')),
+ });
+ requireFinding('direct Codex hook', `${codex.stdout}\n${readMaybe(join(smokeDir, 'direct.ndjson'))}`);
+
+ clearRuntimeState();
+ const pre = run('node', ['.cursor/skills/impeccable/scripts/hook-before-edit.mjs'], {
+ cwd: targetRepo,
+ env,
+ logName: 'direct-cursor-before.log',
+ input: JSON.stringify({
+ hook_event_name: 'preToolUse',
+ cwd: targetRepo,
+ tool_name: 'Write',
+ tool_input: {
+ file_path: join(targetRepo, smokeFiles.direct),
+ content: badFixtureContent(),
+ },
+ }),
+ });
+ requireFinding('direct Cursor preToolUse hook', `${pre.stdout}\n${readMaybe(join(smokeDir, 'direct.ndjson'))}`);
+
+ record('direct script contracts', true, 'Claude, Codex, and Cursor preToolUse scripts detect side-tab');
+}
+
+function runConfirmedExceptionPersistenceChecks() {
+ const providers = selectedProviders.filter((provider) => ['claude', 'codex', 'cursor'].includes(provider));
+ for (const provider of providers) {
+ runConfirmedExceptionForProvider(provider);
+ }
+ record('confirmed exception persistence', true, `${providers.join(', ')} ignored confirmed overused-font values through shared hook.json, not source comments`);
+}
+
+function runConfirmedExceptionForProvider(provider) {
+ clearRuntimeState();
+ const rel = confirmedSmokeFile(provider);
+ const file = writeConfirmedFixture(rel);
+ const configPath = join(targetRepo, '.impeccable', 'hook.json');
+ const beforeLog = `${provider}-confirmed-before.ndjson`;
+ const afterLog = `${provider}-confirmed-after.ndjson`;
+
+ rmSync(join(smokeDir, beforeLog), { force: true });
+ rmSync(join(smokeDir, afterLog), { force: true });
+
+ const first = runInstalledProviderHook(provider, file, beforeLog);
+ requireRuleFinding(`${provider} confirmed exception first hook`, `${first.stdout}\n${first.stderr}\n${readMaybe(join(smokeDir, beforeLog))}`, 'overused-font');
+ if (existsSync(configPath)) {
+ throw new Error(`${provider} hook wrote .impeccable/hook.json before explicit confirmation`);
+ }
+
+ run('node', [
+ providerAdminScript(provider),
+ 'ignore-value',
+ 'overused-font',
+ 'Roboto',
+ '--shared',
+ '--reason',
+ `Provider smoke confirmed Roboto is intentional for ${provider}`,
+ ], {
+ cwd: targetRepo,
+ logName: `${provider}-confirmed-admin.log`,
+ timeoutMs: 60 * 1000,
+ });
+
+ const config = readJson(configPath);
+ assertSpecificFontIgnoreConfig(provider, config);
+
+ clearTransientHookState();
+ const second = runInstalledProviderHook(provider, file, afterLog);
+ if (provider === 'cursor') {
+ const payload = JSON.parse(second.stdout || '{}');
+ if (payload.permission !== 'allow') {
+ throw new Error('Cursor confirmed ignore-value did not allow the proposed write');
+ }
+ } else if (/overused-font|Required design corrections/.test(second.stdout || '')) {
+ throw new Error(`${provider} confirmed ignore-value emitted a correction after persistence`);
+ }
+
+ const afterEvents = readAuditEvents(join(smokeDir, afterLog));
+ const suppressed = afterEvents.some((event) =>
+ event.file === file
+ && (
+ (Number(event.findings) > 0 && Number(event.freshFindings) === 0)
+ || (Number(event.findings) > 0 && Number(event.blockedFindings) === 0)
+ )
+ );
+ if (!suppressed) {
+ throw new Error(`${provider} confirmed ignore-value did not produce suppression audit evidence`);
+ }
+
+ clearRuntimeState();
+}
+
+function runAgentChosenFontExceptionChecks() {
+ const providers = selectedProviders.filter((provider) => ['claude', 'codex', 'cursor'].includes(provider));
+ for (const provider of providers) {
+ runAgentChosenFontExceptionForProvider(provider);
+ }
+ record('agent-chosen font exception', true, `${providers.join(', ')} persisted Roboto as ignoreValues and did not write ignoreRules`);
+}
+
+function runAgentChosenFontExceptionForProvider(provider) {
+ clearRuntimeState();
+ const rel = agentChoiceSmokeFile(provider);
+ const file = writeConfirmedFixture(rel);
+ const configPath = join(targetRepo, '.impeccable', 'hook.json');
+ const beforeLog = `${provider}-agent-choice-before.ndjson`;
+ const afterLog = `${provider}-agent-choice-after.ndjson`;
+
+ rmSync(join(smokeDir, beforeLog), { force: true });
+ rmSync(join(smokeDir, afterLog), { force: true });
+
+ const first = runInstalledProviderHook(provider, file, beforeLog);
+ requireRuleFinding(`${provider} agent-choice first hook`, `${first.stdout}\n${first.stderr}\n${readMaybe(join(smokeDir, beforeLog))}`, 'overused-font');
+ if (existsSync(configPath)) {
+ throw new Error(`${provider} hook wrote .impeccable/hook.json before explicit confirmation`);
+ }
+
+ runProviderAgentFontException(provider, rel);
+
+ const config = readJson(configPath);
+ assertSpecificFontIgnoreConfig(provider, config);
+
+ clearTransientHookState();
+ const second = runInstalledProviderHook(provider, file, afterLog);
+ if (provider === 'cursor') {
+ const payload = JSON.parse(second.stdout || '{}');
+ if (payload.permission !== 'allow') {
+ throw new Error('Cursor agent-chosen ignore-value did not allow the proposed write');
+ }
+ } else if (/overused-font|Required design corrections/.test(second.stdout || '')) {
+ throw new Error(`${provider} agent-chosen ignore-value emitted a correction after persistence`);
+ }
+
+ clearRuntimeState();
+}
+
+function runProviderAgentFontException(provider, rel) {
+ const prompt = fontExceptionPrompt(provider, rel);
+ if (provider === 'claude') {
+ run('claude', [
+ '-p',
+ '--setting-sources', 'project',
+ '--permission-mode', 'acceptEdits',
+ '--tools', 'Read,Bash',
+ '--allowedTools', 'Read Bash',
+ '--debug', 'hooks',
+ '--debug-file', join(smokeDir, 'claude-agent-choice-debug.log'),
+ prompt,
+ ], {
+ cwd: targetRepo,
+ logName: 'claude-agent-choice.log',
+ timeoutMs: 10 * 60 * 1000,
+ });
+ return;
+ }
+
+ if (provider === 'codex') {
+ run('codex', [
+ 'exec',
+ '-C', targetRepo,
+ '--dangerously-bypass-hook-trust',
+ '--dangerously-bypass-approvals-and-sandbox',
+ '--json',
+ prompt,
+ ], {
+ cwd: targetRepo,
+ logName: 'codex-agent-choice.log',
+ timeoutMs: 10 * 60 * 1000,
+ });
+ return;
+ }
+
+ if (provider === 'cursor') {
+ ensureCursorAgent();
+ const res = run('agent', [
+ '-p',
+ '--force',
+ '--trust',
+ '--workspace', targetRepo,
+ '--output-format', 'stream-json',
+ prompt,
+ ], {
+ cwd: targetRepo,
+ logName: 'cursor-agent-choice.log',
+ timeoutMs: 10 * 60 * 1000,
+ allowFailure: true,
+ });
+ if (res.error || res.status !== 0) {
+ const output = `${res.stdout}\n${res.stderr}\n${res.error?.message || ''}`;
+ if (/Authentication required|agent login|CURSOR_API_KEY/i.test(output)) {
+ const err = new Error('Cursor CLI authentication required. Run `agent login` or set CURSOR_API_KEY, then rerun `bun run smoke:hooks -- --providers=cursor`.');
+ err.classification = 'cursor auth required';
+ throw err;
+ }
+ throw new Error(res.error ? `agent failed: ${res.error.message}` : `agent exited ${res.status}`);
+ }
+ return;
+ }
+
+ throw new Error(`Unsupported agent-choice provider: ${provider}`);
+}
+
+function assertSpecificFontIgnoreConfig(provider, config) {
+ if (Array.isArray(config.ignoreRules) && config.ignoreRules.includes('overused-font')) {
+ throw new Error(`${provider} wrote ignoreRules["overused-font"]; specific fonts must use ignoreValues`);
+ }
+ const ignoredValue = Array.isArray(config.ignoreValues)
+ && config.ignoreValues.some((entry) => entry.rule === 'overused-font' && entry.value === 'roboto');
+ if (!ignoredValue) {
+ throw new Error(`${provider} did not persist overused-font=roboto in ignoreValues`);
+ }
+}
+
+function runInstalledProviderHook(provider, file, logName) {
+ const env = { IMPECCABLE_HOOK_LOG: join(smokeDir, logName) };
+ if (provider === 'claude') {
+ return run('node', ['.claude/skills/impeccable/scripts/hook.mjs'], {
+ cwd: targetRepo,
+ env,
+ logName: `direct-${provider}-confirmed-${logName.replace(/\.ndjson$/, '.log')}`,
+ input: JSON.stringify(postToolUseEvent(`confirmed-${provider}`, file, 'Edit')),
+ });
+ }
+ if (provider === 'codex') {
+ return run('node', ['.agents/skills/impeccable/scripts/hook.mjs'], {
+ cwd: targetRepo,
+ env,
+ logName: `direct-${provider}-confirmed-${logName.replace(/\.ndjson$/, '.log')}`,
+ input: JSON.stringify(postToolUseEvent(`confirmed-${provider}`, file, 'apply_patch')),
+ });
+ }
+ if (provider === 'cursor') {
+ return run('node', ['.cursor/skills/impeccable/scripts/hook-before-edit.mjs'], {
+ cwd: targetRepo,
+ env,
+ logName: `direct-${provider}-confirmed-${logName.replace(/\.ndjson$/, '.log')}`,
+ input: JSON.stringify({
+ hook_event_name: 'preToolUse',
+ cwd: targetRepo,
+ tool_name: 'Write',
+ tool_input: {
+ file_path: file,
+ content: readFileSync(file, 'utf8'),
+ },
+ }),
+ });
+ }
+ throw new Error(`Unsupported confirmed exception provider: ${provider}`);
+}
+
+function confirmedSmokeFile(provider) {
+ if (provider === 'claude') return smokeFiles.confirmedClaude;
+ if (provider === 'codex') return smokeFiles.confirmedCodex;
+ if (provider === 'cursor') return smokeFiles.confirmedCursor;
+ throw new Error(`Unsupported confirmed exception provider: ${provider}`);
+}
+
+function agentChoiceSmokeFile(provider) {
+ if (provider === 'claude') return smokeFiles.agentChoiceClaude;
+ if (provider === 'codex') return smokeFiles.agentChoiceCodex;
+ if (provider === 'cursor') return smokeFiles.agentChoiceCursor;
+ throw new Error(`Unsupported agent-choice provider: ${provider}`);
+}
+
+function providerAdminScript(provider) {
+ if (provider === 'claude') return '.claude/skills/impeccable/scripts/hook-admin.mjs';
+ if (provider === 'codex') return '.agents/skills/impeccable/scripts/hook-admin.mjs';
+ if (provider === 'cursor') return '.cursor/skills/impeccable/scripts/hook-admin.mjs';
+ throw new Error(`Unsupported admin provider: ${provider}`);
+}
+
+function runClaudeProviderSmoke() {
+ clearRuntimeState();
+ const env = { IMPECCABLE_HOOK_LOG: join(smokeDir, 'claude.ndjson') };
+ const prompt = providerPrompt(smokeFiles.claude);
+ const res = run('claude', [
+ '-p',
+ '--setting-sources', 'project',
+ '--permission-mode', 'acceptEdits',
+ '--tools', 'Read,Write,Edit',
+ '--allowedTools', 'Read Write Edit',
+ '--debug', 'hooks',
+ '--debug-file', join(smokeDir, 'claude-debug.log'),
+ prompt,
+ ], {
+ cwd: targetRepo,
+ env,
+ logName: 'claude-provider.log',
+ timeoutMs: 10 * 60 * 1000,
+ });
+ const evidence = `${res.stdout}\n${res.stderr}\n${readMaybe(join(smokeDir, 'claude.ndjson'))}\n${readMaybe(join(smokeDir, 'claude-debug.log'))}`;
+ requireFile(smokeFiles.claude, 'Claude provider fixture');
+ requireFinding('Claude provider hook', evidence);
+ if (!/PostToolUse|hook/i.test(evidence)) throw new Error('Claude provider evidence lacks hook/PostToolUse marker');
+ record('claude provider', true, 'Claude edit triggered PostToolUse hook and side-tab detection');
+}
+
+function runCodexProviderSmoke() {
+ clearRuntimeState();
+ const env = { IMPECCABLE_HOOK_LOG: join(smokeDir, 'codex.ndjson') };
+ const prompt = `Use apply_patch to ${providerPrompt(smokeFiles.codex)}`;
+ const res = run('codex', [
+ 'exec',
+ '-C', targetRepo,
+ '--dangerously-bypass-hook-trust',
+ '--dangerously-bypass-approvals-and-sandbox',
+ '--json',
+ prompt,
+ ], {
+ cwd: targetRepo,
+ env,
+ logName: 'codex-provider.log',
+ timeoutMs: 10 * 60 * 1000,
+ });
+ const evidence = `${res.stdout}\n${res.stderr}\n${readMaybe(join(smokeDir, 'codex.ndjson'))}`;
+ const cacheEvidence = `${readMaybe(join(targetRepo, '.impeccable', 'hook.cache.json'))}\n${readMaybe(join(targetRepo, '.impeccable', 'hook.pending.json'))}`;
+ requireFile(smokeFiles.codex, 'Codex provider fixture');
+ requireFinding('Codex provider hook', `${evidence}\n${cacheEvidence}`);
+ record('codex provider', true, 'Codex apply_patch triggered project hook and side-tab detection');
+}
+
+function runCursorProviderSmoke() {
+ ensureCursorAgent();
+ clearRuntimeState();
+ const env = { IMPECCABLE_HOOK_LOG: join(smokeDir, 'cursor.ndjson') };
+ const prompt = providerPrompt(smokeFiles.cursor);
+ const res = run('agent', [
+ '-p',
+ '--force',
+ '--trust',
+ '--workspace', targetRepo,
+ '--output-format', 'stream-json',
+ prompt,
+ ], {
+ cwd: targetRepo,
+ env,
+ logName: 'cursor-provider.log',
+ timeoutMs: 10 * 60 * 1000,
+ allowFailure: true,
+ });
+ if (res.error || res.status !== 0) {
+ const output = `${res.stdout}\n${res.stderr}\n${res.error?.message || ''}`;
+ if (/Authentication required|agent login|CURSOR_API_KEY/i.test(output)) {
+ const err = new Error('Cursor CLI authentication required. Run `agent login` or set CURSOR_API_KEY, then rerun `bun run smoke:hooks -- --providers=cursor`.');
+ err.classification = 'cursor auth required';
+ throw err;
+ }
+ throw new Error(res.error ? `agent failed: ${res.error.message}` : `agent exited ${res.status}`);
+ }
+ const evidence = `${res.stdout}\n${res.stderr}\n${readMaybe(join(smokeDir, 'cursor.ndjson'))}\n${readMaybe(join(targetRepo, '.impeccable', 'hook.pending.json'))}\n${readMaybe(join(targetRepo, '.impeccable', 'hook.cache.json'))}`;
+ requireFinding('Cursor provider hook', evidence);
+ const auditEvents = readAuditEvents(join(smokeDir, 'cursor.ndjson'));
+ if (!auditEvents.some((event) => event.event === 'preToolUse' && event.blocked === true)) {
+ throw new Error('Cursor provider evidence lacks a preToolUse audit entry with blocked=true');
+ }
+ const fixturePath = join(targetRepo, smokeFiles.cursor);
+ const intentionalIgnore = auditEvents.some((event) =>
+ event.event === 'preToolUse'
+ && event.file === fixturePath
+ && event.skipped === 'config-ignore-file'
+ );
+ if (existsSync(fixturePath)) {
+ const fixtureContent = readFileSync(fixturePath, 'utf8');
+ if (/border-left\s*:\s*[2-9]\d*px/i.test(fixtureContent)) {
+ if (!intentionalIgnore || !/ignoreFiles|ignore-file/i.test(evidence)) {
+ throw new Error('Cursor provider left the blocked side-tab fixture on disk without an explicit Impeccable ignore-file escape hatch');
+ }
+ }
+ }
+ record('cursor provider', true, 'Cursor agent triggered preToolUse hook, blocked side-tab, and only proceeded through explicit ignore handling for the intentional fixture');
+}
+
+function ensureCursorAgent() {
+ const version = run('agent', ['--version'], {
+ cwd: targetRepo,
+ logName: 'cursor-agent-version-before.log',
+ allowFailure: true,
+ timeoutMs: 60 * 1000,
+ });
+ if (version.status === 0) return;
+
+ run('/bin/bash', ['-c', '/usr/bin/curl https://cursor.com/install -fsS | /bin/bash'], {
+ cwd: targetRepo,
+ logName: 'cursor-agent-install.log',
+ timeoutMs: 5 * 60 * 1000,
+ });
+ run('agent', ['--version'], {
+ cwd: targetRepo,
+ logName: 'cursor-agent-version-after.log',
+ timeoutMs: 60 * 1000,
+ });
+}
+
+function writeBadFixture(rel) {
+ const abs = join(targetRepo, rel);
+ mkdirSync(dirname(abs), { recursive: true });
+ writeFileSync(abs, badFixtureContent());
+ return abs;
+}
+
+function writeConfirmedFixture(rel) {
+ const abs = join(targetRepo, rel);
+ mkdirSync(dirname(abs), { recursive: true });
+ writeFileSync(abs, confirmedFixtureContent());
+ return abs;
+}
+
+function badFixtureContent() {
+ return [
+ '<!doctype html>',
+ '<html>',
+ ' <body>',
+ ' <style>',
+ ' .card {',
+ ' border-left: 4px solid #7c3aed;',
+ ' border-radius: 16px;',
+ ' padding: 16px;',
+ ' }',
+ ' </style>',
+ ' <div class="card">Temporary Impeccable provider smoke fixture</div>',
+ ' </body>',
+ '</html>',
+ '',
+ ].join('\n');
+}
+
+function confirmedFixtureContent() {
+ return [
+ '<!doctype html>',
+ '<html>',
+ ' <body>',
+ ' <style>',
+ ' /* impeccable: ignore overused-font */',
+ ' body { font-family: "Roboto", ui-sans-serif, system-ui, sans-serif; }',
+ ' .card { border-radius: 16px; padding: 16px; }',
+ ' </style>',
+ ' <div class="card">Temporary Impeccable confirmed exception fixture using Roboto.</div>',
+ ' </body>',
+ '</html>',
+ '',
+ ].join('\n');
+}
+
+function providerPrompt(rel) {
+ return [
+ `Create ${rel} as an intentionally bad Impeccable hook test fixture.`,
+ 'The file must be HTML and include a rounded card with exactly this CSS pattern: border-left: 4px solid #7c3aed; border-radius: 16px; padding: 16px.',
+ 'This is intentionally bad UI for hook verification, so do not fix or remove the side border if a hook warns about it.',
+ 'After creating the file, stop.',
+ ].join(' ');
+}
+
+function fontExceptionPrompt(provider, rel) {
+ return [
+ `Read the installed Impeccable hooks reference for ${provider}, then persist a confirmed hook exception for Roboto specifically in ${rel}.`,
+ 'The user confirms Roboto is intentional for this fixture, but did not ask to ignore overused fonts generally.',
+ 'Use the /impeccable hooks / hook-admin flow; do not edit .impeccable/hook.json by hand and do not edit the source fixture.',
+ 'The final config must use ignoreValues for overused-font=roboto and must not add overused-font to ignoreRules.',
+ 'After updating the config, stop.',
+ ].join(' ');
+}
+
+function postToolUseEvent(sessionId, file, toolName) {
+ return {
+ session_id: sessionId,
+ cwd: targetRepo,
+ hook_event_name: 'PostToolUse',
+ tool_name: toolName,
+ tool_input: { file_path: file },
+ };
+}
+
+function requireFile(rel, label) {
+ const abs = join(targetRepo, rel);
+ if (!existsSync(abs)) throw new Error(`${label} was not created: ${rel}`);
+}
+
+function requireFinding(label, text) {
+ requireRuleFinding(label, text, 'side-tab');
+}
+
+function requireRuleFinding(label, text, rule) {
+ const rulePattern = new RegExp(rule.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'));
+ if (!rulePattern.test(text) || !/Required design corrections|findings?|antipattern|side-tab|overused-font/.test(text)) {
+ throw new Error(`${label} did not show ${rule} detector evidence`);
+ }
+}
+
+function readAuditEvents(path) {
+ return readMaybe(path)
+ .split('\n')
+ .map((line) => line.trim())
+ .filter(Boolean)
+ .map((line) => {
+ try { return JSON.parse(line); } catch { return null; }
+ })
+ .filter(Boolean);
+}
+
+function readMaybe(path) {
+ try {
+ return readFileSync(path, 'utf8');
+ } catch {
+ return '';
+ }
+}
+
+function readJson(path) {
+ return JSON.parse(readFileSync(path, 'utf8'));
+}
+
+function cleanSmokeArtifacts() {
+ rmSync(smokeDir, { recursive: true, force: true });
+ mkdirSync(smokeDir, { recursive: true });
+ cleanSmokeFiles();
+}
+
+function cleanSmokeFiles() {
+ for (const rel of Object.values(smokeFiles)) {
+ rmSync(join(targetRepo, rel), { force: true });
+ }
+}
+
+function clearRuntimeState() {
+ for (const rel of [
+ '.impeccable/hook.cache.json',
+ '.impeccable/hook.pending.json',
+ '.impeccable/hook.json',
+ '.impeccable/hook.local.json',
+ ]) {
+ rmSync(join(targetRepo, rel), { force: true });
+ }
+}
+
+function clearTransientHookState() {
+ for (const rel of [
+ '.impeccable/hook.cache.json',
+ '.impeccable/hook.pending.json',
+ ]) {
+ rmSync(join(targetRepo, rel), { force: true });
+ }
+}
diff --git a/scripts/test-suites.mjs b/scripts/test-suites.mjs
index 82530f352..9490bc17c 100644
--- a/scripts/test-suites.mjs
+++ b/scripts/test-suites.mjs
@@ -25,11 +25,11 @@ export const SUITES = {
triggers: [
...COMMON_INFRA_PATTERNS,
/^scripts\/(?!benchmark-detector|build-browser-detector|build-extension)/,
- /^skill\/(SKILL\.src\.md|agents\/|reference\/|scripts\/(context|context-signals|critique-storage|design-parser|impeccable-paths|is-generated))/,
+ /^skill\/(SKILL\.src\.md|agents\/|reference\/|scripts\/(cleanup-deprecated|context|context-signals|critique-storage|design-parser|hook|impeccable-paths|is-generated))/,
/^site\/(pages|content|components|layouts)\//,
/^README(\.npm)?\.md$/,
/^cli\/bin\//,
- /^tests\/(build|context|context-signals|critique-storage|design-parser|docs-integrity|impeccable-paths|skills-cli|test-suites|windows-path-fix)\.test\.(js|mjs)$/,
+ /^tests\/(build|cleanup-deprecated|context|context-signals|critique-storage|design-parser|docs-integrity|hook|hook-build|impeccable-paths|skills-cli|test-suites|windows-path-fix)\.test\.(js|mjs)$/,
/^tests\/lib\//,
],
commands: [
@@ -55,6 +55,8 @@ export const SUITES = {
'tests/context-signals.test.mjs',
'tests/critique-storage.test.mjs',
'tests/design-parser.test.mjs',
+ 'tests/hook-build.test.mjs',
+ 'tests/hook.test.mjs',
'tests/impeccable-paths.test.mjs',
'tests/test-suites.test.mjs',
],
diff --git a/skill/SKILL.src.md b/skill/SKILL.src.md
index e26a01280..b378800ac 100644
--- a/skill/SKILL.src.md
+++ b/skill/SKILL.src.md
@@ -144,7 +144,7 @@ If someone could look at this interface and say "AI made that" without doubt, it
| `optimize [target]` | Fix | Diagnose and fix UI performance | [reference/optimize.md](reference/optimize.md) |
| `live` | Iterate | Visual variant mode: pick elements in the browser, generate alternatives | [reference/live.md](reference/live.md) |
-Plus two management commands: `pin <command>` and `unpin <command>`, detailed below.
+Plus three management commands: `pin <command>`, `unpin <command>`, and `hooks <on|off|status|...>`, detailed below.
### Routing rules
@@ -161,7 +161,7 @@ Plus two management commands: `pin <command>` and `unpin <command>`, detailed be
**If `scan.targets` is non-empty, run `node {{scripts_path}}/detect.mjs --json <scan.targets joined by spaces>` once** (the bundled detector over local files: no network, no npx). `scan.via` tells you what they are: `git-changes` (the markup/style files in your dirty tree, the most relevant set), `source-dir` (e.g. `src`, `app`), `html`, or `root`. Fold the hits into your picks: many quality / contrast hits → `audit` or `polish`; a specific slop family → the matching command (gradient text or eyebrows → `quieter` / `typeset`, flat or gray palette → `colorize`, and so on). It's a real, current signal that beats guessing. If detect errors or the tree is large and slow, skip it and recommend the user run `audit` themselves; never block the suggestion on it.
Keep it to 2-3 pointed picks with the exact command to type. The menu stays the fallback; the recommendation is the lede.
-2. **First word matches a command**: load its reference file and follow its instructions. Everything after the command name is the target.
+2. **First word matches a command** (table above OR `pin` / `unpin` / `hooks`): load its reference file and follow its instructions. Everything after the command name is the target.
3. **First word doesn't match, but the intent clearly maps to one command** (e.g. "fix the spacing" → `layout`, "rewrite this error message" → `clarify`, "the colors feel flat" → `colorize`): load that command's reference and proceed as if invoked. If two commands could fit, ask once which.
4. **No clear command match**: general design invocation. Apply the setup steps, the General rules, and the loaded register reference, using the full argument as context.
@@ -180,3 +180,7 @@ node {{scripts_path}}/pin.mjs <pin|unpin> <command>
```
Valid `<command>` is any command from the table above. Report the script's result concisely. Confirm the new shortcut on success, relay stderr verbatim on error.
+
+## Hooks
+
+`{{command_prefix}}impeccable hooks <on|off|status|ignore-rule|ignore-file|ignore-value|reset>` manages the design detector hook for this project. The hook auto-runs the detector after direct UI file edits and surfaces findings as system reminders. Full flow is in [reference/hooks.md](reference/hooks.md); load it when the user invokes `{{command_prefix}}impeccable hooks` with any argument.
diff --git a/skill/reference/hooks.md b/skill/reference/hooks.md
new file mode 100644
index 000000000..f96d9ba55
--- /dev/null
+++ b/skill/reference/hooks.md
@@ -0,0 +1,82 @@
+# /impeccable hooks
+
+Manage the **design detector hook** for the current project.
+
+The hook runs the impeccable design detector on direct file edits to design-relevant files (`.tsx`, `.jsx`, `.html`, `.vue`, `.svelte`, `.astro`, `.css`, `.scss`, `.sass`, `.less`, `.ts`, `.js`). Claude Code and Codex use `PostToolUse` and push a short system reminder into the agent's context after the edit; findings get a correction prompt, pending issues get a re-nudge, and clean UI-ish files get a short ack unless `IMPECCABLE_HOOK_QUIET=1` is set. Plain `.ts` and `.js` files are still scanned, but stay quiet unless the detector finds something. Cursor uses `preToolUse` to block bad proposed writes before they land and stays silent when it allows a clean write.
+
+This command toggles the hook **per project** by editing `.impeccable/hook.json`. Local-only ignore policy lives in `.impeccable/hook.local.json`, which is gitignored. To disable globally, set `IMPECCABLE_HOOK_DISABLED=1` in your shell environment.
+
+Supported harnesses: Claude Code (`.claude/settings.json` in the project), Codex (`.codex/hooks.json` in the project), and Cursor (`.cursor/hooks.json` in the project).
+
+On **Cursor**, `preToolUse` checks proposed Write/Edit/Shell write content and denies only when the real detector finds an issue. The denial message is visible to the agent as the tool error, so the agent can reconsider before the bad write lands.
+
+## Routing
+
+The first argument is the action. Defaults to `status`.
+
+| Action | What it does |
+|---|---|
+| `status` | Print current state, shared/local config paths, ignored rules / files / values, env override. |
+| `on` | Set `enabled: true` in `.impeccable/hook.json`. |
+| `off` | Set `enabled: false` in `.impeccable/hook.json`. |
+| `ignore-rule <id>` | Append `<id>` to `ignoreRules`; for `overused-font`, requires `--all-values`. |
+| `ignore-file <glob>` | Append `<glob>` to `ignoreFiles`. |
+| `ignore-value <id> <value> [--shared] [--reason "..."]` | Append a rule/value suppression to shared `.impeccable/hook.json`. |
+| `ignore-value <id> <value> --local [--reason "..."]` | Append a private rule/value suppression to `.impeccable/hook.local.json`. |
+| `reset` | Delete the project config, dedup cache, and Cursor pending queue. |
+
+## Flow
+
+1. Resolve the action from the user's argument. If no action was given, default to `status`.
+2. Invoke the admin script and pass the user's output through verbatim:
+
+ ```bash
+ node {{scripts_path}}/hook-admin.mjs <action> [args...]
+ ```
+
+3. If `<action>` is `off`, follow up with a one-line note: "Done. New edits will not trigger the design hook in this project until you run `{{command_prefix}}impeccable hooks on`."
+4. If `<action>` is `on`, follow up with: "Done. The design hook will fire after the next Edit/Write/MultiEdit on a UI file."
+5. If `<action>` is `ignore-value`, `ignore-file`, or `ignore-rule`, just print the script output. The default scope is shared `.impeccable/hook.json`; add `--local` only when the user explicitly asks for a private exception.
+6. If `<action>` is `status`, just print the script output. Do not add commentary unless the user asked a follow-up question.
+
+## Intentional findings
+
+The hook itself never writes ignore config. Persist an exception only after the user explicitly confirms the flagged issue is intentional, and always go through `hook-admin.mjs`.
+
+Prefer the narrowest exception:
+
+- If the finding line shows an exact `ignore-value` command, run that command. This writes shared `.impeccable/hook.json` by default.
+- For `overused-font`, use `ignore-value` when the user confirms a specific font. Do not use `ignore-rule overused-font` for a specific font.
+- If the finding has no value-specific command, such as `side-tab`, prefer `ignore-file <path>` for the current file.
+- Use `ignore-rule <id>` only when the user asks to suppress that whole rule across the project. For broad overused-font suppression, use `ignore-rule overused-font --all-values` only when the user asks to ignore overused fonts generally.
+- Do not add source comments such as `impeccable: ignore`; inline comments pollute code and are not a supported suppression mechanism.
+
+Example value-specific exception:
+
+```bash
+node {{scripts_path}}/hook-admin.mjs ignore-value overused-font Inter --shared --reason "User confirmed Inter is intentional"
+```
+
+Example whole-rule font exception:
+
+```bash
+node {{scripts_path}}/hook-admin.mjs ignore-rule overused-font --all-values --reason "User asked to ignore overused fonts generally"
+```
+
+Example file-scoped exception:
+
+```bash
+node {{scripts_path}}/hook-admin.mjs ignore-file "src/legacy/Card.tsx"
+```
+
+## Constraints
+
+- Never modify `.impeccable/hook.json` or `.impeccable/hook.local.json` by hand from this command. Always go through `hook-admin.mjs` so writes stay validated and the file shape stays consistent.
+- Do not edit the hook scripts themselves (`hook.mjs`, `hook-lib.mjs`, `hook-before-edit.mjs`) from this flow. Those are skill plumbing.
+- Cursor can block a proposed write when the detector finds a real issue. Claude Code and Codex do not block the edit; they emit a post-edit reminder instead. Disabling stops both blocking and reminders.
+- The hook is bundled with the Impeccable skill and installed through project-local manifests: `.claude/settings.json`, `.codex/hooks.json`, and `.cursor/hooks.json`. On Codex, the user must approve the hook via `/hooks` the first time. On Cursor, confirm hooks are enabled under Settings -> Hooks.
+
+## Failure modes
+
+- If `.impeccable/hook.json` or `.impeccable/hook.local.json` is unreadable or malformed, the hook ignores that file and uses the remaining valid config/defaults. `hook-admin.mjs status` will show malformed files as ignored.
+- If the user asks to "disable the hook" globally, suggest both options: `IMPECCABLE_HOOK_DISABLED=1` env var (one-shot, follows the shell), and `{{command_prefix}}impeccable hooks off` (persistent for this project, committable).
diff --git a/skill/scripts/hook-admin.mjs b/skill/scripts/hook-admin.mjs
new file mode 100644
index 000000000..86fcfa909
--- /dev/null
+++ b/skill/scripts/hook-admin.mjs
@@ -0,0 +1,300 @@
+#!/usr/bin/env node
+/**
+ * `/impeccable hooks <on|off|status|reset>` — manage the design hook
+ * via .impeccable/hook.json and .impeccable/hook.local.json in the current
+ * project.
+ *
+ * Usage:
+ * node hook-admin.mjs status # print current state
+ * node hook-admin.mjs on # set enabled: true
+ * node hook-admin.mjs off # set enabled: false
+ * node hook-admin.mjs ignore-rule <rule-id> # append to ignoreRules
+ * node hook-admin.mjs ignore-rule overused-font --all-values
+ * node hook-admin.mjs ignore-file <glob> # append to ignoreFiles
+ * node hook-admin.mjs ignore-value <rule> <value> # append to shared ignoreValues
+ * node hook-admin.mjs ignore-value <rule> <value> --local
+ * node hook-admin.mjs reset # remove all config + cache
+ *
+ * Designed to be invoked by the LLM from the reference/hooks.md flow.
+ * Output is human-readable; the harness will pass it back to the user.
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+
+import {
+ getConfigPath,
+ getLocalConfigPath,
+ getCachePath,
+ getPendingPath,
+ readConfig,
+ DEFAULT_CONFIG,
+ ensureHookGitExcludes,
+ normalizeIgnoreValue,
+ normalizeIgnoreValueEntries,
+} from './hook-lib.mjs';
+
+const ACTIONS = new Set(['status', 'on', 'off', 'ignore-rule', 'ignore-file', 'ignore-value', 'reset']);
+
+function readRawConfigFile(filePath) {
+ if (!fs.existsSync(filePath)) return { exists: false, malformed: false, raw: null };
+ try {
+ return { exists: true, malformed: false, raw: JSON.parse(fs.readFileSync(filePath, 'utf-8')) };
+ } catch {
+ return { exists: true, malformed: true, raw: null };
+ }
+}
+
+function readRawConfig(cwd, opts = {}) {
+ const filePath = opts.local ? getLocalConfigPath(cwd) : getConfigPath(cwd);
+ return readRawConfigFile(filePath).raw;
+}
+
+function writeConfig(cwd, config, opts = {}) {
+ const filePath = opts.local ? getLocalConfigPath(cwd) : getConfigPath(cwd);
+ if (opts.local) ensureHookGitExcludes(cwd);
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
+ fs.writeFileSync(filePath, JSON.stringify(config, null, 2) + '\n');
+ return filePath;
+}
+
+function mergeConfig(existing) {
+ // Persist the full shape so /impeccable hooks edits leave a complete file
+ // for the user to see, not an unhelpful `{"enabled":false}`.
+ const base = existing && typeof existing === 'object' ? existing : {};
+ return {
+ enabled: base.enabled === false ? false : true,
+ ignoreRules: Array.isArray(base.ignoreRules) ? Array.from(new Set(base.ignoreRules.map(String))) : [],
+ ignoreFiles: Array.isArray(base.ignoreFiles) ? Array.from(new Set(base.ignoreFiles.map(String))) : [],
+ ignoreValues: normalizeIgnoreValueEntries(base.ignoreValues || []),
+ limits: {
+ maxFindings: Number.isFinite(base?.limits?.maxFindings) ? base.limits.maxFindings : DEFAULT_CONFIG.limits.maxFindings,
+ maxChars: Number.isFinite(base?.limits?.maxChars) ? base.limits.maxChars : DEFAULT_CONFIG.limits.maxChars,
+ },
+ };
+}
+
+function mergeLocalConfig(existing) {
+ const base = existing && typeof existing === 'object' ? existing : {};
+ const out = {};
+ if (Object.prototype.hasOwnProperty.call(base, 'enabled')) {
+ out.enabled = base.enabled === false ? false : true;
+ }
+ if (Array.isArray(base.ignoreRules)) {
+ out.ignoreRules = Array.from(new Set(base.ignoreRules.map(String)));
+ }
+ if (Array.isArray(base.ignoreFiles)) {
+ out.ignoreFiles = Array.from(new Set(base.ignoreFiles.map(String)));
+ }
+ out.ignoreValues = normalizeIgnoreValueEntries(base.ignoreValues || []);
+ if (base.limits && typeof base.limits === 'object') {
+ const limits = {};
+ if (Number.isFinite(base.limits.maxFindings)) limits.maxFindings = base.limits.maxFindings;
+ if (Number.isFinite(base.limits.maxChars)) limits.maxChars = base.limits.maxChars;
+ if (Object.keys(limits).length) out.limits = limits;
+ }
+ return out;
+}
+
+function statusReport(cwd) {
+ const shared = readRawConfigFile(getConfigPath(cwd));
+ const local = readRawConfigFile(getLocalConfigPath(cwd));
+ const cfg = readConfig(cwd);
+ const envKill = process.env.IMPECCABLE_HOOK_DISABLED;
+ const envState = envKill ? `IMPECCABLE_HOOK_DISABLED=${envKill}` : 'unset';
+ const cfgPath = path.relative(cwd, getConfigPath(cwd)) || '.impeccable/hook.json';
+ const localPath = path.relative(cwd, getLocalConfigPath(cwd)) || '.impeccable/hook.local.json';
+ const cachePath = path.relative(cwd, getCachePath(cwd)) || '.impeccable/hook.cache.json';
+ const fileState = (info, relPath, absent) => {
+ if (info.malformed) return `${relPath} (malformed; ignored)`;
+ if (info.exists) return relPath;
+ return `${relPath} (${absent})`;
+ };
+ const ignoreValues = cfg.ignoreValues.map((entry) => `${entry.rule}=${entry.value}`);
+
+ const lines = [
+ `Impeccable design hook`,
+ ` state: ${cfg.enabled ? 'enabled' : 'disabled'}`,
+ ` shared file: ${fileState(shared, cfgPath, 'using defaults; file not present')}`,
+ ` local file: ${fileState(local, localPath, 'not present')}`,
+ ` ignoreRules: ${cfg.ignoreRules.length ? cfg.ignoreRules.join(', ') : '(none)'}`,
+ ` ignoreFiles: ${cfg.ignoreFiles.length ? cfg.ignoreFiles.join(', ') : '(none)'}`,
+ ` ignoreValues: ${ignoreValues.length ? ignoreValues.join(', ') : '(none)'}`,
+ ` maxFindings: ${cfg.limits.maxFindings}`,
+ ` maxChars: ${cfg.limits.maxChars}`,
+ ` env override: ${envState}`,
+ ` cache file: ${fs.existsSync(getCachePath(cwd)) ? cachePath : `${cachePath} (not present)`}`,
+ ];
+ return lines.join('\n');
+}
+
+function setEnabled(cwd, value) {
+ const config = mergeConfig(readRawConfig(cwd));
+ config.enabled = value;
+ const target = writeConfig(cwd, config);
+ return `Design hook ${value ? 'enabled' : 'disabled'} for this project (wrote ${path.relative(cwd, target) || target}).`;
+}
+
+function normalizeRuleId(rule) {
+ return String(rule || '').trim().toLowerCase();
+}
+
+function parseIgnoreRuleArgs(args) {
+ const positionals = [];
+ let allValues = false;
+
+ for (let i = 0; i < args.length; i++) {
+ const arg = String(args[i] || '');
+ if (arg === '--all-values') {
+ allValues = true;
+ } else if (arg === '--reason') {
+ while (i + 1 < args.length && !String(args[i + 1]).startsWith('--')) i++;
+ } else if (arg.startsWith('--reason=')) {
+ // Accepted for command symmetry; ignoreRules stores rule ids only.
+ } else if (arg.startsWith('--')) {
+ throw new Error(`Unknown ignore-rule flag: ${arg}`);
+ } else {
+ positionals.push(arg);
+ }
+ }
+
+ return {
+ rule: normalizeRuleId(positionals[0]),
+ allValues,
+ };
+}
+
+function addIgnoreRule(cwd, args) {
+ const parsed = parseIgnoreRuleArgs(args);
+ const rule = parsed.rule;
+ if (!rule) throw new Error('Pass a rule id, e.g. /impeccable hooks ignore-rule side-tab');
+ if (rule === 'overused-font' && !parsed.allValues) {
+ throw new Error('overused-font is value-specific by default. Use /impeccable hooks ignore-value overused-font <font> for a confirmed font, or /impeccable hooks ignore-rule overused-font --all-values only when the user asked to ignore overused fonts generally.');
+ }
+ const config = mergeConfig(readRawConfig(cwd));
+ if (!config.ignoreRules.includes(rule)) config.ignoreRules.push(rule);
+ writeConfig(cwd, config);
+ return `Added "${rule}" to ignoreRules. Current: ${config.ignoreRules.join(', ')}`;
+}
+
+function addIgnoreFile(cwd, glob) {
+ if (!glob) throw new Error('Pass a glob, e.g. /impeccable hooks ignore-file "src/legacy/**"');
+ const config = mergeConfig(readRawConfig(cwd));
+ if (!config.ignoreFiles.includes(glob)) config.ignoreFiles.push(glob);
+ writeConfig(cwd, config);
+ return `Added "${glob}" to ignoreFiles. Current: ${config.ignoreFiles.join(', ')}`;
+}
+
+function parseIgnoreValueArgs(args) {
+ const positionals = [];
+ let shared = false;
+ let local = false;
+ let reason = '';
+
+ for (let i = 0; i < args.length; i++) {
+ const arg = args[i];
+ if (arg === '--shared') {
+ shared = true;
+ } else if (arg === '--local') {
+ local = true;
+ } else if (arg === '--reason') {
+ const chunks = [];
+ while (i + 1 < args.length && !String(args[i + 1]).startsWith('--')) {
+ chunks.push(args[++i]);
+ }
+ reason = chunks.join(' ').trim();
+ } else if (String(arg).startsWith('--reason=')) {
+ reason = String(arg).slice('--reason='.length).trim();
+ } else {
+ positionals.push(arg);
+ }
+ }
+
+ const [rule, ...valueParts] = positionals;
+ return {
+ rule: String(rule || '').trim().toLowerCase(),
+ value: normalizeIgnoreValue(valueParts.join(' ')),
+ shared,
+ local,
+ reason,
+ };
+}
+
+function addIgnoreValue(cwd, args) {
+ const parsed = parseIgnoreValueArgs(args);
+ if (!parsed.rule || !parsed.value) {
+ throw new Error('Pass a rule id and value, e.g. /impeccable hooks ignore-value overused-font Inter');
+ }
+
+ if (parsed.shared && parsed.local) {
+ throw new Error('Pass only one scope flag: --shared or --local');
+ }
+
+ const local = parsed.local;
+ const config = local
+ ? mergeLocalConfig(readRawConfig(cwd, { local: true }))
+ : mergeConfig(readRawConfig(cwd, { local: false }));
+ const key = `${parsed.rule}\0${parsed.value}`;
+ const existing = config.ignoreValues.find((entry) => `${entry.rule}\0${entry.value}` === key);
+
+ if (existing) {
+ if (parsed.reason) existing.reason = parsed.reason;
+ } else {
+ const entry = {
+ rule: parsed.rule,
+ value: parsed.value,
+ createdAt: new Date().toISOString(),
+ };
+ if (parsed.reason) entry.reason = parsed.reason;
+ config.ignoreValues.push(entry);
+ }
+
+ const target = writeConfig(cwd, config, { local });
+ const scope = local ? 'local ignoreValues' : 'shared ignoreValues';
+ return `Added ${parsed.rule}=${parsed.value} to ${scope} (${path.relative(cwd, target) || target}).`;
+}
+
+function reset(cwd) {
+ const removed = [];
+ for (const filePath of [getConfigPath(cwd), getLocalConfigPath(cwd), getCachePath(cwd), getPendingPath(cwd)]) {
+ try {
+ if (fs.existsSync(filePath)) {
+ fs.unlinkSync(filePath);
+ removed.push(path.relative(cwd, filePath) || filePath);
+ }
+ } catch { /* ignore */ }
+ }
+ return removed.length
+ ? `Reset design hook config and cache (removed: ${removed.join(', ')}).`
+ : 'No hook config or cache to remove. Already at defaults.';
+}
+
+function main() {
+ const [, , actionArg, ...rest] = process.argv;
+ const action = (actionArg || 'status').toLowerCase();
+ const cwd = process.cwd();
+
+ if (!ACTIONS.has(action)) {
+ process.stderr.write(`Unknown action: ${action}\nValid: ${Array.from(ACTIONS).join(', ')}\n`);
+ process.exit(1);
+ }
+
+ try {
+ let out = '';
+ switch (action) {
+ case 'status': out = statusReport(cwd); break;
+ case 'on': out = setEnabled(cwd, true); break;
+ case 'off': out = setEnabled(cwd, false); break;
+ case 'ignore-rule': out = addIgnoreRule(cwd, rest); break;
+ case 'ignore-file': out = addIgnoreFile(cwd, rest[0]); break;
+ case 'ignore-value': out = addIgnoreValue(cwd, rest); break;
+ case 'reset': out = reset(cwd); break;
+ }
+ process.stdout.write(out + '\n');
+ } catch (err) {
+ process.stderr.write(`Error: ${err.message || err}\n`);
+ process.exit(1);
+ }
+}
+
+main();
diff --git a/skill/scripts/hook-before-edit.mjs b/skill/scripts/hook-before-edit.mjs
new file mode 100644
index 000000000..61cd50039
--- /dev/null
+++ b/skill/scripts/hook-before-edit.mjs
@@ -0,0 +1,472 @@
+#!/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' });
+});
diff --git a/skill/scripts/hook-lib.mjs b/skill/scripts/hook-lib.mjs
new file mode 100644
index 000000000..02199f530
--- /dev/null
+++ b/skill/scripts/hook-lib.mjs
@@ -0,0 +1,1232 @@
+/**
+ * Shared library for the Impeccable design hook.
+ *
+ * Pure-ish helpers split out from `hook.mjs` so unit tests can exercise
+ * config parsing, finding filtering, dedup, render, and cache logic without
+ * spawning a subprocess. `hook.mjs` itself is the thin stdin/stdout shim.
+ *
+ * Public surface (everything exported is part of the contract):
+ * ENVELOPE_PREFIX, ALLOWED_EXTS, ACK_EXTS, SENSITIVE_PATH, GENERATED_PATH, TRUTHY
+ * truthy(value)
+ * readConfig(cwd) / DEFAULT_CONFIG / getConfigPath(cwd) / getLocalConfigPath(cwd)
+ * normalizeIgnoreValue(value)
+ * readCache(cwd) / persistCache(cwd, cache)
+ * bumpEditCount(cache, sessionId, filePath) -> number
+ * suppressionNotice(filePath)
+ * filterFindings(findings, content, ext, config)
+ * dedupeAgainstCache(findings, cache, sessionId, filePath)
+ * renderTemplate(findings, filePath, config, opts)
+ * renderCleanAck(filePath, opts) / renderPendingAck(filePath, known, opts)
+ * shouldEmitAckForFile(filePath)
+ * writeAuditLog(env, entry)
+ * loadDetector() -> Promise<{ detectText, detectHtml }>
+ * matchesAnyGlob(filePath, globs)
+ * normalizeScanTargets(primaryTargets, projectCwd)
+ * runHook(deps) -> { exitCode, stdout, audit, reason? }
+ *
+ * Design notes:
+ * - All errors are swallowed at the runHook seam. The detector throwing must
+ * never break a turn. See PRD §5 "Failure modes".
+ * - Cache shape is JSON-friendly; we gc the oldest sessions when there are
+ * more than 8 to keep file size predictable across long-lived projects.
+ * - The detector loader looks for `detector/detect-antipatterns.mjs` next to
+ * this file first (built skill layout) and falls back to the repo root's
+ * `cli/engine/detect-antipatterns.mjs` (running from source).
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+import { pathToFileURL, fileURLToPath } from 'node:url';
+
+const __filename = fileURLToPath(import.meta.url);
+const __dirname = path.dirname(__filename);
+
+export const ENVELOPE_PREFIX = '[impeccable@1]';
+
+export const ALLOWED_EXTS = new Set([
+ '.tsx', '.jsx', '.html', '.htm', '.vue', '.svelte', '.astro',
+ '.css', '.scss', '.sass', '.less', '.ts', '.js',
+]);
+
+export const ACK_EXTS = new Set([
+ '.tsx', '.jsx', '.html', '.htm', '.vue', '.svelte', '.astro',
+ '.css', '.scss', '.sass', '.less',
+]);
+
+// Hard-skip regex for sensitive files. Cannot be turned off via config.
+// Match tokenized secret/credential filenames, not UI names such as
+// CredentialForm.tsx, SecretPage.jsx, or secretary-dashboard.vue.
+export const SENSITIVE_PATH = new RegExp([
+ String.raw`(?:^|[/\\])\.env(?:\.|$)`,
+ String.raw`(?:^|[/\\])\.git(?:[/\\]|$)`,
+ String.raw`(?:^|[/\\])id_rsa(?:$|[._-])[^/\\]*$`,
+ String.raw`(?:^|[/\\])[^/\\]*\.pem$`,
+ String.raw`(?:^|[/\\])(?:[^/\\]*[._-])?(?:secret|secrets|credential|credentials)(?=[._-])[^/\\]*\.(?:json|ya?ml|toml|ini|conf|config|env|txt|key|cert|crt|pem|js|ts)$`,
+].join('|'), 'i');
+
+// Hard-skip regex for generated, lock, minified, and build-output paths.
+export const GENERATED_PATH = /(?:\.generated\.[a-z]+$|\.d\.ts$|\.min\.[a-z]+$|[/\\]node_modules[/\\]|[/\\](?:dist|build|out|\.next|\.cache|coverage)[/\\]|[/\\]?[^/\\]+\.lock(?:\.json)?$)/i;
+
+export const TRUTHY = /^(1|true|yes|on)$/i;
+
+export const DEFAULT_CONFIG = Object.freeze({
+ enabled: true,
+ ignoreRules: [],
+ ignoreFiles: [],
+ ignoreValues: [],
+ limits: { maxFindings: 5, maxChars: 8000 },
+});
+
+export const HOOK_LOCAL_IGNORE_PATTERNS = Object.freeze([
+ '.impeccable/hook.cache.json',
+ '.impeccable/hook.pending.json',
+ '.impeccable/hook.local.json',
+]);
+
+const HOOK_IGNORE_MARKER_OPEN = '# impeccable-hook-ignore-start';
+const HOOK_IGNORE_MARKER_CLOSE = '# impeccable-hook-ignore-end';
+const CACHE_MAX_SESSIONS = 8;
+export const EDIT_COUNT_THRESHOLD = 6;
+
+export function truthy(value) {
+ return typeof value === 'string' && TRUTHY.test(value);
+}
+
+function depthIsSet(value) {
+ if (value === undefined || value === null) return false;
+ const text = String(value).trim();
+ if (!text) return false;
+ if (TRUTHY.test(text)) return true;
+ return /^\d+$/.test(text) && Number(text) > 0;
+}
+
+function safeReadJson(filePath) {
+ try {
+ return JSON.parse(fs.readFileSync(filePath, 'utf-8'));
+ } catch {
+ return null;
+ }
+}
+
+export function getConfigPath(cwd) {
+ return path.join(cwd, '.impeccable', 'hook.json');
+}
+
+export function getLocalConfigPath(cwd) {
+ return path.join(cwd, '.impeccable', 'hook.local.json');
+}
+
+export function getCachePath(cwd) {
+ return path.join(cwd, '.impeccable', 'hook.cache.json');
+}
+
+export function getPendingPath(cwd) {
+ return path.join(cwd, '.impeccable', 'hook.pending.json');
+}
+
+export function resolveProjectCwd(event, fallback = process.cwd()) {
+ return event?.cwd
+ || (Array.isArray(event?.workspace_roots) && event.workspace_roots[0])
+ || envProjectDir(fallback)
+ || fallback;
+}
+
+export function readConfig(cwd) {
+ const config = cloneDefaultConfig();
+ applyConfigSource(config, safeReadJson(getConfigPath(cwd)));
+ applyConfigSource(config, safeReadJson(getLocalConfigPath(cwd)));
+ return config;
+}
+
+function numberOr(value, fallback) {
+ return Number.isFinite(value) && value > 0 ? value : fallback;
+}
+
+function cloneDefaultConfig() {
+ return {
+ ...DEFAULT_CONFIG,
+ ignoreRules: [],
+ ignoreFiles: [],
+ ignoreValues: [],
+ limits: { ...DEFAULT_CONFIG.limits },
+ };
+}
+
+function applyConfigSource(config, raw) {
+ if (!raw || typeof raw !== 'object') return config;
+ if (Object.prototype.hasOwnProperty.call(raw, 'enabled')) {
+ config.enabled = raw.enabled === false ? false : true;
+ }
+ if (Array.isArray(raw.ignoreRules)) {
+ config.ignoreRules = uniqueStrings([...config.ignoreRules, ...raw.ignoreRules]);
+ }
+ if (Array.isArray(raw.ignoreFiles)) {
+ config.ignoreFiles = uniqueStrings([...config.ignoreFiles, ...raw.ignoreFiles]);
+ }
+ if (Array.isArray(raw.ignoreValues)) {
+ config.ignoreValues = mergeIgnoreValues(config.ignoreValues, raw.ignoreValues);
+ }
+ if (raw.limits && typeof raw.limits === 'object') {
+ config.limits = {
+ maxFindings: numberOr(raw.limits.maxFindings, config.limits.maxFindings),
+ maxChars: numberOr(raw.limits.maxChars, config.limits.maxChars),
+ };
+ }
+ return config;
+}
+
+function uniqueStrings(values) {
+ return Array.from(new Set(values.map(String)));
+}
+
+export function normalizeIgnoreValue(value) {
+ return String(value || '')
+ .trim()
+ .replace(/^["']|["']$/g, '')
+ .replace(/\+/g, ' ')
+ .replace(/\s+/g, ' ')
+ .toLowerCase();
+}
+
+function normalizeIgnoreRule(rule) {
+ return String(rule || '').trim().toLowerCase();
+}
+
+export function normalizeIgnoreValueEntries(entries) {
+ if (!Array.isArray(entries)) return [];
+ const out = [];
+ for (const entry of entries) {
+ if (!entry || typeof entry !== 'object') continue;
+ const rule = normalizeIgnoreRule(entry.rule);
+ const value = normalizeIgnoreValue(entry.value);
+ if (!rule || !value) continue;
+ const normalized = { rule, value };
+ if (typeof entry.reason === 'string' && entry.reason.trim()) {
+ normalized.reason = entry.reason.trim();
+ }
+ if (typeof entry.createdAt === 'string' && entry.createdAt.trim()) {
+ normalized.createdAt = entry.createdAt.trim();
+ }
+ out.push(normalized);
+ }
+ return out;
+}
+
+function mergeIgnoreValues(existing, incoming) {
+ const map = new Map();
+ for (const entry of normalizeIgnoreValueEntries(existing)) {
+ map.set(`${entry.rule}\0${entry.value}`, entry);
+ }
+ for (const entry of normalizeIgnoreValueEntries(incoming)) {
+ map.set(`${entry.rule}\0${entry.value}`, entry);
+ }
+ return Array.from(map.values());
+}
+
+export function readCache(cwd) {
+ const raw = safeReadJson(getCachePath(cwd));
+ if (!raw || typeof raw !== 'object' || raw.version !== 1) {
+ return { version: 1, sessions: {} };
+ }
+ return {
+ version: 1,
+ sessions: raw.sessions && typeof raw.sessions === 'object' ? raw.sessions : {},
+ };
+}
+
+export function persistCache(cwd, cache) {
+ const sessions = cache.sessions || {};
+ const ids = Object.keys(sessions);
+ if (ids.length > CACHE_MAX_SESSIONS) {
+ // Garbage-collect oldest sessions by updatedAt.
+ const ordered = ids
+ .map((id) => [id, sessions[id]?.updatedAt || 0])
+ .sort((a, b) => b[1] - a[1])
+ .slice(0, CACHE_MAX_SESSIONS);
+ const next = {};
+ for (const [id] of ordered) next[id] = sessions[id];
+ cache = { ...cache, sessions: next };
+ }
+ const target = getCachePath(cwd);
+ try {
+ ensureHookGitExcludes(cwd);
+ fs.mkdirSync(path.dirname(target), { recursive: true });
+ fs.writeFileSync(target, JSON.stringify(cache));
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+export function ensureHookGitExcludes(cwd = process.cwd()) {
+ try {
+ const target = resolveHookGitExcludeTarget(cwd);
+ if (!target) {
+ return { mode: 'none', changed: false, patterns: [...HOOK_LOCAL_IGNORE_PATTERNS] };
+ }
+
+ const patterns = target.patternPrefix
+ ? HOOK_LOCAL_IGNORE_PATTERNS.map((pattern) => `${target.patternPrefix}/${pattern}`)
+ : [...HOOK_LOCAL_IGNORE_PATTERNS];
+ const markerSuffix = target.patternPrefix || '.';
+ const markerOpen = `${HOOK_IGNORE_MARKER_OPEN} ${markerSuffix}`;
+ const markerClose = `${HOOK_IGNORE_MARKER_CLOSE} ${markerSuffix}`;
+ const existing = fs.existsSync(target.path) ? fs.readFileSync(target.path, 'utf-8') : '';
+ const block = [markerOpen, ...patterns, markerClose].join('\n');
+ const markerRe = new RegExp(`${escapeRegExp(markerOpen)}[\\s\\S]*?${escapeRegExp(markerClose)}`);
+
+ let updated;
+ if (markerRe.test(existing)) {
+ updated = existing.replace(markerRe, block);
+ } else {
+ const prefix = existing.length === 0 ? '' : existing.endsWith('\n') ? existing : `${existing}\n`;
+ updated = `${prefix}${prefix.endsWith('\n\n') || prefix === '' ? '' : '\n'}${block}\n`;
+ }
+
+ if (updated !== existing) {
+ fs.mkdirSync(path.dirname(target.path), { recursive: true });
+ fs.writeFileSync(target.path, updated, 'utf-8');
+ }
+
+ return {
+ mode: 'git-info-exclude',
+ file: path.relative(path.resolve(cwd), target.path).split(path.sep).join('/'),
+ changed: updated !== existing,
+ patterns,
+ };
+ } catch {
+ return { mode: 'error', changed: false, patterns: [...HOOK_LOCAL_IGNORE_PATTERNS] };
+ }
+}
+
+function resolveHookGitExcludeTarget(cwd) {
+ const start = path.resolve(cwd);
+ let dir = start;
+ while (true) {
+ const dotGit = path.join(dir, '.git');
+ if (fs.existsSync(dotGit)) {
+ const gitDir = resolveGitDir(dotGit, dir);
+ if (!gitDir) return null;
+ const relPrefix = path.relative(dir, start).split(path.sep).join('/');
+ return {
+ path: path.join(gitDir, 'info', 'exclude'),
+ patternPrefix: relPrefix && relPrefix !== '.' ? relPrefix : '',
+ };
+ }
+ const parent = path.dirname(dir);
+ if (parent === dir) return null;
+ dir = parent;
+ }
+}
+
+function resolveGitDir(dotGit, worktreeDir) {
+ const stat = fs.statSync(dotGit);
+ if (stat.isDirectory()) return dotGit;
+ if (!stat.isFile()) return null;
+
+ const body = fs.readFileSync(dotGit, 'utf-8').trim();
+ const match = body.match(/^gitdir:\s*(.+)$/i);
+ if (!match) return null;
+ return path.isAbsolute(match[1]) ? match[1] : path.resolve(worktreeDir, match[1]);
+}
+
+function escapeRegExp(value) {
+ return String(value).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+}
+
+function ensureSession(cache, sessionId) {
+ if (!cache.sessions[sessionId]) {
+ cache.sessions[sessionId] = { updatedAt: Date.now(), files: {} };
+ }
+ return cache.sessions[sessionId];
+}
+
+function ensureFile(cache, sessionId, filePath) {
+ const session = ensureSession(cache, sessionId);
+ if (!session.files[filePath]) {
+ session.files[filePath] = { editCount: 0, findings: [] };
+ }
+ return session.files[filePath];
+}
+
+export function bumpEditCount(cache, sessionId, filePath) {
+ const fileEntry = ensureFile(cache, sessionId, filePath);
+ fileEntry.editCount = (fileEntry.editCount || 0) + 1;
+ ensureSession(cache, sessionId).updatedAt = Date.now();
+ return fileEntry.editCount;
+}
+
+export function suppressionNotice(filePath) {
+ return `${ENVELOPE_PREFIX} Suppressing further design hints on ${filePath}. More than ${EDIT_COUNT_THRESHOLD} edits in this session reached. Run /impeccable audit to revisit.`;
+}
+
+// Glob → RegExp. Supports `**`, `*`, `?`, and `{a,b}` alternation.
+function globToRegex(glob) {
+ let re = '^';
+ let i = 0;
+ while (i < glob.length) {
+ const c = glob[i];
+ if (c === '*') {
+ if (glob[i + 1] === '*') {
+ re += '.*';
+ i += 2;
+ if (glob[i] === '/') i += 1;
+ } else {
+ re += '[^/]*';
+ i += 1;
+ }
+ } else if (c === '?') {
+ re += '[^/]';
+ i += 1;
+ } else if (c === '{') {
+ const end = glob.indexOf('}', i);
+ if (end === -1) { re += '\\{'; i += 1; continue; }
+ const parts = glob.slice(i + 1, end).split(',').map((p) => p.replace(/[.+^$()|[\]\\]/g, '\\$&'));
+ re += `(?:${parts.join('|')})`;
+ i = end + 1;
+ } else if (/[.+^$()|[\]\\]/.test(c)) {
+ re += `\\${c}`;
+ i += 1;
+ } else {
+ re += c;
+ i += 1;
+ }
+ }
+ re += '$';
+ return new RegExp(re);
+}
+
+export function matchesAnyGlob(filePath, globs) {
+ if (!Array.isArray(globs) || globs.length === 0) return false;
+ const normalized = filePath.split(path.sep).join('/');
+ for (const glob of globs) {
+ try {
+ const re = globToRegex(String(glob));
+ if (re.test(normalized)) return true;
+ // Match against basename too for convenience: `*.generated.tsx` should
+ // catch `src/foo.generated.tsx` without requiring `**/`.
+ const base = normalized.split('/').pop();
+ if (re.test(base)) return true;
+ } catch {
+ /* malformed glob, skip */
+ }
+ }
+ return false;
+}
+
+export function filterFindings(findings, _content, _ext, config) {
+ if (!Array.isArray(findings) || findings.length === 0) return [];
+ const ignoreRules = new Set((config.ignoreRules || []).map((rule) => normalizeIgnoreRule(rule)));
+ const ignoreValues = normalizeIgnoreValueEntries(config.ignoreValues || []);
+ return findings.filter((f) => {
+ if (!f || typeof f !== 'object') return false;
+ if (ignoreRules.has(normalizeIgnoreRule(f.antipattern))) return false;
+ if (isIgnoredFindingValue(f, ignoreValues)) return false;
+ return true;
+ });
+}
+
+function isIgnoredFindingValue(finding, ignoreValues) {
+ if (!Array.isArray(ignoreValues) || ignoreValues.length === 0) return false;
+ const rule = normalizeIgnoreRule(finding.antipattern);
+ const value = extractFindingIgnoreValue(finding);
+ if (!rule || !value) return false;
+ return ignoreValues.some((entry) => entry.rule === rule && entry.value === value);
+}
+
+export function extractFindingIgnoreValue(finding) {
+ if (!finding || typeof finding !== 'object') return '';
+ const rule = normalizeIgnoreRule(finding.antipattern);
+ if (rule !== 'overused-font') return '';
+ return normalizeIgnoreValue(extractFindingIgnoreValueRaw(finding));
+}
+
+function extractFindingIgnoreValueRaw(finding) {
+ const direct = cleanIgnoreValueDisplay(finding.ignoreValue || finding.value || '');
+ if (direct) return direct;
+
+ const candidates = [finding.detail, finding.snippet].filter((v) => typeof v === 'string' && v);
+ for (const text of candidates) {
+ const primary = text.match(/Primary font:\s*([^()\n;]+)/i);
+ if (primary) return cleanIgnoreValueDisplay(primary[1]);
+
+ const family = text.match(/font-family\s*:\s*["']?([^'",;\n]+)/i);
+ if (family) return cleanIgnoreValueDisplay(family[1]);
+
+ const google = text.match(/[?&]family=([^&:;\n]+)/i);
+ if (google) {
+ try {
+ return cleanIgnoreValueDisplay(decodeURIComponent(google[1]));
+ } catch {
+ return cleanIgnoreValueDisplay(google[1]);
+ }
+ }
+ }
+
+ return '';
+}
+
+function cleanIgnoreValueDisplay(value) {
+ return String(value || '')
+ .trim()
+ .replace(/^["']|["']$/g, '')
+ .replace(/\+/g, ' ')
+ .replace(/\s+/g, ' ');
+}
+
+export function dedupeAgainstCache(findings, cache, sessionId, filePath) {
+ if (!Array.isArray(findings) || findings.length === 0) return [];
+ const fileEntry = ensureFile(cache, sessionId, filePath);
+ const known = new Set(fileEntry.findings || []);
+ const fresh = [];
+ for (const f of findings) {
+ const key = `${f.antipattern}:${f.line || 0}`;
+ if (known.has(key)) continue;
+ known.add(key);
+ fresh.push(f);
+ }
+ return fresh;
+}
+
+export function rememberFindings(cache, sessionId, filePath, findings) {
+ const fileEntry = ensureFile(cache, sessionId, filePath);
+ const known = new Set(fileEntry.findings || []);
+ for (const f of findings) known.add(`${f.antipattern}:${f.line || 0}`);
+ fileEntry.findings = Array.from(known);
+ ensureSession(cache, sessionId).updatedAt = Date.now();
+}
+
+export function renderTemplate(findings, filePath, config, opts = {}) {
+ if (!Array.isArray(findings) || findings.length === 0) return '';
+ const limits = config?.limits || DEFAULT_CONFIG.limits;
+ const cap = Math.max(1, limits.maxFindings || DEFAULT_CONFIG.limits.maxFindings);
+ const maxChars = Math.max(500, limits.maxChars || DEFAULT_CONFIG.limits.maxChars);
+
+ const cwd = opts.cwd || process.cwd();
+ const display = relativize(filePath, cwd);
+ const total = findings.length;
+ const shown = findings.slice(0, cap);
+ const remaining = total - shown.length;
+
+ const header = `${ENVELOPE_PREFIX} Required design corrections in ${display} (${total} issue(s)):`;
+ const lines = shown.map((f) => formatFindingLine(f));
+ const more = remaining > 0
+ ? `... and ${remaining} more (see /impeccable audit).`
+ : null;
+ const footer = directiveFooter(display);
+
+ const blocks = [header, ...lines];
+ if (more) blocks.push(more);
+ blocks.push('');
+ blocks.push(footer);
+ let text = blocks.join('\n');
+
+ if (text.length > maxChars) {
+ text = clampToBudget(header, lines, more, footer, maxChars);
+ }
+ return text;
+}
+
+function renderGroupedTemplate(groups, config, opts = {}) {
+ const realGroups = groups.filter((group) => Array.isArray(group.findings) && group.findings.length > 0);
+ if (realGroups.length === 0) return '';
+ if (realGroups.length === 1) {
+ const [group] = realGroups;
+ return renderTemplate(group.findings, group.filePath, config, opts);
+ }
+
+ const limits = config?.limits || DEFAULT_CONFIG.limits;
+ const cap = Math.max(1, limits.maxFindings || DEFAULT_CONFIG.limits.maxFindings);
+ const maxChars = Math.max(500, limits.maxChars || DEFAULT_CONFIG.limits.maxChars);
+ const cwd = opts.cwd || process.cwd();
+ const total = realGroups.reduce((sum, group) => sum + group.findings.length, 0);
+ const header = `${ENVELOPE_PREFIX} Required design corrections across ${realGroups.length} files (${total} issue(s)):`;
+ const lines = [];
+ let shownCount = 0;
+
+ for (const group of realGroups) {
+ const display = relativize(group.filePath, cwd);
+ lines.push(`${display} (${group.findings.length} issue(s)):`);
+ const remainingCap = Math.max(0, cap - shownCount);
+ const shown = group.findings.slice(0, remainingCap);
+ for (const finding of shown) {
+ lines.push(formatFindingLine(finding));
+ }
+ shownCount += shown.length;
+ const hidden = group.findings.length - shown.length;
+ if (hidden > 0) {
+ lines.push(`- ... ${hidden} more in ${display} (see /impeccable audit).`);
+ }
+ }
+
+ const footer = directiveFooter('the affected files', { grouped: true });
+ let text = [header, ...lines, '', footer].join('\n');
+ if (text.length > maxChars) {
+ text = clampGroupedToBudget(header, lines, footer, maxChars);
+ }
+ return text;
+}
+
+function clampGroupedToBudget(header, lines, footer, maxChars) {
+ const assemble = (linesArr, omitted) => [
+ header,
+ ...linesArr,
+ ...(omitted ? ['... and more (see /impeccable audit).'] : []),
+ '',
+ footer,
+ ].join('\n');
+
+ let working = lines.slice();
+ let omitted = false;
+ let assembled = assemble(working, omitted);
+ while (assembled.length > maxChars && working.length > 1) {
+ working.pop();
+ omitted = true;
+ assembled = assemble(working, omitted);
+ }
+ if (assembled.length > maxChars) {
+ assembled = `${assembled.slice(0, maxChars - 1)}…`;
+ }
+ return assembled;
+}
+
+function clampToBudget(header, lines, more, footer, maxChars) {
+ const assemble = (linesArr, moreText) => {
+ const blocks = [header, ...linesArr];
+ if (moreText) blocks.push(moreText);
+ blocks.push('');
+ blocks.push(footer);
+ return blocks.join('\n');
+ };
+
+ let working = lines.slice();
+ let moreText = more;
+ let assembled = assemble(working, moreText);
+ while (assembled.length > maxChars && working.length > 1) {
+ working.pop();
+ moreText = '... and more (see /impeccable audit).';
+ assembled = assemble(working, moreText);
+ }
+ if (assembled.length > maxChars) {
+ assembled = `${assembled.slice(0, maxChars - 1)}…`;
+ }
+ return assembled;
+}
+
+function formatFindingLine(f) {
+ const prefix = f.line && f.line > 0 ? `- L${f.line}` : '-';
+ const desc = (f.description || '').trim();
+ const name = (f.name || '').trim();
+ // Description from the registry already ends in punctuation; join with a
+ // single space. `name` may have a trailing period already, keep it clean.
+ const nameSegment = name ? `${name.replace(/\.+\s*$/, '')}.` : '';
+ const ignoreCommand = formatFindingIgnoreCommand(f);
+ const ignoreSegment = ignoreCommand
+ ? ` If the user explicitly confirms this value is intentional: \`${ignoreCommand}\`.`
+ : '';
+ return `${prefix} [${f.antipattern}] ${nameSegment} ${desc}${ignoreSegment}`.replace(/\s+/g, ' ').trim();
+}
+
+function formatFindingIgnoreCommand(finding) {
+ if (!finding || typeof finding !== 'object') return '';
+ const rule = normalizeIgnoreRule(finding.antipattern);
+ if (!rule) return '';
+ const normalizedValue = extractFindingIgnoreValue(finding);
+ if (!normalizedValue) return '';
+ const value = extractFindingIgnoreValueRaw(finding);
+ const valueArg = quoteCommandArg(value);
+ const reason = quoteCommandArg(`User confirmed ${value} is intentional`);
+ return `/impeccable hooks ignore-value ${rule} ${valueArg} --shared --reason ${reason}`;
+}
+
+function quoteCommandArg(value) {
+ const text = String(value || '').trim();
+ if (/^[A-Za-z0-9._:-]+$/.test(text)) return text;
+ return `"${text.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
+}
+
+function relativize(filePath, cwd) {
+ try {
+ const rel = path.relative(cwd, filePath);
+ if (!rel || rel.startsWith('..')) return filePath;
+ return rel.split(path.sep).join('/');
+ } catch {
+ return filePath;
+ }
+}
+
+// Codex `apply_patch` exposes the raw patch in `tool_input.command`, not
+// `tool_input.file_path`. Claude Code may send both; parse the patch body
+// so we can scan the file(s) the tool actually touched.
+// https://developers.openai.com/codex/hooks#posttooluse
+const APPLY_PATCH_FILE_RE = /^\*\*\* (?:Update|Add) File: (.+)$/gm;
+
+export function parseApplyPatchPaths(command, projectCwd) {
+ if (!command || typeof command !== 'string') return [];
+ const out = [];
+ for (const m of command.matchAll(APPLY_PATCH_FILE_RE)) {
+ let p = (m[1] || '').trim();
+ if (!p) continue;
+ if (!path.isAbsolute(p)) p = path.resolve(projectCwd, p);
+ out.push(p);
+ }
+ return out;
+}
+
+export function resolveTargetFiles(event, projectCwd) {
+ const ti = event?.tool_input;
+ const out = [];
+ const add = (filePath) => {
+ if (typeof filePath !== 'string' || !filePath) return;
+ if (!out.includes(filePath)) out.push(filePath);
+ };
+
+ if (event?.tool_name === 'apply_patch' && ti && typeof ti.command === 'string') {
+ for (const filePath of parseApplyPatchPaths(ti.command, projectCwd)) add(filePath);
+ }
+ if (ti && typeof ti.file_path === 'string' && ti.file_path) {
+ add(ti.file_path);
+ }
+ // Cursor Write / StrReplace use `path`, not `file_path`.
+ if (ti && typeof ti.path === 'string' && ti.path) {
+ add(ti.path);
+ }
+ if (typeof event?.file_path === 'string' && event.file_path) {
+ add(event.file_path);
+ }
+ return out;
+}
+
+export function resolveHarness(env = {}, event = null) {
+ const explicit = env?.IMPECCABLE_HOOK_HARNESS;
+ if (explicit === 'cursor') return 'cursor';
+ if (explicit === 'claude' || explicit === 'codex') return 'claude';
+ if (typeof event?.conversation_id === 'string' && event.conversation_id) return 'cursor';
+ return 'claude';
+}
+
+export function normalizeHookEvent(event, projectCwd, harness = 'claude') {
+ if (!event || typeof event !== 'object' || harness !== 'cursor') return event;
+
+ const cwd = event.cwd
+ || (Array.isArray(event.workspace_roots) && event.workspace_roots[0])
+ || envProjectDir(projectCwd)
+ || projectCwd;
+ const sessionId = event.session_id || event.conversation_id || 'unknown';
+
+ const ti = event.tool_input && typeof event.tool_input === 'object' ? event.tool_input : {};
+ const filePath = ti.file_path || ti.path || event.file_path;
+ if (filePath) {
+ return {
+ ...event,
+ cwd,
+ session_id: sessionId,
+ tool_input: { ...ti, file_path: filePath },
+ };
+ }
+
+ return { ...event, cwd, session_id: sessionId };
+}
+
+function envProjectDir(fallback) {
+ if (typeof process.env.CURSOR_PROJECT_DIR === 'string' && process.env.CURSOR_PROJECT_DIR) {
+ return process.env.CURSOR_PROJECT_DIR;
+ }
+ return fallback;
+}
+
+// UI components often keep slop in a sibling/co-located stylesheet while the
+// JSX edit is what triggered PostToolUse. Scan those styles too so an App.jsx
+// patch doesn't report "clean" while styles.css still has Inter/bounce/etc.
+const UI_CODE_EXTS = new Set(['.jsx', '.tsx', '.vue', '.svelte', '.astro']);
+const STYLE_EXTS = new Set(['.css', '.scss', '.sass', '.less']);
+const CO_SCAN_STYLE_NAMES = [
+ 'styles.css', 'styles.scss', 'styles.sass', 'styles.less',
+ 'index.css', 'index.scss', 'index.sass', 'index.less',
+ 'global.css', 'global.scss', 'global.sass', 'global.less',
+ 'globals.css', 'globals.scss', 'globals.sass', 'globals.less',
+];
+const MAX_SCAN_TARGETS = 6;
+
+const STATIC_STYLE_IMPORT_RE = /import\s+(?:[\w*{}\s,$]+\s+from\s+)?['"]([^'"]+\.(?:css|scss|sass|less))['"]/gi;
+
+function hasPathTraversal(filePath) {
+ return typeof filePath === 'string' && filePath.includes('..');
+}
+
+function isInsideProject(filePath, projectCwd) {
+ if (!filePath || !projectCwd || hasPathTraversal(filePath)) return false;
+ try {
+ const rel = path.relative(projectCwd, filePath);
+ return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));
+ } catch {
+ return false;
+ }
+}
+
+export function parseStaticStyleImports(content, fromFile, projectCwd) {
+ if (!content || typeof content !== 'string') return [];
+ const dir = path.dirname(fromFile);
+ const out = [];
+ for (const m of content.matchAll(STATIC_STYLE_IMPORT_RE)) {
+ let p = (m[1] || '').trim();
+ if (!p) continue;
+ if (p.startsWith('.')) p = path.resolve(dir, p);
+ else if (!path.isAbsolute(p)) p = path.resolve(projectCwd, p);
+ if (!isInsideProject(p, projectCwd)) continue;
+ out.push(p);
+ }
+ return out;
+}
+
+export function coLocatedStylesheets(filePath) {
+ const dir = path.dirname(filePath);
+ const base = path.basename(filePath, path.extname(filePath));
+ const candidates = new Set([
+ path.join(dir, `${base}.css`),
+ path.join(dir, `${base}.module.css`),
+ path.join(dir, `${base}.scss`),
+ path.join(dir, `${base}.module.scss`),
+ path.join(dir, `${base}.sass`),
+ path.join(dir, `${base}.module.sass`),
+ path.join(dir, `${base}.less`),
+ path.join(dir, `${base}.module.less`),
+ ]);
+ for (const name of CO_SCAN_STYLE_NAMES) {
+ candidates.add(path.join(dir, name));
+ }
+ return [...candidates].filter((p) => fs.existsSync(p));
+}
+
+export function normalizeScanTargets(primaryTargets, projectCwd) {
+ if (!Array.isArray(primaryTargets) || primaryTargets.length === 0) return [];
+ const ordered = [];
+ const seen = new Set();
+ const baseCwd = projectCwd || process.cwd();
+ const normalizeTarget = (p) => {
+ // Preserve literal `..` segments so downstream sensitive-path checks
+ // still fire. path.resolve would collapse `/foo/../etc/passwd`.
+ if (hasPathTraversal(p)) return p;
+ return path.isAbsolute(p) ? p : path.resolve(baseCwd, p);
+ };
+ const add = (p) => {
+ if (ordered.length >= MAX_SCAN_TARGETS) return;
+ const abs = normalizeTarget(p);
+ if (seen.has(abs)) return;
+ seen.add(abs);
+ ordered.push(abs);
+ return abs;
+ };
+
+ for (const p of primaryTargets) add(p);
+ return ordered;
+}
+
+export function expandScanTargets(primaryTargets, projectCwd) {
+ const ordered = normalizeScanTargets(primaryTargets, projectCwd);
+ if (ordered.length === 0) return [];
+ const seen = new Set(ordered);
+ const baseCwd = projectCwd || process.cwd();
+ const add = (p) => {
+ if (ordered.length >= MAX_SCAN_TARGETS) return;
+ const abs = hasPathTraversal(p) ? p : (path.isAbsolute(p) ? p : path.resolve(baseCwd, p));
+ if (seen.has(abs)) return;
+ seen.add(abs);
+ ordered.push(abs);
+ return abs;
+ };
+
+ const normalizedPrimaries = [];
+ for (const p of ordered) normalizedPrimaries.push(p);
+
+ for (const p of normalizedPrimaries) {
+ if (ordered.length >= MAX_SCAN_TARGETS) break;
+ if (!isInsideProject(p, baseCwd)) continue;
+ const ext = path.extname(p).toLowerCase();
+ if (STYLE_EXTS.has(ext) || !UI_CODE_EXTS.has(ext)) continue;
+
+ let content = '';
+ try { content = fs.readFileSync(p, 'utf-8'); } catch { /* unreadable primary */ }
+
+ for (const imp of parseStaticStyleImports(content, p, projectCwd)) {
+ add(imp);
+ if (ordered.length >= MAX_SCAN_TARGETS) break;
+ }
+ for (const col of coLocatedStylesheets(p)) {
+ add(col);
+ if (ordered.length >= MAX_SCAN_TARGETS) break;
+ }
+ }
+
+ return ordered;
+}
+
+export function writeAuditLog(env, entry) {
+ const target = env?.IMPECCABLE_HOOK_LOG;
+ if (!target || typeof target !== 'string') return false;
+ try {
+ const expanded = target.startsWith('~/')
+ ? path.join(process.env.HOME || process.env.USERPROFILE || '.', target.slice(2))
+ : target;
+ fs.mkdirSync(path.dirname(expanded), { recursive: true });
+ const line = JSON.stringify({ ts: new Date().toISOString(), ...entry }) + '\n';
+ fs.appendFileSync(expanded, line);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+const DETECTOR_CANDIDATES = [
+ path.join(__dirname, 'detector', 'detect-antipatterns.mjs'),
+ path.join(__dirname, '..', '..', 'cli', 'engine', 'detect-antipatterns.mjs'),
+ path.join(__dirname, '..', '..', '..', 'cli', 'engine', 'detect-antipatterns.mjs'),
+];
+
+let detectorCache = null;
+export async function loadDetector(candidates = DETECTOR_CANDIDATES) {
+ if (detectorCache) return detectorCache;
+ const found = candidates.find((c) => fs.existsSync(c));
+ if (!found) return null;
+ const mod = await import(pathToFileURL(found));
+ detectorCache = { detectText: mod.detectText, detectHtml: mod.detectHtml };
+ return detectorCache;
+}
+
+// For tests: allow injecting a detector implementation.
+export function setDetectorForTesting(impl) {
+ detectorCache = impl;
+}
+
+// ────────────────────────────────────────────────────────────────────────
+// Nudge/steer messages for the no-silent-fires policy.
+//
+// The hook is designed to be a conversational presence: every fire that
+// actually scans a file emits a developer-role message into the model's
+// next turn. Three states map to three templates:
+//
+// 1. **Fresh findings** → `renderTemplate` (existing, imperative).
+// 2. **Pending findings** → `renderPendingAck` (re-nudge for issues the
+// model was already told about in this
+// session but hasn't fixed yet).
+// 3. **Truly clean** → `renderCleanAck` (short positive nudge that
+// keeps the design discipline in context).
+//
+// All three are short (≤ ~40 tokens each) so the cumulative cost stays
+// bounded across a long active editing session. Users who explicitly want
+// silence-on-clean can set `IMPECCABLE_HOOK_QUIET=1` — runHook checks that
+// env before emitting #2 or #3.
+//
+// Why not stay silent on dedup-clean? Earlier versions did. The model
+// quickly forgets the prior reminder once tool output scrolls past it, so
+// re-nudging on the same file with a short "still pending" line keeps the
+// pressure on. The wording deliberately points back to "earlier this
+// session" so the model knows it's a re-mind, not a new finding.
+// ────────────────────────────────────────────────────────────────────────
+
+const STEER_LINE = 'Keep typography hierarchy, spacing rhythm, and color contrast intentional on the next change.';
+
+export function renderCleanAck(filePath, opts = {}) {
+ const cwd = opts.cwd || process.cwd();
+ const display = relativize(filePath, cwd);
+ return `${ENVELOPE_PREFIX} Design hook scanned ${display}. No anti-patterns. ${STEER_LINE}`;
+}
+
+export function renderPendingAck(filePath, knownFindings, opts = {}) {
+ const cwd = opts.cwd || process.cwd();
+ const display = relativize(filePath, cwd);
+ const count = knownFindings.length;
+ // `knownFindings` here are the cache strings like "side-tab:3".
+ const sample = knownFindings.slice(0, 3).join(', ');
+ const more = count > 3 ? `, +${count - 3} more` : '';
+ return `${ENVELOPE_PREFIX} Design hook scanned ${display}. Still has ${count} issue(s) flagged earlier this session (${sample}${more}). Address them before finalizing — the previous reminder still applies.`;
+}
+
+export function shouldEmitAckForFile(filePath) {
+ return ACK_EXTS.has(path.extname(String(filePath || '')).toLowerCase());
+}
+
+// The directive footer is the part of the hook output that steers model
+// behavior. Three intentional moves:
+// 1. **Imperative, not advisory.** "Fix these..." beats "Consider
+// revising..." which the model treats as a soft suggestion it can
+// override when the user asked for any kind of throwaway / demo UI.
+// 2. **Explicit exception clause.** Without it, the model will try to
+// "fix" intentional bad fixtures, anti-pattern examples in docs, or
+// test cases. Naming the exception inline beats hoping the model
+// infers it from context.
+// 3. **Acknowledgement instruction.** Hook output is injected as
+// developer-role context, not a chat turn, so the user never sees the
+// raw envelope. Asking the model to surface the fix in its reply is
+// the cheapest way to make the feedback loop visible to the user.
+function directiveFooter(display, opts = {}) {
+ const ignoreFileCommand = `/impeccable hooks ignore-file ${quoteCommandArg(display)}`;
+ const fileIgnoreGuidance = opts.grouped
+ ? 'run `/impeccable hooks ignore-file <path>` for the specific file'
+ : `run \`${ignoreFileCommand}\``;
+ return [
+ 'Fix these in your next reply before finalizing. Acknowledge what you changed so the user sees the correction.',
+ '',
+ 'Skip the fix only if the user explicitly asked for an intentionally bad UI, an anti-pattern example, a test fixture, or documentation of bad design. In that case, say so and continue.',
+ '',
+ `Do not add source comments such as \`impeccable: ignore\`; those pollute the code and do not suppress hook findings. Do not add hook ignores unless the user explicitly confirms the finding is intentional. Prefer the narrowest persisted exception: run the exact \`/impeccable hooks ignore-value ... --shared\` command shown next to a value-specific finding. For \`overused-font\`, use \`ignore-value\` for a specific font and use \`/impeccable hooks ignore-rule overused-font --all-values\` only when the user asks to ignore overused fonts generally. For file-specific findings without an ignore-value command, ${fileIgnoreGuidance}; use \`/impeccable hooks ignore-rule <id>\` only when the user asks to suppress the whole non-value-specific rule. Run /impeccable audit for the full pass.`,
+ ].join('\n');
+}
+
+/**
+ * Run the hook with explicit dependencies. Returns a result object:
+ * { exitCode, stdout, audit, reason? }
+ *
+ * Never throws. All errors are converted to `exitCode: 0` + audit entry.
+ */
+export async function runHook({ stdinJson, env = {}, cwd = process.cwd(), now = Date.now, detector } = {}) {
+ const audit = { ts: new Date(now()).toISOString(), event: 'PostToolUse' };
+ const result = (extra) => ({ exitCode: 0, stdout: '', audit: { ...audit, ...extra } });
+
+ try {
+ // Re-entrancy guard.
+ if (depthIsSet(env.IMPECCABLE_HOOK_DEPTH) || depthIsSet(env.CLAUDE_HOOK_DEPTH)) {
+ return result({ reentrant: true, durationMs: 0 });
+ }
+
+ if (truthy(env.IMPECCABLE_HOOK_DISABLED)) {
+ return result({ skipped: 'env-disabled', durationMs: 0 });
+ }
+
+ const started = Date.now();
+
+ let event;
+ try {
+ event = typeof stdinJson === 'string' ? JSON.parse(stdinJson) : stdinJson;
+ } catch {
+ return result({ skipped: 'stdin-malformed', durationMs: Date.now() - started });
+ }
+ if (!event || typeof event !== 'object') {
+ return result({ skipped: 'stdin-empty', durationMs: Date.now() - started });
+ }
+
+ const harness = resolveHarness(env, event);
+ event = normalizeHookEvent(event, cwd, harness);
+ audit.harness = harness;
+
+ const projectCwd = event.cwd || cwd;
+ const primaryFiles = normalizeScanTargets(resolveTargetFiles(event, projectCwd), projectCwd);
+ const primaryFileSet = new Set(primaryFiles);
+ const targetFiles = expandScanTargets(primaryFiles, projectCwd);
+ audit.session = event.session_id || null;
+ if (event.tool_name) audit.tool = event.tool_name;
+
+ if (targetFiles.length === 0) {
+ return result({ skipped: 'no-file-path', durationMs: Date.now() - started });
+ }
+
+ const config = readConfig(projectCwd);
+ if (config.enabled === false) {
+ return result({ skipped: 'config-disabled', durationMs: Date.now() - started });
+ }
+
+ const cache = readCache(projectCwd);
+ const sessionId = event.session_id || 'unknown';
+ const det = detector || await loadDetector();
+ if (!det || typeof det.detectText !== 'function') {
+ persistCache(projectCwd, cache);
+ return result({ skipped: 'detector-missing', durationMs: Date.now() - started });
+ }
+
+ let pendingWinner = null;
+ let cleanWinner = null;
+ const freshGroups = [];
+ let suppressionWinner = null;
+ let detectorThrewAny = false;
+ let lastSkip = 'no-scannable-file';
+ let suppressedHit = false;
+
+ for (const filePath of targetFiles) {
+ audit.file = filePath;
+
+ if (hasPathTraversal(filePath) || SENSITIVE_PATH.test(filePath)) {
+ lastSkip = 'sensitive';
+ continue;
+ }
+ if (GENERATED_PATH.test(filePath)) {
+ lastSkip = 'generated';
+ continue;
+ }
+
+ const ext = path.extname(filePath).toLowerCase();
+ audit.ext = ext;
+ if (!ALLOWED_EXTS.has(ext)) {
+ lastSkip = 'extension';
+ continue;
+ }
+
+ const relForMatch = relativize(filePath, projectCwd);
+ if (matchesAnyGlob(relForMatch, config.ignoreFiles) || matchesAnyGlob(filePath, config.ignoreFiles)) {
+ lastSkip = 'config-ignore-file';
+ continue;
+ }
+ if (!fs.existsSync(filePath)) {
+ lastSkip = 'file-missing';
+ continue;
+ }
+
+ if (primaryFileSet.has(filePath)) {
+ const editCount = bumpEditCount(cache, sessionId, filePath);
+ audit.editCount = editCount;
+
+ if (editCount > EDIT_COUNT_THRESHOLD) {
+ const wasJustCrossed = editCount === EDIT_COUNT_THRESHOLD + 1;
+ if (wasJustCrossed && !suppressionWinner) {
+ suppressionWinner = { filePath };
+ }
+ lastSkip = 'suppressed';
+ suppressedHit = true;
+ continue;
+ }
+ }
+
+ const content = fs.readFileSync(filePath, 'utf-8');
+ let findings;
+ let detectorThrew = false;
+ if ((ext === '.html' || ext === '.htm') && typeof det.detectHtml === 'function') {
+ try { findings = await det.detectHtml(filePath); } catch { findings = []; detectorThrew = true; }
+ } else {
+ try { findings = await det.detectText(content, filePath); } catch { findings = []; detectorThrew = true; }
+ }
+
+ const filtered = filterFindings(findings || [], content, ext, config);
+ const fresh = dedupeAgainstCache(filtered, cache, sessionId, filePath);
+ audit.findings = (findings || []).length;
+ audit.freshFindings = fresh.length;
+
+ if (fresh.length > 0) {
+ rememberFindings(cache, sessionId, filePath, fresh);
+ freshGroups.push({ filePath, findings: fresh });
+ continue;
+ }
+
+ if (detectorThrew) {
+ detectorThrewAny = true;
+ continue;
+ }
+
+ if (filtered.length > 0 && !pendingWinner) {
+ const known = (ensureFile(cache, sessionId, filePath).findings || []).slice();
+ pendingWinner = { filePath, known };
+ } else if (filtered.length === 0 && !cleanWinner) {
+ cleanWinner = { filePath };
+ }
+ }
+
+ persistCache(projectCwd, cache);
+
+ if (freshGroups.length > 0) {
+ const firstGroup = freshGroups[0];
+ const text = renderGroupedTemplate(freshGroups, config, { cwd: projectCwd });
+ const allFindings = freshGroups.flatMap((group) => group.findings);
+ return {
+ exitCode: 0,
+ stdout: payload(text, 'PostToolUse', harness),
+ emission: {
+ kind: 'fresh',
+ file: firstGroup.filePath,
+ findings: firstGroup.findings,
+ groups: freshGroups,
+ },
+ audit: {
+ ...audit,
+ file: firstGroup.filePath,
+ emitted: true,
+ freshFiles: freshGroups.length,
+ freshFindings: allFindings.length,
+ chars: text.length,
+ durationMs: Date.now() - started,
+ },
+ };
+ }
+
+ if (detectorThrewAny && !pendingWinner && !cleanWinner) {
+ return result({ emitted: false, error: 'detector-threw', durationMs: Date.now() - started });
+ }
+
+ if (truthy(env.IMPECCABLE_HOOK_QUIET)) {
+ return result({ emitted: false, quiet: true, durationMs: Date.now() - started });
+ }
+
+ if (pendingWinner && shouldEmitAckForFile(pendingWinner.filePath)) {
+ const text = renderPendingAck(pendingWinner.filePath, pendingWinner.known, { cwd: projectCwd });
+ return {
+ exitCode: 0,
+ stdout: payload(text, 'PostToolUse', harness),
+ emission: { kind: 'pending', file: pendingWinner.filePath, known: pendingWinner.known },
+ audit: {
+ ...audit,
+ file: pendingWinner.filePath,
+ emitted: true,
+ kind: 'pending',
+ pending: pendingWinner.known.length,
+ chars: text.length,
+ durationMs: Date.now() - started,
+ },
+ };
+ }
+
+ if (suppressionWinner) {
+ const text = suppressionNotice(relativize(suppressionWinner.filePath, projectCwd));
+ return {
+ exitCode: 0,
+ stdout: payload(text, 'PostToolUse', harness),
+ emission: { kind: 'suppression', file: suppressionWinner.filePath },
+ audit: {
+ ...audit,
+ file: suppressionWinner.filePath,
+ suppressed: true,
+ emitted: true,
+ durationMs: Date.now() - started,
+ },
+ };
+ }
+
+ if (cleanWinner && shouldEmitAckForFile(cleanWinner.filePath)) {
+ const text = renderCleanAck(cleanWinner.filePath, { cwd: projectCwd });
+ return {
+ exitCode: 0,
+ stdout: payload(text, 'PostToolUse', harness),
+ emission: { kind: 'clean', file: cleanWinner.filePath },
+ audit: {
+ ...audit,
+ file: cleanWinner.filePath,
+ emitted: true,
+ kind: 'clean',
+ chars: text.length,
+ durationMs: Date.now() - started,
+ },
+ };
+ }
+
+ if (pendingWinner || cleanWinner) {
+ return result({ emitted: false, skipped: 'non-ui-ack', durationMs: Date.now() - started });
+ }
+
+ if (suppressedHit) {
+ return result({ suppressed: true, emitted: false, durationMs: Date.now() - started });
+ }
+
+ return result({ skipped: lastSkip, durationMs: Date.now() - started });
+ } catch (err) {
+ return {
+ exitCode: 0,
+ stdout: '',
+ audit: { ...audit, error: String(err && err.message ? err.message : err) },
+ };
+ }
+}
+
+export function payload(text, eventName = 'PostToolUse', harness = 'claude') {
+ if (harness === 'cursor') {
+ return JSON.stringify({ additional_context: text });
+ }
+ return JSON.stringify({
+ hookSpecificOutput: { hookEventName: eventName, additionalContext: text },
+ });
+}
diff --git a/skill/scripts/hook.mjs b/skill/scripts/hook.mjs
new file mode 100644
index 000000000..b862f8033
--- /dev/null
+++ b/skill/scripts/hook.mjs
@@ -0,0 +1,61 @@
+#!/usr/bin/env node
+/**
+ * Impeccable design hook — PostToolUse entry point.
+ *
+ * Reads the Claude Code / Codex / Cursor hook event from stdin, runs the design
+ * detector against the touched file, and emits a system reminder via
+ * `hookSpecificOutput.additionalContext` when findings exist.
+ *
+ * Contract: never break a turn. Always exit 0. Clean files emit a small ack
+ * unless quiet mode is enabled.
+ *
+ * Most logic lives in `hook-lib.mjs` so it is unit-testable without a
+ * subprocess. This file is the thin stdin/stdout adapter.
+ */
+
+import { runHook, 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');
+}
+
+async function main() {
+ // Snapshot the inherited env FIRST so the re-entrancy guard checks the
+ // parent's value, not the value we are about to export for any child
+ // processes the hook might ever spawn.
+ const inheritedEnv = { ...process.env };
+ process.env.IMPECCABLE_HOOK_DEPTH = process.env.IMPECCABLE_HOOK_DEPTH || '1';
+
+ let stdinJson = '';
+ try { stdinJson = await readStdin(); } catch { /* fall through */ }
+
+ const result = await runHook({
+ stdinJson,
+ env: inheritedEnv,
+ cwd: process.cwd(),
+ });
+
+ writeAuditLog(process.env, result.audit);
+
+ if (result.stdout) process.stdout.write(result.stdout);
+ process.exit(result.exitCode || 0);
+}
+
+main().catch((err) => {
+ // Last-ditch: never break the agent's turn even if something we did not
+ // anticipate goes wrong. Audit-log the failure if logging is enabled.
+ try {
+ writeAuditLog(process.env, {
+ ts: new Date().toISOString(),
+ event: 'PostToolUse',
+ error: String(err && err.message ? err.message : err),
+ });
+ } catch { /* swallow */ }
+ if (process.env.IMPECCABLE_HOOK_DEBUG) {
+ process.stderr.write(`[impeccable-hook] ${err}\n`);
+ }
+ process.exit(0);
+});
diff --git a/skill/scripts/live-inject.mjs b/skill/scripts/live-inject.mjs
index 4e5c5dc0a..69ce530c1 100644
--- a/skill/scripts/live-inject.mjs
+++ b/skill/scripts/live-inject.mjs
@@ -32,6 +32,8 @@ const IGNORE_MARKER_CLOSE = '# impeccable-live-ignore-end';
export const LIVE_IGNORE_PATTERNS = Object.freeze([
'.impeccable/hook.cache.json',
+ '.impeccable/hook.pending.json',
+ '.impeccable/hook.local.json',
'.impeccable/live/server.json',
'.impeccable/live/sessions/',
'.impeccable/live/previews/',
diff --git a/tests/detect-antipatterns-browser.test.mjs b/tests/detect-antipatterns-browser.test.mjs
index e37a92ac0..9511a6c89 100644
--- a/tests/detect-antipatterns-browser.test.mjs
+++ b/tests/detect-antipatterns-browser.test.mjs
@@ -181,6 +181,14 @@ describe('detectUrl — browser-only fixtures', () => {
}
});
+ it('overused-font: hook inline-ignore comments do not suppress browser findings', async () => {
+ const f = await detectUrl(`${baseUrl}/fixtures/antipatterns/hook-inline-ignore.html`);
+ assert.ok(
+ f.some(r => r.antipattern === 'overused-font' || r.type === 'overused-font' || r.id === 'overused-font'),
+ `expected browser scan to include overused-font despite inline comments: ${JSON.stringify(f)}`,
+ );
+ });
+
it('body-text-viewport-edge: 3 flag paragraphs/list-items, 0 pass cases', async () => {
const f = await detectUrl(`${baseUrl}/fixtures/antipatterns/body-text-viewport-edge.html`);
const edges = f.filter(r => r.antipattern === 'body-text-viewport-edge');
diff --git a/tests/detect-antipatterns.test.js b/tests/detect-antipatterns.test.js
index 935d30673..b3b1b6bdb 100644
--- a/tests/detect-antipatterns.test.js
+++ b/tests/detect-antipatterns.test.js
@@ -152,6 +152,11 @@ describe('detectText — CSS borders', () => {
expect(f.some(r => r.antipattern === 'side-tab')).toBe(true);
});
+ test('detects border-left shorthand in Sass', () => {
+ const f = detectText(".card\n border-left: 4px solid #3b82f6", 'test.sass');
+ expect(f.some(r => r.antipattern === 'side-tab')).toBe(true);
+ });
+
test('ignores neutral border', () => {
const f = detectText('.card { border-left: 4px solid #e5e7eb; }', 'test.css');
expect(f.filter(r => r.antipattern === 'side-tab')).toHaveLength(0);
@@ -802,6 +807,10 @@ describe('ANTIPATTERNS registry', () => {
// ---------------------------------------------------------------------------
describe('walkDir', () => {
+ test('includes Sass files in scannable extensions', () => {
+ expect(SCANNABLE_EXTENSIONS.has('.sass')).toBe(true);
+ });
+
test('finds scannable files', () => {
const files = walkDir(FIXTURES);
expect(files.length).toBeGreaterThanOrEqual(3);
@@ -1398,6 +1407,16 @@ describe('buildImportGraph', () => {
expect(themeImports.has(path.join(MF, 'variables.scss'))).toBe(true);
});
+ test('resolves Sass @import', () => {
+ const graph = buildImportGraph([
+ path.join(MF, 'theme.sass'),
+ path.join(MF, 'variables.sass'),
+ ]);
+ const themeImports = graph.get(path.join(MF, 'theme.sass'));
+ expect(themeImports).toBeDefined();
+ expect(themeImports.has(path.join(MF, 'variables.sass'))).toBe(true);
+ });
+
test('ignores bare/node_modules imports', () => {
const graph = buildImportGraph([
path.join(MF, 'App.tsx'),
diff --git a/tests/fixtures/antipatterns/hook-inline-ignore.html b/tests/fixtures/antipatterns/hook-inline-ignore.html
new file mode 100644
index 000000000..e5739a4e0
--- /dev/null
+++ b/tests/fixtures/antipatterns/hook-inline-ignore.html
@@ -0,0 +1,56 @@
+<!doctype html>
+<html>
+ <head>
+ <meta charset="utf-8">
+ <title>Hook inline ignore comments do not suppress detector findings</title>
+ <style>
+ /* impeccable: ignore overused-font */
+ body {
+ font-family: "Roboto", ui-sans-serif, system-ui, sans-serif;
+ margin: 0;
+ padding: 48px;
+ }
+
+ main {
+ max-width: 62ch;
+ }
+ </style>
+ </head>
+ <body>
+ <!-- impeccable: ignore overused-font -->
+ <main>
+ <h1>Roboto remains a detector finding</h1>
+ <p>
+ This fixture deliberately uses Roboto across enough visible text for
+ the browser detector to report the overused-font page finding. Hook
+ exceptions must live in .impeccable/hook.json instead of source comments.
+ </p>
+ <p>
+ The comments above look like old inline hook suppressions, but they are
+ intentionally inert and should not hide the finding from headless scans.
+ </p>
+ <ul>
+ <li>Roboto usage sample one.</li>
+ <li>Roboto usage sample two.</li>
+ <li>Roboto usage sample three.</li>
+ <li>Roboto usage sample four.</li>
+ <li>Roboto usage sample five.</li>
+ <li>Roboto usage sample six.</li>
+ <li>Roboto usage sample seven.</li>
+ <li>Roboto usage sample eight.</li>
+ <li>Roboto usage sample nine.</li>
+ <li>Roboto usage sample ten.</li>
+ <li>Roboto usage sample eleven.</li>
+ <li>Roboto usage sample twelve.</li>
+ <li>Roboto usage sample thirteen.</li>
+ <li>Roboto usage sample fourteen.</li>
+ <li>Roboto usage sample fifteen.</li>
+ <li>Roboto usage sample sixteen.</li>
+ <li>Roboto usage sample seventeen.</li>
+ <li>Roboto usage sample eighteen.</li>
+ <li>Roboto usage sample nineteen.</li>
+ <li>Roboto usage sample twenty.</li>
+ </ul>
+ </main>
+ </body>
+</html>
diff --git a/tests/fixtures/antipatterns/multifile/theme.sass b/tests/fixtures/antipatterns/multifile/theme.sass
new file mode 100644
index 000000000..f8611c57e
--- /dev/null
+++ b/tests/fixtures/antipatterns/multifile/theme.sass
@@ -0,0 +1,5 @@
+@import './variables'
+
+.card
+ border-left: 4px solid $primary
+ border-radius: 12px
diff --git a/tests/fixtures/antipatterns/multifile/variables.sass b/tests/fixtures/antipatterns/multifile/variables.sass
new file mode 100644
index 000000000..2aba0d8ba
--- /dev/null
+++ b/tests/fixtures/antipatterns/multifile/variables.sass
@@ -0,0 +1,3 @@
+$primary: #3b82f6
+$radius: 12px
+$spacing: 16px
diff --git a/tests/framework-fixtures/vite8-react-insert/fixture.json b/tests/framework-fixtures/vite8-react-insert/fixture.json
index b91dada73..6e447d19e 100644
--- a/tests/framework-fixtures/vite8-react-insert/fixture.json
+++ b/tests/framework-fixtures/vite8-react-insert/fixture.json
@@ -21,6 +21,8 @@
"position": "after",
"prompt": "Add a testimonial strip below features",
"expectSelector": ".inserted-strip",
+ "expectSelectorLlm": "[class*=\"testimonial\"]",
+ "expectSourcePattern": "testimonial",
"assertAnchorContains": "feature-grid"
},
"probe": {
diff --git a/tests/hook-build.test.mjs b/tests/hook-build.test.mjs
new file mode 100644
index 000000000..fc4a5df2e
--- /dev/null
+++ b/tests/hook-build.test.mjs
@@ -0,0 +1,173 @@
+/**
+ * Integration tests for the design-hook build pipeline.
+ * Run: node --test tests/hook-build.test.mjs
+ */
+
+import { describe, it } from 'node:test';
+import assert from 'node:assert/strict';
+import fs from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath, pathToFileURL } from 'node:url';
+
+import {
+ buildClaudeSettingsManifest,
+ buildCodexHooksManifest,
+ buildCursorHooksManifest,
+ hooksJsonFor,
+} from '../scripts/lib/transformers/hooks.js';
+
+const REPO_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+
+function readJson(rel) {
+ return JSON.parse(fs.readFileSync(path.join(REPO_ROOT, rel), 'utf8'));
+}
+
+function expectCommand(command, expectedPath) {
+ assert.equal(typeof command, 'string');
+ assert.match(command, /^node "/);
+ assert.ok(command.includes(expectedPath), `missing ${expectedPath} in ${command}`);
+ assert.ok(!command.includes('hook-probe.mjs'), `probe hook still referenced in ${command}`);
+}
+
+describe('hook manifest builders', () => {
+ it('builds Claude project settings for the real detector hook', () => {
+ const manifest = buildClaudeSettingsManifest();
+ const group = manifest.hooks.PostToolUse[0];
+ const handler = group.hooks[0];
+
+ assert.equal(group.matcher, 'Edit|Write|MultiEdit');
+ assert.equal(handler.type, 'command');
+ assert.equal(handler.timeout, 5);
+ assert.equal(handler.statusMessage, 'Scanning design');
+ expectCommand(handler.command, '.claude/skills/impeccable/scripts/hook.mjs');
+ assert.ok(handler.command.includes('${CLAUDE_PROJECT_DIR}'));
+ assert.equal(handler.args, undefined);
+ assert.equal(manifest.hooks.SessionStart, undefined);
+ });
+
+ it('builds Codex project-local hooks for the real detector hook', () => {
+ const manifest = buildCodexHooksManifest();
+ const group = manifest.hooks.PostToolUse[0];
+ const handler = group.hooks[0];
+
+ assert.equal(group.matcher, 'Edit|Write|apply_patch');
+ assert.equal(handler.type, 'command');
+ assert.equal(handler.timeout, 5);
+ assert.equal(handler.statusMessage, 'Scanning design');
+ expectCommand(handler.command, '.agents/skills/impeccable/scripts/hook.mjs');
+ assert.ok(handler.command.includes('git rev-parse --show-toplevel'));
+ assert.ok(!handler.command.includes('${PLUGIN_ROOT}'));
+ assert.equal(manifest.hooks.SessionStart, undefined);
+ });
+
+ it('builds one Cursor pre-write blocking hook', () => {
+ const manifest = buildCursorHooksManifest();
+ const beforeEdit = manifest.hooks.preToolUse[0];
+
+ assert.equal(manifest.version, 1);
+ assert.ok(Array.isArray(manifest.hooks.preToolUse));
+ assert.equal(Object.keys(manifest.hooks).length, 1);
+ assert.equal(manifest.hooks.afterFileEdit, undefined);
+ assert.equal(manifest.hooks.stop, undefined);
+ assert.equal(manifest.hooks.sessionStart, undefined);
+ expectCommand(beforeEdit.command, '.cursor/skills/impeccable/scripts/hook-before-edit.mjs');
+ assert.equal(beforeEdit.timeout, 5);
+ });
+
+ it('routes supported hook builders and leaves other providers alone', () => {
+ assert.ok(hooksJsonFor('claude'));
+ assert.ok(hooksJsonFor('codex'));
+ assert.ok(hooksJsonFor('cursor'));
+ assert.equal(hooksJsonFor('gemini'), null);
+ });
+});
+
+describe('generated hook artifacts in repo', () => {
+ for (const rel of [
+ '.claude/settings.json',
+ '.cursor/hooks.json',
+ '.codex/hooks.json',
+ ]) {
+ it(`${rel} exists and is valid JSON`, () => {
+ const abs = path.join(REPO_ROOT, rel);
+ assert.ok(fs.existsSync(abs), `${rel} missing - did you forget bun run build?`);
+ assert.doesNotThrow(() => JSON.parse(fs.readFileSync(abs, 'utf8')));
+ });
+ }
+
+ it('root hook manifests exactly match the hook builders', () => {
+ assert.deepEqual(readJson('.claude/settings.json'), buildClaudeSettingsManifest());
+ assert.deepEqual(readJson('.cursor/hooks.json'), buildCursorHooksManifest());
+ assert.deepEqual(readJson('.codex/hooks.json'), buildCodexHooksManifest());
+ });
+
+ it('Claude project settings reference hook.mjs in .claude/skills', () => {
+ const manifest = readJson('.claude/settings.json');
+ const handler = manifest.hooks.PostToolUse[0].hooks[0];
+
+ expectCommand(handler.command, '.claude/skills/impeccable/scripts/hook.mjs');
+ assert.ok(fs.existsSync(path.join(REPO_ROOT, '.claude/skills/impeccable/scripts/hook.mjs')));
+ assert.ok(fs.existsSync(path.join(REPO_ROOT, '.claude/skills/impeccable/scripts/hook-lib.mjs')));
+ assert.ok(fs.existsSync(path.join(REPO_ROOT, '.claude/skills/impeccable/scripts/detector/detect-antipatterns.mjs')));
+ });
+
+ it('Cursor project hooks reference only the pre-write runtime in .cursor/skills', () => {
+ const manifest = readJson('.cursor/hooks.json');
+ const beforeEdit = manifest.hooks.preToolUse[0];
+
+ assert.equal(Object.keys(manifest.hooks).length, 1);
+ expectCommand(beforeEdit.command, '.cursor/skills/impeccable/scripts/hook-before-edit.mjs');
+ assert.ok(fs.existsSync(path.join(REPO_ROOT, '.cursor/skills/impeccable/scripts/hook-before-edit.mjs')));
+ assert.equal(fs.existsSync(path.join(REPO_ROOT, '.cursor/skills/impeccable/scripts/hook-after-edit.mjs')), false);
+ assert.equal(fs.existsSync(path.join(REPO_ROOT, '.cursor/skills/impeccable/scripts/hook-stop.mjs')), false);
+ assert.ok(fs.existsSync(path.join(REPO_ROOT, '.cursor/skills/impeccable/scripts/hook-lib.mjs')));
+ assert.ok(fs.existsSync(path.join(REPO_ROOT, '.cursor/skills/impeccable/scripts/detector/detect-antipatterns.mjs')));
+ });
+
+ it('Codex project hooks reference hook.mjs in the .agents skill payload', () => {
+ const manifest = readJson('.codex/hooks.json');
+ const handler = manifest.hooks.PostToolUse[0].hooks[0];
+
+ expectCommand(handler.command, '.agents/skills/impeccable/scripts/hook.mjs');
+ assert.ok(fs.existsSync(path.join(REPO_ROOT, '.agents/skills/impeccable/SKILL.md')));
+ assert.ok(fs.existsSync(path.join(REPO_ROOT, '.agents/skills/impeccable/scripts/hook.mjs')));
+ assert.ok(fs.existsSync(path.join(REPO_ROOT, '.agents/skills/impeccable/scripts/hook-lib.mjs')));
+ assert.ok(fs.existsSync(path.join(REPO_ROOT, '.agents/skills/impeccable/scripts/detector/detect-antipatterns.mjs')));
+ });
+
+ it('does not generate probe scripts into provider skill payloads', () => {
+ for (const providerDir of ['.claude', '.cursor', '.agents', 'plugin']) {
+ const probe = path.join(REPO_ROOT, providerDir, 'skills', 'impeccable', 'scripts', 'hook-probe.mjs');
+ assert.equal(fs.existsSync(probe), false, `${providerDir} still has hook-probe.mjs`);
+ }
+ });
+
+ it('does not generate plugin or stale Codex hook packaging artifacts', () => {
+ for (const rel of [
+ '.claude/hooks/hooks.json',
+ '.agents/hooks',
+ '.agents/plugins/marketplace.json',
+ 'plugin-codex',
+ 'plugin/hooks/hooks.json',
+ 'plugin/.codex-plugin/plugin.json',
+ ]) {
+ assert.equal(fs.existsSync(path.join(REPO_ROOT, rel)), false, `${rel} should not exist`);
+ }
+ });
+
+ it('generated hook runtime can import the bundled detector', async () => {
+ for (const scriptDir of [
+ '.claude/skills/impeccable/scripts',
+ '.cursor/skills/impeccable/scripts',
+ '.agents/skills/impeccable/scripts',
+ 'plugin/skills/impeccable/scripts',
+ ]) {
+ const abs = path.join(REPO_ROOT, scriptDir);
+ assert.ok(fs.existsSync(path.join(abs, 'detector', 'detect-antipatterns.mjs')),
+ `detector bundle missing in ${scriptDir}`);
+ const hookLib = await import(pathToFileURL(path.join(abs, 'hook-lib.mjs')));
+ const detector = await hookLib.loadDetector();
+ assert.equal(typeof detector.detectText, 'function');
+ }
+ });
+});
diff --git a/tests/hook.test.mjs b/tests/hook.test.mjs
new file mode 100644
index 000000000..9d98fc6f5
--- /dev/null
+++ b/tests/hook.test.mjs
@@ -0,0 +1,1570 @@
+/**
+ * Unit tests for the Impeccable design hook.
+ * Run: node --test tests/hook.test.mjs
+ *
+ * Exercises hook-lib.mjs through `runHook()` with an injected detector so the
+ * suite stays fast and detector-independent. A second block exercises the
+ * library helpers (config, cache, filter, render) directly.
+ */
+
+import { describe, it, beforeEach, afterEach } from 'node:test';
+import assert from 'node:assert/strict';
+import fs from 'node:fs';
+import path from 'node:path';
+import os from 'node:os';
+import { execFileSync } from 'node:child_process';
+
+import {
+ ENVELOPE_PREFIX,
+ ALLOWED_EXTS,
+ ACK_EXTS,
+ DEFAULT_CONFIG,
+ SENSITIVE_PATH,
+ GENERATED_PATH,
+ truthy,
+ getConfigPath,
+ getLocalConfigPath,
+ ensureHookGitExcludes,
+ readConfig,
+ readCache,
+ persistCache,
+ bumpEditCount,
+ rememberFindings,
+ dedupeAgainstCache,
+ filterFindings,
+ renderTemplate,
+ renderCleanAck,
+ renderPendingAck,
+ shouldEmitAckForFile,
+ matchesAnyGlob,
+ writeAuditLog,
+ suppressionNotice,
+ parseApplyPatchPaths,
+ resolveTargetFiles,
+ resolveHarness,
+ normalizeHookEvent,
+ expandScanTargets,
+ parseStaticStyleImports,
+ coLocatedStylesheets,
+ runHook,
+ payload,
+ extractFindingIgnoreValue,
+} from '../skill/scripts/hook-lib.mjs';
+import { detectHtml, detectText } from '../cli/engine/detect-antipatterns.mjs';
+
+function mkTmp() {
+ return fs.mkdtempSync(path.join(os.tmpdir(), 'impeccable-hook-'));
+}
+
+function fakeDetector(findings) {
+ return {
+ detectText: () => findings,
+ detectHtml: () => findings,
+ };
+}
+
+function finding(id, line, extras = {}) {
+ return {
+ antipattern: id,
+ name: extras.name || 'Test finding',
+ description: extras.description || 'A test finding description.',
+ severity: extras.severity || 'warning',
+ file: extras.file || 'src/Card.tsx',
+ line,
+ snippet: extras.snippet || '<snippet>',
+ };
+}
+
+describe('truthy()', () => {
+ it('matches the documented values, case-insensitive', () => {
+ for (const v of ['1', 'true', 'TRUE', 'yes', 'YES', 'on', 'On']) {
+ assert.equal(truthy(v), true, `expected truthy("${v}")`);
+ }
+ for (const v of ['', '0', 'false', 'no', 'off', 'yep', undefined, null, 42]) {
+ assert.equal(truthy(v), false, `expected falsy(${JSON.stringify(v)})`);
+ }
+ });
+});
+
+describe('SENSITIVE_PATH / GENERATED_PATH', () => {
+ it('skips .env, .pem, id_rsa, secrets, credentials, .git', () => {
+ for (const p of [
+ '/x/.env', '/x/.env.production', '/x/server.pem', '/x/id_rsa',
+ '/x/id_rsa.pub', '/x/api-secret.json', '/x/client_secret.ts',
+ '/x/credentials.yml', '/x/.git/config',
+ ]) {
+ assert.ok(SENSITIVE_PATH.test(p), `expected sensitive: ${p}`);
+ }
+ });
+
+ it('does not flag normal source files as sensitive', () => {
+ for (const p of [
+ '/x/src/Card.tsx',
+ '/x/app/page.html',
+ '/x/styles/main.css',
+ '/x/src/CredentialForm.tsx',
+ '/x/src/SecretPage.jsx',
+ '/x/src/secretary-dashboard.vue',
+ '/x/src/credentials-panel.tsx',
+ ]) {
+ assert.ok(!SENSITIVE_PATH.test(p), `unexpected sensitive: ${p}`);
+ }
+ });
+
+ it('skips generated / lock / build output paths', () => {
+ for (const p of [
+ '/x/src/foo.generated.tsx', '/x/types.d.ts', '/x/bundle.min.js',
+ '/x/node_modules/lib/index.tsx', '/x/dist/Card.tsx', '/x/build/index.html',
+ '/x/pkg.lock.json', '/x/.next/server.js', '/x/coverage/report.html',
+ ]) {
+ assert.ok(GENERATED_PATH.test(p), `expected generated: ${p}`);
+ }
+ });
+});
+
+describe('readConfig()', () => {
+ let cwd;
+ beforeEach(() => { cwd = mkTmp(); });
+ afterEach(() => fs.rmSync(cwd, { recursive: true, force: true }));
+
+ it('returns defaults when file missing', () => {
+ const cfg = readConfig(cwd);
+ assert.equal(cfg.enabled, true);
+ assert.equal(cfg.limits.maxFindings, DEFAULT_CONFIG.limits.maxFindings);
+ });
+
+ it('parses enabled, ignoreRules, ignoreFiles, limits', () => {
+ fs.mkdirSync(path.join(cwd, '.impeccable'), { recursive: true });
+ fs.writeFileSync(path.join(cwd, '.impeccable', 'hook.json'), JSON.stringify({
+ enabled: false,
+ ignoreRules: ['side-tab'],
+ ignoreFiles: ['src/legacy/**'],
+ minSeverity: 'error',
+ limits: { maxFindings: 2, maxChars: 1000 },
+ }));
+ const cfg = readConfig(cwd);
+ assert.equal(cfg.enabled, false);
+ assert.deepEqual(cfg.ignoreRules, ['side-tab']);
+ assert.deepEqual(cfg.ignoreFiles, ['src/legacy/**']);
+ assert.deepEqual(cfg.ignoreValues, []);
+ assert.equal(cfg.limits.maxFindings, 2);
+ assert.equal(cfg.limits.maxChars, 1000);
+ });
+
+ it('merges shared config first and local config second', () => {
+ fs.mkdirSync(path.join(cwd, '.impeccable'), { recursive: true });
+ fs.writeFileSync(getConfigPath(cwd), JSON.stringify({
+ enabled: false,
+ ignoreRules: ['side-tab'],
+ ignoreFiles: ['src/legacy/**'],
+ ignoreValues: [
+ { rule: 'overused-font', value: 'inter', reason: 'team default' },
+ ],
+ minSeverity: 'error',
+ limits: { maxFindings: 2, maxChars: 1000 },
+ }));
+ fs.writeFileSync(getLocalConfigPath(cwd), JSON.stringify({
+ enabled: true,
+ ignoreRules: ['gradient-text', 'side-tab'],
+ ignoreFiles: ['src/local/**'],
+ ignoreValues: [
+ { rule: 'overused-font', value: 'Roboto' },
+ { rule: 'overused-font', value: 'Inter', reason: 'local override' },
+ ],
+ minSeverity: 'warning',
+ limits: { maxFindings: 4 },
+ }));
+
+ const cfg = readConfig(cwd);
+ assert.equal(cfg.enabled, true);
+ assert.deepEqual(cfg.ignoreRules, ['side-tab', 'gradient-text']);
+ assert.deepEqual(cfg.ignoreFiles, ['src/legacy/**', 'src/local/**']);
+ assert.deepEqual(cfg.ignoreValues, [
+ { rule: 'overused-font', value: 'inter', reason: 'local override' },
+ { rule: 'overused-font', value: 'roboto' },
+ ]);
+ assert.equal(cfg.limits.maxFindings, 4);
+ assert.equal(cfg.limits.maxChars, 1000);
+ });
+
+ it('tolerates malformed JSON and falls back to defaults', () => {
+ fs.mkdirSync(path.join(cwd, '.impeccable'), { recursive: true });
+ fs.writeFileSync(path.join(cwd, '.impeccable', 'hook.json'), '{ not json');
+ const cfg = readConfig(cwd);
+ assert.equal(cfg.enabled, true);
+ });
+
+ it('ignores malformed local config while preserving valid shared config', () => {
+ fs.mkdirSync(path.join(cwd, '.impeccable'), { recursive: true });
+ fs.writeFileSync(getConfigPath(cwd), JSON.stringify({
+ enabled: false,
+ ignoreRules: ['side-tab'],
+ limits: { maxFindings: 3 },
+ }));
+ fs.writeFileSync(getLocalConfigPath(cwd), '{ not json');
+ const cfg = readConfig(cwd);
+ assert.equal(cfg.enabled, false);
+ assert.deepEqual(cfg.ignoreRules, ['side-tab']);
+ assert.equal(cfg.limits.maxFindings, 3);
+ });
+});
+
+describe('readCache / persistCache / bumpEditCount', () => {
+ let cwd;
+ beforeEach(() => { cwd = mkTmp(); });
+ afterEach(() => fs.rmSync(cwd, { recursive: true, force: true }));
+
+ it('round-trips a session', () => {
+ const cache = readCache(cwd);
+ bumpEditCount(cache, 'sid-1', '/x/a.tsx');
+ bumpEditCount(cache, 'sid-1', '/x/a.tsx');
+ rememberFindings(cache, 'sid-1', '/x/a.tsx', [finding('side-tab', 12)]);
+ persistCache(cwd, cache);
+
+ const reloaded = readCache(cwd);
+ const file = reloaded.sessions['sid-1'].files['/x/a.tsx'];
+ assert.equal(file.editCount, 2);
+ assert.ok(file.findings.includes('side-tab:12'));
+ });
+
+ it('garbage-collects oldest sessions over CACHE_MAX_SESSIONS', () => {
+ const cache = readCache(cwd);
+ // Stamp 10 sessions, each with a unique updatedAt so ordering is stable.
+ for (let i = 0; i < 10; i++) {
+ const id = `sid-${i}`;
+ cache.sessions[id] = { updatedAt: 1000 + i, files: {} };
+ }
+ persistCache(cwd, cache);
+ const reloaded = readCache(cwd);
+ assert.equal(Object.keys(reloaded.sessions).length, 8);
+ assert.ok(reloaded.sessions['sid-9'], 'newest preserved');
+ assert.ok(!reloaded.sessions['sid-0'], 'oldest gc-ed');
+ });
+});
+
+describe('ensureHookGitExcludes()', () => {
+ let cwd;
+ beforeEach(() => { cwd = mkTmp(); });
+ afterEach(() => fs.rmSync(cwd, { recursive: true, force: true }));
+
+ it('adds hook runtime files to local git info exclude, not tracked .gitignore', () => {
+ execFileSync('git', ['init', '-q'], { cwd });
+
+ const result = ensureHookGitExcludes(cwd);
+ assert.equal(result.mode, 'git-info-exclude');
+ assert.equal(result.changed, true);
+ assert.equal(fs.existsSync(path.join(cwd, '.gitignore')), false);
+
+ const exclude = fs.readFileSync(path.join(cwd, '.git', 'info', 'exclude'), 'utf-8');
+ assert.match(exclude, /\.impeccable\/hook\.cache\.json/);
+ assert.match(exclude, /\.impeccable\/hook\.pending\.json/);
+ assert.match(exclude, /\.impeccable\/hook\.local\.json/);
+
+ const second = ensureHookGitExcludes(cwd);
+ assert.equal(second.changed, false);
+ const rewritten = fs.readFileSync(path.join(cwd, '.git', 'info', 'exclude'), 'utf-8');
+ assert.equal((rewritten.match(/impeccable-hook-ignore-start/g) || []).length, 1);
+ });
+});
+
+describe('matchesAnyGlob()', () => {
+ it('handles `**`, `*`, basename, and `{}` alternation', () => {
+ assert.ok(matchesAnyGlob('src/legacy/Foo.tsx', ['src/legacy/**']));
+ assert.ok(matchesAnyGlob('src/Foo.generated.tsx', ['**/*.generated.tsx']));
+ assert.ok(matchesAnyGlob('src/Foo.generated.tsx', ['*.generated.tsx']));
+ // {ts,tsx} expands to (?:ts|tsx) so the actual file path is what matches.
+ assert.ok(matchesAnyGlob('src/widget/Foo.tsx', ['src/widget/Foo.{ts,tsx}']));
+ assert.ok(matchesAnyGlob('src/widget/Foo.ts', ['src/widget/Foo.{ts,tsx}']));
+ assert.ok(!matchesAnyGlob('src/widgets/Foo.tsx', ['src/legacy/**']));
+ assert.ok(!matchesAnyGlob('src/Foo.tsx', []));
+ });
+});
+
+describe('filterFindings()', () => {
+ it('drops by ignoreRules and ignores legacy minSeverity config', () => {
+ const content = [
+ 'a', // line 1
+ 'b', // line 2
+ ].join('\n');
+ const findings = [
+ finding('side-tab', 1, { severity: 'warning' }),
+ finding('gradient-text', 2, { severity: 'warning' }),
+ finding('overused-font', 5, { severity: 'advisory' }),
+ ];
+ const filtered = filterFindings(findings, content, '.ts', {
+ ignoreRules: ['side-tab'],
+ minSeverity: 'error',
+ limits: DEFAULT_CONFIG.limits,
+ });
+ assert.deepEqual(filtered.map((f) => f.antipattern), ['gradient-text', 'overused-font']);
+ });
+
+ it('does not treat source comments as hook suppression', () => {
+ const content = [
+ '/* impeccable: ignore * */',
+ '.card { font-family: "Roboto", sans-serif; }',
+ '<!-- impeccable: ignore side-tab -->',
+ '<div style="border-left: 4px solid #7c3aed; border-radius: 16px;">Card</div>',
+ ].join('\n');
+ const filtered = filterFindings(
+ [finding('overused-font', 2), finding('side-tab', 4)],
+ content, '.html',
+ { ignoreRules: [], minSeverity: 'warning', limits: DEFAULT_CONFIG.limits }
+ );
+ assert.deepEqual(filtered.map((f) => f.antipattern), ['overused-font', 'side-tab']);
+ });
+
+ it('drops only matching rule/value pairs from ignoreValues', () => {
+ const findings = [
+ finding('overused-font', 1, { snippet: 'Primary font: Inter (86% of text)' }),
+ finding('overused-font', 2, { snippet: 'Primary font: Roboto' }),
+ finding('side-tab', 3),
+ ];
+ const filtered = filterFindings(findings, '', '.css', {
+ ignoreRules: [],
+ ignoreValues: [{ rule: 'overused-font', value: 'inter' }],
+ minSeverity: 'warning',
+ limits: DEFAULT_CONFIG.limits,
+ });
+ assert.deepEqual(filtered.map((f) => `${f.antipattern}:${f.line}`), ['overused-font:2', 'side-tab:3']);
+ });
+
+ it('extracts overused-font values from primary, CSS, and Google font snippets', () => {
+ assert.equal(
+ extractFindingIgnoreValue(finding('overused-font', 1, { snippet: 'Primary font: Open Sans (80% of text)' })),
+ 'open sans',
+ );
+ assert.equal(
+ extractFindingIgnoreValue(finding('overused-font', 1, { snippet: 'body { font-family: "Inter", sans-serif; }' })),
+ 'inter',
+ );
+ assert.equal(
+ extractFindingIgnoreValue(finding('overused-font', 1, { snippet: 'https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400' })),
+ 'plus jakarta sans',
+ );
+ assert.equal(extractFindingIgnoreValue(finding('side-tab', 1)), '');
+ });
+});
+
+describe('hook-admin.mjs', () => {
+ let cwd;
+ const script = path.resolve('skill', 'scripts', 'hook-admin.mjs');
+
+ beforeEach(() => { cwd = mkTmp(); });
+ afterEach(() => fs.rmSync(cwd, { recursive: true, force: true }));
+
+ function runAdmin(args) {
+ return execFileSync(process.execPath, [script, ...args], {
+ cwd,
+ env: { ...process.env },
+ encoding: 'utf-8',
+ });
+ }
+
+ it('ignore-value writes shared config by default without creating local config', () => {
+ const out = runAdmin(['ignore-value', 'overused-font', 'Inter', '--reason', 'User confirmed Inter']);
+ assert.match(out, /overused-font=inter/);
+ assert.equal(fs.existsSync(getLocalConfigPath(cwd)), false);
+ const shared = JSON.parse(fs.readFileSync(getConfigPath(cwd), 'utf-8'));
+ assert.equal(shared.enabled, true);
+ assert.deepEqual(shared.ignoreRules, []);
+ assert.deepEqual(shared.ignoreValues.map(({ rule, value, reason }) => ({ rule, value, reason })), [
+ { rule: 'overused-font', value: 'inter', reason: 'User confirmed Inter' },
+ ]);
+ assert.match(shared.ignoreValues[0].createdAt, /^\d{4}-\d{2}-\d{2}T/);
+ });
+
+ it('ignore-value --shared remains accepted for shared config', () => {
+ runAdmin(['ignore-value', 'overused-font', 'Open', 'Sans', '--shared', '--reason', 'Brand font']);
+ assert.equal(fs.existsSync(getLocalConfigPath(cwd)), false);
+ const shared = JSON.parse(fs.readFileSync(getConfigPath(cwd), 'utf-8'));
+ assert.deepEqual(shared.ignoreValues.map(({ rule, value, reason }) => ({ rule, value, reason })), [
+ { rule: 'overused-font', value: 'open sans', reason: 'Brand font' },
+ ]);
+ });
+
+ it('ignore-value --local writes private config and status reports local ignores', () => {
+ runAdmin(['ignore-value', 'overused-font', 'Inter', '--local']);
+ runAdmin(['ignore-value', 'OVERUSED-FONT', '"Inter"', '--local', '--reason', 'Still intentional']);
+ assert.equal(fs.existsSync(getConfigPath(cwd)), false);
+ const local = JSON.parse(fs.readFileSync(getLocalConfigPath(cwd), 'utf-8'));
+ assert.equal(local.enabled, undefined, 'local ignore should not override shared enabled state');
+ assert.equal(local.ignoreValues.length, 1);
+ assert.equal(local.ignoreValues[0].reason, 'Still intentional');
+
+ const status = runAdmin(['status']);
+ assert.match(status, /local file:\s+\.impeccable\/hook\.local\.json/);
+ assert.match(status, /ignoreValues:\s+overused-font=inter/);
+ });
+
+ it('ignore-rule overused-font requires explicit broad suppression', () => {
+ assert.throws(
+ () => runAdmin(['ignore-rule', 'overused-font']),
+ /ignore-value overused-font <font>|--all-values/,
+ );
+ assert.equal(fs.existsSync(getConfigPath(cwd)), false);
+ });
+
+ it('ignore-rule overused-font --all-values writes a whole-rule suppression', () => {
+ const out = runAdmin(['ignore-rule', 'overused-font', '--all-values', '--reason', 'User asked to ignore overused fonts generally']);
+ assert.match(out, /Added "overused-font" to ignoreRules/);
+ const shared = JSON.parse(fs.readFileSync(getConfigPath(cwd), 'utf-8'));
+ assert.deepEqual(shared.ignoreRules, ['overused-font']);
+ assert.deepEqual(shared.ignoreValues, []);
+ });
+
+ it('ignore-rule still allows non-value rules without --all-values', () => {
+ runAdmin(['ignore-rule', 'side-tab']);
+ const shared = JSON.parse(fs.readFileSync(getConfigPath(cwd), 'utf-8'));
+ assert.deepEqual(shared.ignoreRules, ['side-tab']);
+ });
+
+ it('ignore-value rejects conflicting scope flags', () => {
+ assert.throws(
+ () => runAdmin(['ignore-value', 'overused-font', 'Inter', '--shared', '--local']),
+ /Pass only one scope flag/,
+ );
+ });
+
+ it('ignore-file writes shared config that suppresses a later hook run', async () => {
+ const file = path.join(cwd, 'src/ConfirmedCard.html');
+ fs.mkdirSync(path.dirname(file), { recursive: true });
+ fs.writeFileSync(file, '<div style="border-left: 4px solid #7c3aed; border-radius: 16px; padding: 16px;">Card</div>');
+
+ runAdmin(['ignore-file', 'src/ConfirmedCard.html']);
+
+ const shared = JSON.parse(fs.readFileSync(getConfigPath(cwd), 'utf-8'));
+ assert.deepEqual(shared.ignoreFiles, ['src/ConfirmedCard.html']);
+
+ const r = await runHook({
+ stdinJson: JSON.stringify({
+ session_id: 'confirmed-ignore-file',
+ cwd,
+ hook_event_name: 'PostToolUse',
+ tool_name: 'Edit',
+ tool_input: { file_path: file },
+ }),
+ env: {},
+ cwd,
+ detector: fakeDetector([finding('side-tab', 1)]),
+ });
+ assert.equal(r.stdout, '');
+ assert.equal(r.audit.skipped, 'config-ignore-file');
+ });
+});
+
+describe('renderTemplate()', () => {
+ it('starts with the versioned envelope and caps to maxFindings', () => {
+ const findings = Array.from({ length: 12 }, (_, i) =>
+ finding('side-tab', i + 1, { name: `R${i}`, description: 'd' }));
+ const text = renderTemplate(findings, '/x/Card.tsx', DEFAULT_CONFIG, { cwd: '/x' });
+ assert.ok(text.startsWith(`${ENVELOPE_PREFIX} Required design corrections in Card.tsx (12 issue(s)):`));
+ assert.match(text, /\.\.\. and 7 more \(see \/impeccable audit\)\./);
+ // Exactly 5 finding lines.
+ const lines = text.split('\n').filter((l) => l.startsWith('- '));
+ assert.equal(lines.length, 5);
+ assert.ok(text.length <= DEFAULT_CONFIG.limits.maxChars);
+ });
+
+ it('emits a directive footer (imperative + exception clause + confirmed ignore guidance)', () => {
+ // Steers the model: imperative "fix", explicit exception for
+ // intentional bad UI / fixtures, and "acknowledge" so the user
+ // sees the correction in the chat reply. See `directiveFooter()`
+ // in hook-lib.mjs for the rationale.
+ const text = renderTemplate(
+ [finding('side-tab', 1, { name: 'X' })],
+ '/x/Card.tsx', DEFAULT_CONFIG, { cwd: '/x' }
+ );
+ assert.match(text, /Fix these in your next reply/);
+ assert.match(text, /Acknowledge what you changed/);
+ assert.match(text, /intentionally bad UI|anti-pattern example|test fixture/);
+ assert.match(text, /Do not add hook ignores unless the user explicitly confirms/);
+ assert.match(text, /Do not add source comments such as `impeccable: ignore`/);
+ assert.match(text, /ignore-value \.\.\. --shared/);
+ assert.match(text, /ignore-rule overused-font --all-values/);
+ assert.match(text, /\/impeccable hooks ignore-file Card\.tsx/);
+ assert.match(text, /ignore-rule <id>/);
+ assert.match(text, /\/impeccable audit/);
+ });
+
+ it('shows the exact value-specific command for overused-font findings', () => {
+ const text = renderTemplate(
+ [finding('overused-font', 1, { name: 'Overused font', snippet: 'body { font-family: "Roboto", sans-serif; }' })],
+ '/x/fonts.css', DEFAULT_CONFIG, { cwd: '/x' }
+ );
+ assert.match(text, /\/impeccable hooks ignore-value overused-font Roboto --shared/);
+ assert.match(text, /ignore-rule overused-font --all-values/);
+ });
+
+ it('drops the L<line> prefix when line is 0', () => {
+ const text = renderTemplate(
+ [finding('side-tab', 0, { name: 'X' })],
+ '/x/a.tsx', DEFAULT_CONFIG, { cwd: '/x' }
+ );
+ assert.match(text, /^- \[side-tab\]/m);
+ });
+
+ it('does not suggest ignore-value for rules that cannot be value-filtered', () => {
+ const text = renderTemplate(
+ [finding('side-tab', 1, {
+ name: 'Side tab',
+ ignoreValue: 'Inter',
+ })],
+ '/x/a.tsx', DEFAULT_CONFIG, { cwd: '/x' }
+ );
+ assert.doesNotMatch(text, /\/impeccable hooks ignore-value side-tab Inter/);
+ });
+
+ it('clamps oversize output to maxChars', () => {
+ const huge = Array.from({ length: 5 }, (_, i) =>
+ finding('side-tab', i + 1, { name: 'X', description: 'y'.repeat(2000) }));
+ const text = renderTemplate(huge, '/x/a.tsx',
+ { ...DEFAULT_CONFIG, limits: { maxFindings: 5, maxChars: 500 } },
+ { cwd: '/x' });
+ assert.ok(text.length <= 500);
+ });
+});
+
+describe('writeAuditLog()', () => {
+ let cwd;
+ beforeEach(() => { cwd = mkTmp(); });
+ afterEach(() => fs.rmSync(cwd, { recursive: true, force: true }));
+
+ it('appends NDJSON when IMPECCABLE_HOOK_LOG is set', () => {
+ const log = path.join(cwd, 'audit.ndjson');
+ writeAuditLog({ IMPECCABLE_HOOK_LOG: log }, { event: 'PostToolUse', emitted: true });
+ writeAuditLog({ IMPECCABLE_HOOK_LOG: log }, { event: 'PostToolUse', emitted: false });
+ const body = fs.readFileSync(log, 'utf-8');
+ assert.equal(body.trim().split('\n').length, 2);
+ for (const line of body.trim().split('\n')) {
+ const obj = JSON.parse(line);
+ assert.ok(obj.ts && obj.event === 'PostToolUse');
+ }
+ });
+
+ it('is a no-op when IMPECCABLE_HOOK_LOG is unset', () => {
+ assert.equal(writeAuditLog({}, { event: 'x' }), false);
+ });
+});
+
+describe('payload()', () => {
+ it('produces hookSpecificOutput for Claude/Codex', () => {
+ const obj = JSON.parse(payload('hello'));
+ assert.equal(obj.hookSpecificOutput.hookEventName, 'PostToolUse');
+ assert.equal(obj.hookSpecificOutput.additionalContext, 'hello');
+ });
+
+ it('produces additional_context for Cursor', () => {
+ const obj = JSON.parse(payload('hello', 'PostToolUse', 'cursor'));
+ assert.equal(obj.additional_context, 'hello');
+ assert.equal(obj.hookSpecificOutput, undefined);
+ });
+});
+
+describe('runHook()', () => {
+ let cwd;
+ beforeEach(() => { cwd = mkTmp(); });
+ afterEach(() => fs.rmSync(cwd, { recursive: true, force: true }));
+
+ function eventFor(file, sessionId = 'sid-1') {
+ return {
+ session_id: sessionId,
+ cwd,
+ hook_event_name: 'PostToolUse',
+ tool_name: 'Edit',
+ tool_input: { file_path: file },
+ };
+ }
+
+ function writeFixture(rel, body) {
+ const abs = path.join(cwd, rel);
+ fs.mkdirSync(path.dirname(abs), { recursive: true });
+ fs.writeFileSync(abs, body);
+ return abs;
+ }
+
+ it('emits findings on first fire, then a pending-ack on subsequent dedup hits', async () => {
+ // The "no silent fires" policy turns the previously-silent dedup hit
+ // into a pending re-nudge that keeps the unresolved finding in the
+ // model's context across turns. Findings emission still wins outright
+ // over the nudge (`renderTemplate` text), so r1 is unchanged from
+ // before. r2 is what changed: silent → pending ack.
+ const file = writeFixture('src/Card.tsx', 'noop');
+ const det = fakeDetector([finding('side-tab', 1, { name: 'Side-tab' })]);
+
+ const r1 = await runHook({ stdinJson: JSON.stringify(eventFor(file)), env: {}, cwd, detector: det });
+ assert.equal(r1.exitCode, 0);
+ assert.ok(r1.stdout.includes(ENVELOPE_PREFIX));
+ assert.match(r1.stdout, /Required design corrections/);
+ assert.equal(r1.audit.emitted, true);
+
+ const r2 = await runHook({ stdinJson: JSON.stringify(eventFor(file)), env: {}, cwd, detector: det });
+ assert.equal(r2.exitCode, 0);
+ assert.ok(r2.stdout.includes(ENVELOPE_PREFIX));
+ assert.match(r2.stdout, /Still has 1 issue\(s\) flagged earlier this session/);
+ assert.match(r2.stdout, /side-tab:1/);
+ assert.equal(r2.audit.emitted, true);
+ assert.equal(r2.audit.kind, 'pending');
+ });
+
+ it('emits a clean ack when the file has zero findings', async () => {
+ // No-silent-fires policy: a successful scan that finds nothing still
+ // emits a short positive nudge so the hook stays a conversational
+ // presence on every fire.
+ const file = writeFixture('src/Card.tsx', 'noop');
+ const det = fakeDetector([]); // no findings
+ const r = await runHook({ stdinJson: JSON.stringify(eventFor(file)), env: {}, cwd, detector: det });
+ assert.equal(r.exitCode, 0);
+ assert.ok(r.stdout.includes(ENVELOPE_PREFIX));
+ assert.match(r.stdout, /No anti-patterns/);
+ assert.match(r.stdout, /typography hierarchy, spacing rhythm, and color contrast/);
+ assert.equal(r.audit.emitted, true);
+ assert.equal(r.audit.kind, 'clean');
+ });
+
+ it('does not emit clean acks for plain .ts files', async () => {
+ const file = writeFixture('src/server.ts', 'export const value = 1;');
+ const r = await runHook({
+ stdinJson: JSON.stringify(eventFor(file)),
+ env: {},
+ cwd,
+ detector: fakeDetector([]),
+ });
+ assert.equal(r.exitCode, 0);
+ assert.equal(r.stdout, '');
+ assert.equal(r.audit.skipped, 'non-ui-ack');
+ });
+
+ it('still emits findings for plain .ts files', async () => {
+ const file = writeFixture('src/styles.ts', 'export const css = "border-left: 4px solid #7c3aed";');
+ const r = await runHook({
+ stdinJson: JSON.stringify(eventFor(file)),
+ env: {},
+ cwd,
+ detector: fakeDetector([finding('side-tab', 1)]),
+ });
+ assert.match(r.stdout, /Required design corrections/);
+ assert.match(r.stdout, /side-tab/);
+ });
+
+ it('does not emit pending acks for plain .js files', async () => {
+ const file = writeFixture('src/build.js', 'export const value = 1;');
+ const det = fakeDetector([finding('side-tab', 1)]);
+ const first = await runHook({ stdinJson: JSON.stringify(eventFor(file)), env: {}, cwd, detector: det });
+ assert.match(first.stdout, /Required design corrections/);
+
+ const second = await runHook({ stdinJson: JSON.stringify(eventFor(file)), env: {}, cwd, detector: det });
+ assert.equal(second.stdout, '');
+ assert.equal(second.audit.skipped, 'non-ui-ack');
+ });
+
+ it('IMPECCABLE_HOOK_QUIET=1 suppresses clean and pending acks, keeps findings emission', async () => {
+ // The opt-out kill switch for users who want the old silent-on-clean
+ // behavior. Findings still emit because those are real signals; the
+ // QUIET switch only quiets the conversational acks.
+ const fileA = writeFixture('src/A.tsx', 'noop');
+ const fileB = writeFixture('src/B.tsx', 'noop');
+
+ // Clean file: silent under QUIET.
+ const detClean = fakeDetector([]);
+ const rClean = await runHook({
+ stdinJson: JSON.stringify(eventFor(fileA)),
+ env: { IMPECCABLE_HOOK_QUIET: '1' }, cwd, detector: detClean,
+ });
+ assert.equal(rClean.stdout, '');
+ assert.equal(rClean.audit.emitted, false);
+ assert.equal(rClean.audit.quiet, true);
+
+ // Findings file: still emits.
+ const detFindings = fakeDetector([finding('side-tab', 1)]);
+ const rFindings = await runHook({
+ stdinJson: JSON.stringify(eventFor(fileB)),
+ env: { IMPECCABLE_HOOK_QUIET: '1' }, cwd, detector: detFindings,
+ });
+ assert.ok(rFindings.stdout.includes(ENVELOPE_PREFIX));
+ assert.match(rFindings.stdout, /Required design corrections/);
+ assert.equal(rFindings.audit.emitted, true);
+ });
+
+ it('re-entrancy guard short-circuits when IMPECCABLE_HOOK_DEPTH is set', async () => {
+ const file = writeFixture('src/Card.tsx', 'noop');
+ const det = fakeDetector([finding('side-tab', 1)]);
+ const r = await runHook({
+ stdinJson: JSON.stringify(eventFor(file)),
+ env: { IMPECCABLE_HOOK_DEPTH: '1' },
+ cwd,
+ detector: det,
+ });
+ assert.equal(r.stdout, '');
+ assert.equal(r.audit.reentrant, true);
+ });
+
+ it('re-entrancy guard treats numeric CLAUDE_HOOK_DEPTH values as active', async () => {
+ const file = writeFixture('src/Card.tsx', 'noop');
+ const det = fakeDetector([finding('side-tab', 1)]);
+ const r = await runHook({
+ stdinJson: JSON.stringify(eventFor(file)),
+ env: { CLAUDE_HOOK_DEPTH: '2' },
+ cwd,
+ detector: det,
+ });
+ assert.equal(r.stdout, '');
+ assert.equal(r.audit.reentrant, true);
+ });
+
+ it('IMPECCABLE_HOOK_DISABLED kill switch', async () => {
+ const file = writeFixture('src/Card.tsx', 'noop');
+ const det = fakeDetector([finding('side-tab', 1)]);
+ for (const v of ['1', 'true', 'yes', 'on', 'TRUE']) {
+ const r = await runHook({
+ stdinJson: JSON.stringify(eventFor(file)),
+ env: { IMPECCABLE_HOOK_DISABLED: v },
+ cwd,
+ detector: det,
+ });
+ assert.equal(r.stdout, '', `expected silent for value ${v}`);
+ assert.equal(r.audit.skipped, 'env-disabled');
+ }
+ });
+
+ it('config-disabled silences cleanly', async () => {
+ const file = writeFixture('src/Card.tsx', 'noop');
+ fs.mkdirSync(path.join(cwd, '.impeccable'), { recursive: true });
+ fs.writeFileSync(path.join(cwd, '.impeccable', 'hook.json'), JSON.stringify({ enabled: false }));
+ const det = fakeDetector([finding('side-tab', 1)]);
+ const r = await runHook({ stdinJson: JSON.stringify(eventFor(file)), env: {}, cwd, detector: det });
+ assert.equal(r.stdout, '');
+ assert.equal(r.audit.skipped, 'config-disabled');
+ });
+
+ it('rejects sensitive paths before reading file content', async () => {
+ const file = path.join(cwd, '.env');
+ fs.writeFileSync(file, 'SECRET=42');
+ const det = { detectText: () => { throw new Error('should not run'); } };
+ const r = await runHook({
+ stdinJson: JSON.stringify({ ...eventFor(file), tool_input: { file_path: file } }),
+ env: {}, cwd, detector: det,
+ });
+ assert.equal(r.audit.skipped, 'sensitive');
+ });
+
+ it('rejects generated paths', async () => {
+ const file = writeFixture('dist/Card.tsx', 'noop');
+ const r = await runHook({ stdinJson: JSON.stringify(eventFor(file)), env: {}, cwd });
+ assert.equal(r.audit.skipped, 'generated');
+ });
+
+ it('rejects path traversal in file_path', async () => {
+ const r = await runHook({
+ stdinJson: JSON.stringify({ ...eventFor('/foo/../etc/passwd') }),
+ env: {}, cwd,
+ });
+ assert.equal(r.audit.skipped, 'sensitive');
+ });
+
+ it('rejects extensions outside the allowlist', async () => {
+ const file = writeFixture('docs/README.md', 'noop');
+ const r = await runHook({ stdinJson: JSON.stringify(eventFor(file)), env: {}, cwd });
+ assert.equal(r.audit.skipped, 'extension');
+ });
+
+ it('config ignoreFiles glob suppresses', async () => {
+ const file = writeFixture('src/legacy/Foo.tsx', 'noop');
+ fs.mkdirSync(path.join(cwd, '.impeccable'), { recursive: true });
+ fs.writeFileSync(path.join(cwd, '.impeccable', 'hook.json'), JSON.stringify({
+ ignoreFiles: ['src/legacy/**'],
+ }));
+ const det = fakeDetector([finding('side-tab', 1)]);
+ const r = await runHook({ stdinJson: JSON.stringify(eventFor(file)), env: {}, cwd, detector: det });
+ assert.equal(r.stdout, '');
+ assert.equal(r.audit.skipped, 'config-ignore-file');
+ });
+
+ it('emits one-shot suppression notice on the 7th edit and silences after', async () => {
+ const file = writeFixture('src/Card.tsx', 'noop');
+ const det = fakeDetector([finding('side-tab', 1)]);
+ let last;
+ for (let i = 0; i < 8; i++) {
+ // Use a different line each time so we don't dedup; we want to hit
+ // edit-count, not the dedup cache.
+ const f = [finding('side-tab', i + 1)];
+ last = await runHook({
+ stdinJson: JSON.stringify(eventFor(file)),
+ env: {}, cwd, detector: { detectText: () => f, detectHtml: () => f },
+ });
+ }
+ // The 7th call (index 6) crosses the threshold; the 8th (index 7) is silent.
+ assert.equal(last.stdout, '', '8th edit should be silent');
+ assert.equal(last.audit.suppressed, true);
+ });
+
+ it('emits suppressionNotice text on the threshold-crossing edit', async () => {
+ const file = writeFixture('src/Card.tsx', 'noop');
+ const det = fakeDetector([finding('side-tab', 1)]);
+ let r;
+ for (let i = 0; i < 7; i++) {
+ const f = [finding('side-tab', i + 1)];
+ r = await runHook({
+ stdinJson: JSON.stringify(eventFor(file)),
+ env: {}, cwd, detector: { detectText: () => f, detectHtml: () => f },
+ });
+ }
+ assert.ok(r.stdout.includes('Suppressing further design hints'));
+ assert.match(r.stdout, /More than 6 edits in this session reached/);
+ assert.match(r.stdout, /Run \/impeccable audit to revisit/);
+ });
+
+ it('handles MultiEdit and apply_patch payload shapes (file_path field)', async () => {
+ const file = writeFixture('src/Card.tsx', 'noop');
+ const det = fakeDetector([finding('side-tab', 1)]);
+ for (const event of [
+ { ...eventFor(file), tool_name: 'MultiEdit', tool_input: { file_path: file, edits: [] } },
+ { ...eventFor(file), tool_name: 'apply_patch', tool_input: { file_path: file, command: '...' } },
+ ]) {
+ const r = await runHook({ stdinJson: JSON.stringify(event), env: {}, cwd, detector: det });
+ assert.equal(r.exitCode, 0);
+ // First call emits; second is dedup-silent. Reset by using fresh session.
+ assert.ok(r.stdout.length >= 0);
+ }
+ });
+
+ it('parses Codex apply_patch command when file_path is omitted', async () => {
+ writeFixture('src/Card.tsx', '<div className="border-l-4" />');
+ const event = {
+ session_id: 'sid-codex-ap',
+ cwd,
+ hook_event_name: 'PostToolUse',
+ tool_name: 'apply_patch',
+ tool_input: {
+ command: '*** Begin Patch\n*** Update File: src/Card.tsx\n*** End Patch',
+ },
+ };
+ const det = fakeDetector([finding('side-tab', 1)]);
+ const r = await runHook({ stdinJson: JSON.stringify(event), env: {}, cwd, detector: det });
+ assert.equal(r.exitCode, 0);
+ assert.match(r.stdout, /Required design corrections/);
+ });
+
+ it('detector throw is swallowed; never breaks turn', async () => {
+ const file = writeFixture('src/Card.tsx', 'noop');
+ const det = { detectText: () => { throw new Error('boom'); } };
+ const r = await runHook({ stdinJson: JSON.stringify(eventFor(file)), env: {}, cwd, detector: det });
+ assert.equal(r.exitCode, 0);
+ assert.equal(r.stdout, '');
+ });
+
+ it('awaits the real async HTML detector before deciding a page is clean', async () => {
+ const file = writeFixture('index.html', [
+ '<!doctype html>',
+ '<html><body>',
+ '<div style="border-left: 4px solid #6366f1; border-radius: 8px; padding: 16px;">Feature</div>',
+ '</body></html>',
+ ].join('\n'));
+ const r = await runHook({
+ stdinJson: JSON.stringify(eventFor(file)),
+ env: {},
+ cwd,
+ detector: { detectHtml, detectText },
+ });
+ assert.match(r.stdout, /Required design corrections/);
+ assert.doesNotMatch(r.stdout, /No anti-patterns/);
+ assert.ok(r.audit.findings > 0);
+ });
+
+ it('malformed stdin → silent skip', async () => {
+ const r = await runHook({ stdinJson: '{not json', env: {}, cwd });
+ assert.equal(r.audit.skipped, 'stdin-malformed');
+ });
+
+ it('missing file → silent skip (race protection)', async () => {
+ const r = await runHook({
+ stdinJson: JSON.stringify(eventFor(path.join(cwd, 'src/Vanished.tsx'))),
+ env: {}, cwd,
+ });
+ assert.equal(r.audit.skipped, 'file-missing');
+ });
+});
+
+describe('suppressionNotice()', () => {
+ it('starts with envelope and mentions /impeccable audit', () => {
+ const text = suppressionNotice('src/Card.tsx');
+ assert.ok(text.startsWith(ENVELOPE_PREFIX));
+ assert.match(text, /More than 6 edits in this session reached/);
+ assert.match(text, /\/impeccable audit/);
+ });
+});
+
+describe('ALLOWED_EXTS', () => {
+ it('covers the documented design-relevant extensions', () => {
+ for (const ext of ['.tsx', '.jsx', '.html', '.css', '.vue', '.svelte', '.astro', '.ts', '.js', '.scss', '.sass', '.less', '.htm']) {
+ assert.ok(ALLOWED_EXTS.has(ext), `missing: ${ext}`);
+ }
+ for (const ext of ['.md', '.py', '.go', '.json']) {
+ assert.ok(!ALLOWED_EXTS.has(ext), `unexpected allowed: ${ext}`);
+ }
+ });
+
+ it('keeps clean/pending acknowledgements to UI-ish files', () => {
+ for (const ext of ['.tsx', '.jsx', '.html', '.css', '.vue', '.svelte', '.astro', '.scss', '.sass', '.less', '.htm']) {
+ assert.ok(ACK_EXTS.has(ext), `missing ack extension: ${ext}`);
+ assert.equal(shouldEmitAckForFile(`/x/src/App${ext}`), true);
+ }
+ for (const ext of ['.ts', '.js']) {
+ assert.ok(!ACK_EXTS.has(ext), `unexpected ack extension: ${ext}`);
+ assert.equal(shouldEmitAckForFile(`/x/src/tool${ext}`), false);
+ }
+ });
+});
+
+describe('renderCleanAck() / renderPendingAck()', () => {
+ it('renderCleanAck stays short and ends with the steer line', () => {
+ const text = renderCleanAck('/x/src/App.jsx', { cwd: '/x' });
+ assert.match(text, /^\[impeccable@1\] Design hook scanned src\/App\.jsx\. No anti-patterns\./);
+ assert.match(text, /typography hierarchy, spacing rhythm, and color contrast/);
+ // Budget guard: should fit comfortably under a single context-message
+ // injection (~200 chars). Hard upper bound 240 chars.
+ assert.ok(text.length < 240, `clean ack too long: ${text.length} chars`);
+ });
+
+ it('renderPendingAck quotes up to 3 known findings and counts the rest', () => {
+ const known = ['side-tab:3', 'gradient-text:4', 'ai-color-palette:8', 'overused-font:12'];
+ const text = renderPendingAck('/x/src/SlopCard.jsx', known, { cwd: '/x' });
+ assert.match(text, /^\[impeccable@1\] Design hook scanned src\/SlopCard\.jsx\./);
+ assert.match(text, /Still has 4 issue\(s\) flagged earlier this session/);
+ assert.match(text, /side-tab:3, gradient-text:4, ai-color-palette:8/);
+ assert.match(text, /\+1 more/); // 4 total, 3 shown
+ assert.match(text, /Address them before finalizing/);
+ });
+
+ it('renderPendingAck omits the "+N more" suffix when ≤3 known findings', () => {
+ const text = renderPendingAck('/x/src/A.tsx', ['side-tab:1', 'gradient-text:2'], { cwd: '/x' });
+ assert.ok(!text.includes('+'), 'no overflow suffix expected');
+ });
+});
+
+describe('parseApplyPatchPaths()', () => {
+ it('extracts absolute and relative paths from patch bodies', () => {
+ const cwd = '/proj';
+ const rel = parseApplyPatchPaths('*** Update File: src/App.jsx\n', cwd);
+ assert.deepEqual(rel, ['/proj/src/App.jsx']);
+ const abs = parseApplyPatchPaths('*** Add File: /tmp/x.css\n*** Update File: src/y.html\n', cwd);
+ assert.deepEqual(abs, ['/tmp/x.css', '/proj/src/y.html']);
+ });
+});
+
+describe('resolveTargetFiles()', () => {
+ it('uses file_path when present and falls back to apply_patch command', () => {
+ assert.deepEqual(resolveTargetFiles({ tool_input: { file_path: '/a/b.tsx' } }, '/proj'), ['/a/b.tsx']);
+ assert.deepEqual(
+ resolveTargetFiles({ tool_name: 'apply_patch', tool_input: { command: '*** Update File: src/x.css\n' } }, '/proj'),
+ ['/proj/src/x.css'],
+ );
+ assert.deepEqual(resolveTargetFiles({ tool_name: 'Bash', tool_input: { command: 'echo hi' } }, '/proj'), []);
+ });
+
+ it('includes every apply_patch file even when file_path is also present', () => {
+ assert.deepEqual(
+ resolveTargetFiles({
+ tool_name: 'apply_patch',
+ tool_input: {
+ file_path: '/proj/src/App.jsx',
+ command: '*** Update File: src/App.jsx\n*** Update File: src/styles.css\n',
+ },
+ }, '/proj'),
+ ['/proj/src/App.jsx', '/proj/src/styles.css'],
+ );
+ });
+
+ it('accepts Cursor Write/StrReplace path field and top-level file_path', () => {
+ assert.deepEqual(resolveTargetFiles({ tool_input: { path: '/a/b.tsx' } }, '/proj'), ['/a/b.tsx']);
+ assert.deepEqual(resolveTargetFiles({ file_path: '/a/c.css' }, '/proj'), ['/a/c.css']);
+ });
+});
+
+describe('resolveHarness() / normalizeHookEvent()', () => {
+ it('routes explicit env and Cursor conversation_id to cursor harness', () => {
+ assert.equal(resolveHarness({ IMPECCABLE_HOOK_HARNESS: 'cursor' }), 'cursor');
+ assert.equal(resolveHarness({}, { conversation_id: 'c1' }), 'cursor');
+ assert.equal(resolveHarness({}), 'claude');
+ });
+
+ it('maps Cursor postToolUse Write path into file_path + cwd', () => {
+ const normalized = normalizeHookEvent({
+ conversation_id: 'c1',
+ workspace_roots: ['/proj'],
+ tool_name: 'Write',
+ tool_input: { path: 'src/App.jsx' },
+ }, '/fallback', 'cursor');
+ assert.equal(normalized.session_id, 'c1');
+ assert.equal(normalized.cwd, '/proj');
+ assert.equal(normalized.tool_input.file_path, 'src/App.jsx');
+ });
+});
+
+describe('expandScanTargets()', () => {
+ let cwd;
+ beforeEach(() => { cwd = mkTmp(); });
+ afterEach(() => fs.rmSync(cwd, { recursive: true, force: true }));
+
+ function write(rel, body) {
+ const abs = path.join(cwd, rel);
+ fs.mkdirSync(path.dirname(abs), { recursive: true });
+ fs.writeFileSync(abs, body);
+ return abs;
+ }
+
+ it('includes co-located styles.css when the primary edit is App.jsx', () => {
+ const app = write('src/App.jsx', 'export default function App() { return <main className="x" />; }');
+ write('src/styles.css', "body { font-family: 'Inter', sans-serif; }");
+ const expanded = expandScanTargets([app], cwd);
+ assert.deepEqual(expanded, [app, path.join(cwd, 'src/styles.css')]);
+ });
+
+ it('includes common co-located Sass, SCSS, and Less stylesheet names', () => {
+ for (const name of ['index.scss', 'index.sass', 'index.less', 'global.scss', 'global.less', 'globals.scss', 'globals.less']) {
+ const dir = `src/${name.replaceAll('.', '-')}`;
+ const app = write(`${dir}/App.jsx`, 'export default function App() { return <main className="x" />; }');
+ const stylesheet = write(`${dir}/${name}`, ".card\n border-left: 4px solid #3b82f6");
+ const expanded = expandScanTargets([app], cwd);
+ assert.ok(expanded.includes(stylesheet), `missing ${name}`);
+ }
+ });
+
+ it('follows static stylesheet imports from the edited component', () => {
+ const card = write('src/Card.jsx', "import './Card.module.css';\nexport default function Card() { return null; }");
+ const mod = write('src/Card.module.css', '.card { border-left: 4px solid #3b82f6; }');
+ const expanded = expandScanTargets([card], cwd);
+ assert.ok(expanded.includes(mod));
+ });
+
+ it('includes co-located module Sass and Less stylesheets', () => {
+ for (const name of ['Card.module.sass', 'Card.module.less']) {
+ const dir = `src/${name.replaceAll('.', '-')}`;
+ const card = write(`${dir}/Card.jsx`, 'export default function Card() { return <main className="x" />; }');
+ const stylesheet = write(`${dir}/${name}`, '.card { border-left: 4px solid #3b82f6; }');
+ const expanded = expandScanTargets([card], cwd);
+ assert.ok(expanded.includes(stylesheet), `missing ${name}`);
+ }
+ });
+
+ it('resolves relative primary targets against the project cwd', () => {
+ write('src/Card.jsx', "import './Card.module.css';\nexport default function Card() { return null; }");
+ const mod = write('src/Card.module.css', '.card { border-left: 4px solid #3b82f6; }');
+ const expanded = expandScanTargets(['src/Card.jsx'], cwd);
+ assert.deepEqual(expanded, [path.join(cwd, 'src/Card.jsx'), mod]);
+ });
+
+ it('does not follow imports from traversal-looking primary targets', () => {
+ const outside = fs.mkdtempSync(path.join(os.tmpdir(), 'impeccable-hook-outside-'));
+ try {
+ fs.writeFileSync(path.join(outside, 'App.jsx'), "import './styles.css';\nexport default function App() { return null; }");
+ fs.writeFileSync(path.join(outside, 'styles.css'), "body { font-family: 'Inter', sans-serif; }");
+ const traversalPrimary = `${cwd}/../${path.basename(outside)}/App.jsx`;
+ const expanded = expandScanTargets([traversalPrimary], cwd);
+ assert.deepEqual(expanded, [traversalPrimary]);
+ } finally {
+ fs.rmSync(outside, { recursive: true, force: true });
+ }
+ });
+
+ it('does not expand when the primary target is already a stylesheet', () => {
+ const css = write('src/styles.css', "body { font-family: 'Inter', sans-serif; }");
+ assert.deepEqual(expandScanTargets([css], cwd), [css]);
+ });
+});
+
+describe('runHook() — co-located stylesheet scan', () => {
+ let cwd;
+ beforeEach(() => { cwd = mkTmp(); });
+ afterEach(() => fs.rmSync(cwd, { recursive: true, force: true }));
+
+ function write(rel, body) {
+ const abs = path.join(cwd, rel);
+ fs.mkdirSync(path.dirname(abs), { recursive: true });
+ fs.writeFileSync(abs, body);
+ return abs;
+ }
+
+ it('flags slop in styles.css when only App.jsx was edited', async () => {
+ const app = write('src/App.jsx', 'export default function App() { return <main className="x" />; }');
+ write('src/styles.css', "body { font-family: 'Inter', sans-serif; }");
+ const det = {
+ detectText: (content, filePath) => (
+ filePath.endsWith('.css') ? [finding('overused-font', 8)] : []
+ ),
+ detectHtml: () => [],
+ };
+ const r = await runHook({
+ stdinJson: JSON.stringify({
+ session_id: 'co-scan',
+ cwd,
+ hook_event_name: 'PostToolUse',
+ tool_name: 'apply_patch',
+ tool_input: { command: `*** Update File: ${app}\n` },
+ }),
+ env: {},
+ cwd,
+ detector: det,
+ });
+ assert.match(r.stdout, /Required design corrections/);
+ assert.match(r.stdout, /styles\.css/);
+ });
+
+ it('flags slop in co-located .sass when only App.jsx was edited', async () => {
+ const app = write('src/App.jsx', 'export default function App() { return <main className="x" />; }');
+ write('src/styles.sass', ".card\n border-left: 4px solid #3b82f6");
+ const det = {
+ detectText: (content, filePath) => (
+ filePath.endsWith('.sass') ? [finding('side-tab', 2)] : []
+ ),
+ detectHtml: () => [],
+ };
+ const r = await runHook({
+ stdinJson: JSON.stringify({
+ session_id: 'co-scan-sass',
+ cwd,
+ hook_event_name: 'PostToolUse',
+ tool_name: 'apply_patch',
+ tool_input: { command: `*** Update File: ${app}\n` },
+ }),
+ env: {},
+ cwd,
+ detector: det,
+ });
+ assert.match(r.stdout, /Required design corrections/);
+ assert.match(r.stdout, /styles\.sass/);
+ });
+
+ it('emits fresh findings for every file scanned in the same hook run', async () => {
+ const app = write('src/App.jsx', 'export default function App() { return <main className="border-l-4 border-blue-500" />; }');
+ const styles = write('src/styles.css', "body { font-family: 'Inter', sans-serif; }");
+ const seen = [];
+ const det = {
+ detectText: (content, filePath) => {
+ seen.push(filePath);
+ if (filePath.endsWith('App.jsx')) return [finding('side-tab', 1)];
+ if (filePath.endsWith('styles.css')) return [finding('overused-font', 1)];
+ return [];
+ },
+ detectHtml: () => [],
+ };
+
+ const r = await runHook({
+ stdinJson: JSON.stringify({
+ session_id: 'co-scan-fresh-primary',
+ cwd,
+ hook_event_name: 'PostToolUse',
+ tool_name: 'apply_patch',
+ tool_input: { command: `*** Update File: ${app}\n` },
+ }),
+ env: {},
+ cwd,
+ detector: det,
+ });
+
+ assert.match(r.stdout, /Required design corrections/);
+ assert.match(r.stdout, /App\.jsx/);
+ assert.match(r.stdout, /styles\.css/);
+ assert.match(r.stdout, /side-tab/);
+ assert.match(r.stdout, /overused-font/);
+ assert.ok(seen.includes(app), 'primary file should be scanned');
+ assert.ok(seen.includes(styles), 'co-located stylesheet should still be scanned');
+ assert.equal(r.emission.groups.length, 2);
+ const cache = readCache(cwd);
+ const files = cache.sessions['co-scan-fresh-primary'].files;
+ assert.deepEqual(files[app].findings, ['side-tab:1']);
+ assert.deepEqual(files[styles].findings, ['overused-font:1']);
+ });
+
+ it('does not bump edit count for passively co-scanned stylesheets', async () => {
+ const app = write('src/App.jsx', 'export default function App() { return <main className="x" />; }');
+ const styles = write('src/styles.css', "body { font-family: 'Inter', sans-serif; }");
+ const det = {
+ detectText: (content, filePath) => (
+ filePath.endsWith('styles.css') ? [finding('overused-font', 1)] : []
+ ),
+ detectHtml: () => [],
+ };
+
+ const r = await runHook({
+ stdinJson: JSON.stringify({
+ session_id: 'co-scan-edit-count',
+ cwd,
+ hook_event_name: 'PostToolUse',
+ tool_name: 'apply_patch',
+ tool_input: { command: `*** Update File: ${app}\n` },
+ }),
+ env: {},
+ cwd,
+ detector: det,
+ });
+
+ assert.match(r.stdout, /styles\.css/);
+ const cache = readCache(cwd);
+ const files = cache.sessions['co-scan-edit-count'].files;
+ assert.equal(files[app].editCount, 1);
+ assert.equal(files[styles].editCount || 0, 0);
+ });
+
+ it('does not scan imported styles from a traversal-looking primary path', async () => {
+ const outside = fs.mkdtempSync(path.join(os.tmpdir(), 'impeccable-hook-outside-'));
+ try {
+ fs.writeFileSync(path.join(outside, 'App.jsx'), "import './styles.css';\nexport default function App() { return null; }");
+ fs.writeFileSync(path.join(outside, 'styles.css'), "body { font-family: 'Inter', sans-serif; }");
+ const traversalPrimary = `${cwd}/../${path.basename(outside)}/App.jsx`;
+ const det = fakeDetector([finding('overused-font', 1, { name: 'Overused font' })]);
+ const r = await runHook({
+ stdinJson: JSON.stringify({
+ session_id: 'co-scan-traversal',
+ cwd,
+ hook_event_name: 'PostToolUse',
+ tool_name: 'Edit',
+ tool_input: { file_path: traversalPrimary },
+ }),
+ env: {},
+ cwd,
+ detector: det,
+ });
+ assert.equal(r.stdout, '');
+ assert.equal(r.audit.skipped, 'sensitive');
+ } finally {
+ fs.rmSync(outside, { recursive: true, force: true });
+ }
+ });
+});
+
+describe('runHook() — events without file_path', () => {
+ // The sweep fallback was removed in v5 (single-hook simplification).
+ // Code-execution tools that don't carry a `file_path` now hit a clean
+ // silent skip instead of running a git-status sweep. This keeps the
+ // single PostToolUse matcher (Edit/Write/MultiEdit/apply_patch) honest:
+ // anything else is a no-op.
+ let cwd;
+ beforeEach(() => { cwd = mkTmp(); });
+ afterEach(() => fs.rmSync(cwd, { recursive: true, force: true }));
+
+ it('returns silent skip with reason no-file-path', async () => {
+ const event = JSON.stringify({
+ session_id: 'sid-x',
+ cwd,
+ hook_event_name: 'PostToolUse',
+ tool_name: 'mcp__node_repl__js',
+ tool_input: { title: 'do work', code: 'console.log(1)' },
+ });
+ const det = fakeDetector([finding('side-tab', 1)]);
+ const r = await runHook({ stdinJson: event, env: {}, cwd, detector: det });
+ assert.equal(r.exitCode, 0);
+ assert.equal(r.stdout, '');
+ assert.equal(r.audit.skipped, 'no-file-path');
+ });
+});
+
+describe('Cursor hook scripts', () => {
+ let cwd;
+ beforeEach(() => { cwd = mkTmp(); });
+ afterEach(() => fs.rmSync(cwd, { recursive: true, force: true }));
+
+ it('preToolUse denies proposed writes with detector findings before they land', () => {
+ const logPath = path.join(cwd, 'hook.ndjson');
+ const filePath = path.join(cwd, 'src/Card.html');
+
+ const out = execFileSync(process.execPath, [path.join('skill', 'scripts', 'hook-before-edit.mjs')], {
+ cwd: path.resolve('.'),
+ input: JSON.stringify({
+ hook_event_name: 'preToolUse',
+ cwd,
+ tool_name: 'Write',
+ tool_input: {
+ file_path: filePath,
+ content: `
+ <style>
+ .card { border-left: 4px solid #7c3aed; border-radius: 16px; }
+ </style>
+ <div class="card">Hello</div>
+ `,
+ },
+ }),
+ env: { ...process.env, IMPECCABLE_HOOK_LOG: logPath },
+ encoding: 'utf-8',
+ });
+
+ const payload = JSON.parse(out);
+ assert.equal(payload.permission, 'deny');
+ assert.match(payload.user_message, /blocked this write/);
+ assert.match(payload.user_message, /side-tab/);
+ assert.match(payload.agent_message, /Fix these in your next reply/);
+
+ const entries = fs.readFileSync(logPath, 'utf-8').trim().split('\n').map((line) => JSON.parse(line));
+ assert.equal(entries[0].event, 'preToolUse');
+ assert.equal(entries[0].blocked, true);
+ assert.equal(entries[0].blockedFindings, 1);
+ });
+
+ it('preToolUse allows clean proposed writes', () => {
+ const out = execFileSync(process.execPath, [path.join('skill', 'scripts', 'hook-before-edit.mjs')], {
+ cwd: path.resolve('.'),
+ input: JSON.stringify({
+ hook_event_name: 'preToolUse',
+ cwd,
+ tool_name: 'Write',
+ tool_input: {
+ path: 'src/Card.jsx',
+ streamContent: 'export default function Card() { return <section className="card">Hello</section>; }',
+ },
+ }),
+ env: { ...process.env, IMPECCABLE_HOOK_LOG: '' },
+ encoding: 'utf-8',
+ });
+
+ assert.deepEqual(JSON.parse(out), { permission: 'allow' });
+ });
+
+ it('preToolUse denies shell heredoc writes that bypass the Write tool', () => {
+ const filePath = path.join(cwd, 'src/ShellCard.html');
+ const out = execFileSync(process.execPath, [path.join('skill', 'scripts', 'hook-before-edit.mjs')], {
+ cwd: path.resolve('.'),
+ input: JSON.stringify({
+ hook_event_name: 'preToolUse',
+ cwd,
+ tool_name: 'Shell',
+ tool_input: {
+ command: `cat > "${filePath}" <<'EOF'\n<style>.card { border-left: 4px solid #7c3aed; border-radius: 16px; padding: 16px; }</style>\n<div class="card">Hello</div>\nEOF\n`,
+ },
+ }),
+ env: { ...process.env, IMPECCABLE_HOOK_LOG: '' },
+ encoding: 'utf-8',
+ });
+
+ const payload = JSON.parse(out);
+ assert.equal(payload.permission, 'deny');
+ assert.match(payload.user_message, /ShellCard\.html/);
+ assert.match(payload.user_message, /side-tab/);
+ });
+
+ it('preToolUse denies Python heredoc file writes that bypass the Write tool', () => {
+ const filePath = path.join(cwd, 'src/PythonCard.html');
+ const out = execFileSync(process.execPath, [path.join('skill', 'scripts', 'hook-before-edit.mjs')], {
+ cwd: path.resolve('.'),
+ input: JSON.stringify({
+ hook_event_name: 'preToolUse',
+ cwd,
+ tool_name: 'Shell',
+ tool_input: {
+ command: `python3 - <<'PY'\nfrom pathlib import Path\npath = Path('${filePath}')\npath.write_text('''<style>.card { border-left: 4px solid #7c3aed; border-radius: 16px; padding: 16px; }</style>\n<div class="card">Hello</div>\n''', encoding='utf-8')\nPY\n`,
+ },
+ }),
+ env: { ...process.env, IMPECCABLE_HOOK_LOG: '' },
+ encoding: 'utf-8',
+ });
+
+ const payload = JSON.parse(out);
+ assert.equal(payload.permission, 'deny');
+ assert.match(payload.user_message, /PythonCard\.html/);
+ assert.match(payload.user_message, /side-tab/);
+ });
+
+ it('preToolUse denies shell append redirects that bypass the Write tool', () => {
+ const filePath = path.join(cwd, 'src/AppendedCard.html');
+ const out = execFileSync(process.execPath, [path.join('skill', 'scripts', 'hook-before-edit.mjs')], {
+ cwd: path.resolve('.'),
+ input: JSON.stringify({
+ hook_event_name: 'preToolUse',
+ cwd,
+ tool_name: 'Shell',
+ tool_input: {
+ command: `cat >> "${filePath}" <<'EOF'\n<style>.card { border-left: 4px solid #7c3aed; border-radius: 16px; padding: 16px; }</style>\n<div class="card">Hello</div>\nEOF\n`,
+ },
+ }),
+ env: { ...process.env, IMPECCABLE_HOOK_LOG: '' },
+ encoding: 'utf-8',
+ });
+
+ const payload = JSON.parse(out);
+ assert.equal(payload.permission, 'deny');
+ assert.match(payload.user_message, /AppendedCard\.html/);
+ assert.match(payload.user_message, /side-tab/);
+ });
+
+ it('preToolUse denies shell tee writes that bypass the Write tool', () => {
+ const filePath = path.join(cwd, 'src/TeeCard.html');
+ const out = execFileSync(process.execPath, [path.join('skill', 'scripts', 'hook-before-edit.mjs')], {
+ cwd: path.resolve('.'),
+ input: JSON.stringify({
+ hook_event_name: 'preToolUse',
+ cwd,
+ tool_name: 'Shell',
+ tool_input: {
+ command: `cat <<'EOF' | tee -a "${filePath}"\n<style>.card { border-left: 4px solid #7c3aed; border-radius: 16px; padding: 16px; }</style>\n<div class="card">Hello</div>\nEOF\n`,
+ },
+ }),
+ env: { ...process.env, IMPECCABLE_HOOK_LOG: '' },
+ encoding: 'utf-8',
+ });
+
+ const payload = JSON.parse(out);
+ assert.equal(payload.permission, 'deny');
+ assert.match(payload.user_message, /TeeCard\.html/);
+ assert.match(payload.user_message, /side-tab/);
+ });
+
+ it('preToolUse denies shell copy writes when copied content has detector findings', () => {
+ const sourcePath = path.join(cwd, 'src/SourceCard.html');
+ const destPath = path.join(cwd, 'src/CopiedCard.html');
+ fs.mkdirSync(path.dirname(sourcePath), { recursive: true });
+ fs.writeFileSync(sourcePath, `
+ <style>.card { border-left: 4px solid #7c3aed; border-radius: 16px; padding: 16px; }</style>
+ <div class="card">Hello</div>
+ `);
+
+ const out = execFileSync(process.execPath, [path.join('skill', 'scripts', 'hook-before-edit.mjs')], {
+ cwd: path.resolve('.'),
+ input: JSON.stringify({
+ hook_event_name: 'preToolUse',
+ cwd,
+ tool_name: 'Shell',
+ tool_input: {
+ command: `cp "${sourcePath}" "${destPath}"`,
+ },
+ }),
+ env: { ...process.env, IMPECCABLE_HOOK_LOG: '' },
+ encoding: 'utf-8',
+ });
+
+ const payload = JSON.parse(out);
+ assert.equal(payload.permission, 'deny');
+ assert.match(payload.user_message, /CopiedCard\.html/);
+ assert.match(payload.user_message, /side-tab/);
+ });
+
+ it('preToolUse reconstructs Edit old_string/new_string into a full proposed file before scanning', () => {
+ const filePath = path.join(cwd, 'src/EditCard.html');
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
+ const oldString = '<div class="card">Hello</div>';
+ fs.writeFileSync(filePath, oldString);
+ const newString = '<style>.card { border-left: 4px solid #7c3aed; border-radius: 16px; padding: 16px; }</style>\n<div class="card">Hello</div>';
+
+ const out = execFileSync(process.execPath, [path.join('skill', 'scripts', 'hook-before-edit.mjs')], {
+ cwd: path.resolve('.'),
+ input: JSON.stringify({
+ hook_event_name: 'preToolUse',
+ cwd,
+ tool_name: 'Edit',
+ tool_input: {
+ file_path: filePath,
+ old_string: oldString,
+ new_string: newString,
+ },
+ }),
+ env: { ...process.env, IMPECCABLE_HOOK_LOG: '' },
+ encoding: 'utf-8',
+ });
+
+ const payload = JSON.parse(out);
+ assert.equal(payload.permission, 'deny');
+ assert.match(payload.user_message, /EditCard\.html/);
+ assert.match(payload.user_message, /side-tab/);
+ });
+
+ it('preToolUse allows fragment-only edits instead of denying on partial context', () => {
+ const filePath = path.join(cwd, 'src/MissingEditCard.html');
+ const out = execFileSync(process.execPath, [path.join('skill', 'scripts', 'hook-before-edit.mjs')], {
+ cwd: path.resolve('.'),
+ input: JSON.stringify({
+ hook_event_name: 'preToolUse',
+ cwd,
+ tool_name: 'Edit',
+ tool_input: {
+ file_path: filePath,
+ new_string: '<div style="border-left: 4px solid #7c3aed; border-radius: 16px;">Hello</div>',
+ },
+ }),
+ env: { ...process.env, IMPECCABLE_HOOK_LOG: '' },
+ encoding: 'utf-8',
+ });
+
+ assert.deepEqual(JSON.parse(out), { permission: 'allow' });
+ });
+
+ it('preToolUse downgrades repeated identical denials to allow-with-warning after the edit threshold', () => {
+ const filePath = path.join(cwd, 'src/LoopCard.html');
+ const input = JSON.stringify({
+ hook_event_name: 'preToolUse',
+ cwd,
+ session_id: 'cursor-loop',
+ tool_name: 'Write',
+ tool_input: {
+ file_path: filePath,
+ content: '<style>.card { border-left: 4px solid #7c3aed; border-radius: 16px; padding: 16px; }</style><div class="card">Hello</div>',
+ },
+ });
+
+ let payload;
+ for (let i = 0; i < 7; i++) {
+ const out = execFileSync(process.execPath, [path.join('skill', 'scripts', 'hook-before-edit.mjs')], {
+ cwd: path.resolve('.'),
+ input,
+ env: { ...process.env, IMPECCABLE_HOOK_LOG: '' },
+ encoding: 'utf-8',
+ });
+ payload = JSON.parse(out);
+ }
+
+ assert.equal(payload.permission, 'allow');
+ assert.match(payload.agent_message, /allowing this write to avoid a loop/);
+ const cache = readCache(cwd);
+ const denials = cache.sessions['cursor-loop'].files[filePath].cursorDenials;
+ assert.equal(Object.values(denials)[0], 7);
+ });
+
+ it('preToolUse honors truthy IMPECCABLE_HOOK_DISABLED values before stdin parsing', () => {
+ const logPath = path.join(cwd, 'hook.ndjson');
+
+ const out = execFileSync(process.execPath, [path.join('skill', 'scripts', 'hook-before-edit.mjs')], {
+ cwd: path.resolve('.'),
+ input: '{not-json',
+ env: {
+ ...process.env,
+ IMPECCABLE_HOOK_DISABLED: 'true',
+ IMPECCABLE_HOOK_LOG: logPath,
+ },
+ encoding: 'utf-8',
+ });
+
+ assert.deepEqual(JSON.parse(out), { permission: 'allow' });
+ const entries = fs.readFileSync(logPath, 'utf-8').trim().split('\n').map((line) => JSON.parse(line));
+ assert.equal(entries[0].event, 'preToolUse');
+ assert.equal(entries[0].skipped, 'env-disabled');
+ });
+
+});
+
+describe('runHook() — emission enrichment', () => {
+ let cwd;
+ beforeEach(() => { cwd = mkTmp(); });
+ afterEach(() => fs.rmSync(cwd, { recursive: true, force: true }));
+
+ function write(rel, content) {
+ const abs = path.join(cwd, rel);
+ fs.mkdirSync(path.dirname(abs), { recursive: true });
+ fs.writeFileSync(abs, content);
+ return abs;
+ }
+
+ it('returns emission.kind fresh with findings on new hits', async () => {
+ write('src/styles.css', "body { font-family: 'Inter', sans-serif; }");
+ const r = await runHook({
+ stdinJson: JSON.stringify({
+ session_id: 'emit-fresh',
+ cwd,
+ hook_event_name: 'PostToolUse',
+ file_path: path.join(cwd, 'src/styles.css'),
+ }),
+ env: { IMPECCABLE_HOOK_HARNESS: 'claude' },
+ cwd,
+ detector: fakeDetector([finding('overused-font', 8)]),
+ });
+ assert.equal(r.emission?.kind, 'fresh');
+ assert.ok(Array.isArray(r.emission?.findings));
+ assert.equal(r.emission.findings.length, 1);
+ });
+});
diff --git a/tests/live-e2e/steer.mjs b/tests/live-e2e/steer.mjs
index dba865d4d..fff244ce0 100644
--- a/tests/live-e2e/steer.mjs
+++ b/tests/live-e2e/steer.mjs
@@ -48,10 +48,16 @@ export async function runSteerSmoke(page, tmp, fixture, log = () => {}, opts = {
log(`Steer: submitting ${JSON.stringify(message)}`);
await submitSteer(page, message);
- await waitForSteerLocked(page);
- log('Steer: locked (processing)');
+ let sawLocked = false;
+ try {
+ await waitForSteerLocked(page);
+ sawLocked = true;
+ log('Steer: locked (processing)');
+ } catch {
+ log('Steer: processing state not observed; checking completed result');
+ }
await waitForSteerUnlocked(page, { timeout: unlockTimeoutMs });
- log('Steer: unlocked');
+ log(sawLocked ? 'Steer: unlocked' : 'Steer: unlocked or already complete');
const waitForSource = async () => {
const deadline = Date.now() + selectorTimeoutMs;
diff --git a/tests/live-server.test.mjs b/tests/live-server.test.mjs
index a310d5408..3ce521462 100644
--- a/tests/live-server.test.mjs
+++ b/tests/live-server.test.mjs
@@ -99,11 +99,15 @@ it('gitignores local Impeccable runtime artifacts', () => {
'.impeccable/live/manual-edit-apply-transaction.json',
'.impeccable/live/manual-edit-evidence/example.json',
'.impeccable/hook.cache.json',
+ '.impeccable/hook.pending.json',
+ '.impeccable/hook.local.json',
'.impeccable/live/deferred-svelte-component-accepts.json',
], { cwd: REPO_ROOT, encoding: 'utf-8' });
assert.match(ignored, /\.impeccable\/live\/manual-edit-apply-transaction\.json/);
assert.match(ignored, /\.impeccable\/live\/manual-edit-evidence\/example\.json/);
assert.match(ignored, /\.impeccable\/hook\.cache\.json/);
+ assert.match(ignored, /\.impeccable\/hook\.pending\.json/);
+ assert.match(ignored, /\.impeccable\/hook\.local\.json/);
assert.match(ignored, /\.impeccable\/live\/deferred-svelte-component-accepts\.json/);
});
diff --git a/tests/skill-behavior/scenarios.test.mjs b/tests/skill-behavior/scenarios.test.mjs
index dfd94a068..418c6924a 100644
--- a/tests/skill-behavior/scenarios.test.mjs
+++ b/tests/skill-behavior/scenarios.test.mjs
@@ -159,7 +159,7 @@ for (const modelId of resolveModelList()) {
// also counts.
const designSignal =
readsMatching(trace, 'design.md').length > 0 ||
- trace.readPaths.some((p) => /\.(css|scss|less|ts|tsx|js|jsx|json|svelte|astro)$/i.test(p)) ||
+ trace.readPaths.some((p) => /\.(css|scss|sass|less|ts|tsx|js|jsx|json|svelte|astro)$/i.test(p)) ||
trace.listPaths.length > 0;
assert.ok(
designSignal,
diff --git a/tests/skills-cli.test.js b/tests/skills-cli.test.js
index 693fce88f..cd85f114f 100644
--- a/tests/skills-cli.test.js
+++ b/tests/skills-cli.test.js
@@ -14,7 +14,14 @@ import { execSync } from 'child_process';
import { mkdtempSync, existsSync, readdirSync, readFileSync, mkdirSync, writeFileSync, rmSync, lstatSync, realpathSync, readlinkSync, symlinkSync } from 'fs';
import { join } from 'path';
import { tmpdir } from 'os';
-import { migrateUnprefixImpeccable } from '../cli/bin/commands/skills.mjs';
+import {
+ copyProviderHooks,
+ copyProviderSkills,
+ expectedHookDests,
+ mergeHookManifests,
+ migrateUnprefixImpeccable,
+ resolveInstallTargets,
+} from '../cli/bin/commands/skills.mjs';
const CLI = join(import.meta.dir, '..', 'cli', 'bin', 'cli.js');
@@ -73,6 +80,27 @@ function createFakeUniversalBundle(root, providers = ['.claude', '.agents', '.cu
].join('\n'));
writeFileSync(join(skillDir, 'scripts', 'context.mjs'), 'console.log("local bundle context");\n');
}
+ if (providers.includes('.claude')) {
+ mkdirSync(join(bundleRoot, '.claude'), { recursive: true });
+ writeFileSync(join(bundleRoot, '.claude', 'settings.json'), JSON.stringify({
+ description: 'fresh claude hook',
+ hooks: { PostToolUse: [{ matcher: 'Edit', hooks: [{ type: 'command', command: 'node ".claude/skills/impeccable/scripts/hook.mjs"' }] }] },
+ }, null, 2));
+ }
+ if (providers.includes('.cursor')) {
+ mkdirSync(join(bundleRoot, '.cursor'), { recursive: true });
+ writeFileSync(join(bundleRoot, '.cursor', 'hooks.json'), JSON.stringify({
+ version: 1,
+ hooks: { preToolUse: [{ command: 'node ".cursor/skills/impeccable/scripts/hook-before-edit.mjs"' }] },
+ }, null, 2));
+ }
+ if (providers.includes('.agents')) {
+ mkdirSync(join(bundleRoot, '.codex'), { recursive: true });
+ writeFileSync(join(bundleRoot, '.codex', 'hooks.json'), JSON.stringify({
+ description: 'fresh codex hook',
+ hooks: { PostToolUse: [{ matcher: 'apply_patch', hooks: [{ type: 'command', command: 'node "$(git rev-parse --show-toplevel)/.agents/skills/impeccable/scripts/hook.mjs"' }] }] },
+ }, null, 2));
+ }
return bundleRoot;
}
@@ -109,6 +137,7 @@ describe('skills install: already-installed detection', () => {
const tmp = mkdtempSync(join(tmpdir(), 'imp-test-'));
execSync('git init', { cwd: tmp });
createFakeSkills(tmp);
+ writeFileSync(join(tmp, '.claude', 'settings.json'), JSON.stringify({ hooks: {} }));
const output = run('skills install -y', { cwd: tmp });
expect(output).toContain('already installed');
@@ -123,12 +152,49 @@ describe('skills install: already-installed detection', () => {
const skillDir = join(tmp, '.cursor', 'skills', 'i-impeccable');
mkdirSync(skillDir, { recursive: true });
writeFileSync(join(skillDir, 'SKILL.md'), '---\nname: i-impeccable\n---\n');
+ writeFileSync(join(tmp, '.cursor', 'hooks.json'), JSON.stringify({ version: 1, hooks: {} }));
const output = run('skills install -y', { cwd: tmp });
expect(output).toContain('already installed');
rmSync(tmp, { recursive: true, force: true });
}, 15000);
+
+ test('repairs missing hook manifests on already-installed projects', () => {
+ const tmp = mkdtempSync(join(tmpdir(), 'imp-test-repair-hooks-'));
+ execSync('git init', { cwd: tmp });
+ createFakeSkills(tmp, ['impeccable'], ['.claude']);
+ const bundleRoot = createFakeUniversalBundle(tmp, ['.claude']);
+
+ const output = run('skills install -y --providers=claude', {
+ cwd: tmp,
+ env: { ...process.env, IMPECCABLE_BUNDLE_PATH: bundleRoot },
+ });
+
+ expect(output).toContain('already installed');
+ expect(output).toContain('Installed hooks into: .claude');
+ expect(existsSync(join(tmp, '.claude', 'settings.json'))).toBe(true);
+
+ rmSync(tmp, { recursive: true, force: true });
+ }, 15000);
+
+ test('--no-hooks does not repair missing hook manifests on already-installed projects', () => {
+ const tmp = mkdtempSync(join(tmpdir(), 'imp-test-no-hooks-repair-'));
+ execSync('git init', { cwd: tmp });
+ createFakeSkills(tmp, ['impeccable'], ['.claude']);
+ const bundleRoot = createFakeUniversalBundle(tmp, ['.claude']);
+
+ const output = run('skills install -y --providers=claude --no-hooks', {
+ cwd: tmp,
+ env: { ...process.env, IMPECCABLE_BUNDLE_PATH: bundleRoot },
+ });
+
+ expect(output).toContain('already installed');
+ expect(output).not.toContain('Installed hooks into');
+ expect(existsSync(join(tmp, '.claude', 'settings.json'))).toBe(false);
+
+ rmSync(tmp, { recursive: true, force: true });
+ }, 15000);
});
// ─── Submodule/link installs ────────────────────────────────────────────────
@@ -330,6 +396,30 @@ describe('skills install/update: local universal bundle e2e', () => {
expect(readFileSync(join(skillDir, 'SKILL.md'), 'utf8')).toContain(`Local deterministic bundle for ${provider}.`);
expect(existsSync(join(skillDir, 'scripts', 'context.mjs'))).toBe(true);
}
+ expect(existsSync(join(tmp, '.claude', 'settings.json'))).toBe(true);
+ expect(existsSync(join(tmp, '.cursor', 'hooks.json'))).toBe(true);
+ expect(existsSync(join(tmp, '.codex', 'hooks.json'))).toBe(true);
+
+ rmSync(tmp, { recursive: true, force: true });
+ }, 15000);
+
+ test('--no-hooks installs skills without hook manifests', () => {
+ const tmp = mkdtempSync(join(tmpdir(), 'imp-test-local-no-hooks-'));
+ execSync('git init', { cwd: tmp });
+ const bundleRoot = createFakeUniversalBundle(tmp);
+
+ const output = run('skills install -y --providers=claude,codex,cursor --no-hooks', {
+ cwd: tmp,
+ env: { ...process.env, IMPECCABLE_BUNDLE_PATH: bundleRoot },
+ });
+ expect(output).toContain('Done!');
+ expect(output).not.toContain('Installed hooks into');
+ for (const provider of ['.claude', '.agents', '.cursor']) {
+ expect(existsSync(join(tmp, provider, 'skills', 'impeccable', 'SKILL.md'))).toBe(true);
+ }
+ expect(existsSync(join(tmp, '.claude', 'settings.json'))).toBe(false);
+ expect(existsSync(join(tmp, '.cursor', 'hooks.json'))).toBe(false);
+ expect(existsSync(join(tmp, '.codex', 'hooks.json'))).toBe(false);
rmSync(tmp, { recursive: true, force: true });
}, 15000);
@@ -353,6 +443,49 @@ describe('skills install/update: local universal bundle e2e', () => {
expect(content).not.toContain('stale: true');
expect(content).toContain('version: 9.9.9-local');
expect(existsSync(join(skillDir, 'scripts', 'context.mjs'))).toBe(true);
+ expect(existsSync(join(tmp, '.claude', 'settings.json'))).toBe(true);
+
+ rmSync(tmp, { recursive: true, force: true });
+ }, 15000);
+
+ test('skills update --no-hooks refreshes skills without touching malformed hook manifests', () => {
+ const tmp = mkdtempSync(join(tmpdir(), 'imp-test-update-no-hooks-'));
+ execSync('git init', { cwd: tmp });
+ const bundleRoot = createFakeUniversalBundle(tmp, ['.cursor']);
+
+ run('skills install -y --providers=cursor --no-hooks', {
+ cwd: tmp,
+ env: { ...process.env, IMPECCABLE_BUNDLE_PATH: bundleRoot },
+ });
+ mkdirSync(join(tmp, '.cursor'), { recursive: true });
+ writeFileSync(join(tmp, '.cursor', 'hooks.json'), '{ malformed');
+
+ const output = run('skills update -y --no-hooks', {
+ cwd: tmp,
+ env: { ...process.env, IMPECCABLE_BUNDLE_PATH: bundleRoot },
+ });
+ expect(output).toContain('Skills are up to date');
+ expect(readFileSync(join(tmp, '.cursor', 'hooks.json'), 'utf8')).toBe('{ malformed');
+
+ rmSync(tmp, { recursive: true, force: true });
+ }, 15000);
+
+ test('skills update reports malformed hook manifests cleanly on the up-to-date path', () => {
+ const tmp = mkdtempSync(join(tmpdir(), 'imp-test-update-bad-hooks-'));
+ execSync('git init', { cwd: tmp });
+ const bundleRoot = createFakeUniversalBundle(tmp, ['.cursor']);
+
+ run('skills install -y --providers=cursor', {
+ cwd: tmp,
+ env: { ...process.env, IMPECCABLE_BUNDLE_PATH: bundleRoot },
+ });
+ writeFileSync(join(tmp, '.cursor', 'hooks.json'), '{ malformed');
+
+ expect(() => run('skills update -y', {
+ cwd: tmp,
+ env: { ...process.env, IMPECCABLE_BUNDLE_PATH: bundleRoot },
+ stdio: 'pipe',
+ })).toThrow();
rmSync(tmp, { recursive: true, force: true });
}, 15000);
@@ -378,6 +511,39 @@ describe('skills install/update: local universal bundle e2e', () => {
}, 15000);
});
+describe('hook manifest merge helpers', () => {
+ test('mergeHookManifests refreshes fresh description and version while preserving third-party hooks', () => {
+ const merged = mergeHookManifests(
+ {
+ version: 0,
+ description: 'old description',
+ hooks: {
+ preToolUse: [
+ { command: 'node third-party.mjs' },
+ { command: 'node .cursor/skills/impeccable/scripts/hook-before-edit.mjs' },
+ ],
+ },
+ },
+ {
+ version: 1,
+ description: 'fresh description',
+ hooks: {
+ preToolUse: [
+ { command: 'node .cursor/skills/impeccable/scripts/hook-before-edit.mjs' },
+ ],
+ },
+ },
+ );
+
+ expect(merged.version).toBe(1);
+ expect(merged.description).toBe('fresh description');
+ expect(merged.hooks.preToolUse.map((entry) => entry.command)).toEqual([
+ 'node third-party.mjs',
+ 'node .cursor/skills/impeccable/scripts/hook-before-edit.mjs',
+ ]);
+ });
+});
+
// ─── Update fallback (remote direct download smoke) ──────────────────────────
describeRemote('skills update: refreshes from the production universal bundle', () => {